-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTranslationSample.cs
More file actions
94 lines (83 loc) · 3.29 KB
/
Copy pathTranslationSample.cs
File metadata and controls
94 lines (83 loc) · 3.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#nullable enable
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using Assets.Mochineko.WhisperAPI;
using Cysharp.Threading.Tasks;
using Mochineko.Relent.Resilience;
using Mochineko.Relent.UncertainResult;
using Unity.Logging;
using UnityEngine;
namespace Mochineko.WhisperAPI.Samples
{
/// <summary>
/// A sample component to translate speech into English text by Whisper transcription API on Unity.
/// </summary>
public sealed class TranslationSample : MonoBehaviour
{
private static readonly HttpClient httpClient = new();
/// <summary>
/// File path of speech audio.
/// </summary>
[SerializeField] private string filePath = string.Empty;
private readonly IPolicy<string> policy = PolicyFactory.Build();
private readonly TranslationRequestParameters requestParameters = new(
string.Empty,
Model.Whisper1);
[ContextMenu(nameof(Translate))]
public void Translate()
{
TranslateAsync(this.GetCancellationTokenOnDestroy())
.Forget();
}
private async UniTask TranslateAsync(CancellationToken cancellationToken)
{
var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");
if (string.IsNullOrEmpty(apiKey)) throw new NullReferenceException(nameof(apiKey));
var absoluteFilePath = Path.Combine(
Application.dataPath,
"..",
filePath);
requestParameters.File = filePath;
Log.Debug("[WhisperAPI.Samples] Begin to translate.");
// Translate speech into English text by Whisper transcription API.
var result = await policy
.ExecuteAsync(async innerCancellationToken
=> await TranslationAPI
.TranslateFileAsync(
apiKey,
httpClient,
absoluteFilePath,
requestParameters,
innerCancellationToken,
true),
cancellationToken);
switch (result)
{
// Success
case IUncertainSuccessResult<string> success:
{
// Default text response format is JSON.
var text = TranslationResponseBody.FromJson(success.Result)?.Text;
Log.Debug("[WhisperAPI.Samples] Succeeded to translate into: {0}.", text);
break;
}
// Retryable failure
case IUncertainRetryableResult<string> retryable:
{
Log.Error("[WhisperAPI.Samples] Retryable failed to translate because -> {0}.", retryable.Message);
break;
}
// Failure
case IUncertainFailureResult<string> failure:
{
Log.Error("[WhisperAPI.Samples] Failed to translate because -> {0}.", failure.Message);
break;
}
default:
throw new UncertainResultPatternMatchException(nameof(result));
}
}
}
}