53 lines
1.8 KiB
C#
53 lines
1.8 KiB
C#
namespace BLAIzor.Services
|
|
{
|
|
using System.Net.Http.Headers;
|
|
using System.Text.Json;
|
|
|
|
public class WhisperTranscriptionService
|
|
{
|
|
private readonly IConfiguration _configuration;
|
|
private readonly IHttpClientFactory _httpClientFactory;
|
|
private string _apiKey = ""; // Store this securely!
|
|
|
|
public WhisperTranscriptionService(IHttpClientFactory httpClientFactory, IConfiguration configuration)
|
|
{
|
|
_httpClientFactory = httpClientFactory;
|
|
_configuration = configuration;
|
|
}
|
|
|
|
private string GetApiKey() =>
|
|
_configuration?.GetSection("OpenAI")?.GetValue<string>("ApiKey") ?? string.Empty;
|
|
|
|
public async Task<string?> TranscribeAsync(byte[] audioData)
|
|
{
|
|
|
|
_apiKey = GetApiKey();
|
|
|
|
try
|
|
{
|
|
var client = _httpClientFactory.CreateClient();
|
|
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey);
|
|
|
|
var content = new MultipartFormDataContent
|
|
{
|
|
{ new ByteArrayContent(audioData), "file", "audio.webm" },
|
|
{ new StringContent("whisper-1"), "model" }
|
|
};
|
|
|
|
var response = await client.PostAsync("https://api.openai.com/v1/audio/transcriptions", content);
|
|
response.EnsureSuccessStatusCode();
|
|
|
|
var resultJson = await response.Content.ReadAsStringAsync();
|
|
var json = JsonDocument.Parse(resultJson);
|
|
return json.RootElement.GetProperty("text").GetString();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine("STT error: " + ex.Message);
|
|
return null;
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|