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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use async_trait::async_trait;
use laravel::http::client::{self, Response, reqwest};
use laravel::time::ToSpan;
use serde::Serialize;
use serde_json::Value;

use super::{json_body, json_str, real_sleeper};
use crate::support::config;
use crate::translator::{
    Sleeper, Texts, TranslateError, Translated, Translations, Translator, answered_code, log_to_console, same_language,
    trim,
};

/// The most target languages one call takes. More are sent in several calls.
const MAX_TARGETS: usize = 20;

/// The longest `context` one call takes, in characters.
const MAX_CONTEXT: usize = 30_000;

/// The longest wait honoured from a `Retry-After`, in seconds.
const MAX_WAIT: f64 = 30.0;

/// Translates through the Translatorio API (translatorio.com).
///
/// Translatorio protects placeholders such as `:name`, `{count}` and HTML tags itself and reports
/// whether every one came back, so nothing here has to ask a model nicely to keep them. One request
/// carries a batch into up to twenty languages.
///
/// Retries on `429`, `5xx`, a connection failure and the `409` that says the same call is still
/// running reuse one `Idempotency-Key`, so a retried batch is never charged twice, and they wait as
/// long as the API asks. A `402` (out of credits) is never retried: on the first batch it stops the
/// scan with the API's own message; later on, the scan keeps and writes what was already translated
/// and sends nothing more.
pub struct TranslatorioTranslator {
    sleeper: Arc<dyn Sleeper>,
    /// Whether a batch came back translated in this run. Until one has, an error has cost nothing
    /// and stops the scan; after, it would throw away what was already paid for.
    translated_any: AtomicBool,
    /// Set once the account runs out of credits: the batches left are not sent.
    out_of_credits: AtomicBool,
    /// Whether the warning about a long context was already printed.
    context_warned: AtomicBool,
}

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

    /// 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 batch into every language: the source language is answered with the text itself, the
    /// rest go in calls of at most twenty languages, plain texts and texts with HTML apart, and
    /// each answer is filed under the language code it was asked for.
    async fn batch(&self, texts: &Texts, from: &str, to: &[String]) -> Result<Translations, TranslateError> {
        let mut translations = Translations::new();
        let mut targets: Vec<String> = Vec::new();

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

        for (format, group) in by_format(texts) {
            let keys: Vec<&String> = group.keys().collect();
            let values: Vec<&str> = group.values().map(String::as_str).collect();

            for chunk in targets.chunks(MAX_TARGETS) {
                for result in self.request(&values, from, chunk, &format).await? {
                    let index = result.get("index").and_then(Value::as_i64).unwrap_or(-1);

                    let Some(key) = usize::try_from(index).ok().and_then(|index| keys.get(index)) else {
                        continue;
                    };

                    if result.get("intact").and_then(Value::as_bool) == Some(false) {
                        log_to_console(format!(
                            "⚠️  [{key}] a placeholder did not survive the translation; check it by hand."
                        ));
                    }

                    let answered: Vec<(String, &Value)> = result
                        .get("translations")
                        .and_then(Value::as_object)
                        .map(|map| map.iter().map(|(code, value)| (code.clone(), value)).collect())
                        .unwrap_or_default();

                    for language in chunk {
                        if let Some((_, Value::String(translation))) = answered_code(language, &answered) {
                            translations
                                .entry((*key).clone())
                                .or_default()
                                .insert(language.clone(), translation.clone());
                        }
                    }
                }
            }
        }

        Ok(translations)
    }

    /// One call to `/api/v1/translate`, retried with the same `Idempotency-Key` on a connection
    /// failure, a 429, a 5xx and the 409 that says the same call is still running.
    ///
    /// A 402 is never retried: it means the account is out of credits, and retrying it only delays
    /// the message saying so.
    async fn request(
        &self,
        texts: &[&str],
        from: &str,
        to: &[String],
        format: &str,
    ) -> Result<Vec<Value>, TranslateError> {
        let settings = config().translatorio;

        let Some(api_key) = settings.api_key.clone().filter(|key| !trim(key).is_empty()) else {
            return Err(TranslateError::failed(
                "Set TRANSLATORIO_API_KEY (TextsConfig translatorio.api_key) to translate with Translatorio.",
            ));
        };

        let non_empty = |value: &Option<String>| value.clone().filter(|value| !value.is_empty());

        let context = self.context();
        let body = Body {
            texts,
            source: from,
            targets: to,
            format,
            formality: non_empty(&settings.formality),
            glossary: non_empty(&settings.glossary),
            effort: non_empty(&settings.effort),
            context: context.as_deref(),
        };

        let retries = settings.retries;
        let idempotency_key = laravel::str::uuid().to_string();
        let url = format!("{}/api/v1/translate", settings.url.trim_end_matches('/'));
        let mut response: Option<Response> = None;

        for attempt in 0..=retries {
            let sent = client::post(&url)
                .token(&api_key)
                .accept_json()
                .header("Idempotency-Key", &idempotency_key)
                .timeout((settings.timeout as i64).seconds())
                .configure_transport(|transport| transport.redirect(reqwest::redirect::Policy::none()))
                .json(&body)
                .await;

            let current = match sent {
                Ok(current) => current,
                Err(_) => {
                    response = None;

                    if attempt < retries {
                        self.sleeper.sleep(backoff(attempt)).await;
                    }

                    continue;
                }
            };

            let again = is_retryable(&current);
            let wait = if again && attempt < retries {
                Some(wait_for(&current, attempt))
            } else {
                None
            };

            response = Some(current);

            if !again {
                break;
            }

            if let Some(wait) = wait {
                self.sleeper.sleep(wait).await;
            }
        }

        let Some(response) = response else {
            return Err(TranslateError::failed("Translatorio could not be reached."));
        };

        // Only a 2xx JSON answer is a translation: a redirect or a proxy's HTML page must never be
        // read as one.
        let results = json_body(&response)
            .and_then(|answer| answer.get("results").cloned())
            .and_then(|results| match results {
                Value::Array(items) => Some(items),
                _ => None,
            });

        match results {
            Some(results) if response.successful() => Ok(results),
            _ => {
                let message = json_str(&response, "/error/message")
                    .unwrap_or_else(|| format!("HTTP {}", response.status().as_u16()));

                Err(TranslateError::Failed {
                    message: format!("Translatorio refused the batch: {message}"),
                    code: response.status().as_u16(),
                })
            }
        }
    }

    /// The application context, cut to what one call takes, with a warning the first time.
    fn context(&self) -> Option<String> {
        let context = trim(&config().context).to_owned();
        let length = context.chars().count();

        let context = if length > MAX_CONTEXT {
            if !self.context_warned.swap(true, Ordering::SeqCst) {
                log_to_console(format!(
                    "⚠️  The context has {length} characters; Translatorio reads the first 30,000."
                ));
            }

            context.chars().take(MAX_CONTEXT).collect()
        } else {
            context
        };

        (!context.is_empty()).then_some(context)
    }
}

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

