package eu.friedcutlet.yokan.services.translation import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpService import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.contentOrNull import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive class TranslationException(message: String) : RuntimeException(message) /** * LibreTranslate-compatible translator. The implementation intentionally stays behind * [TranslatorService] so OCR/image translation can depend on the app service boundary instead of * a concrete HTTP provider. */ class LibreTranslateTranslatorService( private val http: HttpService, private val endpoint: String = DefaultEndpoint, private val apiKey: String? = null, ) : TranslatorService { override val providerName: String = "LibreTranslate" private val json = Json { ignoreUnknownKeys = true isLenient = true } private val languages = listOf( TranslationLanguage.English, TranslationLanguage.German, TranslationLanguage.Japanese, ) private val supportedPairs: Set = (languages + TranslationLanguage.Auto) .flatMap { source -> languages.map { target -> TranslationPair(source, target) } } .toSet() override fun supportedLanguages(): List = languages override fun supports(source: TranslationLanguage, target: TranslationLanguage): Boolean = TranslationPair(source, target) in supportedPairs override suspend fun translate(request: TranslationRequest): TranslationResult { val text = request.text if (text.isBlank()) { return TranslationResult( originalText = request.text, translatedText = "", source = request.source.takeUnless { it == TranslationLanguage.Auto }, target = request.target, providerName = providerName, ) } if (request.source == request.target) { return TranslationResult( originalText = request.text, translatedText = request.text, source = request.source, target = request.target, providerName = providerName, ) } if (!supports(request.source, request.target)) { throw TranslationException("Unsupported translation pair: ${request.source.code} -> ${request.target.code}") } val response = http.request( HttpRequest( url = endpoint, method = "POST", headers = mapOf( "Accept" to "application/json", "Content-Type" to "application/json", ), body = encodeRequest(request), ), ) if (response.statusCode !in 200..299) { throw TranslationException("Translator request failed with HTTP ${response.statusCode}: ${response.body.take(160)}") } val body = runCatching { json.parseToJsonElement(response.body).jsonObject } .getOrElse { error -> throw TranslationException("Translator returned invalid JSON: ${error.message}") } val translated = body.stringValue("translatedText") ?: body.stringValue("translated_text") ?: throw TranslationException("Translator response did not include translated text.") val detectedSource = detectedSource(body) ?: request.source.takeUnless { it == TranslationLanguage.Auto } return TranslationResult( originalText = request.text, translatedText = translated, source = detectedSource, target = request.target, providerName = providerName, ) } private fun encodeRequest(request: TranslationRequest): String { val entries = mutableMapOf( "q" to JsonPrimitive(request.text), "source" to JsonPrimitive(request.source.code), "target" to JsonPrimitive(request.target.code), "format" to JsonPrimitive("text"), ) apiKey?.takeIf { it.isNotBlank() }?.let { entries["api_key"] = JsonPrimitive(it) } return JsonObject(entries).toString() } private fun detectedSource(body: JsonObject): TranslationLanguage? { body.stringValue("detectedSourceLanguage")?.let { return TranslationLanguage.fromCode(it) } body.stringValue("detected_source_language")?.let { return TranslationLanguage.fromCode(it) } val detected = body["detectedLanguage"]?.jsonObjectOrNull() ?: body["detected_language"]?.jsonObjectOrNull() ?: return null return TranslationLanguage.fromCode(detected.stringValue("language")) } private fun JsonObject.stringValue(key: String): String? = this[key]?.jsonPrimitive?.contentOrNull?.takeIf { it.isNotBlank() } private fun JsonElement.jsonObjectOrNull(): JsonObject? = runCatching { jsonObject }.getOrNull() companion object { const val DefaultEndpoint = "https://translate.argosopentech.com/translate" } } interface TranslatorService { val providerName: String fun supportedLanguages(): List fun supports(source: TranslationLanguage, target: TranslationLanguage): Boolean suspend fun translate(request: TranslationRequest): TranslationResult suspend fun translateBatch(requests: List): List = requests.map { translate(it) } } enum class TranslationLanguage( val code: String, val displayName: String, ) { Auto("auto", "Auto-detect"), English("en", "English"), German("de", "German"), Japanese("ja", "Japanese"), ; companion object { fun fromCode(code: String?): TranslationLanguage? { val normalized = code?.trim()?.lowercase().orEmpty() if (normalized.isBlank()) return null return entries.firstOrNull { language -> language.code == normalized || normalized.startsWith("${language.code}-") } } } } data class TranslationRequest( val text: String, val source: TranslationLanguage = TranslationLanguage.Auto, val target: TranslationLanguage, ) { init { require(target != TranslationLanguage.Auto) { "Translation target language cannot be auto-detect." } } } data class TranslationResult( val originalText: String, val translatedText: String, val source: TranslationLanguage?, val target: TranslationLanguage, val providerName: String, ) data class TranslationPair( val source: TranslationLanguage, val target: TranslationLanguage, )