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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::time::Duration;

use async_trait::async_trait;
use indexmap::IndexMap;
use serde_json::Value;
use tokio::sync::mpsc::UnboundedSender;

use crate::support::settings;

/// The texts to translate, `[key => text]`.
pub type Texts = IndexMap<String, String>;

/// What a translator answers for one text: `[language => translation]`.
pub type Translated = IndexMap<String, String>;

/// What a translator answers for a batch: `[key => [language => translation]]`.
pub type Translations = IndexMap<String, Translated>;

/// Why a translation did not come back.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TranslateError {
    /// A model stopped answering because it reached its output limit, so its JSON is cut short.
    ///
    /// Sending the same batch again would be cut at the same place and paid for again, so the
    /// batch is split instead ([`Translator::batch_translate`]). It is the PHP package's
    /// `ResponseTruncated`.
    Truncated(String),
    /// The translation failed. `code` is the HTTP status when there was one, and 0 otherwise.
    Failed {
        /// What went wrong, written to be read by a person.
        message: String,
        /// The HTTP status, or 0.
        code: u16,
    },
}

impl TranslateError {
    /// A failure with no status.
    pub fn failed(message: impl Into<String>) -> Self {
        Self::Failed {
            message: message.into(),
            code: 0,
        }
    }

    /// The HTTP status of the failure, or 0.
    pub fn code(&self) -> u16 {
        match self {
            Self::Failed { code, .. } => *code,
            Self::Truncated(_) => 0,
        }
    }
}

impl fmt::Display for TranslateError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Truncated(message) => formatter.write_str(message),
            Self::Failed { message, .. } => formatter.write_str(message),
        }
    }
}

impl std::error::Error for TranslateError {}

tokio::task_local! {
    static MESSAGES: UnboundedSender<String>;
}

/// Run a future with the messages translators print while they work, such as `➡️ Sending 12 texts
/// to OpenAI...`, going to a channel. `laratext:scan` shows them as they arrive.
///
/// Outside it, translators are silent, which is what PHP's `logToConsole` does outside the console.
pub async fn with_messages<F: Future>(sender: UnboundedSender<String>, future: F) -> F::Output {
    MESSAGES.scope(sender, future).await
}

/// Say what a translator is doing. A translator of your own can call it too.
pub fn log_to_console(message: impl Into<String>) {
    let message = message.into();

    tracing::debug!(target: "laratext", "{message}");

    let _ = MESSAGES.try_with(|sender| sender.send(message));
}

/// Characters per token assumed when estimating an answer. Low on purpose: English runs near
/// four, but Japanese, Hindi or Thai can take one token for every character or two, and an
/// estimate that is too high only costs one more request.
const CHARS_PER_TOKEN: f64 = 2.0;

/// How much longer a translation is assumed to be than its source.
const EXPANSION: f64 = 1.5;

/// The share of the output limit a batch is sized to fill, leaving room for the estimate to be
/// wrong.
const OUTPUT_MARGIN: f64 = 0.75;

/// What waiting between attempts does. The translators wait through it, so a test can record the
/// waits instead of sitting through them.
#[async_trait]
pub trait Sleeper: Send + Sync {
    /// Wait this many seconds.
    async fn sleep(&self, seconds: f64);
}

/// Waits for real.
#[derive(Debug, Clone, Copy, Default)]
pub struct RealSleeper;

#[async_trait]
impl Sleeper for RealSleeper {
    async fn sleep(&self, seconds: f64) {
        tokio::time::sleep(Duration::from_secs_f64(seconds.max(0.0))).await;
    }
}

/// A translation service.
///
/// Only [`translate`](Self::translate) is required, which is PHP's `TranslatorInterface`. Override
/// [`translate_many`](Self::translate_many) to translate a batch in one request. The provided
/// [`batch_translate`](Self::batch_translate), which `laratext:scan` calls, is the PHP
/// `Translator` base class: it cuts the texts into batches that fit a request, and, for a
/// translator that declares an [`output_token_limit`](Self::output_token_limit), into batches that
/// fit one answer.
///
/// ```ignore
/// use async_trait::async_trait;
/// use laratext::{TranslateError, Translated, Translator};
///
/// pub struct Beautiful;
///
/// #[async_trait]
/// impl Translator for Beautiful {
///     async fn translate(&self, text: &str, _from: &str, to: &[String]) -> Result<Translated, TranslateError> {
///         Ok(to.iter().map(|language| (language.clone(), text.to_owned())).collect())
///     }
/// }
/// ```
#[async_trait]
pub trait Translator: Send + Sync {
    /// Translate one text into one or more languages: `[language => translation]`.
    ///
    /// `to` can contain `from`: `laratext:scan` passes every configured language, the source
    /// language among them, and only a translator that returns a number from
    /// [`output_token_limit`](Self::output_token_limit) is spared. Answer `from` with `text` as it
    /// is, as the bundled translators do. PHP behaves the same way.
    async fn translate(&self, text: &str, from: &str, to: &[String]) -> Result<Translated, TranslateError>;

