forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTranslate.swift
More file actions
34 lines (29 loc) · 973 Bytes
/
Translate.swift
File metadata and controls
34 lines (29 loc) · 973 Bytes
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
import Foundation
import Preferences
@MainActor
var translationCache = [String: String]()
public func translate(text: String, cache: Bool = true) async -> String {
let language = UserDefaults.shared.value(for: \.chatGPTLanguage)
if language.isEmpty { return text }
let key = "\(language)-\(text)"
if cache, let cached = await translationCache[key] {
return cached
}
if let translated = try? await askChatGPT(
systemPrompt: """
You are a translator. Your job is to translate the message into \(language). The reply should only contain the translated content.
User: ###${{some text}}###
Assistant: ${{translated text}}
""",
question: "###\(text)###"
) {
if cache {
let storeTask = Task { @MainActor in
translationCache[key] = translated
}
_ = await storeTask.result
}
return translated
}
return text
}