laratext 0.1.0

Laratext for Laravel Rust: translation keys with their source text, and auto-translation with OpenAI, Claude, Google Translate or Translatorio.
Documentation
use std::sync::Arc;

use async_trait::async_trait;
use laravel::http::client;
use laravel::time::ToSpan;
use serde::Serialize;
use serde_json::Value;

use super::{backoff_seconds, json_body, real_sleeper, refusal, retryable};
use crate::support::config;
use crate::translator::{
    Sleeper, Texts, TranslateError, Translated, Translations, Translator, canonical, log_to_console, same_language,
};

const ENDPOINT: &str = "https://translation.googleapis.com/language/translate/v2";

/// Translates with the Google Cloud Translation API.
///
/// The API takes one target language at a time, so a batch is one request per language. It takes no
/// prompt, so it ignores `TextsConfig::context`.
#[derive(Clone)]
pub struct GoogleTranslator {
    sleeper: Arc<dyn Sleeper>,
}

impl GoogleTranslator {
    /// A translator that reads its settings from the configuration on every request.
    pub fn new() -> Self {
        Self {
            sleeper: real_sleeper(),
        }
    }

    /// Wait through another [`Sleeper`] between attempts, such as one that records the waits.
    #[must_use]
    pub fn with_sleeper(mut self, sleeper: Arc<dyn Sleeper>) -> Self {
        self.sleeper = sleeper;

        self
    }

    /// One language, asked again on a rate limit or a server error.
    ///
    /// Laravel writes `pt_BR` where Google reads `pt-BR`. A regional code Google does not know is
    /// asked again as its base language (`en-GB` as `en`), and the source is always sent as its
    /// base language, which is all Google needs to read it.
    async fn request(
        &self,
        values: &[String],
        from: &str,
        language: &str,
    ) -> Result<Option<Vec<Value>>, TranslateError> {
        let settings = config().google;
        let attempts = settings.retries.max(1);
        let mut target = language.trim().replace('_', "-");
        let base = canonical(language).split('-').next().unwrap_or_default().to_owned();
        let source = canonical(from).split('-').next().unwrap_or_default().to_owned();

        let mut attempt = 1;

        while attempt <= attempts {
            let body = Body {
                q: values,
                source: &source,
                target: &target,
                format: "text",
                key: settings.api_key.as_deref(),
            };

            let response = client::post(ENDPOINT)
                .timeout((settings.timeout as i64).seconds())
                .json(&body)
                .await
                .map_err(|error| TranslateError::failed(error.to_string()))?;

            if response.successful() {
                let translations = json_body(&response)
                    .and_then(|answer| answer.pointer("/data/translations").cloned())
                    .and_then(|translations| match translations {
                        Value::Array(items) => Some(items),
                        _ => None,
                    })
                    .unwrap_or_default();

                return Ok(Some(translations));
            }

            if response.status() == 400 && target != base {
                log_to_console(format!(
                    "⚠️  Google does not take [{target}]; asking for [{base}] instead."
                ));

                target.clone_from(&base);

                // The attempt is not spent.
                continue;
            }

            log_to_console(format!(
                "⚠️  Google answered {} for [{language}]: {}",
                response.status().as_u16(),
                refusal(&response)
            ));

            if !retryable(&response) || attempt == attempts {
                return Ok(None);
            }

            self.sleeper.sleep(backoff_seconds(attempt)).await;

            attempt += 1;
        }

        Ok(None)
    }
}

impl Default for GoogleTranslator {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl Translator for GoogleTranslator {
    async fn translate(&self, text: &str, from: &str, to: &[String]) -> Result<Translated, TranslateError> {
        let texts: Texts = [("text".to_owned(), text.to_owned())].into_iter().collect();

        Ok(self
            .translate_many(&texts, from, to)
            .await?
            .swap_remove("text")
            .unwrap_or_default())
    }

    /// One request per language, as the API takes one target at a time. The source language is
    /// answered with the source text and never sent, and a language the API refuses is reported
    /// and left out, so its keys stay missing and the next scan asks again.
    async fn translate_many(&self, texts: &Texts, from: &str, to: &[String]) -> Result<Translations, TranslateError> {
        let keys: Vec<&String> = texts.keys().collect();
        let values: Vec<String> = texts.values().cloned().collect();
        let mut results = Translations::new();

        for language in to {
            if same_language(language, from) {
                for (key, text) in texts {
                    results
                        .entry(key.clone())
                        .or_default()
                        .insert(language.clone(), text.clone());
                }

                continue;
            }

            let Some(translations) = self.request(&values, from, language).await? else {
                continue;
            };

            for (index, item) in translations.iter().enumerate() {
                let (Some(key), Some(translated)) =
                    (keys.get(index), item.get("translatedText").and_then(Value::as_str))
                else {
                    continue;
                };

                results
                    .entry((*key).clone())
                    .or_default()
                    .insert(language.clone(), translated.to_owned());
            }
        }

        Ok(results)
    }
}

#[derive(Serialize)]
struct Body<'a> {
    q: &'a [String],
    source: &'a str,
    target: &'a str,
    format: &'static str,
    key: Option<&'a str>,
}