Skip to content

Commit 05cd843

Browse files
authored
Merge pull request #454 from Freeesia/feature/fix_correct_ex
GoogleAIで例外が発生したときにエラーメッセージが分かりにくい問題修正
2 parents b970da4 + 764c72e commit 05cd843

3 files changed

Lines changed: 62 additions & 64 deletions

File tree

Plugins/WindowTranslator.Plugin.GoogleAIPlugin/OcrCorrectFilterBase.cs

Lines changed: 37 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ protected OcrCorrectFilterBase(IOptionsSnapshot<LanguageOptions> langOptions, IO
5151
new(){ Category = HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT, Threshold =HarmBlockThreshold.BLOCK_NONE},
5252
],
5353
systemInstruction: GetSystem(langOptions.Value, options));
54-
Task.Run(Correct, this.cts.Token);
54+
Task.Run(LoopCorrect, this.cts.Token);
5555
}
5656

5757
protected abstract string GetSystem(LanguageOptions languageOptions, GoogleAIOptions googleAIOptions);
@@ -98,7 +98,7 @@ public async IAsyncEnumerable<TextRect> ExecutePreTranslate(IAsyncEnumerable<Tex
9898
// WaitCorrectが有効な場合:補正処理を完了してから結果を返す
9999
if (this.waitCorrect)
100100
{
101-
await CorrectCore(queueData, this.cts.Token).ConfigureAwait(false);
101+
await Correct(queueData, this.cts.Token).ConfigureAwait(false);
102102
// 補正後のテキストをキャッシュから返す
103103
foreach (var text in targets)
104104
{
@@ -118,40 +118,45 @@ public async IAsyncEnumerable<TextRect> ExecutePreTranslate(IAsyncEnumerable<Tex
118118

119119
protected abstract ValueTask<IReadOnlyList<T>> GetQueueData(IEnumerable<TextRect> targets, FilterContext context);
120120

121-
private async Task Correct()
121+
private async Task LoopCorrect()
122122
{
123123
await foreach (var texts in this.queue.Reader.ReadAllAsync(this.cts.Token))
124124
{
125-
while (true)
125+
await Correct(texts, this.cts.Token).ConfigureAwait(false);
126+
}
127+
}
128+
129+
private async Task Correct(IReadOnlyList<T> texts, CancellationToken token)
130+
{
131+
while (true)
132+
{
133+
try
126134
{
127-
try
128-
{
129-
await CorrectCore(texts, this.cts.Token).ConfigureAwait(false);
130-
break;
131-
}
132-
catch (ApiException e) when (e.ErrorCode == 400)
133-
{
134-
throw new ApiException(e.ErrorCode, "GeminiのAPIキーが無効です。設定ダイアログからGoogleAIオプションを設定してください", e.ErrorStatus);
135-
}
136-
// サービスが一時的に過負荷になっているか、ダウンしている可能性があります。
137-
catch (ApiException e) when (e.ErrorCode == 503)
138-
{
139-
this.Logger.LogWarning("Geminiのサービスが一時的に過負荷になっているか、ダウンしている可能性があります。500ミリ秒待機して再試行します。");
140-
await Task.Delay(500).ConfigureAwait(false);
141-
continue;
142-
}
143-
// レート制限を超えました。
144-
catch (ApiException e) when (e.ErrorCode == 429)
145-
{
146-
this.Logger.LogWarning("Geminiのレート制限を超えました。10秒待機して再試行します。");
147-
await Task.Delay(10000).ConfigureAwait(false);
148-
continue;
149-
}
150-
// Jsonエラーということは指定した以外のレスポンスが返ってきたのでもう一度
151-
catch (JsonException)
152-
{
153-
continue;
154-
}
135+
await CorrectCore(texts, token).ConfigureAwait(false);
136+
break;
137+
}
138+
catch (ApiException e) when (e.ErrorCode == 400)
139+
{
140+
throw new ApiException(e.ErrorCode, "GeminiのAPIキーが無効です。設定ダイアログからGoogleAIオプションを設定してください", e.ErrorStatus);
141+
}
142+
// サービスが一時的に過負荷になっているか、ダウンしている可能性があります。
143+
catch (ApiException e) when (e.ErrorCode == 503)
144+
{
145+
this.Logger.LogWarning("Geminiのサービスが一時的に過負荷になっているか、ダウンしている可能性があります。500ミリ秒待機して再試行します。");
146+
await Task.Delay(500, token).ConfigureAwait(false);
147+
continue;
148+
}
149+
// レート制限を超えました。
150+
catch (ApiException e) when (e.ErrorCode == 429)
151+
{
152+
this.Logger.LogWarning("Geminiのレート制限を超えました。10秒待機して再試行します。");
153+
await Task.Delay(10000, token).ConfigureAwait(false);
154+
continue;
155+
}
156+
// Jsonエラーということは指定した以外のレスポンスが返ってきたのでもう一度
157+
catch (JsonException)
158+
{
159+
continue;
155160
}
156161
}
157162
}

Plugins/WindowTranslator.Plugin.GoogleAIPlugin/OcrCorrectFromImageFilter.cs

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -82,20 +82,20 @@ private record RecognizedText(int ImageIndex, string OcrText);
8282
protected override async Task CorrectCore(IReadOnlyList<TextTarget> texts, CancellationToken cancellationToken)
8383
{
8484
var sw = Stopwatch.StartNew();
85-
await Parallel.ForEachAsync(texts.Chunk(4), cancellationToken, async (chunk, ct) =>
85+
try
8686
{
87-
var req = new GenerateContentRequest();
88-
var original = chunk.Select(t => t.Original).ToArray();
89-
var json = JsonSerializer.Serialize(original, DefaultSerializerOptions.GenerateObjectJsonOptions);
90-
req.AddText(json);
91-
foreach (var (text, base64) in chunk)
92-
{
93-
this.Cache.TryAdd(text, null);
94-
req.AddInlineData(base64, "image/jpeg");
95-
}
96-
RecognizedText[] corrected;
97-
try
87+
await Parallel.ForEachAsync(texts.Chunk(4), cancellationToken, async (chunk, ct) =>
9888
{
89+
var req = new GenerateContentRequest();
90+
var original = chunk.Select(t => t.Original).ToArray();
91+
var json = JsonSerializer.Serialize(original, DefaultSerializerOptions.GenerateObjectJsonOptions);
92+
req.AddText(json);
93+
foreach (var (text, base64) in chunk)
94+
{
95+
this.Cache.TryAdd(text, null);
96+
req.AddInlineData(base64, "image/jpeg");
97+
}
98+
RecognizedText[] corrected;
9999
corrected = await this.Client.GenerateObjectAsync<RecognizedText[]>(req, cancellationToken)
100100
.ConfigureAwait(false) ?? [];
101101
cancellationToken.ThrowIfCancellationRequested();
@@ -104,13 +104,13 @@ await Parallel.ForEachAsync(texts.Chunk(4), cancellationToken, async (chunk, ct)
104104
{
105105
this.Cache[original[i]] = corrected[i].OcrText;
106106
}
107-
}
108-
catch (Exception e)
109-
{
110-
this.Logger.LogError(e, $"Failed to correct");
111-
}
112-
}).ConfigureAwait(false);
113-
this.Logger.LogDebug($"Correct: {sw.Elapsed}");
107+
}).ConfigureAwait(false);
108+
this.Logger.LogDebug($"Correct: {sw.Elapsed}");
109+
}
110+
catch (AggregateException ae) when (ae.InnerExceptions is [var inner, ..])
111+
{
112+
throw inner;
113+
}
114114
}
115115

116116
protected override void Dropped(IReadOnlyList<TextTarget> texts)

Plugins/WindowTranslator.Plugin.GoogleAIPlugin/OcrCorrectFromTextFilter.cs

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -46,20 +46,13 @@ protected override async Task CorrectCore(IReadOnlyList<string> texts, Cancellat
4646
{
4747
this.Cache.TryAdd(text, null);
4848
}
49-
try
49+
var json = JsonSerializer.Serialize(texts, DefaultSerializerOptions.GenerateObjectJsonOptions);
50+
var corrected = await this.Client.GenerateObjectAsync<string[]>(json, cancellationToken)
51+
.ConfigureAwait(false) ?? [];
52+
cancellationToken.ThrowIfCancellationRequested();
53+
for (var i = 0; i < texts.Count; i++)
5054
{
51-
var json = JsonSerializer.Serialize(texts, DefaultSerializerOptions.GenerateObjectJsonOptions);
52-
var corrected = await this.Client.GenerateObjectAsync<string[]>(json, cancellationToken)
53-
.ConfigureAwait(false) ?? [];
54-
cancellationToken.ThrowIfCancellationRequested();
55-
for (var i = 0; i < texts.Count; i++)
56-
{
57-
this.Cache[texts[i]] = corrected[i];
58-
}
59-
}
60-
catch (Exception e)
61-
{
62-
this.Logger.LogError(e, $"Failed to correct `{texts}`");
55+
this.Cache[texts[i]] = corrected[i];
6356
}
6457
}
6558

0 commit comments

Comments
 (0)