    /// Translate a batch of texts. The default asks [`translate`](Self::translate) for each text.
    async fn translate_many(&self, texts: &Texts, from: &str, to: &[String]) -> Result<Translations, TranslateError> {
        let mut results = Translations::new();

        for (key, text) in texts {
            results.insert(key.clone(), self.translate(text, from, to).await?);
        }

        Ok(results)
    }

    /// Translate a large set of texts, splitting them into safe batches.
    ///
    /// The result is `[key => [language => translation]]`.
    async fn batch_translate(&self, texts: &Texts, from: &str, to: &[String]) -> Result<Translations, TranslateError> {
        batch_translate(self, texts, from, to).await
    }

    /// Translates one batch, letting a [`TranslateError::Truncated`] through so the batch can be
    /// split. The bundled translators override it; by default it is
    /// [`translate_many`](Self::translate_many).
    async fn translate_batch(&self, texts: &Texts, from: &str, to: &[String]) -> Result<Translations, TranslateError> {
        self.translate_many(texts, from, to).await
    }

    /// The most tokens one answer of this translator may hold, or `None` when it declares none.
    ///
    /// A translator that returns a number has its batches sized by what they will produce rather
    /// than by what they send: a batch into twenty languages answers twenty times its size. `None`
    /// keeps the batches cut by [`max_payload_chars`](Self::max_payload_chars) and
    /// [`max_batch_items`](Self::max_batch_items) alone.
    fn output_token_limit(&self) -> Option<usize> {
        None
    }

    /// The most characters one request carries.
    fn max_payload_chars(&self) -> usize {
        2000
    }

    /// The most texts one request carries.
    fn max_batch_items(&self) -> usize {
        100
    }

    /// The application context to append to the prompt, empty when none is set.
    ///
    /// Lets a project tell the translator what the application is about, which register to use,
    /// or which terms to leave alone. Configured in `TextsConfig::context`.
    fn context_instruction(&self) -> String {
        let context = settings(|config| config.context.clone());
        let context = trim(&context);

        if context.is_empty() {
            return String::new();
        }

        format!(" Context about this application, provided by its developers: {context}")
    }
}

/// PHP's `trim`.
pub(crate) fn trim(value: &str) -> &str {
    value.trim_matches(|c| matches!(c, ' ' | '\t' | '\n' | '\r' | '\0' | '\x0b'))
}

/// Translate a large set of texts, automatically splitting them into safe batches.
pub async fn batch_translate<T: Translator + ?Sized>(
    translator: &T,
    texts: &Texts,
    from: &str,
    to: &[String],
) -> Result<Translations, TranslateError> {
    if let Some(limit) = translator.output_token_limit() {
        return batch_translate_within(translator, texts, from, to, limit).await;
    }

    let mut results = Translations::new();

    for batch in split_by_payload_size(texts, translator.max_payload_chars(), translator.max_batch_items()) {
        for (key, translations) in translator.translate_many(&batch, from, to).await? {
            union(results.entry(key).or_default(), translations);
        }
    }

    Ok(results)
}

/// PHP's `+` on arrays: what is already there wins.
fn union(into: &mut Translated, from: Translated) {
    for (language, translation) in from {
        into.entry(language).or_insert(translation);
    }
}

/// Split texts into batches by their estimated length.
pub fn split_by_payload_size(texts: &Texts, max_payload_chars: usize, max_batch_items: usize) -> Vec<Texts> {
    let mut batches = Vec::new();
    let mut current = Texts::new();
    let mut length = 0;

    for (key, text) in texts {
        let text_length = text.chars().count() + key.chars().count() + 4;

        if (!current.is_empty() && length + text_length > max_payload_chars) || current.len() >= max_batch_items {
            batches.push(std::mem::take(&mut current));
            length = 0;
        }

        current.insert(key.clone(), text.clone());
        length += text_length;
    }

    if !current.is_empty() {
        batches.push(current);
    }

    batches
}

