mirror of
https://github.com/Swiftgram/Telegram-iOS.git
synced 2025-10-09 03:20:48 +00:00
Translate one-by-one
This commit is contained in:
parent
fce2bf8595
commit
1c10a1d708
@ -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 there’s 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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user