Skip to content

feat: LibreTranslate Integration #6263

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,15 @@ fun Response.toFile(file: File) = use { response ->
file.sink().use(response.body.source()::readAll)
}

fun FormBody.Builder.addOptional(name: String, value: String?) =
if (value != null) add(name, value) else this

fun FormBody.Builder.addEncodedOptional(name: String, value: String?) =
if (value != null) addEncoded(name, value) else this

fun MultipartBody.Builder.addFormDataPartOptional(name: String, value: String?) =
if (value != null) addFormDataPart(name, value) else this

fun JsonElement.toRequestBody(): RequestBody {
return GsonInstance.ACCESSIBLE_INTEROP.gson.toJson(this)
.toRequestBody(HttpClient.JSON_MEDIA_TYPE)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
/*
* This file is part of LiquidBounce (https://github.com/CCBlueX/LiquidBounce)
*
* Copyright (c) 2015 - 2025 CCBlueX
*
* LiquidBounce is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LiquidBounce is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LiquidBounce. If not, see <https://www.gnu.org/licenses/>.
*/
package net.ccbluex.liquidbounce.api.thirdparty

import net.ccbluex.liquidbounce.api.core.BaseApi
import net.ccbluex.liquidbounce.api.core.addEncodedOptional
import net.ccbluex.liquidbounce.api.core.addFormDataPartOptional
import okhttp3.FormBody
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import org.apache.tika.Tika
import java.io.File

private val tika by lazy(::Tika)

const val LIBRE_TRANSLATE_BASE_URL = "https://libretranslate.com"

/**
* [API Docs (Swagger)](https://libretranslate.com/docs/)
*/
class LibreTranslateApi(baseUrl: String = LIBRE_TRANSLATE_BASE_URL) : BaseApi(baseUrl) {

suspend fun detect(
text: String,
apiKey: String? = null,
): List<DetectionResult> = post(
"/detect",
body = FormBody.Builder()
.addEncoded("q", text)
.addEncodedOptional("api_key", apiKey)
.build(),
)

suspend fun languages(): List<Language> = get("/languages")

suspend fun translate(
text: String,
sourceLanguage: String,
targetLanguage: String,
format: String = "text",
alternatives: Int = 0,
apiKey: String? = null,
): TranslationResponse = post(
Comment on lines +54 to +61

Check warning

Code scanning / detekt

The more parameters a function has the more complex it is. Long parameter lists are often used to control complex algorithms and violate the Single Responsibility Principle. Prefer functions with short parameter lists. Warning library

The function translate(text: String, sourceLanguage: String, targetLanguage: String, format: String, alternatives: Int, apiKey: String?) has too many parameters. The current threshold is set to 6.
"/translate",
body = FormBody.Builder()
.addEncoded("q", text)
.addEncoded("source", sourceLanguage)
.addEncoded("target", targetLanguage)
.addEncoded("format", format)
.addEncoded("alternatives", alternatives.toString())
.addEncodedOptional("api_key", apiKey)
.build(),
)

suspend fun translateFile(
file: File,
sourceLanguage: String,
targetLanguage: String,
apiKey: String? = null,
): FileTranslationResponse = internalTranslateFile(
fileBody = file.asRequestBody(tika.detect(file).toMediaTypeOrNull()),
fileName = file.name,
sourceLanguage,
targetLanguage,
apiKey,
)

suspend fun frontendSettings(): FrontendSettings = get("/frontend/settings")

suspend fun suggest(
originalText: String,
suggestedTranslation: String,
sourceLanguage: String,
targetLanguage: String,
): SuggestionResponse = post(
"/suggest",
body = FormBody.Builder()
.addEncoded("q", originalText)
.addEncoded("s", suggestedTranslation)
.addEncoded("source", sourceLanguage)
.addEncoded("target", targetLanguage)
.build(),
)

private suspend fun internalTranslateFile(
fileBody: RequestBody,
fileName: String? = null,
sourceLanguage: String,
targetLanguage: String,
apiKey: String? = null,
): FileTranslationResponse = post(
"/translate_file",
body = MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", fileName, fileBody)
.addFormDataPart("source", sourceLanguage)
.addFormDataPart("target", targetLanguage)
.addFormDataPartOptional("api_key", apiKey)
.build(),
)

data class DetectionResult(
val confidence: Int,
val language: String
)

data class Language(
val code: String,
val name: String,
val targets: Set<String>
)

data class TranslationResponse(
val translatedText: String
)

data class FileTranslationResponse(
val translatedFileUrl: String
)

data class FrontendSettings(
val apiKeys: Boolean,
val charLimit: Int,
val frontendTimeout: Int,
val keyRequired: Boolean,
val language: LanguageSettings,
val suggestions: Boolean,
val supportedFilesFormat: Set<String>
)

data class LanguageSettings(
val source: LanguageCodeName,
val target: LanguageCodeName
)

data class LanguageCodeName(
val code: String,
val name: String
)

data class SuggestionResponse(
val success: Boolean
)

data class ErrorResponse(
val error: String
)

}
11 changes: 11 additions & 0 deletions src/main/kotlin/net/ccbluex/liquidbounce/config/types/Value.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ package net.ccbluex.liquidbounce.config.types
import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.annotations.SerializedName
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import net.ccbluex.liquidbounce.authlib.account.MinecraftAccount
import net.ccbluex.liquidbounce.config.gson.stategies.Exclude
import net.ccbluex.liquidbounce.config.gson.stategies.ProtocolExclude
Expand Down Expand Up @@ -326,6 +328,15 @@ open class Value<T : Any>(
set(deserializer.deserializeThrowing(string) as T)
}

/**
* Converts the Value into a [StateFlow] for flow operations
*/
fun asFlow(): StateFlow<T> {
val flow = MutableStateFlow(this.get())
this.onChanged { flow.value = it }
return flow
}

}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import net.ccbluex.liquidbounce.event.events.MouseButtonEvent
import net.ccbluex.liquidbounce.event.events.WorldChangeEvent
import net.ccbluex.liquidbounce.event.handler
import net.ccbluex.liquidbounce.features.module.modules.client.ModuleAutoConfig
import net.ccbluex.liquidbounce.features.module.modules.client.ModuleLibreTranslate
import net.ccbluex.liquidbounce.features.module.modules.client.ModuleLiquidChat
import net.ccbluex.liquidbounce.features.module.modules.client.ModuleRichPresence
import net.ccbluex.liquidbounce.features.module.modules.client.ModuleTargets
Expand Down Expand Up @@ -414,7 +415,8 @@ object ModuleManager : EventListener, Iterable<ClientModule> by modules {
ModuleAutoConfig,
ModuleRichPresence,
ModuleTargets,
ModuleLiquidChat
ModuleLiquidChat,
ModuleLibreTranslate,
)