/// Batches sized to the output limit.
///
/// The source language is answered with the source text and never sent. The other languages go
/// together unless the longest text into all of them would not fit one answer, in which case they
/// go in groups. A batch whose answer is cut short anyway is split in two, never sent again whole.
async fn batch_translate_within<T: Translator + ?Sized>(
    translator: &T,
    texts: &Texts,
    from: &str,
    to: &[String],
    limit: usize,
) -> Result<Translations, TranslateError> {
    let mut results = Translations::new();
    let mut targets: Vec<String> = Vec::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());
            }
        } else {
            targets.push(language.clone());
        }
    }

    if targets.is_empty() || texts.is_empty() {
        return Ok(results);
    }

    let budget = ((limit as f64 * OUTPUT_MARGIN).floor() as usize).max(1);
    let per_request = languages_per_request(texts, targets.len(), budget);

    for group in targets.chunks(per_request) {
        for batch in split_for_output(
            texts,
            group.len(),
            budget,
            translator.max_payload_chars(),
            translator.max_batch_items(),
        ) {
            for (key, translations) in translate_fitting(translator, &batch, from, group).await? {
                for (language, translation) in translations {
                    results.entry(key.clone()).or_default().insert(language, translation);
                }
            }
        }
    }

    Ok(results)
}

/// How many languages one request takes, so that the longest text fits one answer.
fn languages_per_request(texts: &Texts, languages: usize, budget: usize) -> usize {
    let mut fits = languages;

    for (key, text) in texts {
        while fits > 1 && estimated_output_tokens(key, text, fits) > budget {
            fits -= 1;
        }
    }

    fits
}

/// Batches whose estimated answer fits the budget, within the payload and item limits as well, so
/// no batch is ever larger than it was before.
fn split_for_output(
    texts: &Texts,
    languages: usize,
    budget: usize,
    max_payload_chars: usize,
    max_batch_items: usize,
) -> Vec<Texts> {
    let mut batches = Vec::new();
    let mut current = Texts::new();
    let mut tokens = 0;
    let mut chars = 0;

    for (key, text) in texts {
        let text_tokens = estimated_output_tokens(key, text, languages);
        let text_chars = text.chars().count() + key.chars().count() + 4;

        if !current.is_empty()
            && (tokens + text_tokens > budget
                || chars + text_chars > max_payload_chars
                || current.len() >= max_batch_items)
        {
            batches.push(std::mem::take(&mut current));
            tokens = 0;
            chars = 0;
        }

        current.insert(key.clone(), text.clone());
        tokens += text_tokens;
        chars += text_chars;
    }

    if !current.is_empty() {
        batches.push(current);
    }

    batches
}

type Boxed<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

/// One batch, split in two for as long as its answer comes back cut short.
fn translate_fitting<'a, T: Translator + ?Sized>(
    translator: &'a T,
    texts: &'a Texts,
    from: &'a str,
    to: &'a [String],
) -> Boxed<'a, Result<Translations, TranslateError>> {
    Box::pin(async move {
        match translator.translate_batch(texts, from, to).await {
            Err(TranslateError::Truncated(_)) => {}
            other => return other,
        }

        if texts.len() > 1 {
            let half = texts.len().div_ceil(2);

            log_to_console(format!(
                "✂️  The answer did not fit the model's output limit; splitting {} texts in two.",
                texts.len()
            ));

            let first: Texts = texts.iter().take(half).map(|(k, v)| (k.clone(), v.clone())).collect();
            let second: Texts = texts.iter().skip(half).map(|(k, v)| (k.clone(), v.clone())).collect();

            let mut results = translate_fitting(translator, &first, from, to).await?;

            // PHP's `+`: the first half wins, and the keys are different anyway.
            for (key, translations) in translate_fitting(translator, &second, from, to).await? {
                results.entry(key).or_insert(translations);
            }

            return Ok(results);
        }

        if to.len() > 1 {
            let half = to.len().div_ceil(2);
            let mut results = translate_fitting(translator, texts, from, &to[..half]).await?;

            for (key, translations) in translate_fitting(translator, texts, from, &to[half..]).await? {
                union(results.entry(key).or_default(), translations);
            }

            return Ok(results);
        }

        let key = texts.keys().next().map(String::as_str).unwrap_or_default();

        log_to_console(format!(
            "❌ [{key}] does not fit one answer of this model, even alone; skipping it."
        ));

        Ok(Translations::new())
    })
}

