diff --git a/Configurations/XAiApiConfiguration.cs b/Configurations/XAiApiConfiguration.cs
index b589cdd..ec9c032 100644
--- a/Configurations/XAiApiConfiguration.cs
+++ b/Configurations/XAiApiConfiguration.cs
@@ -18,16 +18,16 @@ namespace xAiApi.Configurations
///
/// OCR Configuration ...
///
- public XAiOCRDescriptor OCR { get; set; }
+ public XAiOCRDescriptor OCR { get; set; } = new ();
///
/// Transcript Configuration ...
///
- public XAiTransciptDescriptor Transcript { get; set; }
+ public XAiTransciptDescriptor Transcript { get; set; } = new ();
///
/// PDF To Image Configuration ...
///
- public XPDFToImageDescriptor PDFToImageDescriptor {get; set;}
+ public XPDFToImageDescriptor PDFToImageDescriptor {get; set;} = new ();
}
}
\ No newline at end of file
diff --git a/DI/XDIHelperExtension.cs b/DI/XDIHelperExtension.cs
index 70b1002..fcafc9d 100644
--- a/DI/XDIHelperExtension.cs
+++ b/DI/XDIHelperExtension.cs
@@ -4,6 +4,8 @@ using xAiApi.Extensions;
using xCommons.Extensions;
using xAiApi.Configurations;
using xExceptions.Constants;
+using xAiApi.Providers.Extractors;
+using xAiApi.Interfaces.Extractors;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
@@ -67,6 +69,33 @@ namespace xAiApi.DI
source.AddSingleton(configuration);
}
+ ///
+ /// Register AiApi File Content Extractor Services ...
+ ///
+ ///
+ public static void AddXAiFileContentExtractors(
+ this IServiceCollection source
+ )
+ {
+ //
+ // Register File Content Extractors ...
+ source.AddSingleton();
+ source.AddSingleton();
+ source.AddSingleton();
+ source.AddSingleton();
+ source.AddSingleton();
+ source.AddSingleton();
+ source.AddSingleton();
+ source.AddSingleton();
+ source.AddSingleton();
+ source.AddSingleton();
+ source.AddSingleton();
+ source.AddSingleton();
+
+ //
+ source.AddSingleton();
+ }
+
//
#region Private ...
///
diff --git a/Extensions/XProgramExtensions.cs b/Extensions/XProgramExtensions.cs
index 402bd34..c99afba 100644
--- a/Extensions/XProgramExtensions.cs
+++ b/Extensions/XProgramExtensions.cs
@@ -1,11 +1,11 @@
+using xIdentityHelper;
+using xCommons.Extensions;
+using xCommons.Authorization;
using System.Collections.Generic;
-using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.DependencyInjection;
-using xCommons.Authorization;
-using xCommons.Extensions;
-using xIdentityHelper;
namespace xAiApi.Extensions
{
diff --git a/Interfaces/Extractors/IXEpubFileContentExtractor.cs b/Interfaces/Extractors/IXEpubFileContentExtractor.cs
new file mode 100644
index 0000000..d4d293e
--- /dev/null
+++ b/Interfaces/Extractors/IXEpubFileContentExtractor.cs
@@ -0,0 +1,9 @@
+namespace xAiApi.Interfaces.Extractors
+{
+ ///
+ /// Extractor for EPUB electronic publication format
+ /// (application/epub+zip)
+ ///
+ public interface IXEpubFileContentExtractor : IXFileContentExtractorBase
+ { }
+}
\ No newline at end of file
diff --git a/Interfaces/Extractors/IXHtmlFileContentExtractor.cs b/Interfaces/Extractors/IXHtmlFileContentExtractor.cs
new file mode 100644
index 0000000..8f6ef36
--- /dev/null
+++ b/Interfaces/Extractors/IXHtmlFileContentExtractor.cs
@@ -0,0 +1,8 @@
+namespace xAiApi.Interfaces.Extractors
+{
+ ///
+ /// Extractor for HTML documents (text/html, application/xhtml+xml)
+ ///
+ public interface IXHtmlFileContentExtractor : IXFileContentExtractorBase
+ { }
+}
\ No newline at end of file
diff --git a/Interfaces/Extractors/IXOpenDocumentFileContentExtractor.cs b/Interfaces/Extractors/IXOpenDocumentFileContentExtractor.cs
new file mode 100644
index 0000000..f87a973
--- /dev/null
+++ b/Interfaces/Extractors/IXOpenDocumentFileContentExtractor.cs
@@ -0,0 +1,9 @@
+namespace xAiApi.Interfaces.Extractors
+{
+ ///
+ /// Extractor for OpenDocument Format (ODF) documents
+ /// (ODT: OpenDocument Text, ODS: OpenDocument Spreadsheet, ODP: OpenDocument Presentation)
+ ///
+ public interface IXOpenDocumentFileContentExtractor : IXFileContentExtractorBase
+ { }
+}
\ No newline at end of file
diff --git a/Interfaces/Extractors/IXPowerPointFileContentExtractor.cs b/Interfaces/Extractors/IXPowerPointFileContentExtractor.cs
new file mode 100644
index 0000000..e26317e
--- /dev/null
+++ b/Interfaces/Extractors/IXPowerPointFileContentExtractor.cs
@@ -0,0 +1,9 @@
+namespace xAiApi.Interfaces.Extractors
+{
+ ///
+ /// Extractor for all PowerPoint Presentation formats
+ /// (OpenXML: pptx, ppsx, potx, pptm, ppsm, potm | Legacy Binary: ppt, pps, pot)
+ ///
+ public interface IXPowerPointFileContentExtractor : IXFileContentExtractorBase
+ { }
+}
\ No newline at end of file
diff --git a/Interfaces/Extractors/IXRtfFileContentExtractor.cs b/Interfaces/Extractors/IXRtfFileContentExtractor.cs
new file mode 100644
index 0000000..2b405cf
--- /dev/null
+++ b/Interfaces/Extractors/IXRtfFileContentExtractor.cs
@@ -0,0 +1,9 @@
+namespace xAiApi.Interfaces.Extractors
+{
+ ///
+ /// Extractor for Rich Text Format (RTF) documents
+ /// (application/rtf, text/rtf)
+ ///
+ public interface IXRtfFileContentExtractor : IXFileContentExtractorBase
+ { }
+}
\ No newline at end of file
diff --git a/Models/XPDFToImageDescriptor.cs b/Models/XPDFToImageDescriptor.cs
index c0c0b05..9768c84 100644
--- a/Models/XPDFToImageDescriptor.cs
+++ b/Models/XPDFToImageDescriptor.cs
@@ -10,5 +10,9 @@ namespace xAiApi.Models
public bool WithAspectRatio { get; set; } = false;
public bool WithAnnotations { get; set; } = false;
public bool DpiRelativeToBounds { get; set; } = false;
+
+ public int MaxImageWidth { get; set; } = 2000;
+ public int MinTextLengthThreshold { get; set; } = 50;
+ public int MaxPagesForImageFallback { get; set; } = 0;
}
}
\ No newline at end of file
diff --git a/Program.cs b/Program.cs
index d93697e..f2b8c93 100644
--- a/Program.cs
+++ b/Program.cs
@@ -1,3 +1,4 @@
+using System.Text;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
@@ -7,14 +8,24 @@ namespace xAiApi
{
public static void Main(string[] args)
{
+ //
+ Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
+
+ //
CreateHostBuilder(args).Build().Run();
}
- public static IHostBuilder CreateHostBuilder(string[] args) =>
- Host.CreateDefaultBuilder(args)
+ public static IHostBuilder CreateHostBuilder(string[] args)
+ {
+ //
+ var result = Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup();
});
+
+ //
+ return result;
+ }
}
}
diff --git a/Providers/Extractors/XEpubFileContentExtractor.cs b/Providers/Extractors/XEpubFileContentExtractor.cs
new file mode 100644
index 0000000..c9ba2e6
--- /dev/null
+++ b/Providers/Extractors/XEpubFileContentExtractor.cs
@@ -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
+{
+ ///
+ /// Extractor for EPUB electronic publication format
+ /// (application/epub+zip)
+ ///
+ public class XEpubFileContentExtractor : IXEpubFileContentExtractor
+ {
+ ///
+ /// Supported MIME Types ...
+ ///
+ private static readonly string[] SupportedMimeTypes =
+ [
+ "application/epub+zip"
+ ];
+
+ ///
+ /// 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,
+ "book.epub",
+ 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 ExtractEpubAsync(
+ fileStream,
+ cancellationToken
+ );
+ }
+ catch (Exception ex)
+ {
+ //
+ result.ErrorMessage =
+ $"EPUB extraction failed: {ex.Message}";
+ }
+
+ //
+ return result;
+ }
+
+ ///
+ /// Extract Epub Content ...
+ ///
+ ///
+ ///
+ ///
+ private async Task 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;
+ }
+
+ ///
+ /// Extract Text Content from HTML ...
+ ///
+ ///
+ ///
+ 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;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Providers/Extractors/XHtmlFileContentExtractor.cs b/Providers/Extractors/XHtmlFileContentExtractor.cs
new file mode 100644
index 0000000..0b215de
--- /dev/null
+++ b/Providers/Extractors/XHtmlFileContentExtractor.cs
@@ -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
+{
+ ///
+ /// 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;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Providers/Extractors/XOpenDocumentFileContentExtractor.cs b/Providers/Extractors/XOpenDocumentFileContentExtractor.cs
new file mode 100644
index 0000000..7ff90c0
--- /dev/null
+++ b/Providers/Extractors/XOpenDocumentFileContentExtractor.cs
@@ -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
+{
+ ///
+ /// Extractor for OpenDocument Format (ODF) documents
+ /// (ODT: OpenDocument Text, ODS: OpenDocument Spreadsheet, ODP: OpenDocument Presentation)
+ ///
+ public class XOpenDocumentFileContentExtractor : IXOpenDocumentFileContentExtractor
+ {
+ ///
+ /// Supported MIME Types ...
+ ///
+ private static readonly string[] SupportedMimeTypes =
+ [
+ "application/vnd.oasis.opendocument.text", // .odt
+ "application/vnd.oasis.opendocument.spreadsheet", // .ods
+ "application/vnd.oasis.opendocument.presentation" // .odp
+ ];
+
+ ///
+ /// 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.rtf",
+ 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
+ {
+ //
+ 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;
+ }
+
+ ///
+ /// Check Mime Type ...
+ ///
+ ///
+ ///
+ private bool IsOdt(string mimeType)
+ {
+ //
+ var result = mimeType?
+ .ToLowerInvariant() == "application/vnd.oasis.opendocument.text";
+
+ //
+ return result;
+ }
+
+ ///
+ /// Check Mime Type ...
+ ///
+ ///
+ ///
+ private bool IsOds(string mimeType)
+ {
+ //
+ var result = mimeType?
+ .ToLowerInvariant() == "application/vnd.oasis.opendocument.spreadsheet";
+
+ //
+ return result;
+ }
+
+ ///
+ /// Check Mime Type ...
+ ///
+ ///
+ ///
+ private bool IsOdp(string mimeType)
+ {
+ //
+ var result = mimeType?
+ .ToLowerInvariant() == "application/vnd.oasis.opendocument.presentation";
+
+ //
+ return result;
+ }
+
+ ///
+ /// Extract ODT File Content ...
+ ///
+ ///
+ ///
+ ///
+ private async Task 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();
+ 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;
+ }
+
+ ///
+ /// Extract ODS File Content ...
+ ///
+ ///
+ ///
+ ///
+ private async Task 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();
+ 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;
+ }
+
+ ///
+ /// Extract ODS File Content ...
+ ///
+ ///
+ ///
+ ///
+ private async Task 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();
+
+ //
+ 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;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Providers/Extractors/XPdfFileContentExtractor.cs b/Providers/Extractors/XPdfFileContentExtractor.cs
index ec4cd53..10d5c1c 100644
--- a/Providers/Extractors/XPdfFileContentExtractor.cs
+++ b/Providers/Extractors/XPdfFileContentExtractor.cs
@@ -25,26 +25,6 @@ namespace xAiApi.Providers.Extractors
"application/pdf"
];
- ///
- /// Minimum Length for Fallback Using Images ...
- ///
- private const int MinTextLengthThreshold = 50;
-
- ///
- /// Max Pages for Falling Back Using Images ...
- ///
- private const int MaxPagesForImageFallback = 10;
-
- ///
- /// Default DPI for Rendering Images ...
- ///
- private const int RenderDpi = 150;
-
- ///
- /// Max Rendered Image Width ...
- ///
- private const int MaxImageWidth = 2000;
-
///
/// Api Configuration ...
///
@@ -58,6 +38,8 @@ namespace xAiApi.Providers.Extractors
///
/// Check if this extractor supports the specified MIME type ...
///
+ ///
+ ///
public bool CanExtract(string mimeType)
{
//
@@ -69,6 +51,10 @@ namespace xAiApi.Providers.Extractors
///
/// Extract text content from file stream ...
///
+ ///
+ ///
+ ///
+ ///
public async Task 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 ...
///
+ ///
+ ///
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;
}
///
/// Fallback Converts PDF Pages to Images ...
///
+ ///
+ ///
+ ///
+ ///
+ ///
private async Task 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}"
});
}
}
diff --git a/Providers/Extractors/XPlainTextFileContentExtractor.cs b/Providers/Extractors/XPlainTextFileContentExtractor.cs
index b6ef9b6..697d72f 100644
--- a/Providers/Extractors/XPlainTextFileContentExtractor.cs
+++ b/Providers/Extractors/XPlainTextFileContentExtractor.cs
@@ -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
///
/// Check if this extractor supports the specified MIME type ...
///
+ ///
+ ///
public bool CanExtract(string mimeType)
{
//
diff --git a/Providers/Extractors/XPowerPointFileContentExtractor.cs b/Providers/Extractors/XPowerPointFileContentExtractor.cs
new file mode 100644
index 0000000..ad93925
--- /dev/null
+++ b/Providers/Extractors/XPowerPointFileContentExtractor.cs
@@ -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
+{
+ ///
+ /// Extracts content from all PowerPoint formats
+ /// (OpenXML: pptx/ppsx/potx/pptm/ppsm/potm | Legacy Binary: ppt/pps/pot)
+ ///
+ public class XPowerPointFileContentExtractor : IXPowerPointFileContentExtractor
+ {
+ ///
+ /// Supported MIME Types ...
+ ///
+ 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"
+ ];
+
+ ///
+ /// 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: fileStream,
+ fileName: "presentation",
+ mimeType: mimeType,
+ cancellationToken: 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
+ {
+ //
+ 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;
+ }
+
+ ///
+ /// Check Open XML Format ...
+ ///
+ ///
+ ///
+ 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;
+ }
+
+ ///
+ /// Check Legacy Format ...
+ ///
+ ///
+ ///
+ private bool IsLegacyFormat(string mimeType)
+ {
+ //
+ var result = mimeType?.ToLowerInvariant() == "application/vnd.ms-powerpoint";
+ return result;
+ }
+
+ ///
+ /// Extract an Slide Title ...
+ ///
+ ///
+ ///
+ private string GetSlideTitle(SlidePart slidePart)
+ {
+ //
+ var result = string.Empty;
+
+ //
+ // Title placeholder has specific type
+ var titleShape = slidePart.Slide
+ .Descendants()
+ .FirstOrDefault(s => s.NonVisualShapeProperties?
+ .NonVisualDrawingProperties?
+ .Name?.Value?
+ .StartsWith("Title", StringComparison.OrdinalIgnoreCase) == true
+ );
+ if (titleShape != null)
+ {
+ //
+ var titleText = titleShape
+ .Descendants()
+ .Select(t => t.Text?.Trim())
+ .Where(t => !string.IsNullOrWhiteSpace(t));
+ result = string.Join(" ", titleText);
+ }
+
+ //
+ return result;
+ }
+
+ ///
+ /// Extract Speaker Notes ...
+ ///
+ ///
+ ///
+ private string GetSpeakerNotes(SlidePart slidePart)
+ {
+ //
+ var result = string.Empty;
+
+ //
+ var notesSlidePart = slidePart.NotesSlidePart;
+ if (notesSlidePart?.NotesSlide == null)
+ {
+ return result;
+ }
+
+ //
+ var notesTexts = notesSlidePart.NotesSlide
+ .Descendants()
+ .Select(t => t.Text?.Trim())
+ .Where(t => !string.IsNullOrWhiteSpace(t))
+ .ToList();
+
+ //
+ result = notesTexts.Count > 0
+ ? string.Join(Environment.NewLine, notesTexts)
+ : null;
+
+ //
+ return result;
+ }
+
+ ///
+ /// Extract OpenXML Tables ...
+ ///
+ ///
+ ///
+ private static string ExtractOpenXmlTables(SlidePart slidePart)
+ {
+ //
+ var sb = new StringBuilder();
+
+ //
+ var tableElements = slidePart.Slide
+ .Descendants();
+
+ //
+ var tableIndex = 0;
+ foreach (var table in tableElements)
+ {
+ //
+ tableIndex++;
+ sb.AppendLine($" Table {tableIndex}:");
+
+ //
+ foreach (var row in table
+ .Descendants())
+ {
+ //
+ var cells = row
+ .Descendants()
+ .Select(c => string.Join(" ", c
+ .Descendants()
+ .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;
+ }
+
+ ///
+ /// Extract Open XML Format ...
+ ///
+ ///
+ ///
+ ///
+ private async Task 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()
+ .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;
+ }
+
+ ///
+ /// Extract Legacy Format ...
+ ///
+ ///
+ ///
+ ///
+ private async Task 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();
+ 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;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Providers/Extractors/XRtfFileContentExtractor.cs b/Providers/Extractors/XRtfFileContentExtractor.cs
new file mode 100644
index 0000000..ef5d8f6
--- /dev/null
+++ b/Providers/Extractors/XRtfFileContentExtractor.cs
@@ -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
+{
+ ///
+ /// Extractor for Rich Text Format (RTF) documents
+ /// (application/rtf, text/rtf)
+ ///
+ public class XRtfFileContentExtractor : IXRtfFileContentExtractor
+ {
+ ///
+ /// Supported MIME Types ...
+ ///
+ private static readonly string[] SupportedMimeTypes =
+ [
+ "text/rtf",
+ "application/rtf",
+ ];
+
+ ///
+ /// 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.rtf",
+ 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 ExtractRtfAsync(
+ fileStream,
+ cancellationToken
+ );
+ }
+ catch (Exception ex)
+ {
+ //
+ result.ErrorMessage =
+ $"RTF extraction failed: {ex.Message}";
+ }
+
+ //
+ return result;
+ }
+
+ ///
+ /// Extract RTF Content ...
+ ///
+ ///
+ ///
+ ///
+ private async Task 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;
+ }
+
+ ///
+ /// Converts Html to Text ...
+ ///
+ ///
+ ///
+ 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;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Startup.cs b/Startup.cs
index 15c7f94..11b89d1 100644
--- a/Startup.cs
+++ b/Startup.cs
@@ -188,17 +188,8 @@ namespace xAiApi
services.AddXAiApiConfiguration(Configuration);
//
- // Register File Content Extractors ...
- services.AddSingleton();
- services.AddSingleton();
- services.AddSingleton();
- services.AddSingleton();
- services.AddSingleton();
- services.AddSingleton();
- services.AddSingleton();
-
- //
- services.AddSingleton();
+ // Register File Content Extractor Services ...
+ services.AddXAiFileContentExtractors();
//
// Register Default Ai Service ...
diff --git a/appsettings.Development.json b/appsettings.Development.json
index f77ed44..0efae45 100644
--- a/appsettings.Development.json
+++ b/appsettings.Development.json
@@ -1,111 +1,114 @@
{
- "AllowedOrigins": [
- "http://localhost:5000",
- "https://localhost:5001",
- "http://api.saherelm.ir",
- "https://api.saherelm.ir",
- "http://api.saherelmhub.ir",
- "https://api.saherelmhub.ir"
- ],
- "IdentityServiceConfiguration": {
- "Authority": "https://localhost:4001",
- "ApiName": "xSaherElmAPI",
- "ApiSecret": "s@H@1694056",
- "ClientId": "xSaherElmAPIClient",
- "ClientSecret": "s@H@1694056",
- "XPoweredValue": "SaherElmITCenter",
- "XRevisionSecretKey": "SaherElmITCenter@1694056",
- "DefaultClientTimeout": -1
- },
- "StorageConfiguration": {
- "Authority": "https://localhost:5001",
- "IdentityAuthority": "https://localhost:5001",
- "Storage": "Storage",
- "Temp": "Temp",
- "Thumb": "Thumb",
- "Uploads": "Uploads",
- "Widgets": "Widgets",
- "Image": "Image",
- "Audio": "Audio",
- "Video": "Video",
- "Document": "Document",
- "FilePrefix": "xSaherElm_",
- "ThumbPrefix": "Thumb_",
- "ThumbSize": 512,
- "ThumbQuality": 72,
- "MaxFileSize": 41943040
- },
- "AiApiConfiguration": {
- "Models": [
- {
- "ApiKey": "",
- "Name": "Gemma",
- "LLM": "gemma3:1b",
- "Provider": "OpenAI",
- "Url": "http://178.131.88.93:1112/v1"
- },
- {
- "ApiKey": "",
- "Name": "Qwen",
- "LLM": "qwen-9b",
- "Provider": "OpenAI",
- "Url": "http://178.131.88.93:1114/v1"
- },
- {
- "ApiKey": "",
- "Name": "Embed",
- "LLM": "bge-m3",
- "Provider": "OpenAI",
- "Url": "http://178.131.88.93:1113/v1"
- }
- ],
- "Prompts": [
- {
- "Name": "Introduction",
- "Template": "your name is xSaherElmAi, you are a professional ai assistant which develped by SaherElm IT Center, answer each questions by it's language.",
- "Description": "",
- "Params": []
- },
- {
- "Name": "ContentExtraction",
- "Template": "You are an Expert Powerful OCR Engine. your job isReading all Contents in Given Document and Retrieve them as Raw Text by following these rules: 1. Converst all tables to Markdown format. 2. extract numbers, date and times and names exactly as is. 3. do not add any extra descriptions, introduction or summarization from yourself and just return extracted Content.",
- "Description": "",
- "Params": []
- },
- {
- "Name": "Embedding",
- "Template": "your name is xSaherElmAi, you are a professional ai assistant which develped by SaherElm IT Center specified for Embedding Documents",
- "Description": "",
- "Params": []
- }
- ],
- "OCR": {
- "DataPath": "Models",
- "EngineMode": "LstmOnly",
- "EnableOcrFallback": true,
- "DefaultLanguage": "fas+eng"
- },
- "Transcript": {
- "Language": "fa",
- "ModelsPath": "Models/ggml-base.bin"
- },
- "PDFToImageDescriptor": {
- "Dpi": 300,
- "Width": 0,
- "Height": 0,
- "UseTiling": false,
- "WithFormFill": false,
- "WithAspectRatio": false,
- "WithAnnotations": false,
- "DpiRelativeToBounds": false
- }
- },
- "Logging": {
- "LogLevel": {
- "Microsoft": "Warning",
- "Default": "Information",
- "Microsoft.Hosting.Lifetime": "Information"
- }
- },
- "AllowedHosts": "*"
-}
\ No newline at end of file
+ "AllowedOrigins": [
+ "http://localhost:5000",
+ "https://localhost:5001",
+ "http://api.saherelm.ir",
+ "https://api.saherelm.ir",
+ "http://api.saherelmhub.ir",
+ "https://api.saherelmhub.ir"
+ ],
+ "IdentityServiceConfiguration": {
+ "Authority": "https://localhost:4001",
+ "ApiName": "xSaherElmAPI",
+ "ApiSecret": "s@H@1694056",
+ "ClientId": "xSaherElmAPIClient",
+ "ClientSecret": "s@H@1694056",
+ "XPoweredValue": "SaherElmITCenter",
+ "XRevisionSecretKey": "SaherElmITCenter@1694056",
+ "DefaultClientTimeout": -1
+ },
+ "StorageConfiguration": {
+ "Authority": "https://localhost:5001",
+ "IdentityAuthority": "https://localhost:5001",
+ "Storage": "Storage",
+ "Temp": "Temp",
+ "Thumb": "Thumb",
+ "Uploads": "Uploads",
+ "Widgets": "Widgets",
+ "Image": "Image",
+ "Audio": "Audio",
+ "Video": "Video",
+ "Document": "Document",
+ "FilePrefix": "xSaherElm_",
+ "ThumbPrefix": "Thumb_",
+ "ThumbSize": 512,
+ "ThumbQuality": 72,
+ "MaxFileSize": 41943040
+ },
+ "AiApiConfiguration": {
+ "Models": [
+ {
+ "ApiKey": "",
+ "Name": "Gemma",
+ "LLM": "gemma3:1b",
+ "Provider": "OpenAI",
+ "Url": "http://178.131.88.93:1112/v1"
+ },
+ {
+ "ApiKey": "",
+ "Name": "Qwen",
+ "LLM": "qwen-9b",
+ "Provider": "OpenAI",
+ "Url": "http://178.131.88.93:1114/v1"
+ },
+ {
+ "ApiKey": "",
+ "Name": "Embed",
+ "LLM": "bge-m3",
+ "Provider": "OpenAI",
+ "Url": "http://178.131.88.93:1113/v1"
+ }
+ ],
+ "Prompts": [
+ {
+ "Name": "Introduction",
+ "Template": "your name is xSaherElmAi, you are a professional ai assistant which develped by SaherElm IT Center, answer each questions by it's language.",
+ "Description": "",
+ "Params": []
+ },
+ {
+ "Name": "ContentExtraction",
+ "Template": "You are an Expert Powerful OCR Engine. your job isReading all Contents in Given Document and Retrieve them as Raw Text by following these rules: 1. Converst all tables to Markdown format. 2. extract numbers, date and times and names exactly as is. 3. do not add any extra descriptions, introduction or summarization from yourself and just return extracted Content.",
+ "Description": "",
+ "Params": []
+ },
+ {
+ "Name": "Embedding",
+ "Template": "your name is xSaherElmAi, you are a professional ai assistant which develped by SaherElm IT Center specified for Embedding Documents",
+ "Description": "",
+ "Params": []
+ }
+ ],
+ "OCR": {
+ "DataPath": "Models",
+ "EngineMode": "LstmOnly",
+ "EnableOcrFallback": true,
+ "DefaultLanguage": "fas+eng"
+ },
+ "Transcript": {
+ "Language": "fa",
+ "ModelsPath": "Models/ggml-base.bin"
+ },
+ "PDFToImageDescriptor": {
+ "Dpi": 300,
+ "Width": 0,
+ "Height": 0,
+ "UseTiling": false,
+ "WithFormFill": false,
+ "WithAspectRatio": false,
+ "WithAnnotations": false,
+ "DpiRelativeToBounds": false,
+ "MaxImageWidth": 2000,
+ "MinTextLengthThreshold": 50,
+ "MaxPagesForImageFallback": 0
+ }
+ },
+ "Logging": {
+ "LogLevel": {
+ "Microsoft": "Warning",
+ "Default": "Information",
+ "Microsoft.Hosting.Lifetime": "Information"
+ }
+ },
+ "AllowedHosts": "*"
+}
diff --git a/xAiApi.csproj b/xAiApi.csproj
index c27b456..0bac248 100644
--- a/xAiApi.csproj
+++ b/xAiApi.csproj
@@ -24,8 +24,7 @@
-
+
@@ -50,12 +49,19 @@
+
+
+
+
+
+
+