builtin.forEach { module ->
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/*
* This file is part of LiquidBounce (https://github.com/CCBlueX/LiquidBounce)
*
* Copyright (c) 2015 - 2025 CCBlueX
*
* LiquidBounce is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LiquidBounce is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LiquidBounce. If not, see <https://www.gnu.org/licenses/>.
*
*
*/
package net.ccbluex.liquidbounce.features.module.modules.client

import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.filter
import net.ccbluex.liquidbounce.api.core.withScope
import net.ccbluex.liquidbounce.api.thirdparty.LIBRE_TRANSLATE_BASE_URL
import net.ccbluex.liquidbounce.api.thirdparty.LibreTranslateApi
import net.ccbluex.liquidbounce.config.types.NamedChoice
import net.ccbluex.liquidbounce.event.events.NotificationEvent
import net.ccbluex.liquidbounce.features.module.Category
import net.ccbluex.liquidbounce.features.module.ClientModule
import net.ccbluex.liquidbounce.utils.client.logger
import net.ccbluex.liquidbounce.utils.client.notification
import kotlin.time.Duration.Companion.seconds

object ModuleLibreTranslate : ClientModule(
"LibreTranslate",
Category.CLIENT,
hide = true,
state = false,
aliases = arrayOf("Translate", "Translator")
) {

// TODO: debounce for onChanged

private var apiBaseUrl by text("ApiBaseUrl", default = LIBRE_TRANSLATE_BASE_URL)
.doNotIncludeAlways()
.also { value ->
withScope {
value.asFlow().debounce(1.seconds).collect {
val client = LibreTranslateApi(it.trimEnd('/'))
try {
val languages = client.languages()
logger.info(languages.toString())
[email protected] = client
// TODO: success notification
} catch (e: Exception) {
// TODO: error notification
}
}
}
}

private val apiKey by text("ApiKey", default = "")
.doNotIncludeAlways()
.onChange(String::trim)

private val nullableApiKey get() = apiKey.takeIf { it.isNotEmpty() }

private var targetLanguage: String by text("TargetLanguage", default = "")
.doNotIncludeAlways()
.onChange(String::trim)
.also { value ->
withScope {
value.asFlow().filter { it.isNotBlank() }.debounce(1.seconds).collect { lang ->
val client = client ?: return@collect
val languages = client.languages()
val language = languages.find { it.code == lang }
if (language == null) {
targetLanguage = ""
notification("Invalid Language", "Language '$lang' is invalid.", NotificationEvent.Severity.ERROR)

Check warning

Code scanning / detekt

Line detected, which is longer than the defined maximum line length in the code style. Warning

Line detected, which is longer than the defined maximum line length in the code style.
} else {
notification(
title = "Valid Language",
message = "Language ${language.readableString()} can be translated from: " +
languages.filter { lang in it.targets }.joinToString { it.readableString() },
NotificationEvent.Severity.SUCCESS
)
}
}
}
}

fun LibreTranslateApi.Language.readableString() = "'$name'($code)"

private var showSourceLanguage by boolean("ShowSourceLanguage", default = true).doNotIncludeAlways()

private val autoTranslate by multiEnumChoice("AutoTranslate", default = Translatable.entries)
private enum class Translatable(override val choiceName: String) : NamedChoice {
CHAT_MESSAGES("ChatMessages"),
SUBTITLES("Subtitles"),
LIQUID_CHAT_MESSAGES("LiquidChatMessages"),
}


@Volatile
private var client: LibreTranslateApi? = null

// TODO: LiquidChat handler: pub/pri msg

// TODO: Chat handler: player/server msg


}
Loading