/// The tokens a text's translations take in the answer: its key once, then one translation per
/// language with its code.
pub fn estimated_output_tokens(key: &str, text: &str, languages: usize) -> usize {
    let key_tokens = (key.chars().count() as f64 / CHARS_PER_TOKEN).ceil() as usize + 4;
    let translation_tokens = ((text.chars().count() as f64 * EXPANSION) / CHARS_PER_TOKEN).ceil() as usize + 6;

    key_tokens + languages * translation_tokens
}

/// The translations of each key in a decoded answer, filed under the language codes that were asked
/// for.
///
/// A model may answer `pt-BR` for `pt_BR`, or nest `nav.home` as `{"nav": {"home": ...}}` however
/// firmly it is told not to; both are read back. Anything that is not a string is left out, so the
/// key stays missing and the next scan asks for it again.
pub fn translations_in(answer: &Value, keys: &[String], languages: &[String]) -> Translations {
    let mut results = Translations::new();

    for key in keys {
        let Some(entry) = arr_get(answer, key) else {
            continue;
        };

        let Some(codes) = codes_of(entry) else {
            continue;
        };

        for language in languages {
            if let Some((_, Value::String(translation))) = answered_code(language, &codes) {
                results
                    .entry(key.clone())
                    .or_default()
                    .insert(language.clone(), translation.clone());
            }
        }
    }

    results
}

/// The entries of an answer's object or list, with the codes they were filed under.
fn codes_of(entry: &Value) -> Option<Vec<(String, &Value)>> {
    match entry {
        Value::Object(map) => Some(map.iter().map(|(code, value)| (code.clone(), value)).collect()),
        Value::Array(items) => Some(
            items
                .iter()
                .enumerate()
                .map(|(i, value)| (i.to_string(), value))
                .collect(),
        ),
        _ => None,
    }
}

/// Laravel's `Arr::get` with dot notation: the key as it is, and else walked through nested
/// objects.
fn arr_get<'a>(answer: &'a Value, key: &str) -> Option<&'a Value> {
    if let Some(value) = member(answer, key) {
        return Some(value);
    }

    if !key.contains('.') {
        return None;
    }

    let mut node = answer;

    for segment in key.split('.') {
        node = member(node, segment)?;
    }

    Some(node)
}

fn member<'a>(node: &'a Value, key: &str) -> Option<&'a Value> {
    match node {
        Value::Object(map) => map.get(key),
        Value::Array(items) => key.parse::<usize>().ok().and_then(|index| items.get(index)),
        _ => None,
    }
}

/// Whether two codes name the same language: `pt_BR` and `pt-BR` do, `en` and `en_GB` do not.
pub fn same_language(a: &str, b: &str) -> bool {
    canonical(a) == canonical(b)
}

/// Where an answer filed the language asked for: the same code whatever its case and separator, or
/// else its base language (`zh` for `zh_CN`).
pub fn answered_code<'a, 'b>(asked: &str, translations: &'b [(String, &'a Value)]) -> Option<&'b (String, &'a Value)> {
    let wanted = canonical(asked);
    let base = wanted.split('-').next().unwrap_or_default().to_owned();

    translations
        .iter()
        .find(|(code, _)| canonical(code) == wanted)
        .or_else(|| translations.iter().find(|(code, _)| canonical(code) == base))
}

/// A code in lower case with `-` as the separator.
pub fn canonical(code: &str) -> String {
    trim(code).replace('_', "-").to_lowercase()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_code_is_the_same_language_whatever_its_separator_and_case() {
        assert!(same_language("pt_BR", "pt-br"));
        assert!(!same_language("en", "en_GB"));
    }

    #[test]
    fn the_estimate_counts_the_key_once_and_a_translation_per_language() {
        // 3 characters of key: ceil(3 / 2) + 4. 10 characters of text: ceil(10 * 1.5 / 2) + 6.
        assert_eq!(estimated_output_tokens("key", "0123456789", 1), 6 + 14);
        assert_eq!(estimated_output_tokens("key", "0123456789", 3), 6 + 3 * 14);
    }
}