Fix Windows Relation on Audio and PDF Content Extraction ...
This commit is contained in:
@@ -24,5 +24,10 @@ namespace xAiApi.Configurations
|
||||
/// Transcript Configuration ...
|
||||
/// </summary>
|
||||
public XAiTransciptDescriptor Transcript { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// PDF To Image Configuration ...
|
||||
/// </summary>
|
||||
public XPDFToImageDescriptor PDFToImageDescriptor {get; set;}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace xAiApi.Models
|
||||
{
|
||||
public class XPDFToImageDescriptor
|
||||
{
|
||||
public int Dpi { get; set; } = 300;
|
||||
public int Width { get; set; } = 0;
|
||||
public int Height { get; set; } = 0;
|
||||
public bool UseTiling { get; set; } = false;
|
||||
public bool WithFormFill { get; set; } = false;
|
||||
public bool WithAspectRatio { get; set; } = false;
|
||||
public bool WithAnnotations { get; set; } = false;
|
||||
public bool DpiRelativeToBounds { get; set; } = false;
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,14 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using FFMpegCore;
|
||||
using System.Linq;
|
||||
using Whisper.net;
|
||||
using NAudio.Wave;
|
||||
using System.Threading;
|
||||
using xAiModels.Models;
|
||||
using xCommons.Extensions;
|
||||
using xAiApi.Configurations;
|
||||
using xExceptions.Constants;
|
||||
using System.Threading.Tasks;
|
||||
using NAudio.MediaFoundation;
|
||||
using xAiApi.Interfaces.Extractors;
|
||||
|
||||
namespace xAiApi.Providers.Extractors
|
||||
@@ -161,173 +160,76 @@ namespace xAiApi.Providers.Extractors
|
||||
)
|
||||
{
|
||||
//
|
||||
var result = await Task.Run(() =>
|
||||
var tempInput = Path.Combine(
|
||||
Path.GetTempPath(),
|
||||
$"audio_in_{Guid.NewGuid()}{GetExtensionFromMime(mimeType)}"
|
||||
);
|
||||
var tempOutput = Path.Combine(
|
||||
Path.GetTempPath(),
|
||||
$"audio_out_{Guid.NewGuid()}.wav"
|
||||
);
|
||||
|
||||
//
|
||||
MemoryStream result = null;
|
||||
try
|
||||
{
|
||||
//
|
||||
var memoryStream = new MemoryStream();
|
||||
inputStream.CopyTo(memoryStream);
|
||||
memoryStream.Position = 0;
|
||||
using var fs = File.Create(tempInput);
|
||||
await inputStream.CopyToAsync(fs, cancellationToken);
|
||||
await FFMpegArguments
|
||||
.FromFileInput(tempInput)
|
||||
.OutputToFile(tempOutput, overwrite: true, options => options
|
||||
.WithAudioCodec("pcm_s16le")
|
||||
.WithCustomArgument("-ar 16000")
|
||||
.WithCustomArgument("-ac 1")
|
||||
.ForceFormat("wav"))
|
||||
.ProcessAsynchronously();
|
||||
|
||||
//
|
||||
var targetFormat = new WaveFormat(16000, 16, 1);
|
||||
string tempFilePath = null;
|
||||
|
||||
result = new();
|
||||
using var fsTmp = File.OpenRead(tempOutput);
|
||||
await fsTmp.CopyToAsync(result, cancellationToken);
|
||||
result.Position = 0;
|
||||
}
|
||||
catch
|
||||
{
|
||||
result = null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
WaveStream reader = GetAudioReader(memoryStream, mimeType, ref tempFilePath);
|
||||
if (reader == null)
|
||||
{
|
||||
//
|
||||
XException.NotAllowed.Throw(
|
||||
$"Unsupported audio format: {mimeType}"
|
||||
);
|
||||
}
|
||||
// Remove Temparory Files ...
|
||||
if (File.Exists(tempInput)) File.Delete(tempInput);
|
||||
if (File.Exists(tempOutput)) File.Delete(tempOutput);
|
||||
}
|
||||
|
||||
//
|
||||
var needsConversion =
|
||||
reader.WaveFormat.SampleRate != 16000 ||
|
||||
reader.WaveFormat.Channels != 1 ||
|
||||
reader.WaveFormat.BitsPerSample != 16 ||
|
||||
reader.WaveFormat.Encoding != WaveFormatEncoding.Pcm;
|
||||
var outputStream = new MemoryStream();
|
||||
if (!needsConversion)
|
||||
{
|
||||
//
|
||||
reader.CopyTo(outputStream);
|
||||
reader.Dispose();
|
||||
}
|
||||
else
|
||||
{
|
||||
//
|
||||
MediaFoundationApi.Startup();
|
||||
using var resampler = new MediaFoundationResampler(
|
||||
reader,
|
||||
targetFormat
|
||||
);
|
||||
resampler.ResamplerQuality = 60;
|
||||
|
||||
//
|
||||
WaveFileWriter.WriteWavFileToStream(outputStream, resampler);
|
||||
reader.Dispose();
|
||||
}
|
||||
|
||||
//
|
||||
outputStream.Position = 0;
|
||||
return outputStream;
|
||||
}
|
||||
finally
|
||||
{
|
||||
//
|
||||
if (!string.IsNullOrEmpty(tempFilePath) &&
|
||||
File.Exists(tempFilePath))
|
||||
{
|
||||
//
|
||||
try
|
||||
{
|
||||
File.Delete(tempFilePath);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
//
|
||||
memoryStream.Dispose();
|
||||
}
|
||||
}, cancellationToken);
|
||||
//
|
||||
if (result.IsNull())
|
||||
{
|
||||
XException.ActionFailed.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get appropriate WaveStream reader based on MIME type ...
|
||||
/// Retrieve File Extension based on mime type ...
|
||||
/// </summary>
|
||||
/// <param name="stream">Input stream (MemoryStream)</param>
|
||||
/// <param name="mimeType">MIME type of audio file</param>
|
||||
/// <param name="tempFilePath">Path to temp file (if created)</param>
|
||||
/// <returns>WaveStream reader or null if unsupported</returns>
|
||||
private WaveStream GetAudioReader(
|
||||
MemoryStream stream,
|
||||
string mimeType,
|
||||
ref string tempFilePath
|
||||
)
|
||||
/// <param name="mimeType"></param>
|
||||
/// <returns></returns>
|
||||
private string GetExtensionFromMime(string mimeType)
|
||||
{
|
||||
//
|
||||
try
|
||||
return mimeType?.ToLowerInvariant() switch
|
||||
{
|
||||
//
|
||||
var normalizedMime = mimeType?.ToLowerInvariant() ?? string.Empty;
|
||||
switch (normalizedMime)
|
||||
{
|
||||
//
|
||||
case "audio/wav":
|
||||
case "audio/wave":
|
||||
case "audio/x-wav":
|
||||
return new WaveFileReader(stream);
|
||||
|
||||
//
|
||||
case "audio/mpeg":
|
||||
case "audio/mp3":
|
||||
return new Mp3FileReader(stream);
|
||||
|
||||
//
|
||||
case "audio/m4a":
|
||||
case "audio/mp4":
|
||||
case "audio/aac":
|
||||
case "audio/ogg":
|
||||
case "audio/webm":
|
||||
case "audio/x-m4a":
|
||||
//
|
||||
var extension = normalizedMime switch
|
||||
{
|
||||
"audio/m4a" or "audio/mp4" or "audio/aac" or "audio/x-m4a" => ".m4a",
|
||||
"audio/ogg" => ".ogg",
|
||||
"audio/webm" => ".webm",
|
||||
_ => ".tmp"
|
||||
};
|
||||
tempFilePath = Path.Combine(
|
||||
Path.GetTempPath(),
|
||||
$"audio_{Guid.NewGuid()}{extension}"
|
||||
);
|
||||
|
||||
//
|
||||
stream.Position = 0;
|
||||
using (var fileStream = File.Create(tempFilePath))
|
||||
{
|
||||
stream.CopyTo(fileStream);
|
||||
}
|
||||
|
||||
//
|
||||
MediaFoundationApi.Startup();
|
||||
return new MediaFoundationReader(tempFilePath);
|
||||
|
||||
default:
|
||||
//
|
||||
tempFilePath = Path.Combine(
|
||||
Path.GetTempPath(),
|
||||
$"audio_{Guid.NewGuid()}.tmp"
|
||||
);
|
||||
stream.Position = 0;
|
||||
using (var fileStream = File.Create(tempFilePath))
|
||||
{
|
||||
stream.CopyTo(fileStream);
|
||||
}
|
||||
try
|
||||
{
|
||||
MediaFoundationApi.Startup();
|
||||
return new MediaFoundationReader(tempFilePath);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
"audio/mpeg" or "audio/mp3" => ".mp3",
|
||||
"audio/m4a" or "audio/mp4" or "audio/aac" or "audio/x-m4a" => ".m4a",
|
||||
"audio/ogg" => ".ogg",
|
||||
"audio/webm" => ".webm",
|
||||
"audio/wav" or "audio/wave" or "audio/x-wav" => ".wav",
|
||||
_ => ".tmp"
|
||||
};
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using SkiaSharp;
|
||||
using PDFtoImage;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using PdfiumViewer;
|
||||
using System.Threading;
|
||||
using xAiModels.Models;
|
||||
using xAiApi.Configurations;
|
||||
using System.Threading.Tasks;
|
||||
using xAiApi.Interfaces.Extractors;
|
||||
|
||||
@@ -43,6 +45,16 @@ namespace xAiApi.Providers.Extractors
|
||||
/// </summary>
|
||||
private const int MaxImageWidth = 2000;
|
||||
|
||||
/// <summary>
|
||||
/// Api Configuration ...
|
||||
/// </summary>
|
||||
private readonly XAiApiConfiguration configuration;
|
||||
|
||||
public XPdfFileContentExtractor(XAiApiConfiguration configuration)
|
||||
{
|
||||
this.configuration = configuration;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Check if this extractor supports the specified MIME type ...
|
||||
/// </summary>
|
||||
@@ -211,18 +223,33 @@ namespace xAiApi.Providers.Extractors
|
||||
try
|
||||
{
|
||||
//
|
||||
using var document = PdfDocument.Load(pdfStream);
|
||||
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();
|
||||
|
||||
//
|
||||
var allPagesCount = Conversion.GetPageCount(pdfStream);
|
||||
var pageCount = Math.Min(
|
||||
document.PageCount,
|
||||
allPagesCount,
|
||||
MaxPagesForImageFallback
|
||||
);
|
||||
|
||||
//
|
||||
for (int pageIndex = 0; pageIndex < pageCount; pageIndex++)
|
||||
for (int pageIndex = 0; pageIndex < allPagesCount; pageIndex++)
|
||||
{
|
||||
//
|
||||
// Check Cancellation Token ...
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
@@ -232,52 +259,23 @@ namespace xAiApi.Providers.Extractors
|
||||
try
|
||||
{
|
||||
//
|
||||
var pageSize = document.PageSizes[pageIndex];
|
||||
|
||||
//
|
||||
var scaleFactor = RenderDpi / 72.0;
|
||||
var renderWidth = (int)Math.Ceiling(pageSize.Width * scaleFactor);
|
||||
var renderHeight = (int)Math.Ceiling(pageSize.Height * scaleFactor);
|
||||
|
||||
//
|
||||
if (renderWidth > MaxImageWidth)
|
||||
var skBitmap = images[pageIndex];
|
||||
using (skBitmap)
|
||||
using (var image = SKImage.FromBitmap(skBitmap))
|
||||
using (var data = image.Encode(SKEncodedImageFormat.Png, 100))
|
||||
using (var ms = new MemoryStream())
|
||||
{
|
||||
//
|
||||
var ratio = (double)MaxImageWidth / renderWidth;
|
||||
renderWidth = MaxImageWidth;
|
||||
renderHeight = (int)(renderHeight * ratio);
|
||||
data.SaveTo(ms);
|
||||
result.Images.Add(new XExtractedImage
|
||||
{
|
||||
Bytes = ms.ToArray(),
|
||||
MimeType = "image/png",
|
||||
Description = $"Page {pageIndex}, rendered from {fileName}"
|
||||
});
|
||||
}
|
||||
|
||||
//
|
||||
using var bitmap = document.Render(
|
||||
dpiX: RenderDpi,
|
||||
dpiY: RenderDpi,
|
||||
page: pageIndex,
|
||||
width: renderWidth,
|
||||
forPrinting: false,
|
||||
height: renderHeight
|
||||
);
|
||||
|
||||
//
|
||||
byte[] imageBytes;
|
||||
using (var memoryStream = new MemoryStream())
|
||||
{
|
||||
//
|
||||
bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
|
||||
imageBytes = memoryStream.ToArray();
|
||||
}
|
||||
|
||||
//
|
||||
result.Images.Add(new XExtractedImage
|
||||
{
|
||||
Bytes = imageBytes,
|
||||
MimeType = "image/png",
|
||||
PageNumber = pageIndex + 1,
|
||||
Description = $"Page {pageIndex + 1} of {fileName} ({renderWidth}x{renderHeight})"
|
||||
});
|
||||
}
|
||||
catch (Exception)
|
||||
{ }
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -88,6 +88,16 @@
|
||||
"Transcript": {
|
||||
"Language": "fa",
|
||||
"ModelsPath": "Models/ggml-base.bin"
|
||||
},
|
||||
"PDFToImageDescriptor": {
|
||||
"Dpi": 300,
|
||||
"Width": null,
|
||||
"Height": null,
|
||||
"UseTiling": false,
|
||||
"WithFormFill": false,
|
||||
"WithAspectRatio": false,
|
||||
"WithAnnotations": false,
|
||||
"DpiRelativeToBounds": false
|
||||
}
|
||||
},
|
||||
"Logging": {
|
||||
|
||||
+5
-8
@@ -24,7 +24,8 @@
|
||||
|
||||
<!-- Icon Handling -->
|
||||
<ItemGroup>
|
||||
<None Include="../../Resources/Images/favicon.png" Link="icon.png" Pack="true" PackagePath="\icon.png" />
|
||||
<None Include="../../Resources/Images/favicon.png" Link="icon.png" Pack="true"
|
||||
PackagePath="\icon.png" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Local Modules -->
|
||||
@@ -46,22 +47,18 @@
|
||||
|
||||
<!-- Dependencies -->
|
||||
<ItemGroup>
|
||||
<PackageReference Include="NAudio" Version="2.4.0" />
|
||||
<PackageReference Include="Tesseract" Version="5.2.0" />
|
||||
<PackageReference Include="PDFtoImage" Version="4.1.1" />
|
||||
<PackageReference Include="FFMpegCore" Version="4.8.0" />
|
||||
<PackageReference Include="Whisper.net" Version="1.9.1" />
|
||||
<PackageReference Include="OllamaSharp" Version="5.4.25" />
|
||||
<PackageReference Include="PdfiumViewer" Version="2.13.0" />
|
||||
<PackageReference Include="ExcelDataReader" Version="3.9.0" />
|
||||
<PackageReference Include="Whisper.net.Runtime" Version="1.9.1" />
|
||||
<PackageReference Include="DocumentFormat.OpenXml" Version="3.5.1" />
|
||||
<PackageReference Include="ExcelDataReader.DataSet" Version="3.9.0" />
|
||||
<PackageReference Include="UglyToad.PdfPig" Version="1.7.0-custom-5" />
|
||||
<PackageReference Include="PdfiumViewer.Native.x86.v8-xfa" Version="2018.4.8.256" />
|
||||
<PackageReference Include="PdfiumViewer.Native.x86_64.v8-xfa" Version="2018.4.8.256" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.11" />
|
||||
<PackageReference Include="PdfiumViewer.Native.x86.no_v8-no_xfa" Version="2018.4.8.256" />
|
||||
<PackageReference Include="IdentityModel.AspNetCore.OAuth2Introspection" Version="5.0.0" />
|
||||
<PackageReference Include="PdfiumViewer.Native.x86_64.no_v8-no_xfa" Version="2018.4.8.256" />
|
||||
<PackageReference Include="SkiaSharp.NativeAssets.Linux.NoDependencies" Version="3.116.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- For XML Documentation Support -->
|
||||
|
||||
Reference in New Issue
Block a user