236 lines
7.0 KiB
C#
236 lines
7.0 KiB
C#
using System;
|
|
using System.IO;
|
|
using FFMpegCore;
|
|
using System.Linq;
|
|
using Whisper.net;
|
|
using System.Threading;
|
|
using xAiModels.Models;
|
|
using xCommons.Extensions;
|
|
using xAiApi.Configurations;
|
|
using xExceptions.Constants;
|
|
using System.Threading.Tasks;
|
|
using xAiApi.Interfaces.Extractors;
|
|
|
|
namespace xAiApi.Providers.Extractors
|
|
{
|
|
/// <summary>
|
|
/// Extracts text content from Audio files ...
|
|
/// </summary>
|
|
public class XAudioFileContentExtractor : IXAudioFileContentExtractor
|
|
{
|
|
/// <summary>
|
|
/// Supported MIME Types ...
|
|
/// </summary>
|
|
private static readonly string[] SupportedMimeTypes =
|
|
[
|
|
"audio/mpeg",
|
|
"audio/mp3",
|
|
"audio/wav",
|
|
"audio/wave",
|
|
"audio/x-wav",
|
|
"audio/ogg",
|
|
"audio/m4a",
|
|
"audio/mp4",
|
|
"audio/aac",
|
|
"audio/x-m4a",
|
|
"audio/webm"
|
|
];
|
|
|
|
private readonly XAiApiConfiguration configuration;
|
|
|
|
public XAudioFileContentExtractor(
|
|
XAiApiConfiguration configuration
|
|
)
|
|
{
|
|
//
|
|
if (configuration.Transcript.IsNullOrDefault() ||
|
|
configuration.Transcript.ModelsPath.IsNullOrEmpty())
|
|
{
|
|
XException.InvalidConfiguration.Throw();
|
|
}
|
|
|
|
//
|
|
this.configuration = configuration;
|
|
}
|
|
|
|
/// <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,
|
|
"audio",
|
|
mimeType,
|
|
cancellationToken
|
|
);
|
|
|
|
//
|
|
return result.AudioTranscript;
|
|
}
|
|
|
|
/// <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
|
|
{
|
|
//
|
|
using var memoryStream = new MemoryStream();
|
|
await fileStream.CopyToAsync(memoryStream, cancellationToken);
|
|
memoryStream.Position = 0;
|
|
|
|
//
|
|
using var wavStream = await ConvertToWavAsync(
|
|
mimeType: mimeType,
|
|
inputStream: memoryStream,
|
|
cancellationToken: cancellationToken
|
|
);
|
|
|
|
//
|
|
using var factory = WhisperFactory.FromPath(configuration.Transcript.ModelsPath);
|
|
using var processor = factory.CreateBuilder()
|
|
.WithLanguage(configuration.Transcript.Language)
|
|
.Build();
|
|
|
|
//
|
|
var segments = new System.Text.StringBuilder();
|
|
await foreach (var segment in processor.ProcessAsync(wavStream, cancellationToken))
|
|
{
|
|
segments.Append(segment.Text);
|
|
}
|
|
|
|
//
|
|
result.AudioTranscript = segments.ToString().Trim();
|
|
result.Text = result.AudioTranscript;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
result.ErrorMessage = $"Audio extraction failed: {ex.Message}";
|
|
}
|
|
|
|
//
|
|
return result;
|
|
}
|
|
|
|
//
|
|
#region Private ...
|
|
/// <summary>
|
|
/// Audio Format Converting to WAV 16kHz Mono 16-bit PCM ...
|
|
/// </summary>
|
|
private async Task<Stream> ConvertToWavAsync(
|
|
Stream inputStream,
|
|
string mimeType,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
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
|
|
{
|
|
//
|
|
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();
|
|
|
|
//
|
|
result = new();
|
|
using var fsTmp = File.OpenRead(tempOutput);
|
|
await fsTmp.CopyToAsync(result, cancellationToken);
|
|
result.Position = 0;
|
|
}
|
|
catch
|
|
{
|
|
result = null;
|
|
}
|
|
finally
|
|
{
|
|
//
|
|
// Remove Temparory Files ...
|
|
if (File.Exists(tempInput)) File.Delete(tempInput);
|
|
if (File.Exists(tempOutput)) File.Delete(tempOutput);
|
|
}
|
|
|
|
//
|
|
if (result.IsNull())
|
|
{
|
|
XException.ActionFailed.Throw();
|
|
}
|
|
|
|
//
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Retrieve File Extension based on mime type ...
|
|
/// </summary>
|
|
/// <param name="mimeType"></param>
|
|
/// <returns></returns>
|
|
private string GetExtensionFromMime(string mimeType)
|
|
{
|
|
//
|
|
return mimeType?.ToLowerInvariant() switch
|
|
{
|
|
"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
|
|
}
|
|
} |