-
-
Notifications
You must be signed in to change notification settings - Fork 540
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
Closed
Changes from 3 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
167 changes: 167 additions & 0 deletions
167
src/main/kotlin/net/ccbluex/liquidbounce/api/thirdparty/LibreTranslateApi.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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( | ||
"/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 | ||
) | ||
|
||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
115 changes: 115 additions & 0 deletions
115
...in/kotlin/net/ccbluex/liquidbounce/features/module/modules/client/ModuleLibreTranslate.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 warningCode 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 | ||
|
||
|
||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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