Yokan / rebuild
Course 1 8624561

TranslatorService.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/translation/TranslatorService.kt

implementation186 lines
1package eu.friedcutlet.yokan.services.translation23import eu.friedcutlet.yokan.services.http.HttpRequest4import eu.friedcutlet.yokan.services.http.HttpService5import kotlinx.serialization.json.Json6import kotlinx.serialization.json.JsonElement7import kotlinx.serialization.json.JsonObject8import kotlinx.serialization.json.JsonPrimitive9import kotlinx.serialization.json.contentOrNull10import kotlinx.serialization.json.jsonObject11import kotlinx.serialization.json.jsonPrimitive1213class TranslationException(message: String) : RuntimeException(message)1415/**16 * LibreTranslate-compatible translator. The implementation intentionally stays behind17 * [TranslatorService] so OCR/image translation can depend on the app service boundary instead of18 * a concrete HTTP provider.19 */20class LibreTranslateTranslatorService(21    private val http: HttpService,22    private val endpoint: String = DefaultEndpoint,23    private val apiKey: String? = null,24) : TranslatorService {25    override val providerName: String = "LibreTranslate"2627    private val json = Json {28        ignoreUnknownKeys = true29        isLenient = true30    }3132    private val languages = listOf(33        TranslationLanguage.English,34        TranslationLanguage.German,35        TranslationLanguage.Japanese,36    )3738    private val supportedPairs: Set<TranslationPair> =39        (languages + TranslationLanguage.Auto)40            .flatMap { source -> languages.map { target -> TranslationPair(source, target) } }41            .toSet()4243    override fun supportedLanguages(): List<TranslationLanguage> = languages4445    override fun supports(source: TranslationLanguage, target: TranslationLanguage): Boolean =46        TranslationPair(source, target) in supportedPairs4748    override suspend fun translate(request: TranslationRequest): TranslationResult {49        val text = request.text50        if (text.isBlank()) {51            return TranslationResult(52                originalText = request.text,53                translatedText = "",54                source = request.source.takeUnless { it == TranslationLanguage.Auto },55                target = request.target,56                providerName = providerName,57            )58        }59        if (request.source == request.target) {60            return TranslationResult(61                originalText = request.text,62                translatedText = request.text,63                source = request.source,64                target = request.target,65                providerName = providerName,66            )67        }68        if (!supports(request.source, request.target)) {69            throw TranslationException("Unsupported translation pair: ${request.source.code} -> ${request.target.code}")70        }7172        val response = http.request(73            HttpRequest(74                url = endpoint,75                method = "POST",76                headers = mapOf(77                    "Accept" to "application/json",78                    "Content-Type" to "application/json",79                ),80                body = encodeRequest(request),81            ),82        )83        if (response.statusCode !in 200..299) {84            throw TranslationException("Translator request failed with HTTP ${response.statusCode}: ${response.body.take(160)}")85        }8687        val body = runCatching { json.parseToJsonElement(response.body).jsonObject }88            .getOrElse { error -> throw TranslationException("Translator returned invalid JSON: ${error.message}") }89        val translated = body.stringValue("translatedText")90            ?: body.stringValue("translated_text")91            ?: throw TranslationException("Translator response did not include translated text.")92        val detectedSource = detectedSource(body) ?: request.source.takeUnless { it == TranslationLanguage.Auto }9394        return TranslationResult(95            originalText = request.text,96            translatedText = translated,97            source = detectedSource,98            target = request.target,99            providerName = providerName,100        )101    }102103    private fun encodeRequest(request: TranslationRequest): String {104        val entries = mutableMapOf<String, JsonElement>(105            "q" to JsonPrimitive(request.text),106            "source" to JsonPrimitive(request.source.code),107            "target" to JsonPrimitive(request.target.code),108            "format" to JsonPrimitive("text"),109        )110        apiKey?.takeIf { it.isNotBlank() }?.let { entries["api_key"] = JsonPrimitive(it) }111        return JsonObject(entries).toString()112    }113114    private fun detectedSource(body: JsonObject): TranslationLanguage? {115        body.stringValue("detectedSourceLanguage")?.let { return TranslationLanguage.fromCode(it) }116        body.stringValue("detected_source_language")?.let { return TranslationLanguage.fromCode(it) }117        val detected = body["detectedLanguage"]?.jsonObjectOrNull()118            ?: body["detected_language"]?.jsonObjectOrNull()119            ?: return null120        return TranslationLanguage.fromCode(detected.stringValue("language"))121    }122123    private fun JsonObject.stringValue(key: String): String? =124        this[key]?.jsonPrimitive?.contentOrNull?.takeIf { it.isNotBlank() }125126    private fun JsonElement.jsonObjectOrNull(): JsonObject? =127        runCatching { jsonObject }.getOrNull()128129    companion object {130        const val DefaultEndpoint = "https://translate.argosopentech.com/translate"131    }132}133134interface TranslatorService {135    val providerName: String136137    fun supportedLanguages(): List<TranslationLanguage>138    fun supports(source: TranslationLanguage, target: TranslationLanguage): Boolean139    suspend fun translate(request: TranslationRequest): TranslationResult140    suspend fun translateBatch(requests: List<TranslationRequest>): List<TranslationResult> =141        requests.map { translate(it) }142}143144enum class TranslationLanguage(145    val code: String,146    val displayName: String,147) {148    Auto("auto", "Auto-detect"),149    English("en", "English"),150    German("de", "German"),151    Japanese("ja", "Japanese"),152    ;153154    companion object {155        fun fromCode(code: String?): TranslationLanguage? {156            val normalized = code?.trim()?.lowercase().orEmpty()157            if (normalized.isBlank()) return null158            return entries.firstOrNull { language ->159                language.code == normalized || normalized.startsWith("${language.code}-")160            }161        }162    }163}164165data class TranslationRequest(166    val text: String,167    val source: TranslationLanguage = TranslationLanguage.Auto,168    val target: TranslationLanguage,169) {170    init {171        require(target != TranslationLanguage.Auto) { "Translation target language cannot be auto-detect." }172    }173}174175data class TranslationResult(176    val originalText: String,177    val translatedText: String,178    val source: TranslationLanguage?,179    val target: TranslationLanguage,180    val providerName: String,181)182183data class TranslationPair(184    val source: TranslationLanguage,185    val target: TranslationLanguage,186)187

Search chapters, reference and source filenames.