fix: use exact MyMemory matches when top translation is blank

This commit is contained in:
Valdemar Lorenzen
2026-10-15 10:52:17 +02:00
parent d0a66c29a8
commit c31424b217
3 changed files with 55 additions and 4 deletions
+21 -4
View File
@@ -26,18 +26,35 @@ public enum MyMemoryAPI {
guard result.quotaFinished != true, result.responseStatus != 429 else {
throw Failure(message: "MyMemory's anonymous daily quota is exhausted. Try later or choose OpenAI.")
}
guard result.responseStatus == 200,
let translation = result.responseData?.translatedText,
!translation.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
guard result.responseStatus == 200 else {
throw Failure(message: "MyMemory returned no successful translation. Try again later or choose OpenAI.")
}
return translation
if let translation = result.responseData?.translatedText,
!translation.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
return translation
}
// The service can rank an empty memory first; only use another exact en→ja match.
if let match = result.matches?.first(where: {
$0.segment == text && $0.source.split(separator: "-").first == "en"
&& $0.target.split(separator: "-").first == "ja"
&& !$0.translation.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}) {
return match.translation
}
throw Failure(message: "MyMemory returned no successful translation. Try again later or choose OpenAI.")
}
private struct Response: Decodable {
let responseStatus: Int
let quotaFinished: Bool?
let responseData: Translation?
let matches: [Match]?
struct Match: Decodable {
let segment: String
let translation: String
let source: String
let target: String
}
struct Translation: Decodable { let translatedText: String? }
}
private struct Failure: LocalizedError {