feat: complete translation language controls and styling

This commit is contained in:
2026-10-17 23:49:36 +02:00
parent 038a5b78a0
commit 11e604e79e
9 changed files with 310 additions and 75 deletions
+14 -8
View File
@@ -1,21 +1,27 @@
import Foundation
public enum MyMemoryAPI {
public static func translate(_ text: String) async throws -> String {
try await translate(text) { try await URLSession.shared.data(for: $0) }
public static func translate(
_ text: String, sourceLanguage: String = "en", targetLanguage: String = "ja"
) async throws -> String {
try await translate(text, sourceLanguage: sourceLanguage, targetLanguage: targetLanguage) {
try await URLSession.shared.data(for: $0)
}
}
static func translate(
_ text: String, load: @Sendable (URLRequest) async throws -> (Data, URLResponse)
_ text: String, sourceLanguage: String = "en", targetLanguage: String = "ja",
load: @Sendable (URLRequest) async throws -> (Data, URLResponse)
) async throws -> String {
guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw Failure(message: "Enter English text to translate.")
throw Failure(message: "Enter text to translate.")
}
guard text.utf8.count <= 500 else {
throw Failure(message: "MyMemory allows at most 500 UTF-8 bytes per translation. Shorten the text or choose OpenAI.")
}
var url = URLComponents(string: "https://api.mymemory.translated.net/get")!
url.queryItems = [URLQueryItem(name: "q", value: text), URLQueryItem(name: "langpair", value: "en|ja")]
url.queryItems = [URLQueryItem(name: "q", value: text),
URLQueryItem(name: "langpair", value: "\(sourceLanguage)|\(targetLanguage)")]
let request = URLRequest(url: url.url!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 30)
let (data, response) = try await load(request)
try Task.checkCancellation()
@@ -33,10 +39,10 @@ public enum MyMemoryAPI {
!translation.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
return translation
}
// The service can rank an empty memory first; only use another exact en→ja match.
// The service can rank an empty memory first; only use another exact match for the requested pair.
if let match = result.matches?.first(where: {
$0.segment == text && $0.source.split(separator: "-").first == "en"
&& $0.target.split(separator: "-").first == "ja"
$0.segment == text && $0.source.split(separator: "-").first == Substring(sourceLanguage)
&& $0.target.split(separator: "-").first == Substring(targetLanguage)
&& !$0.translation.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}) {
return match.translation