Skip to content
Merged
Changes from all 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 @@ -19,30 +19,66 @@

package net.ccbluex.liquidbounce.features.global

import com.google.common.cache.Cache
import com.google.common.cache.CacheBuilder
import net.ccbluex.liquidbounce.api.thirdparty.translator.TranslateLanguage
import net.ccbluex.liquidbounce.api.thirdparty.translator.TranslationResult
import net.ccbluex.liquidbounce.api.thirdparty.translator.TranslatorApi
import net.ccbluex.liquidbounce.api.thirdparty.translator.providers.GoogleTranslateApi
import net.ccbluex.liquidbounce.config.types.group.ValueGroup
import net.ccbluex.liquidbounce.event.EventListener
import java.time.Duration

private data class TranslationCacheKey(
val sourceLanguage: String,
val targetLanguage: String,
val text: String,
)

object GlobalSettingsAutoTranslate : ValueGroup(name = "AutoTranslate"), TranslatorApi, EventListener {

private val translationLazyCache = lazy<Cache<TranslationCacheKey, TranslationResult.Success>> {
CacheBuilder.newBuilder()
.maximumSize(512)
.expireAfterWrite(Duration.ofMinutes(15))
.build()
}

private val translationCache by translationLazyCache

private val providers = modes(this, "Provider", 0) {
arrayOf(
GoogleTranslateApi(it)
)
}

init {
providers.onChanged {
if (translationLazyCache.isInitialized()) {
translationCache.invalidateAll()
}
}
}

override suspend fun translateInternal(
sourceLanguage: TranslateLanguage,
targetLanguage: TranslateLanguage,
text: String
): TranslationResult {
return providers.activeMode.translateInternal(
sourceLanguage,
targetLanguage,
text
val key = TranslationCacheKey(
sourceLanguage.literal,
targetLanguage.literal,
text,
)

translationCache.getIfPresent(key)?.let { return it }

val result = providers.activeMode.translateInternal(sourceLanguage, targetLanguage, text)

if (result is TranslationResult.Success) {
translationCache.put(key, result)
}

return result
}
}