openai/openai-dotnet
Publicmirrored from https://github.com/openai/openai-dotnetAvailable
OpenAI/src/Custom/Audio/AudioClient.cs
655lines · modecode
| 1 | using Microsoft.TypeSpec.Generator.Customizations; |
| 2 | using System; |
| 3 | using System.ClientModel; |
| 4 | using System.ClientModel.Primitives; |
| 5 | using System.Diagnostics.CodeAnalysis; |
| 6 | using System.IO; |
| 7 | using System.Text.Json; |
| 8 | using System.Threading; |
| 9 | using System.Threading.Tasks; |
| 10 | |
| 11 | namespace OpenAI.Audio; |
| 12 | |
| 13 | // CUSTOM: |
| 14 | // - Renamed. |
| 15 | // - Suppressed constructor that takes endpoint parameter; endpoint is now a property in the options class. |
| 16 | // - Suppressed methods that only take the options parameter. |
| 17 | /// <summary> The service client for OpenAI audio operations. </summary> |
| 18 | [CodeGenType("Audio")] |
| 19 | [CodeGenSuppress("AudioClient", typeof(ClientPipeline), typeof(Uri))] |
| 20 | [CodeGenSuppress("GenerateSpeechAsync", typeof(SpeechGenerationOptions), typeof(CancellationToken))] |
| 21 | [CodeGenSuppress("GenerateSpeech", typeof(SpeechGenerationOptions), typeof(CancellationToken))] |
| 22 | public partial class AudioClient |
| 23 | { |
| 24 | private readonly string _model; |
| 25 | |
| 26 | // CUSTOM: Added as a convenience. |
| 27 | /// <summary> Initializes a new instance of <see cref="AudioClient"/>. </summary> |
| 28 | /// <param name="model"> The name of the model to use in requests sent to the service. To learn more about the available models, see <see href="https://platform.openai.com/docs/models"/>. </param> |
| 29 | /// <param name="apiKey"> The API key to authenticate with the service. </param> |
| 30 | /// <exception cref="ArgumentNullException"> <paramref name="model"/> or <paramref name="apiKey"/> is null. </exception> |
| 31 | /// <exception cref="ArgumentException"> <paramref name="model"/> is an empty string, and was expected to be non-empty. </exception> |
| 32 | public AudioClient(string model, string apiKey) : this(model, new ApiKeyCredential(apiKey), new OpenAIClientOptions()) |
| 33 | { |
| 34 | } |
| 35 | |
| 36 | // CUSTOM: |
| 37 | // - Added `model` parameter. |
| 38 | // - Used a custom pipeline. |
| 39 | // - Demoted the endpoint parameter to be a property in the options class. |
| 40 | /// <summary> Initializes a new instance of <see cref="AudioClient"/>. </summary> |
| 41 | /// <param name="model"> The name of the model to use in requests sent to the service. To learn more about the available models, see <see href="https://platform.openai.com/docs/models"/>. </param> |
| 42 | /// <param name="credential"> The <see cref="ApiKeyCredential"/> to authenticate with the service. </param> |
| 43 | /// <exception cref="ArgumentNullException"> <paramref name="model"/> or <paramref name="credential"/> is null. </exception> |
| 44 | /// <exception cref="ArgumentException"> <paramref name="model"/> is an empty string, and was expected to be non-empty. </exception> |
| 45 | public AudioClient(string model, ApiKeyCredential credential) : this(model, credential, new OpenAIClientOptions()) |
| 46 | { |
| 47 | } |
| 48 | |
| 49 | // CUSTOM: |
| 50 | // - Added `model` parameter. |
| 51 | // - Used a custom pipeline. |
| 52 | // - Demoted the endpoint parameter to be a property in the options class. |
| 53 | /// <summary> Initializes a new instance of <see cref="AudioClient"/>. </summary> |
| 54 | /// <param name="model"> The name of the model to use in requests sent to the service. To learn more about the available models, see <see href="https://platform.openai.com/docs/models"/>. </param> |
| 55 | /// <param name="credential"> The <see cref="ApiKeyCredential"/> to authenticate with the service. </param> |
| 56 | /// <param name="options"> The options to configure the client. </param> |
| 57 | /// <exception cref="ArgumentNullException"> <paramref name="model"/> or <paramref name="credential"/> is null. </exception> |
| 58 | /// <exception cref="ArgumentException"> <paramref name="model"/> is an empty string, and was expected to be non-empty. </exception> |
| 59 | public AudioClient(string model, ApiKeyCredential credential, OpenAIClientOptions options) : this(model, OpenAIClient.CreateApiKeyAuthenticationPolicy(credential), options) |
| 60 | { |
| 61 | } |
| 62 | |
| 63 | // CUSTOM: Added as a convenience. |
| 64 | /// <summary> Initializes a new instance of <see cref="AudioClient"/>. </summary> |
| 65 | /// <param name="model"> The name of the model to use in requests sent to the service. To learn more about the available models, see <see href="https://platform.openai.com/docs/models"/>. </param> |
| 66 | /// <param name="authenticationPolicy"> The authentication policy used to authenticate with the service. </param> |
| 67 | /// <exception cref="ArgumentNullException"> <paramref name="model"/> or <paramref name="authenticationPolicy"/> is null. </exception> |
| 68 | /// <exception cref="ArgumentException"> <paramref name="model"/> is an empty string, and was expected to be non-empty. </exception> |
| 69 | [Experimental("OPENAI001")] |
| 70 | public AudioClient(string model, AuthenticationPolicy authenticationPolicy) : this(model, authenticationPolicy, new OpenAIClientOptions()) |
| 71 | { |
| 72 | } |
| 73 | |
| 74 | // CUSTOM: Added as a convenience. |
| 75 | /// <summary> Initializes a new instance of <see cref="AudioClient"/>. </summary> |
| 76 | /// <param name="model"> The name of the model to use in requests sent to the service. To learn more about the available models, see <see href="https://platform.openai.com/docs/models"/>. </param> |
| 77 | /// <param name="authenticationPolicy"> The authentication policy used to authenticate with the service. </param> |
| 78 | /// <param name="options"> The options to configure the client. </param> |
| 79 | /// <exception cref="ArgumentNullException"> <paramref name="model"/> or <paramref name="authenticationPolicy"/> is null. </exception> |
| 80 | /// <exception cref="ArgumentException"> <paramref name="model"/> is an empty string, and was expected to be non-empty. </exception> |
| 81 | [Experimental("OPENAI001")] |
| 82 | public AudioClient(string model, AuthenticationPolicy authenticationPolicy, OpenAIClientOptions options) |
| 83 | { |
| 84 | Argument.AssertNotNullOrEmpty(model, nameof(model)); |
| 85 | Argument.AssertNotNull(authenticationPolicy, nameof(authenticationPolicy)); |
| 86 | options ??= new OpenAIClientOptions(); |
| 87 | |
| 88 | _model = model; |
| 89 | Pipeline = OpenAIClient.CreatePipeline(authenticationPolicy, options); |
| 90 | _endpoint = OpenAIClient.GetEndpoint(options); |
| 91 | } |
| 92 | |
| 93 | // CUSTOM: |
| 94 | // - Added `model` parameter. |
| 95 | // - Used a custom pipeline. |
| 96 | // - Demoted the endpoint parameter to be a property in the options class. |
| 97 | // - Made protected. |
| 98 | /// <summary> Initializes a new instance of <see cref="AudioClient"/>. </summary> |
| 99 | /// <param name="pipeline"> The HTTP pipeline to send and receive REST requests and responses. </param> |
| 100 | /// <param name="model"> The name of the model to use in requests sent to the service. To learn more about the available models, see <see href="https://platform.openai.com/docs/models"/>. </param> |
| 101 | /// <param name="options"> The options to configure the client. </param> |
| 102 | /// <exception cref="ArgumentNullException"> <paramref name="pipeline"/> or <paramref name="model"/> is null. </exception> |
| 103 | /// <exception cref="ArgumentException"> <paramref name="model"/> is an empty string, and was expected to be non-empty. </exception> |
| 104 | protected internal AudioClient(ClientPipeline pipeline, string model, OpenAIClientOptions options) |
| 105 | { |
| 106 | Argument.AssertNotNull(pipeline, nameof(pipeline)); |
| 107 | Argument.AssertNotNullOrEmpty(model, nameof(model)); |
| 108 | options ??= new OpenAIClientOptions(); |
| 109 | |
| 110 | _model = model; |
| 111 | Pipeline = pipeline; |
| 112 | _endpoint = OpenAIClient.GetEndpoint(options); |
| 113 | } |
| 114 | |
| 115 | [Experimental("SCME0002")] |
| 116 | public AudioClient(AudioClientSettings settings) |
| 117 | : this(settings?.Model, AuthenticationPolicy.Create(settings), settings?.Options) |
| 118 | { |
| 119 | } |
| 120 | |
| 121 | /// <summary> |
| 122 | /// Gets the name of the model used in requests sent to the service. |
| 123 | /// </summary> |
| 124 | [Experimental("OPENAI001")] |
| 125 | public string Model => _model; |
| 126 | |
| 127 | /// <summary> |
| 128 | /// Gets the endpoint URI for the service. |
| 129 | /// </summary> |
| 130 | [Experimental("OPENAI001")] |
| 131 | public Uri Endpoint => _endpoint; |
| 132 | |
| 133 | #region GenerateSpeech |
| 134 | |
| 135 | /// <summary> Generates a life-like, spoken audio recording of the input text. </summary> |
| 136 | /// <remarks> |
| 137 | /// The default format of the generated audio is <see cref="GeneratedSpeechFormat.Mp3"/> unless otherwise specified |
| 138 | /// via <see cref="SpeechGenerationOptions.ResponseFormat"/>. |
| 139 | /// </remarks> |
| 140 | /// <param name="text"> The text to generate audio for. </param> |
| 141 | /// <param name="voice"> The voice to use in the generated audio. </param> |
| 142 | /// <param name="options"> The options to configure the audio generation. </param> |
| 143 | /// <param name="cancellationToken"> A token that can be used to cancel this method call. </param> |
| 144 | /// <exception cref="ArgumentNullException"> <paramref name="text"/> is null. </exception> |
| 145 | /// <returns> The generated audio in the specified output format. </returns> |
| 146 | public virtual async Task<ClientResult<BinaryData>> GenerateSpeechAsync(string text, GeneratedSpeechVoice voice, SpeechGenerationOptions options = null, CancellationToken cancellationToken = default) |
| 147 | { |
| 148 | Argument.AssertNotNull(text, nameof(text)); |
| 149 | |
| 150 | options ??= new(); |
| 151 | CreateSpeechGenerationOptions(text, voice, ref options); |
| 152 | |
| 153 | using BinaryContent content = options.ToBinaryContent(); |
| 154 | ClientResult result = await GenerateSpeechAsync(content, cancellationToken.ToRequestOptions()).ConfigureAwait(false); |
| 155 | return ClientResult.FromValue(result.GetRawResponse().Content, result.GetRawResponse()); |
| 156 | } |
| 157 | |
| 158 | /// <summary> Generates a life-like, spoken audio recording of the input text. </summary> |
| 159 | /// <remarks> |
| 160 | /// The default format of the generated audio is <see cref="GeneratedSpeechFormat.Mp3"/> unless otherwise specified |
| 161 | /// via <see cref="SpeechGenerationOptions.ResponseFormat"/>. |
| 162 | /// </remarks> |
| 163 | /// <param name="text"> The text to generate audio for. </param> |
| 164 | /// <param name="voice"> The voice to use in the generated audio. </param> |
| 165 | /// <param name="options"> The options to configure the audio generation. </param> |
| 166 | /// <param name="cancellationToken"> A token that can be used to cancel this method call. </param> |
| 167 | /// <exception cref="ArgumentNullException"> <paramref name="text"/> is null. </exception> |
| 168 | /// <returns> The generated audio in the specified output format. </returns> |
| 169 | public virtual ClientResult<BinaryData> GenerateSpeech(string text, GeneratedSpeechVoice voice, SpeechGenerationOptions options = null, CancellationToken cancellationToken = default) |
| 170 | { |
| 171 | Argument.AssertNotNull(text, nameof(text)); |
| 172 | |
| 173 | options ??= new(); |
| 174 | CreateSpeechGenerationOptions(text, voice, ref options); |
| 175 | |
| 176 | using BinaryContent content = options.ToBinaryContent(); |
| 177 | ClientResult result = GenerateSpeech(content, cancellationToken.ToRequestOptions()); ; |
| 178 | return ClientResult.FromValue(result.GetRawResponse().Content, result.GetRawResponse()); |
| 179 | } |
| 180 | |
| 181 | /// <summary> Generates a life-like, spoken audio recording of the input text as a streaming SSE event collection. </summary> |
| 182 | /// <param name="text"> The text to generate audio for. </param> |
| 183 | /// <param name="voice"> The voice to use in the generated audio. </param> |
| 184 | /// <param name="options"> The options to configure the audio generation. </param> |
| 185 | /// <param name="cancellationToken"> A token that can be used to cancel this method call. </param> |
| 186 | /// <exception cref="ArgumentNullException"> <paramref name="text"/> is null. </exception> |
| 187 | /// <returns> A streaming collection of speech generation updates. </returns> |
| 188 | [Experimental("OPENAI001")] |
| 189 | public virtual AsyncCollectionResult<StreamingSpeechUpdate> GenerateSpeechStreamingAsync(string text, GeneratedSpeechVoice voice, SpeechGenerationOptions options = null, CancellationToken cancellationToken = default) |
| 190 | { |
| 191 | Argument.AssertNotNull(text, nameof(text)); |
| 192 | EnsureModelSupportsSpeechStreaming(); |
| 193 | |
| 194 | options ??= new(); |
| 195 | options.StreamFormat = InternalCreateSpeechRequestStreamFormat.Sse; |
| 196 | CreateSpeechGenerationOptions(text, voice, ref options); |
| 197 | |
| 198 | using BinaryContent content = options.ToBinaryContent(); |
| 199 | return new AsyncSseUpdateCollection<StreamingSpeechUpdate>( |
| 200 | async () => await GenerateSpeechAsync(content, cancellationToken.ToRequestOptions(streaming: true)).ConfigureAwait(false), |
| 201 | StreamingSpeechUpdate.DeserializeStreamingSpeechUpdate, |
| 202 | cancellationToken); |
| 203 | } |
| 204 | |
| 205 | /// <summary> Generates a life-like, spoken audio recording of the input text as a streaming SSE event collection. </summary> |
| 206 | /// <param name="text"> The text to generate audio for. </param> |
| 207 | /// <param name="voice"> The voice to use in the generated audio. </param> |
| 208 | /// <param name="options"> The options to configure the audio generation. </param> |
| 209 | /// <param name="cancellationToken"> A token that can be used to cancel this method call. </param> |
| 210 | /// <exception cref="ArgumentNullException"> <paramref name="text"/> is null. </exception> |
| 211 | /// <returns> A streaming collection of speech generation updates. </returns> |
| 212 | [Experimental("OPENAI001")] |
| 213 | public virtual CollectionResult<StreamingSpeechUpdate> GenerateSpeechStreaming(string text, GeneratedSpeechVoice voice, SpeechGenerationOptions options = null, CancellationToken cancellationToken = default) |
| 214 | { |
| 215 | Argument.AssertNotNull(text, nameof(text)); |
| 216 | EnsureModelSupportsSpeechStreaming(); |
| 217 | |
| 218 | options ??= new(); |
| 219 | options.StreamFormat = InternalCreateSpeechRequestStreamFormat.Sse; |
| 220 | CreateSpeechGenerationOptions(text, voice, ref options); |
| 221 | |
| 222 | using BinaryContent content = options.ToBinaryContent(); |
| 223 | return new SseUpdateCollection<StreamingSpeechUpdate>( |
| 224 | () => GenerateSpeech(content, cancellationToken.ToRequestOptions(streaming: true)), |
| 225 | StreamingSpeechUpdate.DeserializeStreamingSpeechUpdate, |
| 226 | cancellationToken); |
| 227 | } |
| 228 | |
| 229 | #endregion |
| 230 | |
| 231 | #region TranscribeAudio |
| 232 | |
| 233 | /// <summary> Transcribes the input audio. </summary> |
| 234 | /// <param name="audio"> The audio stream to transcribe. </param> |
| 235 | /// <param name="audioFilename"> |
| 236 | /// The filename associated with the audio stream. The filename's extension (for example: .mp3) will be used to |
| 237 | /// validate the format of the input audio. The request may fail if the filename's extension and the actual |
| 238 | /// format of the input audio do not match. |
| 239 | /// </param> |
| 240 | /// <param name="options"> The options to configure the audio transcription. </param> |
| 241 | /// <param name="cancellationToken"> A token that can be used to cancel this method call. </param> |
| 242 | /// <exception cref="ArgumentNullException"> <paramref name="audio"/> or <paramref name="audioFilename"/> is null. </exception> |
| 243 | /// <exception cref="ArgumentException"> <paramref name="audioFilename"/> is an empty string, and was expected to be non-empty. </exception> |
| 244 | public virtual async Task<ClientResult<AudioTranscription>> TranscribeAudioAsync(Stream audio, string audioFilename, AudioTranscriptionOptions options = null, CancellationToken cancellationToken = default) |
| 245 | { |
| 246 | Argument.AssertNotNull(audio, nameof(audio)); |
| 247 | Argument.AssertNotNullOrEmpty(audioFilename, nameof(audioFilename)); |
| 248 | |
| 249 | if (options?.ResponseFormat == AudioTranscriptionFormat.Diarized) |
| 250 | { |
| 251 | throw new InvalidOperationException( |
| 252 | $"{nameof(AudioTranscriptionOptions.ResponseFormat)} must not be set to {nameof(AudioTranscriptionFormat.Diarized)} when calling {nameof(TranscribeAudio)}. " |
| 253 | + $"For diarized transcription, call {nameof(TranscribeAudioDiarizedAsync)} instead."); |
| 254 | } |
| 255 | |
| 256 | using MultiPartFormDataBinaryContent content |
| 257 | = CreatePerCallTranscriptionOptions(options) |
| 258 | .ToMultipartContent(audio, audioFilename); |
| 259 | |
| 260 | ClientResult result = await TranscribeAudioAsync(content, content.ContentType, cancellationToken.ToRequestOptions()).ConfigureAwait(false); |
| 261 | return ClientResult.FromValue(AudioTranscription.FromResponse(result.GetRawResponse()), result.GetRawResponse()); |
| 262 | } |
| 263 | |
| 264 | /// <summary> Transcribes the input audio. </summary> |
| 265 | /// <param name="audio"> The audio stream to transcribe. </param> |
| 266 | /// <param name="audioFilename"> |
| 267 | /// The filename associated with the audio stream. The filename's extension (for example: .mp3) will be used to |
| 268 | /// validate the format of the input audio. The request may fail if the filename's extension and the actual |
| 269 | /// format of the input audio do not match. |
| 270 | /// </param> |
| 271 | /// <param name="options"> The options to configure the audio transcription. </param> |
| 272 | /// <param name="cancellationToken"> A token that can be used to cancel this method call. </param> |
| 273 | /// <exception cref="ArgumentNullException"> <paramref name="audio"/> or <paramref name="audioFilename"/> is null. </exception> |
| 274 | /// <exception cref="ArgumentException"> <paramref name="audioFilename"/> is an empty string, and was expected to be non-empty. </exception> |
| 275 | public virtual ClientResult<AudioTranscription> TranscribeAudio(Stream audio, string audioFilename, AudioTranscriptionOptions options = null, CancellationToken cancellationToken = default) |
| 276 | { |
| 277 | Argument.AssertNotNull(audio, nameof(audio)); |
| 278 | Argument.AssertNotNullOrEmpty(audioFilename, nameof(audioFilename)); |
| 279 | |
| 280 | if (options?.ResponseFormat == AudioTranscriptionFormat.Diarized) |
| 281 | { |
| 282 | throw new InvalidOperationException( |
| 283 | $"{nameof(AudioTranscriptionOptions.ResponseFormat)} must not be set to {nameof(AudioTranscriptionFormat.Diarized)} when calling {nameof(TranscribeAudio)}. " |
| 284 | + $"For diarized transcription, call {nameof(TranscribeAudioDiarized)} instead."); |
| 285 | } |
| 286 | |
| 287 | using MultiPartFormDataBinaryContent content |
| 288 | = CreatePerCallTranscriptionOptions(options) |
| 289 | .ToMultipartContent(audio, audioFilename); |
| 290 | |
| 291 | ClientResult result = TranscribeAudio(content, content.ContentType, cancellationToken.ToRequestOptions()); |
| 292 | return ClientResult.FromValue(AudioTranscription.FromResponse(result.GetRawResponse()), result.GetRawResponse()); |
| 293 | } |
| 294 | |
| 295 | /// <summary> Transcribes the input audio. </summary> |
| 296 | /// <param name="audioFilePath"> |
| 297 | /// The path of the audio file to transcribe. The provided file path's extension (for example: .mp3) will be |
| 298 | /// used to validate the format of the input audio. The request may fail if the file path's extension and the |
| 299 | /// actual format of the input audio do not match. |
| 300 | /// </param> |
| 301 | /// <param name="options"> The options to configure the audio transcription. </param> |
| 302 | /// <exception cref="ArgumentNullException"> <paramref name="audioFilePath"/> is null. </exception> |
| 303 | /// <exception cref="ArgumentException"> <paramref name="audioFilePath"/> is an empty string, and was expected to be non-empty. </exception> |
| 304 | public virtual async Task<ClientResult<AudioTranscription>> TranscribeAudioAsync(string audioFilePath, AudioTranscriptionOptions options = null) |
| 305 | { |
| 306 | Argument.AssertNotNullOrEmpty(audioFilePath, nameof(audioFilePath)); |
| 307 | |
| 308 | using FileStream audioStream = File.OpenRead(audioFilePath); |
| 309 | return await TranscribeAudioAsync(audioStream, audioFilePath, options).ConfigureAwait(false); |
| 310 | } |
| 311 | |
| 312 | /// <summary> Transcribes the input audio. </summary> |
| 313 | /// <param name="audioFilePath"> |
| 314 | /// The path of the audio file to transcribe. The provided file path's extension (for example: .mp3) will be |
| 315 | /// used to validate the format of the input audio. The request may fail if the file path's extension and the |
| 316 | /// actual format of the input audio do not match. |
| 317 | /// </param> |
| 318 | /// <param name="options"> The options to configure the audio transcription. </param> |
| 319 | /// <exception cref="ArgumentNullException"> <paramref name="audioFilePath"/> is null. </exception> |
| 320 | /// <exception cref="ArgumentException"> <paramref name="audioFilePath"/> is an empty string, and was expected to be non-empty. </exception> |
| 321 | public virtual ClientResult<AudioTranscription> TranscribeAudio(string audioFilePath, AudioTranscriptionOptions options = null) |
| 322 | { |
| 323 | Argument.AssertNotNullOrEmpty(audioFilePath, nameof(audioFilePath)); |
| 324 | |
| 325 | using FileStream audioStream = File.OpenRead(audioFilePath); |
| 326 | return TranscribeAudio(audioStream, audioFilePath, options); |
| 327 | } |
| 328 | |
| 329 | /// <summary> Transcribes the input audio with diarization. </summary> |
| 330 | /// <param name="audio"> The audio stream to transcribe. </param> |
| 331 | /// <param name="audioFilename"> |
| 332 | /// The filename associated with the audio stream. The filename's extension (for example: .mp3) will be used to |
| 333 | /// validate the format of the input audio. The request may fail if the filename's extension and the actual |
| 334 | /// format of the input audio do not match. |
| 335 | /// </param> |
| 336 | /// <param name="options"> The options to configure the audio transcription. </param> |
| 337 | /// <param name="cancellationToken"> A token that can be used to cancel this method call. </param> |
| 338 | /// <exception cref="ArgumentNullException"> <paramref name="audio"/> or <paramref name="audioFilename"/> is null. </exception> |
| 339 | /// <exception cref="ArgumentException"> <paramref name="audioFilename"/> is an empty string, and was expected to be non-empty. </exception> |
| 340 | [Experimental("OPENAI001")] |
| 341 | public virtual async Task<ClientResult<DiarizedAudioTranscription>> TranscribeAudioDiarizedAsync(Stream audio, string audioFilename, AudioTranscriptionOptions options = null, CancellationToken cancellationToken = default) |
| 342 | { |
| 343 | Argument.AssertNotNull(audio, nameof(audio)); |
| 344 | Argument.AssertNotNullOrEmpty(audioFilename, nameof(audioFilename)); |
| 345 | |
| 346 | if (options?.ResponseFormat is not null && options.ResponseFormat != AudioTranscriptionFormat.Diarized) |
| 347 | { |
| 348 | throw new InvalidOperationException( |
| 349 | $"{nameof(AudioTranscriptionOptions.ResponseFormat)} must be {nameof(AudioTranscriptionFormat.Diarized)} when calling {nameof(TranscribeAudioDiarized)}. " |
| 350 | + $"For non-diarized transcription, call {nameof(TranscribeAudioAsync)} instead."); |
| 351 | } |
| 352 | |
| 353 | using MultiPartFormDataBinaryContent content |
| 354 | = CreatePerCallTranscriptionOptions(options) |
| 355 | .ToMultipartContent(audio, audioFilename); |
| 356 | |
| 357 | ClientResult result = await TranscribeAudioAsync(content, content.ContentType, cancellationToken.ToRequestOptions()).ConfigureAwait(false); |
| 358 | using var document = JsonDocument.Parse(result.GetRawResponse().Content); |
| 359 | return ClientResult.FromValue(DiarizedAudioTranscription.DeserializeDiarizedAudioTranscription(document.RootElement, null), result.GetRawResponse()); |
| 360 | } |
| 361 | |
| 362 | /// <summary> Transcribes the input audio with diarization. </summary> |
| 363 | /// <param name="audio"> The audio stream to transcribe. </param> |
| 364 | /// <param name="audioFilename"> |
| 365 | /// The filename associated with the audio stream. The filename's extension (for example: .mp3) will be used to |
| 366 | /// validate the format of the input audio. The request may fail if the filename's extension and the actual |
| 367 | /// format of the input audio do not match. |
| 368 | /// </param> |
| 369 | /// <param name="options"> The options to configure the audio transcription. </param> |
| 370 | /// <param name="cancellationToken"> A token that can be used to cancel this method call. </param> |
| 371 | /// <exception cref="ArgumentNullException"> <paramref name="audio"/> or <paramref name="audioFilename"/> is null. </exception> |
| 372 | /// <exception cref="ArgumentException"> <paramref name="audioFilename"/> is an empty string, and was expected to be non-empty. </exception> |
| 373 | [Experimental("OPENAI001")] |
| 374 | public virtual ClientResult<DiarizedAudioTranscription> TranscribeAudioDiarized(Stream audio, string audioFilename, AudioTranscriptionOptions options = null, CancellationToken cancellationToken = default) |
| 375 | { |
| 376 | Argument.AssertNotNull(audio, nameof(audio)); |
| 377 | Argument.AssertNotNullOrEmpty(audioFilename, nameof(audioFilename)); |
| 378 | |
| 379 | if (options?.ResponseFormat is not null && options.ResponseFormat != AudioTranscriptionFormat.Diarized) |
| 380 | { |
| 381 | throw new InvalidOperationException( |
| 382 | $"{nameof(AudioTranscriptionOptions.ResponseFormat)} must be {nameof(AudioTranscriptionFormat.Diarized)} when calling {nameof(TranscribeAudioDiarized)}. " |
| 383 | + $"For non-diarized transcription, call {nameof(TranscribeAudio)} instead."); |
| 384 | } |
| 385 | |
| 386 | using MultiPartFormDataBinaryContent content |
| 387 | = CreatePerCallTranscriptionOptions(options) |
| 388 | .ToMultipartContent(audio, audioFilename); |
| 389 | |
| 390 | ClientResult result = TranscribeAudio(content, content.ContentType, cancellationToken.ToRequestOptions()); |
| 391 | using var document = JsonDocument.Parse(result.GetRawResponse().Content); |
| 392 | return ClientResult.FromValue(DiarizedAudioTranscription.DeserializeDiarizedAudioTranscription(document.RootElement, null), result.GetRawResponse()); |
| 393 | } |
| 394 | |
| 395 | /// <summary> Transcribes the input audio with diarization. </summary> |
| 396 | /// <param name="audioFilePath"> |
| 397 | /// The path of the audio file to transcribe. The provided file path's extension (for example: .mp3) will be |
| 398 | /// used to validate the format of the input audio. The request may fail if the file path's extension and the |
| 399 | /// actual format of the input audio do not match. |
| 400 | /// </param> |
| 401 | /// <param name="options"> The options to configure the audio transcription. </param> |
| 402 | /// <exception cref="ArgumentNullException"> <paramref name="audioFilePath"/> is null. </exception> |
| 403 | /// <exception cref="ArgumentException"> <paramref name="audioFilePath"/> is an empty string, and was expected to be non-empty. </exception> |
| 404 | [Experimental("OPENAI001")] |
| 405 | public virtual async Task<ClientResult<DiarizedAudioTranscription>> TranscribeAudioDiarizedAsync(string audioFilePath, AudioTranscriptionOptions options = null) |
| 406 | { |
| 407 | Argument.AssertNotNullOrEmpty(audioFilePath, nameof(audioFilePath)); |
| 408 | |
| 409 | using FileStream audioStream = File.OpenRead(audioFilePath); |
| 410 | return await TranscribeAudioDiarizedAsync(audioStream, audioFilePath, options).ConfigureAwait(false); |
| 411 | } |
| 412 | |
| 413 | /// <summary> Transcribes the input audio with diarization. </summary> |
| 414 | /// <param name="audioFilePath"> |
| 415 | /// The path of the audio file to transcribe. The provided file path's extension (for example: .mp3) will be |
| 416 | /// used to validate the format of the input audio. The request may fail if the file path's extension and the |
| 417 | /// actual format of the input audio do not match. |
| 418 | /// </param> |
| 419 | /// <param name="options"> The options to configure the audio transcription. </param> |
| 420 | /// <exception cref="ArgumentNullException"> <paramref name="audioFilePath"/> is null. </exception> |
| 421 | /// <exception cref="ArgumentException"> <paramref name="audioFilePath"/> is an empty string, and was expected to be non-empty. </exception> |
| 422 | [Experimental("OPENAI001")] |
| 423 | public virtual ClientResult<DiarizedAudioTranscription> TranscribeAudioDiarized(string audioFilePath, AudioTranscriptionOptions options = null) |
| 424 | { |
| 425 | Argument.AssertNotNullOrEmpty(audioFilePath, nameof(audioFilePath)); |
| 426 | |
| 427 | using FileStream audioStream = File.OpenRead(audioFilePath); |
| 428 | return TranscribeAudioDiarized(audioStream, audioFilePath, options); |
| 429 | } |
| 430 | |
| 431 | // CUSTOM: Added Experimental attribute. |
| 432 | [Experimental("OPENAI001")] |
| 433 | public virtual AsyncCollectionResult<StreamingAudioTranscriptionUpdate> TranscribeAudioStreamingAsync(Stream audio, string audioFilename, AudioTranscriptionOptions options = null, CancellationToken cancellationToken = default) |
| 434 | { |
| 435 | Argument.AssertNotNull(audio, nameof(audio)); |
| 436 | Argument.AssertNotNullOrEmpty(audioFilename, nameof(audioFilename)); |
| 437 | |
| 438 | EnsureModelSupportsStreaming(); |
| 439 | |
| 440 | MultiPartFormDataBinaryContent content |
| 441 | = CreatePerCallTranscriptionOptions(options, stream: true) |
| 442 | .ToMultipartContent(audio, audioFilename); |
| 443 | |
| 444 | return new AsyncSseUpdateCollection<StreamingAudioTranscriptionUpdate>( |
| 445 | async () => await TranscribeAudioAsync(content, content.ContentType, cancellationToken.ToRequestOptions(streaming: true)).ConfigureAwait(false), |
| 446 | StreamingAudioTranscriptionUpdate.DeserializeStreamingAudioTranscriptionUpdate, |
| 447 | cancellationToken); |
| 448 | } |
| 449 | |
| 450 | // CUSTOM: Added Experimental attribute. |
| 451 | [Experimental("OPENAI001")] |
| 452 | public virtual AsyncCollectionResult<StreamingAudioTranscriptionUpdate> TranscribeAudioStreamingAsync(string audioFilePath, AudioTranscriptionOptions options = null, CancellationToken cancellationToken = default) |
| 453 | { |
| 454 | Argument.AssertNotNullOrEmpty(audioFilePath, nameof(audioFilePath)); |
| 455 | |
| 456 | EnsureModelSupportsStreaming(); |
| 457 | |
| 458 | FileStream inputStream = File.OpenRead(audioFilePath); |
| 459 | |
| 460 | MultiPartFormDataBinaryContent content |
| 461 | = CreatePerCallTranscriptionOptions(options, stream: true) |
| 462 | .ToMultipartContent(inputStream, audioFilePath); |
| 463 | |
| 464 | AsyncSseUpdateCollection<StreamingAudioTranscriptionUpdate> result = new( |
| 465 | async () => await TranscribeAudioAsync(content, content.ContentType, cancellationToken.ToRequestOptions(streaming: true)).ConfigureAwait(false), |
| 466 | StreamingAudioTranscriptionUpdate.DeserializeStreamingAudioTranscriptionUpdate, |
| 467 | cancellationToken); |
| 468 | result.AdditionalDisposalActions.Add(() => inputStream?.Dispose()); |
| 469 | return result; |
| 470 | } |
| 471 | |
| 472 | // CUSTOM: Added Experimental attribute. |
| 473 | [Experimental("OPENAI001")] |
| 474 | public virtual CollectionResult<StreamingAudioTranscriptionUpdate> TranscribeAudioStreaming(Stream audio, string audioFilename, AudioTranscriptionOptions options = null, CancellationToken cancellationToken = default) |
| 475 | { |
| 476 | Argument.AssertNotNull(audio, nameof(audio)); |
| 477 | Argument.AssertNotNullOrEmpty(audioFilename, nameof(audioFilename)); |
| 478 | |
| 479 | EnsureModelSupportsStreaming(); |
| 480 | |
| 481 | MultiPartFormDataBinaryContent content |
| 482 | = CreatePerCallTranscriptionOptions(options, stream: true) |
| 483 | .ToMultipartContent(audio, audioFilename); |
| 484 | |
| 485 | return new SseUpdateCollection<StreamingAudioTranscriptionUpdate>( |
| 486 | () => TranscribeAudio(content, content.ContentType, cancellationToken.ToRequestOptions(streaming: true)), |
| 487 | StreamingAudioTranscriptionUpdate.DeserializeStreamingAudioTranscriptionUpdate, |
| 488 | cancellationToken); |
| 489 | } |
| 490 | |
| 491 | // CUSTOM: Added Experimental attribute. |
| 492 | [Experimental("OPENAI001")] |
| 493 | public virtual CollectionResult<StreamingAudioTranscriptionUpdate> TranscribeAudioStreaming(string audioFilePath, AudioTranscriptionOptions options = null, CancellationToken cancellationToken = default) |
| 494 | { |
| 495 | Argument.AssertNotNullOrEmpty(audioFilePath, nameof(audioFilePath)); |
| 496 | |
| 497 | EnsureModelSupportsStreaming(); |
| 498 | |
| 499 | FileStream inputStream = File.OpenRead(audioFilePath); |
| 500 | |
| 501 | MultiPartFormDataBinaryContent content |
| 502 | = CreatePerCallTranscriptionOptions(options, stream: true) |
| 503 | .ToMultipartContent(inputStream, audioFilePath); |
| 504 | |
| 505 | SseUpdateCollection<StreamingAudioTranscriptionUpdate> result = new( |
| 506 | () => TranscribeAudio(content, content.ContentType, cancellationToken.ToRequestOptions(streaming: true)), |
| 507 | StreamingAudioTranscriptionUpdate.DeserializeStreamingAudioTranscriptionUpdate, |
| 508 | cancellationToken); |
| 509 | result.AdditionalDisposalActions.Add(() => inputStream?.Dispose()); |
| 510 | return result; |
| 511 | } |
| 512 | |
| 513 | private void EnsureModelSupportsStreaming() |
| 514 | { |
| 515 | if (string.Equals(_model, "whisper-1", StringComparison.OrdinalIgnoreCase)) |
| 516 | { |
| 517 | string isEnabled = Environment.GetEnvironmentVariable("OPENAI_ENABLE_TRANSCRIPTION_SSE_STREAMING"); |
| 518 | if (!string.Equals(isEnabled, "true", StringComparison.OrdinalIgnoreCase)) |
| 519 | { |
| 520 | throw new NotSupportedException( |
| 521 | "The selected model 'whisper-1' does not support SSE streaming transcription. " + |
| 522 | "Please use a compatible model or set the environment variable 'OPENAI_ENABLE_TRANSCRIPTION_SSE_STREAMING=true' to bypass this check."); |
| 523 | } |
| 524 | } |
| 525 | } |
| 526 | |
| 527 | private void EnsureModelSupportsSpeechStreaming() |
| 528 | { |
| 529 | if (string.Equals(_model, "tts-1", StringComparison.OrdinalIgnoreCase) |
| 530 | || string.Equals(_model, "tts-1-hd", StringComparison.OrdinalIgnoreCase)) |
| 531 | { |
| 532 | string isEnabled = Environment.GetEnvironmentVariable("OPENAI_ENABLE_TTS_SSE_STREAMING"); |
| 533 | if (!string.Equals(isEnabled, "true", StringComparison.OrdinalIgnoreCase)) |
| 534 | { |
| 535 | throw new NotSupportedException( |
| 536 | $"The selected model '{_model}' does not support SSE streaming for speech generation. " |
| 537 | + "Please use a compatible model or set the environment variable 'OPENAI_ENABLE_TTS_SSE_STREAMING=true' to bypass this check."); |
| 538 | } |
| 539 | } |
| 540 | } |
| 541 | |
| 542 | #endregion |
| 543 | |
| 544 | #region TranslateAudio |
| 545 | |
| 546 | /// <summary> Translates the input audio into English. </summary> |
| 547 | /// <param name="audio"> The audio stream to translate. </param> |
| 548 | /// <param name="audioFilename"> |
| 549 | /// The filename associated with the audio stream. The filename's extension (for example: .mp3) will be used to |
| 550 | /// validate the format of the input audio. The request may fail if the filename's extension and the actual |
| 551 | /// format of the input audio do not match. |
| 552 | /// </param> |
| 553 | /// <param name="options"> The options to configure the audio translation. </param> |
| 554 | /// <param name="cancellationToken"> A token that can be used to cancel this method call. </param> |
| 555 | /// <exception cref="ArgumentNullException"> <paramref name="audio"/> or <paramref name="audioFilename"/> is null. </exception> |
| 556 | /// <exception cref="ArgumentException"> <paramref name="audioFilename"/> is an empty string, and was expected to be non-empty. </exception> |
| 557 | public virtual async Task<ClientResult<AudioTranslation>> TranslateAudioAsync(Stream audio, string audioFilename, AudioTranslationOptions options = null, CancellationToken cancellationToken = default) |
| 558 | { |
| 559 | Argument.AssertNotNull(audio, nameof(audio)); |
| 560 | Argument.AssertNotNullOrEmpty(audioFilename, nameof(audioFilename)); |
| 561 | |
| 562 | options ??= new(); |
| 563 | CreateAudioTranslationOptions(audio, audioFilename, ref options); |
| 564 | |
| 565 | using MultiPartFormDataBinaryContent content = options.ToMultipartContent(audio, audioFilename); |
| 566 | ClientResult result = await TranslateAudioAsync(content, content.ContentType, cancellationToken.ToRequestOptions()).ConfigureAwait(false); |
| 567 | return ClientResult.FromValue(AudioTranslation.FromResponse(result.GetRawResponse()), result.GetRawResponse()); |
| 568 | } |
| 569 | |
| 570 | /// <summary> Translates the input audio into English. </summary> |
| 571 | /// <param name="audio"> The audio stream to translate. </param> |
| 572 | /// <param name="audioFilename"> |
| 573 | /// The filename associated with the audio stream. The filename's extension (for example: .mp3) will be used to |
| 574 | /// validate the format of the input audio. The request may fail if the filename's extension and the actual |
| 575 | /// format of the input audio do not match. |
| 576 | /// </param> |
| 577 | /// <param name="options"> The options to configure the audio translation. </param> |
| 578 | /// <param name="cancellationToken"> A token that can be used to cancel this method call. </param> |
| 579 | /// <exception cref="ArgumentNullException"> <paramref name="audio"/> or <paramref name="audioFilename"/> is null. </exception> |
| 580 | /// <exception cref="ArgumentException"> <paramref name="audioFilename"/> is an empty string, and was expected to be non-empty. </exception> |
| 581 | public virtual ClientResult<AudioTranslation> TranslateAudio(Stream audio, string audioFilename, AudioTranslationOptions options = null, CancellationToken cancellationToken = default) |
| 582 | { |
| 583 | Argument.AssertNotNull(audio, nameof(audio)); |
| 584 | Argument.AssertNotNullOrEmpty(audioFilename, nameof(audioFilename)); |
| 585 | |
| 586 | options ??= new(); |
| 587 | CreateAudioTranslationOptions(audio, audioFilename, ref options); |
| 588 | |
| 589 | using MultiPartFormDataBinaryContent content = options.ToMultipartContent(audio, audioFilename); |
| 590 | ClientResult result = TranslateAudio(content, content.ContentType, cancellationToken.ToRequestOptions()); |
| 591 | return ClientResult.FromValue(AudioTranslation.FromResponse(result.GetRawResponse()), result.GetRawResponse()); |
| 592 | } |
| 593 | |
| 594 | /// <summary> Translates the input audio into English. </summary> |
| 595 | /// <param name="audioFilePath"> |
| 596 | /// The path of the audio file to translate. The provided file path's extension (for example: .mp3) will be |
| 597 | /// used to validate the format of the input audio. The request may fail if the file path's extension and the |
| 598 | /// actual format of the input audio do not match. |
| 599 | /// </param> |
| 600 | /// <param name="options"> The options to configure the audio translation. </param> |
| 601 | /// <exception cref="ArgumentNullException"> <paramref name="audioFilePath"/> was null. </exception> |
| 602 | /// <exception cref="ArgumentException"> <paramref name="audioFilePath"/> is an empty string, and was expected to be non-empty. </exception> |
| 603 | public virtual ClientResult<AudioTranslation> TranslateAudio(string audioFilePath, AudioTranslationOptions options = null) |
| 604 | { |
| 605 | Argument.AssertNotNullOrEmpty(audioFilePath, nameof(audioFilePath)); |
| 606 | |
| 607 | using FileStream audioStream = File.OpenRead(audioFilePath); |
| 608 | return TranslateAudio(audioStream, audioFilePath, options); |
| 609 | } |
| 610 | |
| 611 | /// <summary> Translates the input audio into English. </summary> |
| 612 | /// <param name="audioFilePath"> |
| 613 | /// The path of the audio file to translate. The provided file path's extension (for example: .mp3) will be |
| 614 | /// used to validate the format of the input audio. The request may fail if the file path's extension and the |
| 615 | /// actual format of the input audio do not match. |
| 616 | /// </param> |
| 617 | /// <param name="options"> The options to configure the audio translation. </param> |
| 618 | /// <exception cref="ArgumentNullException"> <paramref name="audioFilePath"/> was null. </exception> |
| 619 | /// <exception cref="ArgumentException"> <paramref name="audioFilePath"/> is an empty string, and was expected to be non-empty. </exception> |
| 620 | public virtual async Task<ClientResult<AudioTranslation>> TranslateAudioAsync(string audioFilePath, AudioTranslationOptions options = null) |
| 621 | { |
| 622 | Argument.AssertNotNull(audioFilePath, nameof(audioFilePath)); |
| 623 | |
| 624 | using FileStream audioStream = File.OpenRead(audioFilePath); |
| 625 | return await TranslateAudioAsync(audioStream, audioFilePath, options); |
| 626 | } |
| 627 | |
| 628 | #endregion |
| 629 | |
| 630 | private void CreateSpeechGenerationOptions(string text, GeneratedSpeechVoice voice, ref SpeechGenerationOptions options) |
| 631 | { |
| 632 | options.Input = text; |
| 633 | options.Voice = voice; |
| 634 | options.Model = _model; |
| 635 | } |
| 636 | |
| 637 | internal virtual AudioTranscriptionOptions CreatePerCallTranscriptionOptions(AudioTranscriptionOptions userOptions, bool stream = false) |
| 638 | { |
| 639 | AudioTranscriptionOptions copiedOptions = userOptions is null ? new() : userOptions.GetClone(); |
| 640 | |
| 641 | copiedOptions.Model = _model; |
| 642 | |
| 643 | if (stream) |
| 644 | { |
| 645 | copiedOptions.Stream = true; |
| 646 | } |
| 647 | |
| 648 | return copiedOptions; |
| 649 | } |
| 650 | |
| 651 | private void CreateAudioTranslationOptions(Stream audio, string audioFilename, ref AudioTranslationOptions options) |
| 652 | { |
| 653 | options.Model = _model; |
| 654 | } |
| 655 | } |
| 656 | |