Translate one-by-one

This commit is contained in:
Kylmakalle 2025-07-11 19:50:22 +03:00
parent fce2bf8595
commit 1c10a1d708

View File

@ -480,28 +480,32 @@ public func requestTranslateUrl(url: URL) -> Signal<String, TranslateFetchError>
public func gtranslate(_ text: String, _ toLang: String) -> Signal<String, TranslateFetchError> { public func gtranslate(_ text: String, _ toLang: String) -> Signal<String, TranslateFetchError> {
let parts = gtranslateSplitTextBySentences(text) // 1) Preserve *all* line breaks, including empty ones
let lines = text.components(separatedBy: "\n")
let translationSignals: [Signal<String, TranslateFetchError>] = parts.map { part in
return gtranslateSentence(part, toLang) // 2) Map each line to either a passthrough signal or a translate signal
} let translationSignals: [Signal<String, TranslateFetchError>] = lines.map { rawLine in
// Grab the "core" text and its leading whitespace
return combineLatest(translationSignals) let leadingWhitespace = rawLine.prefix { $0.isWhitespace }
|> map { results -> String in let core = rawLine.trimmingCharacters(in: .whitespacesAndNewlines)
var result: String = ""
// If theres nothing to translate, just emit the line back
for translatedPart in results { if core.isEmpty {
if !result.isEmpty { return .single(rawLine)
result += " " }
// Otherwise translate the core, then re-attach the indentation
return gtranslateSentence(core, toLang)
|> map { translatedCore in
return String(leadingWhitespace) + translatedCore
} }
result += translatedPart }
}
if result.isEmpty { // 3) Combine them and re-join with newlines
return text // Fallback to original text if translation failed return combineLatest(translationSignals)
} |> map { results in
let joined = results.joined(separator: "\n")
return result return joined.isEmpty ? text : joined
} }
} }