add support for OCR ...

This commit is contained in:
2026-10-03 22:26:03 +03:30
parent 7cad889cd0
commit 70c2d5a649
5 changed files with 102 additions and 21 deletions
@@ -5,6 +5,10 @@ using System.Threading;
using xAiModels.Models;
using System.Threading.Tasks;
using xAiApi.Interfaces.Extractors;
using xAiApi.Configurations;
using xCommons.Extensions;
using xExceptions.Constants;
using Tesseract;
namespace xAiApi.Providers.Extractors
{
@@ -24,16 +28,25 @@ namespace xAiApi.Providers.Extractors
];
/// <summary>
/// آیا OCR فعال است (برای مدل‌های غیر Vision) ...
/// AI Api Configuration ...
/// </summary>
private readonly bool _enableOcrFallback;
private readonly XAiApiConfiguration configuration;
public XImageFileContentExtractor() : this(enableOcrFallback: true)
{ }
public XImageFileContentExtractor(bool enableOcrFallback = true)
public XImageFileContentExtractor(
XAiApiConfiguration configuration
)
{
_enableOcrFallback = enableOcrFallback;
//
if (configuration.IsNullOrDefault() ||
configuration.OCR.IsNullOrDefault() ||
configuration.OCR.DataPath.IsNullOrEmpty() ||
configuration.OCR.DefaultLanguage.IsNullOrEmpty())
{
XException.InvalidConfiguration.Throw();
}
//
this.configuration = configuration;
}
/// <summary>
@@ -103,8 +116,9 @@ namespace xAiApi.Providers.Extractors
Description = $"Attached image: {fileName}"
});
// OCR Fallback برای مدل‌های متنی
if (_enableOcrFallback)
//
// OCR Fallback ...
if (configuration.OCR.EnableOcrFallback)
{
//
try
@@ -135,8 +149,44 @@ namespace xAiApi.Providers.Extractors
)
{
//
// TODO: Complete this ...
return await Task.FromResult(string.Empty);
return await Task.Run(() =>
{
//
// Validate Path ...
if (!Directory.Exists(configuration.OCR.DataPath))
{
//
throw new DirectoryNotFoundException(
$"TessData directory not found at: {configuration.OCR.DataPath}. " +
"Please download traineddata files from https://github.com/tesseract-ocr/tessdata"
);
}
//
using var engine = new TesseractEngine(
datapath: configuration.OCR.DataPath,
language: configuration.OCR.DefaultLanguage,
engineMode: configuration.OCR.EngineMode
);
//
using var pix = Pix.LoadFromMemory(imageBytes);
//
cancellationToken.ThrowIfCancellationRequested();
//
using var page = engine.Process(pix);
//
var text = page.GetText();
//
text = text?.Trim();
//
return text ?? string.Empty;
}, cancellationToken);
}
}
}