diff --git a/Configurations/XAiApiConfiguration.cs b/Configurations/XAiApiConfiguration.cs index 2153bc2..b589cdd 100644 --- a/Configurations/XAiApiConfiguration.cs +++ b/Configurations/XAiApiConfiguration.cs @@ -24,5 +24,10 @@ namespace xAiApi.Configurations /// Transcript Configuration ... /// public XAiTransciptDescriptor Transcript { get; set; } + + /// + /// PDF To Image Configuration ... + /// + public XPDFToImageDescriptor PDFToImageDescriptor {get; set;} } } \ No newline at end of file diff --git a/Models/XPDFToImageDescriptor.cs b/Models/XPDFToImageDescriptor.cs new file mode 100644 index 0000000..c0c0b05 --- /dev/null +++ b/Models/XPDFToImageDescriptor.cs @@ -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; + } +} \ No newline at end of file diff --git a/Providers/Extractors/XAudioFileContentExtractor.cs b/Providers/Extractors/XAudioFileContentExtractor.cs index 8f6e18a..55ebf7b 100644 --- a/Providers/Extractors/XAudioFileContentExtractor.cs +++ b/Providers/Extractors/XAudioFileContentExtractor.cs @@ -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; } /// - /// Get appropriate WaveStream reader based on MIME type ... + /// Retrieve File Extension based on mime type ... /// - /// Input stream (MemoryStream) - /// MIME type of audio file - /// Path to temp file (if created) - /// WaveStream reader or null if unsupported - private WaveStream GetAudioReader( - MemoryStream stream, - string mimeType, - ref string tempFilePath - ) + /// + /// + 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 } diff --git a/Providers/Extractors/XPdfFileContentExtractor.cs b/Providers/Extractors/XPdfFileContentExtractor.cs index 629018f..ec4cd53 100644 --- a/Providers/Extractors/XPdfFileContentExtractor.cs +++ b/Providers/Extractors/XPdfFileContentExtractor.cs @@ -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 /// private const int MaxImageWidth = 2000; + /// + /// Api Configuration ... + /// + private readonly XAiApiConfiguration configuration; + + public XPdfFileContentExtractor(XAiApiConfiguration configuration) + { + this.configuration = configuration; + } + /// /// Check if this extractor supports the specified MIME type ... /// @@ -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) diff --git a/appsettings.Development.json b/appsettings.Development.json index ea92863..1533e1f 100644 --- a/appsettings.Development.json +++ b/appsettings.Development.json @@ -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": { diff --git a/xAiApi.csproj b/xAiApi.csproj index 71e53bb..c27b456 100644 --- a/xAiApi.csproj +++ b/xAiApi.csproj @@ -24,7 +24,8 @@ - + @@ -46,22 +47,18 @@ - + + - - - - - - +