#[async_trait]
impl Translator for TranslatorioTranslator {
    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
            .batch(&texts, from, to)
            .await?
            .swap_remove("text")
            .unwrap_or_default())
    }

    /// Translates multiple strings into multiple target languages.
    ///
    /// A batch that fails once others have succeeded is left out and reported, as the other
    /// translators do: the scan writes what came back, and the keys left out are still missing, so
    /// the next scan sends them again.
    async fn translate_many(&self, texts: &Texts, from: &str, to: &[String]) -> Result<Translations, TranslateError> {
        if texts.is_empty() {
            return Ok(Translations::new());
        }

        if self.out_of_credits.load(Ordering::SeqCst) {
            log_to_console(format!(
                "⏭️  Skipping {} texts: the Translatorio account is out of credits.",
                texts.len()
            ));

            return Ok(Translations::new());
        }

        log_to_console(format!(
            "➡️ Sending {} texts to Translatorio for translation into [{}]...",
            texts.len(),
            to.join(", ")
        ));

        let translations = match self.batch(texts, from, to).await {
            Ok(translations) => translations,
            Err(error) => {
                if !self.translated_any.load(Ordering::SeqCst) {
                    return Err(error);
                }

                if error.code() == 402 {
                    self.out_of_credits.store(true, Ordering::SeqCst);

                    log_to_console(format!(
                        "❌ {error} The keys translated so far are kept; run the scan again once there are credits to finish the rest."
                    ));
                } else {
                    log_to_console(format!(
                        "❌ {error} Skipping these {} keys; the next scan sends them again.",
                        texts.len()
                    ));
                }

                return Ok(Translations::new());
            }
        };

        self.translated_any.store(true, Ordering::SeqCst);

        log_to_console(format!(
            "✅ Received translations for: {}",
            translations.keys().cloned().collect::<Vec<_>>().join(", ")
        ));

        Ok(translations)
    }

    /// Translatorio takes up to 100 texts and 50,000 characters a call; a batch stays well under
    /// both so a long catalogue never reaches either limit.
    fn max_payload_chars(&self) -> usize {
        20_000
    }

    fn max_batch_items(&self) -> usize {
        100
    }
}

