Skip to content

Commit 5eae3c7

Browse files
committed
fix: Fix google translator translating literal array of text
1 parent bfc9f02 commit 5eae3c7

File tree

1 file changed

+17
-13
lines changed

1 file changed

+17
-13
lines changed

flex-translator/src/main/kotlin/com/xpdustry/flex/translator/GoogleBasicTranslator.kt

+17-13
Original file line numberDiff line numberDiff line change
@@ -32,18 +32,22 @@ import java.net.http.HttpResponse
3232
import java.util.Locale
3333
import java.util.concurrent.CompletableFuture
3434
import java.util.concurrent.Executor
35+
import kotlinx.serialization.ExperimentalSerializationApi
3536
import kotlinx.serialization.json.Json
36-
import kotlinx.serialization.json.JsonArray
37-
import kotlinx.serialization.json.JsonPrimitive
37+
import kotlinx.serialization.json.addAll
38+
import kotlinx.serialization.json.buildJsonObject
3839
import kotlinx.serialization.json.jsonArray
3940
import kotlinx.serialization.json.jsonObject
4041
import kotlinx.serialization.json.jsonPrimitive
42+
import kotlinx.serialization.json.put
43+
import kotlinx.serialization.json.putJsonArray
4144

4245
// TODO Add backoff and retries (in case of 429)
4346
internal class GoogleBasicTranslator(private val apiKey: String, executor: Executor) : BaseTranslator() {
4447
private val http = HttpClient.newBuilder().executor(executor).build()
4548
internal val supported: Set<Locale> = fetchSupportedLanguages()
4649

50+
@OptIn(ExperimentalSerializationApi::class)
4751
override fun translateDetecting(
4852
texts: List<String>,
4953
source: Locale,
@@ -72,21 +76,21 @@ internal class GoogleBasicTranslator(private val apiKey: String, executor: Execu
7276
return CompletableFuture.completedFuture(List(texts.size) { i -> TranslatedText(texts[i], fixedSource) })
7377
}
7478

75-
val parameters =
76-
mutableMapOf(
77-
"key" to apiKey,
78-
"q" to JsonArray(texts.map(::JsonPrimitive)).toString(),
79-
"target" to fixedTarget.toLanguageTag(),
80-
"format" to "text",
81-
)
82-
83-
if (fixedSource != Translator.AUTO_DETECT) {
84-
parameters["source"] = fixedSource.toLanguageTag()
79+
val json = buildJsonObject {
80+
put("key", apiKey)
81+
putJsonArray("q") { addAll(texts) }
82+
put("target", fixedTarget.toLanguageTag())
83+
put("format", "text")
84+
if (fixedSource != Translator.AUTO_DETECT) {
85+
put("source", fixedSource.toLanguageTag())
86+
}
8587
}
8688

8789
return http
8890
.sendAsync(
89-
HttpRequest.newBuilder(createApiUri(TRANSLATION_V2_ENDPOINT, parameters)).GET().build(),
91+
HttpRequest.newBuilder(createApiUri(TRANSLATION_V2_ENDPOINT))
92+
.POST(HttpRequest.BodyPublishers.ofString(json.toString()))
93+
.build(),
9094
HttpResponse.BodyHandlers.ofString(),
9195
)
9296
.thenCompose { response ->

0 commit comments

Comments
 (0)