/// The texts grouped by the format they are sent as.
///
/// With `format` set to `auto`, a text with HTML tags goes as `html`, so its tags are protected
/// too, and the rest as `text`. Any other value is used for every text.
fn by_format(texts: &Texts) -> Vec<(String, Texts)> {
    let format = config().translatorio.format;

    if format != "auto" {
        return vec![(format, texts.clone())];
    }

    let mut groups: Vec<(String, Texts)> = Vec::new();

    for (key, text) in texts {
        let format = if has_html_tag(text) { "html" } else { "text" };

        match groups.iter_mut().find(|(known, _)| known == format) {
            Some((_, group)) => {
                group.insert(key.clone(), text.clone());
            }
            None => groups.push((format.to_owned(), [(key.clone(), text.clone())].into_iter().collect())),
        }
    }

    groups
}

/// `/<\/?[a-zA-Z][^>]*>/`: an opening or closing HTML tag.
fn has_html_tag(text: &str) -> bool {
    let bytes = text.as_bytes();

    for (index, byte) in bytes.iter().enumerate() {
        if *byte != b'<' {
            continue;
        }

        let name = if bytes.get(index + 1) == Some(&b'/') {
            index + 2
        } else {
            index + 1
        };

        if bytes.get(name).is_some_and(u8::is_ascii_alphabetic) && bytes[name..].contains(&b'>') {
            return true;
        }
    }

    false
}

/// Whether an answer is worth asking again for: a rate limit, a server error, or the same call
/// still running after a timeout cut the first attempt short.
fn is_retryable(response: &Response) -> bool {
    response.status() == 429
        || response.status().as_u16() >= 500
        || (response.status() == 409 && json_str(response, "/error/code").as_deref() == Some("idempotency_in_flight"))
}

/// How long the API asked to wait, in its header or its body, or else the backoff.
fn wait_for(response: &Response, attempt: u32) -> f64 {
    let header = response
        .header("retry-after")
        .filter(|value| !value.is_empty())
        .map(str::to_owned);

    let asked = header.or_else(|| {
        json_body(response)
            .and_then(|answer| answer.pointer("/error/retry_after").cloned())
            .and_then(|value| match value {
                Value::Number(number) => Some(number.to_string()),
                Value::String(text) => Some(text),
                _ => None,
            })
    });

    match asked
        .as_deref()
        .filter(|asked| crate::support::is_numeric(asked))
        .map(str::trim)
    {
        Some(asked) => asked
            .parse::<f64>()
            .map_or_else(|_| backoff(attempt), |seconds| seconds.clamp(0.0, MAX_WAIT)),
        None => backoff(attempt),
    }
}

/// Seconds: 0.5, 1, 2, then 4.
fn backoff(attempt: u32) -> f64 {
    f64::from(2u32.saturating_pow(attempt).min(8)) * 0.5
}

#[derive(Serialize)]
struct Body<'a> {
    texts: &'a [&'a str],
    source: &'a str,
    targets: &'a [String],
    format: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    formality: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    glossary: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    effort: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    context: Option<&'a str>,
}