Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

chore(i18n): remove the in-repo auto translation tool

Hampusb122af59294c
diff --git a/.github/workflows/i18n-source-sync.yaml b/.github/workflows/i18n-source-sync.yaml
index 1c6e36a49..40cf2f500 100644
--- a/.github/workflows/i18n-source-sync.yaml
+++ b/.github/workflows/i18n-source-sync.yaml
@@ -61,8 +61,6 @@ jobs:
--step install_dependencies
- name: Refresh source catalogs
- env:
- OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }}
run: pnpm i18n:source-sync
- name: Format generated catalogs
diff --git a/.gitignore b/.gitignore
index f022f46af..a1c3f9225 100644
--- a/.gitignore
+++ b/.gitignore
@@ -28,8 +28,6 @@
/fluxer_app/pkgs/libfluxcore/
/fluxer_app/pkgs/libfluxwebp/
/fluxer_app/src/features/i18n/locales/*/messages.mjs
-**/auto-i18n-reviewed-unchanged.json.lock
-**/weblate/locales/auto-i18n-reviewed-unchanged.json
/fluxer_app/src/features/messaging/utils/markdown/parser/MarkdownParserWasmBytes.ts
/fluxer_app/src/features/theme/styles/generated/
/fluxer_app/src/features/ui/components/SVGMasks.tsx
@@ -46,7 +44,6 @@
/artifacts/
/desktop-shared-assets/
/desktop-modules/
-/s3_payload/
/upload_staging/
diff --git a/Cargo.toml b/Cargo.toml
index f40a20ddc..85bac5033 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -11,7 +11,6 @@ members = [
"fluxer_snowflakes",
"tools/ci",
"tools/dev",
- "tools/i18n_auto",
"fluxer_users",
"fluxer_unfurl",
"packages/markdown_parser/rust",
diff --git a/tools/i18n_auto/Cargo.toml b/tools/i18n_auto/Cargo.toml
deleted file mode 100644
index 55458f757..000000000
--- a/tools/i18n_auto/Cargo.toml
+++ /dev/null
@@ -1,13 +0,0 @@
-[package]
-name = "fluxer-i18n-auto"
-version = "0.1.0"
-edition.workspace = true
-license.workspace = true
-
-[dependencies]
-anyhow = "1.0.104"
-clap = { version = "4.6.7", features = ["derive"] }
-regex = "1.13"
-reqwest = { version = "0.13.5", default-features = false, features = ["blocking", "json", "rustls"] }
-serde = { version = "1.0.229", features = ["derive"] }
-serde_json = "1.0.151"
diff --git a/tools/i18n_auto/src/auto.rs b/tools/i18n_auto/src/auto.rs
deleted file mode 100644
index ceb6f0d85..000000000
--- a/tools/i18n_auto/src/auto.rs
+++ /dev/null
@@ -1,133 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-use std::fs;
-use std::path::PathBuf;
-
-use anyhow::Result;
-
-use crate::config::{
- DEFAULT_OPENROUTER_BASE_URL, DEFAULT_OPENROUTER_MODEL, EmptyFallback, EnvOverlay, env_value,
- trim_trailing_slash,
-};
-use crate::openrouter::is_openrouter_available;
-use crate::runner::translate_main;
-
-const ENV_KEYS: &[&str] = &[
- "FLUXER_AUTO_I18N",
- "FLUXER_AUTO_I18N_LOCALE_CONCURRENCY",
- "FLUXER_AUTO_I18N_PROGRESS_INTERVAL",
- "FLUXER_AUTO_I18N_REQUEST_TIMEOUT",
- "FLUXER_AUTO_I18N_STRING_CONCURRENCY",
- "I18N_LLM_MODEL",
- "OPENROUTER_API_KEY",
- "OPENROUTER_APP_TITLE",
- "OPENROUTER_BASE_URL",
- "OPENROUTER_FALLBACK_MODELS",
- "OPENROUTER_HTTP_REFERER",
- "OPENROUTER_MODEL",
- "OPENROUTER_PROVIDER_SORT",
-];
-
-pub fn auto_main(args: &[String]) -> Result<u8> {
- let env_overrides = load_env_from_files(ENV_KEYS);
- let fluxer_auto_i18n = env_value("FLUXER_AUTO_I18N", &env_overrides, "");
- let openrouter_base_url = trim_trailing_slash(&env_value(
- "OPENROUTER_BASE_URL",
- &env_overrides,
- DEFAULT_OPENROUTER_BASE_URL,
- ));
- let openrouter_api_key = env_value("OPENROUTER_API_KEY", &env_overrides, "");
- let i18n_llm_model = env_value("I18N_LLM_MODEL", &env_overrides, "")
- .if_empty(|| env_value("OPENROUTER_MODEL", &env_overrides, DEFAULT_OPENROUTER_MODEL));
- let bypass_run_gate = args.iter().any(|arg| {
- matches!(arg.as_str(), "--help" | "-h" | "--dry-run") || arg.starts_with("--dry-run=")
- });
- let explicitly_disabled = matches!(
- fluxer_auto_i18n.to_lowercase().as_str(),
- "0" | "false" | "no" | "off"
- );
- if explicitly_disabled && !bypass_run_gate {
- eprintln!("i18n:auto skipped: FLUXER_AUTO_I18N=0 disables automatic translations.");
- return Ok(0);
- }
- let openrouter_is_available =
- is_openrouter_available(&openrouter_base_url, &openrouter_api_key);
- let should_run = fluxer_auto_i18n == "1" || (!explicitly_disabled && openrouter_is_available);
- if !should_run && !bypass_run_gate {
- eprintln!(
- "i18n:auto skipped: OpenRouter is unavailable. Set OPENROUTER_API_KEY, or set FLUXER_AUTO_I18N=1 to attempt translations with {} at {}.",
- if i18n_llm_model.is_empty() {
- DEFAULT_OPENROUTER_MODEL
- } else {
- &i18n_llm_model
- },
- openrouter_base_url
- );
- return Ok(0);
- }
- if should_run && fluxer_auto_i18n != "1" && openrouter_is_available {
- println!(
- "i18n:auto detected OpenRouter availability at {openrouter_base_url}; running without FLUXER_AUTO_I18N=1."
- );
- }
-
- translate_main(args, &env_overrides)
-}
-
-pub fn load_env_from_files(keys: &[&str]) -> EnvOverlay {
- let target_keys = keys
- .iter()
- .copied()
- .collect::<std::collections::HashSet<_>>();
- let mut env = EnvOverlay::new();
- let Some(home) = std::env::var_os("HOME").map(PathBuf::from) else {
- return env;
- };
- for candidate in [
- ".bash_profile",
- ".bashrc",
- ".profile",
- ".zprofile",
- ".zshrc",
- ] {
- let file_path = home.join(candidate);
- let Ok(content) = fs::read_to_string(file_path) else {
- continue;
- };
- for line in content.lines() {
- let Some((key, value)) = parse_export_line(line) else {
- continue;
- };
- if target_keys.contains(key.as_str()) {
- env.entry(key).or_insert(value);
- }
- }
- }
- env
-}
-
-pub fn parse_export_line(line: &str) -> Option<(String, String)> {
- let trimmed = line.trim();
- let key_value = trimmed.strip_prefix("export ")?;
- let (key, value) = key_value.split_once('=')?;
- let mut chars = key.chars();
- let first = chars.next()?;
- if !(first.is_alphabetic() || first == '_') {
- return None;
- }
- if !chars.all(|character| character.is_alphanumeric() || character == '_') {
- return None;
- }
- Some((key.to_string(), strip_quotes(value)))
-}
-
-pub fn strip_quotes(value: &str) -> String {
- let trimmed = value.trim();
- let first = trimmed.chars().next();
- let last = trimmed.chars().next_back();
- if trimmed.len() >= 2 && first == last && matches!(first, Some('\'' | '"')) {
- trimmed[1..trimmed.len() - 1].to_string()
- } else {
- trimmed.to_string()
- }
-}
diff --git a/tools/i18n_auto/src/config.rs b/tools/i18n_auto/src/config.rs
deleted file mode 100644
index 5651d787e..000000000
--- a/tools/i18n_auto/src/config.rs
+++ /dev/null
@@ -1,77 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-use std::collections::HashMap;
-use std::path::{Path, PathBuf};
-
-pub const SOURCE_LOCALE: &str = "en-US";
-pub const DEFAULT_OPENROUTER_BASE_URL: &str = "https://openrouter.ai/api/v1";
-pub const DEFAULT_OPENROUTER_MODEL: &str = "google/gemini-2.5-flash-lite";
-pub const DEFAULT_OPENROUTER_FALLBACK_MODELS: &str =
- "openai/gpt-4.1-nano,mistralai/mistral-nemo,mistralai/mistral-small-3.2-24b-instruct";
-pub const DEFAULT_OPENROUTER_PROVIDER_SORT: &str = "throughput";
-pub const DEFAULT_OPENROUTER_HTTP_REFERER: &str = "https://fluxer.chat";
-pub const DEFAULT_OPENROUTER_APP_TITLE: &str = "Fluxer i18n auto";
-pub const DEFAULT_STRING_CONCURRENCY: usize = 2;
-pub const DEFAULT_LOCALE_CONCURRENCY: usize = 1;
-pub const DEFAULT_REQUEST_TIMEOUT_SECONDS: f64 = 300.0;
-pub const DEFAULT_PROGRESS_INTERVAL_SECONDS: f64 = 20.0;
-pub const GUIDANCE_EXCERPT_CHAR_LIMIT: usize = 1600;
-
-pub const AUTO_I18N_REVIEWED_UNCHANGED_FILE: &str = "auto-i18n-reviewed-unchanged.json";
-
-pub type EnvOverlay = HashMap<String, String>;
-
-pub fn default_app_dir() -> PathBuf {
- let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
- manifest_dir
- .parent()
- .and_then(Path::parent)
- .map(|repo_root| repo_root.join("fluxer_app"))
- .unwrap_or_else(|| PathBuf::from("fluxer_app"))
-}
-
-pub fn i18n_dir(app_dir: &Path) -> PathBuf {
- app_dir.join("src").join("features").join("i18n")
-}
-
-pub fn locales_dir(app_dir: &Path) -> PathBuf {
- i18n_dir(app_dir).join("locales")
-}
-
-pub fn env_value(key: &str, env_overrides: &EnvOverlay, fallback: &str) -> String {
- std::env::var(key)
- .ok()
- .filter(|value| !value.is_empty())
- .or_else(|| env_overrides.get(key).cloned())
- .unwrap_or_else(|| fallback.to_string())
-}
-
-pub fn positive_float_env(key: &str, fallback: f64, env_overrides: &EnvOverlay) -> f64 {
- let value = env_value(key, env_overrides, "");
- if value.is_empty() {
- return fallback;
- }
- value
- .parse::<f64>()
- .ok()
- .filter(|parsed| *parsed > 0.0)
- .unwrap_or(fallback)
-}
-
-pub fn positive_int_env(key: &str, fallback: usize, env_overrides: &EnvOverlay) -> usize {
- positive_float_env(key, fallback as f64, env_overrides).max(1.0) as usize
-}
-
-pub fn trim_trailing_slash(value: &str) -> String {
- value.trim_end_matches('/').to_string()
-}
-
-pub(crate) trait EmptyFallback {
- fn if_empty(self, fallback: impl FnOnce() -> String) -> String;
-}
-
-impl EmptyFallback for String {
- fn if_empty(self, fallback: impl FnOnce() -> String) -> String {
- if self.is_empty() { fallback() } else { self }
- }
-}
diff --git a/tools/i18n_auto/src/json_catalog.rs b/tools/i18n_auto/src/json_catalog.rs
deleted file mode 100644
index aedf3c6d0..000000000
--- a/tools/i18n_auto/src/json_catalog.rs
+++ /dev/null
@@ -1,182 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-use std::collections::BTreeMap;
-use std::path::PathBuf;
-
-use anyhow::{Context, Result, bail};
-use serde_json::{Map, Value};
-
-use crate::po::{Entry, Translation};
-use crate::ts_catalog::StaticTsCatalogKind;
-
-#[derive(Clone, Debug, Eq, PartialEq)]
-pub struct StaticJsonCatalogConfig {
- pub kind: StaticTsCatalogKind,
- pub source_path: PathBuf,
-}
-
-fn parse_object(content: &str, what: &str) -> Result<Map<String, Value>> {
- let value: Value =
- serde_json::from_str(content).with_context(|| format!("failed to parse {what}"))?;
- match value {
- Value::Object(map) => Ok(map),
- _ => bail!("{what} must be a JSON object"),
- }
-}
-
-fn flatten(
- kind: &StaticTsCatalogKind,
- map: &Map<String, Value>,
-) -> Result<BTreeMap<String, String>> {
- let mut out = BTreeMap::new();
- for (key, value) in map {
- match kind {
- StaticTsCatalogKind::SimpleMessages => match value {
- Value::String(text) => {
- out.insert(key.clone(), text.clone());
- }
- _ => bail!("{key} must be a string"),
- },
- StaticTsCatalogKind::EmailTemplates => match value {
- Value::Object(fields) => {
- for (field, text) in fields {
- match text {
- Value::String(text) => {
- out.insert(format!("{key}.{field}"), text.clone());
- }
- _ => bail!("{key}.{field} must be a string"),
- }
- }
- }
- _ => bail!("{key} must be an object of template fields"),
- },
- }
- }
- Ok(out)
-}
-
-fn render(kind: &StaticTsCatalogKind, values: &BTreeMap<String, String>) -> Result<String> {
- let mut root = Map::new();
- match kind {
- StaticTsCatalogKind::SimpleMessages => {
- for (key, text) in values {
- root.insert(key.clone(), Value::String(text.clone()));
- }
- }
- StaticTsCatalogKind::EmailTemplates => {
- for (context, text) in values {
- let Some((template, field)) = context.split_once('.') else {
- bail!("{context} must name a template field as <template>.<field>");
- };
- let entry = root
- .entry(template.to_string())
- .or_insert_with(|| Value::Object(Map::new()));
- let Value::Object(fields) = entry else {
- bail!("{template} must be an object of template fields");
- };
- fields.insert(field.to_string(), Value::String(text.clone()));
- }
- }
- }
- let mut buffer = Vec::new();
- let formatter = serde_json::ser::PrettyFormatter::with_indent(b"\t");
- let mut serializer = serde_json::Serializer::with_formatter(&mut buffer, formatter);
- serde::Serialize::serialize(&Value::Object(root), &mut serializer)
- .context("failed to serialize catalog")?;
- let mut rendered = String::from_utf8(buffer).context("catalog is not valid UTF-8")?;
- rendered.push('\n');
- Ok(rendered)
-}
-
-fn static_comments(kind: &StaticTsCatalogKind, context: &str) -> Vec<String> {
- match kind {
- StaticTsCatalogKind::SimpleMessages => vec![format!("#. Static catalog key: {context}")],
- StaticTsCatalogKind::EmailTemplates => vec![format!("#. Email template field: {context}")],
- }
-}
-
-pub fn read_static_json_entries(
- config: &StaticJsonCatalogConfig,
- source_content: &str,
- target_content: &str,
- reset: bool,
-) -> Result<Vec<Entry>> {
- let source = flatten(
- &config.kind,
- &parse_object(source_content, "the source catalog")?,
- )?;
- let target = flatten(
- &config.kind,
- &parse_object(target_content, "the locale catalog")?,
- )?;
- Ok(source
- .into_iter()
- .enumerate()
- .map(|(index, (context, msgid))| {
- let msgstr = if reset {
- String::new()
- } else {
- target.get(&context).cloned().unwrap_or_default()
- };
- Entry {
- comments: static_comments(&config.kind, &context),
- references: vec![format!("#: {}", config.source_path.display())],
- msgctxt: Some(context),
- msgid,
- msgstr,
- line_number: index + 1,
- }
- })
- .collect())
-}
-
-pub fn rebuild_static_json_allow_replacing(
- config: &StaticJsonCatalogConfig,
- source_content: &str,
- target_content: &str,
- translations: &[Translation],
-) -> Result<String> {
- let source = flatten(
- &config.kind,
- &parse_object(source_content, "the source catalog")?,
- )?;
- let mut target = flatten(
- &config.kind,
- &parse_object(target_content, "the locale catalog")?,
- )?;
- for translation in translations {
- let Some(context) = translation.msgctxt.as_ref() else {
- continue;
- };
- if !source.contains_key(context) {
- continue;
- }
- target.insert(context.clone(), translation.msgstr.clone());
- }
- let merged = source
- .keys()
- .map(|context| {
- let text = target
- .get(context)
- .cloned()
- .unwrap_or_else(|| source[context].clone());
- (context.clone(), text)
- })
- .collect::<BTreeMap<_, _>>();
- render(&config.kind, &merged)
-}
-
-pub fn reset_static_json_translations(
- config: &StaticJsonCatalogConfig,
- target_content: &str,
-) -> Result<String> {
- let target = flatten(
- &config.kind,
- &parse_object(target_content, "the locale catalog")?,
- )?;
- let cleared = target
- .into_keys()
- .map(|context| (context, String::new()))
- .collect::<BTreeMap<_, _>>();
- render(&config.kind, &cleared)
-}
diff --git a/tools/i18n_auto/src/lib.rs b/tools/i18n_auto/src/lib.rs
deleted file mode 100644
index ac338f5e0..000000000
--- a/tools/i18n_auto/src/lib.rs
+++ /dev/null
@@ -1,14 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-pub mod auto;
-pub mod config;
-pub mod json_catalog;
-pub mod llm;
-pub mod locales;
-pub mod openrouter;
-pub mod po;
-pub mod prompts;
-pub mod reviewed_unchanged;
-pub mod runner;
-pub mod tokens;
-pub mod ts_catalog;
diff --git a/tools/i18n_auto/src/llm.rs b/tools/i18n_auto/src/llm.rs
deleted file mode 100644
index 52ecac2db..000000000
--- a/tools/i18n_auto/src/llm.rs
+++ /dev/null
@@ -1,88 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-use anyhow::Result;
-use regex::Regex;
-use serde_json::{Map, Value, json};
-
-#[derive(Clone, Debug, Eq, PartialEq)]
-pub struct LocalizationResult {
- pub localized: String,
- pub notes: String,
-}
-
-impl LocalizationResult {
- pub fn localized(localized: impl Into<String>) -> Self {
- Self {
- localized: localized.into(),
- notes: String::new(),
- }
- }
-}
-
-pub trait LocalizationClient: Sync {
- fn base_url(&self) -> &str;
- fn model(&self) -> &str;
- fn request_timeout_seconds(&self) -> f64;
- fn localize(
- &self,
- options: &Map<String, Value>,
- system_prompt: &str,
- user_prompt: &str,
- ) -> Result<LocalizationResult>;
-}
-
-pub fn base_options() -> Map<String, Value> {
- let mut options = Map::new();
- options.insert("temperature".to_string(), json!(0.1));
- options.insert("top_p".to_string(), json!(0.9));
- options.insert("num_ctx".to_string(), json!(4096));
- options.insert("num_predict".to_string(), json!(800));
- options
-}
-
-pub fn clean_translation_response(content: &str) -> String {
- let trimmed = trim_special_response_tokens(content.trim());
- let fenced_re = Regex::new(r"(?is)^```(?:[a-z]+)?\s*([\s\S]*?)\s*```$")
- .expect("valid fenced response regex");
- let mut raw = fenced_re
- .captures(trimmed)
- .and_then(|captures| captures.get(1))
- .map(|matched| matched.as_str().trim().to_string())
- .unwrap_or_else(|| trimmed.to_string());
- let label_re = Regex::new(r"(?is)^(?:localized(?: string)?|translation|answer):\s*([\s\S]+)$")
- .expect("valid label response regex");
- if let Some(captures) = label_re.captures(&raw)
- && let Some(value) = captures.get(1)
- {
- raw = value.as_str().trim().to_string();
- }
- if raw.starts_with('{')
- && raw.ends_with('}')
- && let Ok(Value::Object(object)) = serde_json::from_str::<Value>(&raw)
- && let Some(localized) = object.get("localized").and_then(Value::as_str)
- {
- return localized.to_string();
- }
- if raw.len() >= 2
- && raw.starts_with('"')
- && raw.ends_with('"')
- && let Ok(Value::String(value)) = serde_json::from_str::<Value>(&raw)
- {
- return value;
- }
- raw
-}
-
-fn trim_special_response_tokens(content: &str) -> &str {
- let mut trimmed = content.trim();
- loop {
- let next = trimmed
- .strip_suffix("<|im_end|>")
- .or_else(|| trimmed.strip_suffix("<end_of_turn>"))
- .or_else(|| trimmed.strip_suffix("</s>"));
- let Some(next) = next else {
- return trimmed.trim();
- };
- trimmed = next.trim();
- }
-}
diff --git a/tools/i18n_auto/src/locales.rs b/tools/i18n_auto/src/locales.rs
deleted file mode 100644
index 73984aebc..000000000
--- a/tools/i18n_auto/src/locales.rs
+++ /dev/null
@@ -1,50 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-pub const LOCALE_DISPLAY_NAMES: &[(&str, &str)] = &[
- ("ar", "Arabic"),
- ("bg", "Bulgarian"),
- ("cs", "Czech"),
- ("da", "Danish"),
- ("de", "German"),
- ("el", "Greek"),
- ("en-GB", "English (United Kingdom)"),
- ("es-419", "Spanish (Latin America)"),
- ("es-ES", "Spanish (Spain)"),
- ("fi", "Finnish"),
- ("fr", "French"),
- ("he", "Hebrew"),
- ("hi", "Hindi"),
- ("hr", "Croatian"),
- ("hu", "Hungarian"),
- ("id", "Indonesian"),
- ("it", "Italian"),
- ("ja", "Japanese"),
- ("ko", "Korean"),
- ("lt", "Lithuanian"),
- ("nl", "Dutch"),
- ("no", "Norwegian Bokmal"),
- ("pl", "Polish"),
- ("pt-BR", "Portuguese (Brazil)"),
- ("ro", "Romanian"),
- ("ru", "Russian"),
- ("sv-SE", "Swedish (Sweden)"),
- ("th", "Thai"),
- ("tr", "Turkish"),
- ("uk", "Ukrainian"),
- ("vi", "Vietnamese"),
- ("zh-CN", "Simplified Chinese (Mainland China)"),
- ("zh-TW", "Traditional Chinese (Taiwan)"),
-];
-
-pub fn display_name(locale: &str) -> &str {
- LOCALE_DISPLAY_NAMES
- .iter()
- .find_map(|(candidate, name)| (*candidate == locale).then_some(*name))
- .unwrap_or(locale)
-}
-
-pub fn is_supported_locale(locale: &str) -> bool {
- LOCALE_DISPLAY_NAMES
- .iter()
- .any(|(candidate, _name)| *candidate == locale)
-}
diff --git a/tools/i18n_auto/src/main.rs b/tools/i18n_auto/src/main.rs
deleted file mode 100644
index 3a5eae18a..000000000
--- a/tools/i18n_auto/src/main.rs
+++ /dev/null
@@ -1,14 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-use std::process::ExitCode;
-
-fn main() -> ExitCode {
- let args = std::env::args().skip(1).collect::<Vec<_>>();
- match fluxer_i18n_auto::auto::auto_main(&args) {
- Ok(code) => ExitCode::from(code),
- Err(error) => {
- eprintln!("{error:#}");
- ExitCode::from(1)
- }
- }
-}
diff --git a/tools/i18n_auto/src/openrouter.rs b/tools/i18n_auto/src/openrouter.rs
deleted file mode 100644
index ed3c76943..000000000
--- a/tools/i18n_auto/src/openrouter.rs
+++ /dev/null
@@ -1,234 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-use std::time::Duration;
-
-use anyhow::{Context, Result, bail};
-use serde_json::{Map, Value, json};
-
-use crate::llm::{LocalizationClient, LocalizationResult, clean_translation_response};
-
-pub struct OpenRouterClient {
- base_url: String,
- model: String,
- fallback_models: Vec<String>,
- provider_sort: String,
- http_referer: String,
- app_title: String,
- api_key: String,
- request_timeout: Duration,
- client: reqwest::blocking::Client,
-}
-
-#[derive(Clone, Debug, PartialEq)]
-pub struct OpenRouterClientConfig {
- pub base_url: String,
- pub model: String,
- pub fallback_models: Vec<String>,
- pub provider_sort: String,
- pub http_referer: String,
- pub app_title: String,
- pub api_key: String,
- pub request_timeout_seconds: f64,
-}
-
-impl OpenRouterClient {
- pub fn new(config: OpenRouterClientConfig) -> Result<Self> {
- if config.api_key.trim().is_empty() {
- bail!("OPENROUTER_API_KEY is required for i18n:auto");
- }
- let request_timeout = Duration::from_secs_f64(config.request_timeout_seconds);
- let client = reqwest::blocking::Client::builder()
- .timeout(request_timeout)
- .build()
- .context("failed to build OpenRouter HTTP client")?;
- Ok(Self {
- base_url: config.base_url.trim_end_matches('/').to_string(),
- model: config.model,
- fallback_models: config.fallback_models,
- provider_sort: config.provider_sort,
- http_referer: config.http_referer,
- app_title: config.app_title,
- api_key: config.api_key,
- request_timeout,
- client,
- })
- }
-}
-
-impl LocalizationClient for OpenRouterClient {
- fn base_url(&self) -> &str {
- &self.base_url
- }
-
- fn model(&self) -> &str {
- &self.model
- }
-
- fn request_timeout_seconds(&self) -> f64 {
- self.request_timeout.as_secs_f64()
- }
-
- fn localize(
- &self,
- options: &Map<String, Value>,
- system_prompt: &str,
- user_prompt: &str,
- ) -> Result<LocalizationResult> {
- let max_tokens = options
- .get("num_predict")
- .and_then(Value::as_u64)
- .unwrap_or(800);
- let expects_json = system_prompt.contains("Return only valid compact JSON");
- let mut provider = Map::new();
- if !self.provider_sort.is_empty() {
- provider.insert("sort".to_string(), json!(self.provider_sort));
- }
- provider.insert("allow_fallbacks".to_string(), json!(true));
- if expects_json {
- provider.insert("require_parameters".to_string(), json!(true));
- }
-
- let mut payload = Map::new();
- payload.insert("model".to_string(), json!(self.model));
- let fallback_models = self
- .fallback_models
- .iter()
- .map(|model| model.trim())
- .filter(|model| !model.is_empty() && *model != self.model)
- .map(|model| json!(model))
- .take(3)
- .collect::<Vec<_>>();
- if !fallback_models.is_empty() {
- payload.insert("models".to_string(), Value::Array(fallback_models));
- }
- payload.insert(
- "messages".to_string(),
- json!([
- {"role": "system", "content": system_prompt},
- {"role": "user", "content": user_prompt},
- ]),
- );
- payload.insert(
- "temperature".to_string(),
- json!(
- options
- .get("temperature")
- .and_then(Value::as_f64)
- .unwrap_or(0.1)
- ),
- );
- payload.insert(
- "top_p".to_string(),
- json!(options.get("top_p").and_then(Value::as_f64).unwrap_or(0.9)),
- );
- payload.insert("max_tokens".to_string(), json!(max_tokens));
- payload.insert("stream".to_string(), json!(false));
- payload.insert("provider".to_string(), Value::Object(provider));
- if expects_json {
- payload.insert(
- "response_format".to_string(),
- json!({"type": "json_object"}),
- );
- }
-
- let response = self
- .client
- .post(format!("{}/chat/completions", self.base_url))
- .bearer_auth(&self.api_key)
- .header("HTTP-Referer", &self.http_referer)
- .header("X-OpenRouter-Title", &self.app_title)
- .json(&Value::Object(payload))
- .send()
- .with_context(|| {
- format!(
- "OpenRouter request failed after {}s",
- self.request_timeout.as_secs_f64()
- )
- })?;
- let status = response.status();
- let body = response
- .text()
- .context("failed to read OpenRouter response")?;
- if !status.is_success() {
- bail!(
- "OpenRouter API error: {} - {}",
- status.as_u16(),
- truncate_error_body(&body)
- );
- }
- let data = serde_json::from_str::<Value>(&body)
- .context("failed to parse OpenRouter response JSON")?;
- let Some(content) =
- extract_chat_message_content(&data).filter(|content| !content.is_empty())
- else {
- bail!("Empty response from OpenRouter");
- };
- Ok(LocalizationResult::localized(clean_translation_response(
- &content,
- )))
- }
-}
-
-pub fn parse_openrouter_fallback_models(value: &str) -> Vec<String> {
- value
- .split(',')
- .map(str::trim)
- .filter(|model| !model.is_empty())
- .map(ToString::to_string)
- .collect()
-}
-
-pub fn is_openrouter_available(base_url: &str, api_key: &str) -> bool {
- if api_key.trim().is_empty() {
- return false;
- }
- let Ok(client) = reqwest::blocking::Client::builder()
- .timeout(Duration::from_secs(4))
- .build()
- else {
- return false;
- };
- client
- .get(format!("{}/models", base_url.trim_end_matches('/')))
- .bearer_auth(api_key)
- .send()
- .map(|response| response.status().is_success())
- .unwrap_or(false)
-}
-
-fn extract_chat_message_content(data: &Value) -> Option<String> {
- let content = data
- .get("choices")
- .and_then(Value::as_array)
- .and_then(|choices| choices.first())
- .and_then(|choice| choice.get("message"))
- .and_then(|message| message.get("content"))?;
- match content {
- Value::String(value) => Some(value.to_string()),
- Value::Array(parts) => {
- let text = parts
- .iter()
- .filter_map(|part| match part {
- Value::String(value) => Some(value.as_str()),
- Value::Object(object) => object
- .get("text")
- .or_else(|| object.get("content"))
- .and_then(Value::as_str),
- _ => None,
- })
- .collect::<Vec<_>>()
- .join("");
- if text.is_empty() { None } else { Some(text) }
- }
- _ => None,
- }
-}
-
-fn truncate_error_body(body: &str) -> String {
- const MAX_ERROR_BODY_CHARS: usize = 2000;
- let mut truncated = body.chars().take(MAX_ERROR_BODY_CHARS).collect::<String>();
- if body.chars().count() > MAX_ERROR_BODY_CHARS {
- truncated.push_str("...");
- }
- truncated
-}
diff --git a/tools/i18n_auto/src/po.rs b/tools/i18n_auto/src/po.rs
deleted file mode 100644
index 239ec804f..000000000
--- a/tools/i18n_auto/src/po.rs
+++ /dev/null
@@ -1,377 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-use anyhow::{Context, Result, bail};
-use regex::Regex;
-
-#[derive(Clone, Debug, Default, Eq, PartialEq)]
-pub struct Entry {
- pub comments: Vec<String>,
- pub references: Vec<String>,
- pub msgctxt: Option<String>,
- pub msgid: String,
- pub msgstr: String,
- pub line_number: usize,
-}
-
-impl Entry {
- pub fn with_msgid(msgid: impl Into<String>) -> Self {
- Self {
- msgid: msgid.into(),
- ..Self::default()
- }
- }
-
- fn with_line_number(line_number: usize) -> Self {
- Self {
- line_number,
- ..Self::default()
- }
- }
-}
-
-#[derive(Clone, Debug, Eq, PartialEq)]
-pub struct Translation {
- pub msgid: String,
- pub msgstr: String,
- pub msgctxt: Option<String>,
- pub reviewed_unchanged: bool,
- pub notes: String,
-}
-
-impl Translation {
- pub fn new(
- msgctxt: Option<String>,
- msgid: impl Into<String>,
- msgstr: impl Into<String>,
- ) -> Self {
- Self {
- msgid: msgid.into(),
- msgstr: msgstr.into(),
- msgctxt,
- reviewed_unchanged: false,
- notes: String::new(),
- }
- }
-}
-
-pub fn parse_po(content: &str) -> Result<Vec<Entry>> {
- let mut entries = Vec::new();
- let normalized = content.replace("\r\n", "\n");
- let mut current: Option<Entry> = None;
- let mut current_field: Option<Field> = None;
- let mut is_header = true;
-
- for (index, line) in normalized.split('\n').enumerate() {
- if line.starts_with("#. ") || line.starts_with("# ") {
- current
- .get_or_insert_with(|| Entry::with_line_number(index))
- .comments
- .push(line.to_string());
- } else if line.starts_with("#: ") {
- current
- .get_or_insert_with(|| Entry::with_line_number(index))
- .references
- .push(line.to_string());
- } else if let Some(token) = line.strip_prefix("msgctxt ") {
- let entry = current.get_or_insert_with(|| Entry::with_line_number(index));
- entry.msgctxt = Some(parse_po_token(token, index)?);
- current_field = Some(Field::Msgctxt);
- } else if let Some(token) = line.strip_prefix("msgid ") {
- let entry = current.get_or_insert_with(|| Entry::with_line_number(index));
- entry.msgid = parse_po_token(token, index)?;
- current_field = Some(Field::Msgid);
- } else if let Some(token) = line.strip_prefix("msgstr ") {
- let entry = current.get_or_insert_with(|| Entry::with_line_number(index));
- entry.msgstr = parse_po_token(token, index)?;
- current_field = Some(Field::Msgstr);
- } else if line.starts_with('"') && line.ends_with('"') {
- if let (Some(entry), Some(field)) = (current.as_mut(), current_field) {
- let value = parse_po_token(line, index)?;
- match field {
- Field::Msgctxt => {
- if let Some(msgctxt) = entry.msgctxt.as_mut() {
- msgctxt.push_str(&value);
- }
- }
- Field::Msgid => entry.msgid.push_str(&value),
- Field::Msgstr => entry.msgstr.push_str(&value),
- }
- }
- } else if line.is_empty() && current.is_some() {
- let entry = current.take().expect("checked current exists");
- if is_header && entry.msgid.is_empty() {
- is_header = false;
- } else if !entry.msgid.is_empty() {
- entries.push(entry);
- }
- current_field = None;
- }
- }
-
- if let Some(entry) = current
- && !entry.msgid.is_empty()
- {
- entries.push(entry);
- }
-
- Ok(entries)
-}
-
-#[derive(Clone, Copy)]
-enum Field {
- Msgctxt,
- Msgid,
- Msgstr,
-}
-
-pub fn parse_po_token(token: &str, line_number: usize) -> Result<String> {
- let value = serde_json::from_str::<serde_json::Value>(token)
- .with_context(|| format!("Failed to parse PO string on line {}", line_number + 1))?;
- match value {
- serde_json::Value::String(value) => Ok(value),
- _ => bail!("PO string on line {} is not a string", line_number + 1),
- }
-}
-
-pub fn rebuild_po_allow_replacing(content: &str, translations: &[Translation]) -> Result<String> {
- let translation_map = translations
- .iter()
- .map(|translation| {
- Ok((
- entry_key(translation.msgctxt.as_deref(), &translation.msgid)?,
- translation,
- ))
- })
- .collect::<Result<Vec<_>>>()?;
- let normalized = content.replace("\r\n", "\n");
- let trimmed = normalized.trim_end();
- let split_re = Regex::new(r"\n{2,}").expect("valid split regex");
- let blocks = split_re.split(trimmed);
- let mut rebuilt = Vec::new();
- for block in blocks {
- rebuilt.push(rebuild_block_allow_replacing(block, &translation_map)?);
- }
- Ok(format!("{}\n", rebuilt.join("\n\n")))
-}
-
-fn rebuild_block_allow_replacing(
- block: &str,
- translation_map: &[(String, &Translation)],
-) -> Result<String> {
- let lines = block.split('\n').map(str::to_string).collect::<Vec<_>>();
- let Some(msgid_range) = field_range(&lines, "msgid") else {
- return Ok(block.to_string());
- };
- let Some(msgstr_range) = field_range(&lines, "msgstr") else {
- return Ok(block.to_string());
- };
- let msgid = read_field_value(&lines, msgid_range)?;
- let msgctxt = field_range(&lines, "msgctxt")
- .map(|range| read_field_value(&lines, range))
- .transpose()?;
- let key = entry_key(msgctxt.as_deref(), &msgid)?;
- let Some((_, translation)) = translation_map
- .iter()
- .find(|(candidate, _)| *candidate == key)
- else {
- return Ok(block.to_string());
- };
-
- let mut next_lines = lines[..msgstr_range.0].to_vec();
- next_lines.push(format!("msgstr \"{}\"", escape_po(&translation.msgstr)));
- next_lines.extend_from_slice(&lines[msgstr_range.1..]);
- Ok(next_lines.join("\n"))
-}
-
-pub fn reset_po_translations(content: &str) -> Result<String> {
- let translations = parse_po(content)?
- .into_iter()
- .map(|entry| Translation::new(entry.msgctxt, entry.msgid, ""))
- .collect::<Vec<_>>();
- rebuild_po_allow_replacing(content, &translations)
-}
-
-pub fn entry_key(msgctxt: Option<&str>, msgid: &str) -> Result<String> {
- serde_json::to_string(&(msgctxt, msgid)).context("failed to serialize PO entry key")
-}
-
-#[derive(Clone, Copy)]
-struct Range(usize, usize);
-
-fn field_range(lines: &[String], field_name: &str) -> Option<Range> {
- let start = lines
- .iter()
- .position(|line| line.starts_with(&format!("{field_name} ")))?;
- let mut end = start + 1;
- while end < lines.len() && lines[end].starts_with('"') && lines[end].ends_with('"') {
- end += 1;
- }
- Some(Range(start, end))
-}
-
-fn read_field_value(lines: &[String], range: Range) -> Result<String> {
- let Range(start, end) = range;
- let mut value = parse_po_token(
- lines[start]
- .split_once(' ')
- .map(|(_field, token)| token)
- .unwrap_or_default(),
- start,
- )?;
- for (index, line) in lines.iter().enumerate().take(end).skip(start + 1) {
- value.push_str(&parse_po_token(line, index)?);
- }
- Ok(value)
-}
-
-pub fn escape_po(value: &str) -> String {
- value
- .replace('\\', "\\\\")
- .replace('"', "\\\"")
- .replace('\n', "\\n")
- .replace('\t', "\\t")
-}
-
-pub fn extract_translator_comments(entry: &Entry) -> Vec<String> {
- entry
- .comments
- .iter()
- .filter_map(|line| line.strip_prefix("#. "))
- .map(str::trim)
- .filter(|comment| !comment.is_empty() && !is_placeholder_comment(comment))
- .map(str::to_string)
- .collect()
-}
-
-pub fn extract_placeholder_hints(entry: &Entry) -> Vec<String> {
- entry
- .comments
- .iter()
- .filter_map(|line| line.strip_prefix("#. "))
- .map(str::trim)
- .filter(|comment| !comment.is_empty() && is_placeholder_comment(comment))
- .map(str::to_string)
- .collect()
-}
-
-pub fn is_placeholder_comment(comment: &str) -> bool {
- comment.to_lowercase().starts_with("placeholder {") && comment.contains("}:")
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn sample_po() -> &'static str {
- "msgid \"\"\nmsgstr \"\"\n\"Content-Type: text/plain\\n\"\n\n\
- #. Greeting shown on the welcome screen.\n\
- #. placeholder {0}: user.name\n\
- #: src/example.tsx:1\n\
- msgctxt \"welcome title\"\n\
- msgid \"Hello \\\"world\\\"\"\n\
- msgstr \"\"\n\n\
- #. Delete button label.\n\
- #: src/example.tsx:2\n\
- msgctxt \"verb\"\n\
- msgid \"Delete\"\n\
- msgstr \"Delete\"\n\n\
- #: src/example.tsx:3\n\
- msgctxt \"keyboard key\"\n\
- msgid \"Delete\"\n\
- msgstr \"\"\n\n\
- #: src/example.tsx:4\n\
- msgid \"Line one\\n\"\n\
- \"Line two\"\n\
- msgstr \"\"\n"
- }
-
- #[test]
- fn parses_context_comments_duplicates_and_multiline() {
- let entries = parse_po(sample_po()).unwrap();
- assert_eq!(entries.len(), 4);
- let welcome = entries
- .iter()
- .find(|entry| entry.msgctxt.as_deref() == Some("welcome title"))
- .unwrap();
- assert_eq!(welcome.msgid, "Hello \"world\"");
- assert_eq!(
- extract_translator_comments(welcome),
- vec!["Greeting shown on the welcome screen."]
- );
- assert_eq!(
- extract_placeholder_hints(welcome),
- vec!["placeholder {0}: user.name"]
- );
- let multiline = entries
- .iter()
- .find(|entry| entry.msgid.starts_with("Line"))
- .unwrap();
- assert_eq!(multiline.msgid, "Line one\nLine two");
- }
-
- #[test]
- fn rebuilds_by_context() {
- let rebuilt = rebuild_po_allow_replacing(
- sample_po(),
- &[
- Translation::new(
- Some("welcome title".to_string()),
- "Hello \"world\"",
- "Bonjour \"monde\"",
- ),
- Translation::new(Some("verb".to_string()), "Delete", "Supprimer"),
- Translation::new(Some("keyboard key".to_string()), "Delete", "Suppr"),
- ],
- )
- .unwrap();
- let entries = parse_po(&rebuilt).unwrap();
- let msgstr = |msgctxt: &str| {
- entries
- .iter()
- .find(|entry| entry.msgctxt.as_deref() == Some(msgctxt))
- .unwrap()
- .msgstr
- .clone()
- };
- assert_eq!(msgstr("welcome title"), "Bonjour \"monde\"");
- assert_eq!(msgstr("verb"), "Supprimer");
- assert_eq!(msgstr("keyboard key"), "Suppr");
- }
-
- #[test]
- fn untouched_blocks_stay_byte_identical() {
- let content = format!(
- "{}\n#. Audio settings tab.\n#: src/example.tsx:5\nmsgid \"Audio\"\nmsgstr \"Audio\"\n",
- sample_po()
- );
- let rebuilt = rebuild_po_allow_replacing(
- &content,
- &[Translation::new(
- Some("keyboard key".to_string()),
- "Delete",
- "Supprimer",
- )],
- )
- .unwrap();
- let entries = parse_po(&rebuilt).unwrap();
- let verb = entries
- .iter()
- .find(|entry| entry.msgctxt.as_deref() == Some("verb"))
- .unwrap();
- assert_eq!(verb.comments, vec!["#. Delete button label.".to_string()]);
- let audio = entries.iter().find(|entry| entry.msgid == "Audio").unwrap();
- assert_eq!(audio.comments, vec!["#. Audio settings tab.".to_string()]);
- assert_eq!(
- entries
- .iter()
- .find(|entry| entry.msgctxt.as_deref() == Some("keyboard key"))
- .unwrap()
- .msgstr,
- "Supprimer"
- );
- assert_eq!(
- rebuild_po_allow_replacing(&content, &[]).unwrap(),
- format!("{}\n", content.trim_end())
- );
- }
-}
diff --git a/tools/i18n_auto/src/prompts.rs b/tools/i18n_auto/src/prompts.rs
deleted file mode 100644
index aeaa08134..000000000
--- a/tools/i18n_auto/src/prompts.rs
+++ /dev/null
@@ -1,136 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-use std::path::Path;
-
-use anyhow::Result;
-
-use crate::config::{GUIDANCE_EXCERPT_CHAR_LIMIT, locales_dir};
-use crate::locales::display_name;
-
-const GLOBAL_SYSTEM_PROMPT: &str = r#"You localize product UI copy for Fluxer, a modern consumer chat app.
-
-- Preserve the source intent, product function, tone, and authorial wording.
-- Translate only the source string. Context, references, and comments are metadata.
-- Preserve placeholders exactly: {name}, {{count}}, %s, %@, $1, <b>...</b>, Markdown, ICU syntax, emoji, URLs, and line breaks.
-- Preserve source sentence-fragment grammar, including leading ellipses and text that continues prior UI copy.
-- Keep copy concise and natural for product UI, without adding information that is not present in the source.
-- Keep Fluxer's product vocabulary and naming stable unless persisted locale guidance explicitly says otherwise.
-- Avoid embellishing, simplifying, softening, formalising, idiomatic rewrites, or culture-specific substitutions that change the source wording.
-- If the source is ambiguous, choose the most likely chat-app interpretation and keep the result close to the source.
-- Output only the localized string. Do not output JSON, notes, labels, quotes, or Markdown fences."#;
-
-const NON_ENGLISH_SYSTEM_PROMPT: &str = r#"For non-English locales:
-
-- Use target-language grammar, vocabulary, punctuation, and regional conventions.
-- Preserve the capitalisation intention of the source, adapted to target-language conventions.
-- Do not use English-style Title Case unless the target language naturally uses it.
-- Use sentence-style UI capitalisation where appropriate: usually only the first word is capitalised, and parenthesised status labels normally stay lowercase after "(" unless the word is a proper noun.
-- Prefer familiar, friendly, lightweight wording used in popular messaging apps in the target region."#;
-
-const EN_GB_SYSTEM_PROMPT: &str = r#"English (United Kingdom) localisation is a minimal-edit pass over the English (United States) source.
-
-- Keep Fluxer's exact wording, sentence structure, tone, and product vocabulary unless a spelling, punctuation, date, number, measurement, or grammatical locale difference requires a change.
-- Do not replace words with more British-sounding alternatives when the US wording is understandable.
-- Do not translate "US" to "UK", "United States" to "United Kingdom", or change country, region, currency, organisation, or market names unless the source text explicitly asks for that meaning change.
-- Do not add, remove, soften, formalise, idiomatically rewrite, or make the copy more akin to what a Brit would say.
-- Keep our words."#;
-
-pub fn build_system_prompt(locale: &str) -> String {
- [
- Some(format!(
- "You are a professional English (United States) (en-US) to {} ({locale}) translator.",
- display_name(locale)
- )),
- Some(format!(
- "Produce exactly one {} localization for Fluxer.",
- display_name(locale)
- )),
- Some(GLOBAL_SYSTEM_PROMPT.to_string()),
- build_locale_system_prompt(locale),
- ]
- .into_iter()
- .flatten()
- .collect::<Vec<_>>()
- .join("\n\n")
-}
-
-pub fn build_locale_system_prompt(locale: &str) -> Option<String> {
- if locale == "en-GB" {
- Some(EN_GB_SYSTEM_PROMPT.to_string())
- } else if !locale.starts_with("en") {
- Some(NON_ENGLISH_SYSTEM_PROMPT.to_string())
- } else {
- None
- }
-}
-
-pub fn build_target_locale_prompt(locale: &str) -> String {
- format!(
- "Target locale: {}.\nUse the persisted locale guidance below as the source of truth for voice, tone, terminology, punctuation, and regional conventions.",
- display_name(locale)
- )
-}
-
-pub fn load_prompt_guidance(app_dir: &Path, locale: &str) -> Result<Vec<String>> {
- Ok([load_guidance_file(
- &format!("Locale guidance for {}", display_name(locale)),
- &locales_dir(app_dir)
- .join(locale)
- .join("LOCALIZATION_PROMPT.md"),
- )?]
- .into_iter()
- .flatten()
- .collect())
-}
-
-fn load_guidance_file(label: &str, file_path: &Path) -> Result<Option<String>> {
- if !file_path.exists() {
- return Ok(None);
- }
- let excerpt = compact_guidance_excerpt(
- &std::fs::read_to_string(file_path)?,
- GUIDANCE_EXCERPT_CHAR_LIMIT,
- );
- Ok((!excerpt.is_empty()).then(|| format!("{label}:\n{excerpt}")))
-}
-
-pub fn compact_guidance_excerpt(content: &str, limit: usize) -> String {
- let mut compact = content
- .replace("\r\n", "\n")
- .split('\n')
- .map(str::trim)
- .collect::<Vec<_>>()
- .join("\n");
- while compact.contains("\n\n\n") {
- compact = compact.replace("\n\n\n", "\n\n");
- }
- let compact = compact.trim().to_string();
- if compact.len() <= limit {
- return compact;
- }
- let limit = floor_char_boundary(&compact, limit);
- let truncated = &compact[..limit];
- let last_break = [
- truncated.rfind("\n\n"),
- truncated.rfind('\n'),
- truncated.rfind(". "),
- ]
- .into_iter()
- .flatten()
- .max()
- .unwrap_or(0);
- let boundary = if last_break >= limit * 3 / 4 {
- last_break
- } else {
- limit
- };
- format!("{}\n[excerpt truncated]", compact[..boundary].trim_end())
-}
-
-fn floor_char_boundary(value: &str, limit: usize) -> usize {
- let mut boundary = limit.min(value.len());
- while !value.is_char_boundary(boundary) {
- boundary -= 1;
- }
- boundary
-}
diff --git a/tools/i18n_auto/src/reviewed_unchanged.rs b/tools/i18n_auto/src/reviewed_unchanged.rs
deleted file mode 100644
index 29acc4e31..000000000
--- a/tools/i18n_auto/src/reviewed_unchanged.rs
+++ /dev/null
@@ -1,286 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-use std::collections::{BTreeMap, BTreeSet};
-use std::fs::{self, OpenOptions};
-use std::io::ErrorKind;
-use std::path::{Path, PathBuf};
-use std::thread;
-use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
-
-use anyhow::{Context, Result, bail};
-use serde::{Deserialize, Serialize};
-
-const LOCK_TIMEOUT: Duration = Duration::from_secs(30);
-const LOCK_POLL_INTERVAL: Duration = Duration::from_millis(50);
-
-type Locales = BTreeMap<String, Vec<ReviewedUnchangedEntry>>;
-
-#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
-#[serde(from = "StoredEntry", into = "StoredEntry")]
-pub struct ReviewedUnchangedEntry {
- pub msgctxt: Option<String>,
- pub msgid: String,
-}
-
-impl ReviewedUnchangedEntry {
- pub fn new(msgctxt: Option<&str>, msgid: &str) -> Self {
- Self {
- msgctxt: msgctxt.map(str::to_string),
- msgid: msgid.to_string(),
- }
- }
-}
-
-#[derive(Deserialize, Serialize)]
-#[serde(untagged)]
-enum StoredEntry {
- Msgid(String),
- WithContext(String, String),
-}
-
-impl From<StoredEntry> for ReviewedUnchangedEntry {
- fn from(stored: StoredEntry) -> Self {
- match stored {
- StoredEntry::Msgid(msgid) => Self {
- msgctxt: None,
- msgid,
- },
- StoredEntry::WithContext(msgctxt, msgid) => Self {
- msgctxt: Some(msgctxt),
- msgid,
- },
- }
- }
-}
-
-impl From<ReviewedUnchangedEntry> for StoredEntry {
- fn from(entry: ReviewedUnchangedEntry) -> Self {
- match entry.msgctxt {
- Some(msgctxt) => Self::WithContext(msgctxt, entry.msgid),
- None => Self::Msgid(entry.msgid),
- }
- }
-}
-
-pub struct ReviewedUnchangedStore {
- path: PathBuf,
- data: Locales,
- dirty_locales: BTreeSet<String>,
-}
-
-impl ReviewedUnchangedStore {
- pub fn load(path: impl Into<PathBuf>) -> Result<Self> {
- let path = path.into();
- let data = read_store_file(&path)?;
- Ok(Self {
- path,
- data,
- dirty_locales: BTreeSet::new(),
- })
- }
-
- pub fn path(&self) -> &Path {
- &self.path
- }
-
- pub fn contains(&self, locale: &str, msgctxt: Option<&str>, msgid: &str) -> bool {
- let needle = ReviewedUnchangedEntry::new(msgctxt, msgid);
- self.data
- .get(locale)
- .is_some_and(|entries| entries.binary_search(&needle).is_ok())
- }
-
- pub fn mark(&mut self, locale: &str, msgctxt: Option<&str>, msgid: &str) {
- let entry = ReviewedUnchangedEntry::new(msgctxt, msgid);
- let entries = self.data.entry(locale.to_string()).or_default();
- match entries.binary_search(&entry) {
- Ok(_) => {}
- Err(index) => {
- entries.insert(index, entry);
- self.dirty_locales.insert(locale.to_string());
- }
- }
- }
-
- pub fn unmark(&mut self, locale: &str, msgctxt: Option<&str>, msgid: &str) {
- let entry = ReviewedUnchangedEntry::new(msgctxt, msgid);
- let Some(entries) = self.data.get_mut(locale) else {
- return;
- };
- let Ok(index) = entries.binary_search(&entry) else {
- return;
- };
- entries.remove(index);
- if entries.is_empty() {
- self.data.remove(locale);
- }
- self.dirty_locales.insert(locale.to_string());
- }
-
- pub fn locales(&self) -> impl Iterator<Item = (&str, &[ReviewedUnchangedEntry])> {
- self.data
- .iter()
- .map(|(locale, entries)| (locale.as_str(), entries.as_slice()))
- }
-
- pub fn retain_locale(
- &mut self,
- locale: &str,
- mut keep: impl FnMut(&ReviewedUnchangedEntry) -> bool,
- ) -> usize {
- let Some(entries) = self.data.get_mut(locale) else {
- return 0;
- };
- let before = entries.len();
- entries.retain(|entry| keep(entry));
- let removed = before - entries.len();
- if removed == 0 {
- return 0;
- }
- if entries.is_empty() {
- self.data.remove(locale);
- }
- self.dirty_locales.insert(locale.to_string());
- removed
- }
-
- pub fn clear_locale(&mut self, locale: &str) {
- if self.data.remove(locale).is_some() {
- self.dirty_locales.insert(locale.to_string());
- }
- }
-
- pub fn save_if_dirty(&mut self) -> Result<()> {
- if self.dirty_locales.is_empty() {
- return Ok(());
- }
- if let Some(parent) = self.path.parent() {
- fs::create_dir_all(parent)
- .with_context(|| format!("failed to create {}", parent.display()))?;
- }
- let _lock = SidecarLock::acquire(&self.path)?;
- let mut merged = read_store_file(&self.path)?;
- for locale in &self.dirty_locales {
- match self.data.get(locale) {
- Some(entries) if !entries.is_empty() => {
- let mut entries = entries.clone();
- normalize_entries(&mut entries);
- merged.insert(locale.clone(), entries);
- }
- _ => {
- merged.remove(locale);
- }
- }
- }
- write_store_file(&self.path, &merged)?;
- self.data = merged;
- self.dirty_locales.clear();
- Ok(())
- }
-}
-
-fn read_store_file(path: &Path) -> Result<Locales> {
- let content = match fs::read_to_string(path) {
- Ok(content) => content,
- Err(error) if error.kind() == ErrorKind::NotFound => {
- return Ok(Locales::new());
- }
- Err(error) => {
- return Err(error).with_context(|| format!("failed to read {}", path.display()));
- }
- };
- let mut data = serde_json::from_str::<Locales>(&content)
- .with_context(|| format!("failed to parse {}", path.display()))?;
- for entries in data.values_mut() {
- normalize_entries(entries);
- }
- data.retain(|_, entries| !entries.is_empty());
- Ok(data)
-}
-
-fn normalize_entries(entries: &mut Vec<ReviewedUnchangedEntry>) {
- entries.sort();
- entries.dedup();
-}
-
-fn render_store(data: &Locales) -> Result<String> {
- let mut locales = Vec::with_capacity(data.len());
- for (locale, entries) in data {
- let mut lines = Vec::with_capacity(entries.len());
- for entry in entries {
- lines.push(format!("\t\t{}", serde_json::to_string(entry)?));
- }
- locales.push(format!(
- "\t{}: [\n{}\n\t]",
- serde_json::to_string(locale)?,
- lines.join(",\n")
- ));
- }
- if locales.is_empty() {
- return Ok("{}\n".to_string());
- }
- Ok(format!("{{\n{}\n}}\n", locales.join(",\n")))
-}
-
-fn write_store_file(path: &Path, data: &Locales) -> Result<()> {
- let content =
- render_store(data).with_context(|| format!("failed to serialize {}", path.display()))?;
- let timestamp = SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .unwrap_or_default()
- .as_nanos();
- let temp_path = path.with_file_name(format!(
- ".{}.{}.{}.tmp",
- path.file_name()
- .and_then(|name| name.to_str())
- .unwrap_or("auto-i18n-reviewed-unchanged.json"),
- std::process::id(),
- timestamp
- ));
- fs::write(&temp_path, content)
- .with_context(|| format!("failed to write {}", temp_path.display()))?;
- fs::rename(&temp_path, path)
- .with_context(|| format!("failed to replace {}", path.display()))?;
- Ok(())
-}
-
-struct SidecarLock {
- path: PathBuf,
-}
-
-impl SidecarLock {
- fn acquire(sidecar_path: &Path) -> Result<Self> {
- let lock_path = sidecar_path.with_extension("json.lock");
- let started = Instant::now();
- loop {
- match OpenOptions::new()
- .write(true)
- .create_new(true)
- .open(&lock_path)
- {
- Ok(_) => {
- return Ok(Self { path: lock_path });
- }
- Err(error) if error.kind() == ErrorKind::AlreadyExists => {
- if started.elapsed() >= LOCK_TIMEOUT {
- bail!(
- "timed out waiting for reviewed-unchanged sidecar lock {}",
- lock_path.display()
- );
- }
- thread::sleep(LOCK_POLL_INTERVAL);
- }
- Err(error) => {
- return Err(error)
- .with_context(|| format!("failed to create {}", lock_path.display()));
- }
- }
- }
- }
-}
-
-impl Drop for SidecarLock {
- fn drop(&mut self) {
- let _ = fs::remove_file(&self.path);
- }
-}
diff --git a/tools/i18n_auto/src/runner.rs b/tools/i18n_auto/src/runner.rs
deleted file mode 100644
index a798b6fb2..000000000
--- a/tools/i18n_auto/src/runner.rs
+++ /dev/null
@@ -1,2059 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-use std::collections::HashSet;
-use std::fs;
-use std::path::{Path, PathBuf};
-use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
-
-use anyhow::{Context, Result, bail};
-use clap::{Parser, ValueEnum};
-use regex::Regex;
-use serde_json::{Map, Value, json};
-
-use crate::config::{
- AUTO_I18N_REVIEWED_UNCHANGED_FILE, DEFAULT_LOCALE_CONCURRENCY, DEFAULT_OPENROUTER_APP_TITLE,
- DEFAULT_OPENROUTER_BASE_URL, DEFAULT_OPENROUTER_FALLBACK_MODELS,
- DEFAULT_OPENROUTER_HTTP_REFERER, DEFAULT_OPENROUTER_MODEL, DEFAULT_OPENROUTER_PROVIDER_SORT,
- DEFAULT_PROGRESS_INTERVAL_SECONDS, DEFAULT_REQUEST_TIMEOUT_SECONDS, DEFAULT_STRING_CONCURRENCY,
- EmptyFallback, EnvOverlay, SOURCE_LOCALE, default_app_dir, env_value, locales_dir,
- positive_float_env, positive_int_env, trim_trailing_slash,
-};
-use crate::json_catalog::{
- StaticJsonCatalogConfig, read_static_json_entries, rebuild_static_json_allow_replacing,
- reset_static_json_translations,
-};
-use crate::llm::{LocalizationClient, base_options};
-use crate::locales::{display_name, is_supported_locale};
-use crate::openrouter::{
- OpenRouterClient, OpenRouterClientConfig, parse_openrouter_fallback_models,
-};
-use crate::po::{
- Entry, Translation, extract_placeholder_hints, extract_translator_comments, parse_po,
- rebuild_po_allow_replacing, reset_po_translations,
-};
-use crate::prompts::{build_system_prompt, build_target_locale_prompt, load_prompt_guidance};
-use crate::reviewed_unchanged::ReviewedUnchangedStore;
-use crate::tokens::{
- TokenAlias, build_masked_source, build_token_alias_context, extract_icu_controls,
- extract_preserved_tokens, has_icu_control, mask_text_with_aliases,
- normalize_localized_capitalization, restore_masked_tokens, should_keep_unchanged,
- validate_locale_specific_localization, validate_localization,
-};
-use crate::ts_catalog::StaticTsCatalogKind;
-
-const FULL_TRANSLATION_ATTEMPTS: usize = 3;
-const SEGMENT_TRANSLATION_ATTEMPTS: usize = 2;
-const POLISH_TRANSLATION_ATTEMPTS: usize = 2;
-
-#[derive(Clone, Debug, Eq, PartialEq)]
-pub struct TranslateArgs {
- pub all: bool,
- pub batch_size: usize,
- pub catalog: CatalogName,
- pub dry_run: bool,
- pub limit: Option<usize>,
- pub locales: Vec<String>,
- pub msgctxts: Vec<String>,
- pub refresh_source_equal: bool,
- pub reset: bool,
- pub string_concurrency: usize,
- pub locale_concurrency: usize,
- pub progress_interval: Duration,
-}
-
-#[derive(Clone, Debug, Eq, PartialEq)]
-pub enum CatalogLayout {
- NestedMessages,
- StaticJson(StaticJsonCatalogConfig),
-}
-
-#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
-pub enum CatalogName {
- #[value(name = "app")]
- App,
- #[value(name = "errors")]
- Errors,
- #[value(name = "api-content", alias = "content")]
- ApiContent,
- #[value(name = "email", alias = "emails")]
- Email,
-}
-
-impl CatalogName {
- fn label(self) -> &'static str {
- match self {
- CatalogName::App => "app",
- CatalogName::Errors => "errors",
- CatalogName::ApiContent => "api-content",
- CatalogName::Email => "email",
- }
- }
-}
-
-#[derive(Clone, Debug)]
-pub struct RuntimeConfig {
- pub app_dir: PathBuf,
- pub catalog_layout: CatalogLayout,
- pub locales_dir: PathBuf,
- pub reviewed_unchanged_path: PathBuf,
- pub openrouter_api_key: String,
- pub openrouter_app_title: String,
- pub openrouter_base_url: String,
- pub openrouter_fallback_models: Vec<String>,
- pub openrouter_http_referer: String,
- pub openrouter_model: String,
- pub openrouter_provider_sort: String,
- pub request_timeout_seconds: f64,
-}
-
-#[derive(Clone, Debug, Eq, PartialEq)]
-pub struct CatalogPaths {
- pub locales_dir: PathBuf,
- pub catalog_layout: CatalogLayout,
- pub reviewed_unchanged_path: PathBuf,
-}
-
-pub fn catalog_paths(app_dir: &Path, catalog: CatalogName) -> CatalogPaths {
- let repo_root = app_dir
- .parent()
- .map(Path::to_path_buf)
- .unwrap_or_else(|| PathBuf::from("."));
- match catalog {
- CatalogName::App => {
- let locales_dir = locales_dir(app_dir);
- CatalogPaths {
- reviewed_unchanged_path: locales_dir.join(AUTO_I18N_REVIEWED_UNCHANGED_FILE),
- locales_dir,
- catalog_layout: CatalogLayout::NestedMessages,
- }
- }
- CatalogName::Errors => static_json_catalog_paths(
- repo_root
- .join("packages")
- .join("errors")
- .join("src")
- .join("i18n"),
- StaticTsCatalogKind::SimpleMessages,
- ),
- CatalogName::ApiContent => static_json_catalog_paths(
- repo_root
- .join("fluxer_api")
- .join("src")
- .join("api")
- .join("content_i18n"),
- StaticTsCatalogKind::SimpleMessages,
- ),
- CatalogName::Email => static_json_catalog_paths(
- repo_root
- .join("fluxer_api")
- .join("pkgs")
- .join("email")
- .join("src")
- .join("email_i18n"),
- StaticTsCatalogKind::EmailTemplates,
- ),
- }
-}
-
-fn static_json_catalog_paths(i18n_dir: PathBuf, kind: StaticTsCatalogKind) -> CatalogPaths {
- let weblate_dir = i18n_dir.join("weblate");
- CatalogPaths {
- locales_dir: weblate_dir.join("locales"),
- catalog_layout: CatalogLayout::StaticJson(StaticJsonCatalogConfig {
- kind,
- source_path: weblate_dir.join("messages.json"),
- }),
- reviewed_unchanged_path: i18n_dir
- .join("locales")
- .join(AUTO_I18N_REVIEWED_UNCHANGED_FILE),
- }
-}
-
-impl RuntimeConfig {
- pub fn from_env(env_overrides: &EnvOverlay, catalog: CatalogName) -> Self {
- let app_dir = default_app_dir();
- let CatalogPaths {
- locales_dir,
- catalog_layout,
- reviewed_unchanged_path,
- } = catalog_paths(&app_dir, catalog);
- let openrouter_base_url = trim_trailing_slash(&env_value(
- "OPENROUTER_BASE_URL",
- env_overrides,
- DEFAULT_OPENROUTER_BASE_URL,
- ));
- let openrouter_model = env_value("I18N_LLM_MODEL", env_overrides, "")
- .if_empty(|| env_value("OPENROUTER_MODEL", env_overrides, DEFAULT_OPENROUTER_MODEL));
- let openrouter_api_key = env_value("OPENROUTER_API_KEY", env_overrides, "");
- let openrouter_fallback_models = parse_openrouter_fallback_models(&env_value(
- "OPENROUTER_FALLBACK_MODELS",
- env_overrides,
- DEFAULT_OPENROUTER_FALLBACK_MODELS,
- ));
- let openrouter_provider_sort = env_value(
- "OPENROUTER_PROVIDER_SORT",
- env_overrides,
- DEFAULT_OPENROUTER_PROVIDER_SORT,
- );
- let openrouter_http_referer = env_value(
- "OPENROUTER_HTTP_REFERER",
- env_overrides,
- DEFAULT_OPENROUTER_HTTP_REFERER,
- );
- let openrouter_app_title = env_value(
- "OPENROUTER_APP_TITLE",
- env_overrides,
- DEFAULT_OPENROUTER_APP_TITLE,
- );
- let request_timeout_seconds = positive_float_env(
- "FLUXER_AUTO_I18N_REQUEST_TIMEOUT",
- DEFAULT_REQUEST_TIMEOUT_SECONDS,
- env_overrides,
- );
- Self {
- app_dir,
- catalog_layout,
- locales_dir,
- reviewed_unchanged_path,
- openrouter_api_key,
- openrouter_app_title,
- openrouter_base_url,
- openrouter_fallback_models,
- openrouter_http_referer,
- openrouter_model,
- openrouter_provider_sort,
- request_timeout_seconds,
- }
- }
-}
-
-#[derive(Clone, Debug, Eq, PartialEq)]
-pub struct LocaleResult {
- pub locale: String,
- pub translated: usize,
- pub errors: usize,
-}
-
-#[derive(Clone, Debug, Eq, PartialEq)]
-pub struct LocalePlan {
- pub locale: String,
- pub pending: usize,
- pub selected: usize,
-}
-
-#[derive(Clone, Debug)]
-pub struct Prompt {
- pub system_prompt: String,
- pub user_prompt: String,
- pub token_aliases: Vec<TokenAlias>,
-}
-
-#[derive(Parser, Debug)]
-#[command(about = "Translate Lingui PO catalogs with an LLM provider.")]
-struct RawTranslateArgs {
- #[arg(long, help = "Process all non-source locales")]
- all: bool,
- #[arg(long = "locale", help = "Process one locale; repeatable")]
- locales: Vec<String>,
- #[arg(
- long,
- value_enum,
- help = "Catalog target to translate: app, errors, api-content, or email"
- )]
- catalog: Option<CatalogName>,
- #[arg(
- long = "msgctxt",
- help = "Only translate entries with this PO msgctxt or static catalog key; repeatable. Email fields use <template>.<subject|body>."
- )]
- msgctxts: Vec<String>,
- #[arg(
- long,
- help = "Clear msgstr values before translating selected locale(s)"
- )]
- reset: bool,
- #[arg(
- long,
- help = "Clear msgstr values before translating every non-source locale"
- )]
- reset_all: bool,
- #[arg(
- long,
- help = "Translate at most n strings per locale for staged review"
- )]
- limit: Option<i64>,
- #[arg(
- long,
- help = "Translate up to n strings in one validated LLM request; falls back per string on batch failures"
- )]
- batch_size: Option<usize>,
- #[arg(
- long,
- help = "Re-translate existing non-English strings that still equal the source"
- )]
- refresh_source_equal: bool,
- #[arg(long)]
- string_concurrency: Option<usize>,
- #[arg(long)]
- locale_concurrency: Option<usize>,
- #[arg(long)]
- progress_interval: Option<f64>,
- #[arg(long)]
- dry_run: bool,
-}
-
-pub fn translate_main(argv: &[String], env_overrides: &EnvOverlay) -> Result<u8> {
- let raw = match RawTranslateArgs::try_parse_from(
- std::iter::once("i18n-auto").chain(argv.iter().map(String::as_str)),
- ) {
- Ok(raw) => raw,
- Err(error) => {
- error.print()?;
- return Ok(error.exit_code() as u8);
- }
- };
- let args = normalize_args(raw, env_overrides)?;
- let config = RuntimeConfig::from_env(env_overrides, args.catalog);
- run_translation(&config, &args)
-}
-
-fn normalize_args(raw: RawTranslateArgs, env_overrides: &EnvOverlay) -> Result<TranslateArgs> {
- if let Some(limit) = raw.limit
- && limit < 0
- {
- bail!("--limit must be a non-negative integer");
- }
- let progress_interval_seconds = raw.progress_interval.unwrap_or_else(|| {
- positive_float_env(
- "FLUXER_AUTO_I18N_PROGRESS_INTERVAL",
- DEFAULT_PROGRESS_INTERVAL_SECONDS,
- env_overrides,
- )
- });
- if progress_interval_seconds <= 0.0 {
- bail!("--progress-interval must be greater than zero");
- }
- let mut all = raw.all;
- let mut reset = raw.reset;
- if raw.reset_all {
- reset = true;
- all = true;
- }
- let catalog = raw.catalog.unwrap_or(CatalogName::App);
- if !all && raw.locales.is_empty() {
- all = true;
- }
- Ok(TranslateArgs {
- all,
- batch_size: raw.batch_size.unwrap_or(1).max(1),
- catalog,
- dry_run: raw.dry_run,
- limit: raw.limit.map(|limit| limit as usize),
- locales: raw.locales,
- msgctxts: raw.msgctxts,
- refresh_source_equal: raw.refresh_source_equal,
- reset,
- string_concurrency: raw
- .string_concurrency
- .unwrap_or_else(|| {
- positive_int_env(
- "FLUXER_AUTO_I18N_STRING_CONCURRENCY",
- DEFAULT_STRING_CONCURRENCY,
- env_overrides,
- )
- })
- .max(1),
- locale_concurrency: raw
- .locale_concurrency
- .unwrap_or_else(|| {
- positive_int_env(
- "FLUXER_AUTO_I18N_LOCALE_CONCURRENCY",
- DEFAULT_LOCALE_CONCURRENCY,
- env_overrides,
- )
- })
- .max(1),
- progress_interval: Duration::from_secs_f64(progress_interval_seconds),
- })
-}
-
-pub fn run_translation(config: &RuntimeConfig, args: &TranslateArgs) -> Result<u8> {
- let locales = select_locales(config, args)?;
- let client = new_runtime_client(config)?;
- log("Starting i18n translation...", false);
- log(&format!("Catalog target: {}", args.catalog.label()), false);
- log("LLM provider: openrouter", false);
- log(
- &format!("Locales directory: {}", config.locales_dir.display()),
- false,
- );
- log(
- &format!(
- "Catalog layout: {}",
- match &config.catalog_layout {
- CatalogLayout::NestedMessages => "nested messages.po",
- CatalogLayout::StaticJson(_) => "weblate JSON locale catalog",
- }
- ),
- false,
- );
- if let CatalogLayout::StaticJson(static_config) = &config.catalog_layout {
- log(
- &format!("Source catalog: {}", static_config.source_path.display()),
- false,
- );
- }
- log(&format!("Model: {}", client.model()), false);
- log(&format!("LLM endpoint: {}", client.base_url()), false);
- log(
- &format!(
- "LLM request timeout: {}s",
- format_float(client.request_timeout_seconds())
- ),
- false,
- );
- log(&format!("Locales: {}", locales.join(", ")), false);
- log(
- &format!(
- "Requested concurrency: {} locales, {} strings per locale",
- args.locale_concurrency, args.string_concurrency
- ),
- false,
- );
- log(
- &format!(
- "Progress interval: {}s",
- format_float(args.progress_interval.as_secs_f64())
- ),
- false,
- );
- if let Some(limit) = args.limit {
- log(&format!("Limit: {limit} strings per locale"), false);
- }
- if args.batch_size > 1 {
- log(
- &format!("Batch size: {} strings per LLM request", args.batch_size),
- false,
- );
- }
- if !args.msgctxts.is_empty() {
- log(
- &format!("Msgctxt filter: {}", args.msgctxts.join(", ")),
- false,
- );
- }
- if args.refresh_source_equal {
- log("Refresh source-equal strings: enabled", false);
- }
- if args.reset {
- log("Reset mode: enabled", false);
- }
- if args.dry_run {
- log("Dry run: enabled", false);
- }
- let plans = locales
- .iter()
- .map(|locale| build_locale_plan(config, locale, args))
- .collect::<Result<Vec<_>>>()?;
- log_translation_plan(&plans);
- let started = Instant::now();
- let mut results = Vec::new();
- let locale_concurrency = args.locale_concurrency.max(1);
- for chunk in locales.chunks(locale_concurrency) {
- if chunk.len() == 1 {
- results.push(process_locale(config, &client, &chunk[0], args)?);
- continue;
- }
- let chunk_results = std::thread::scope(|scope| {
- let handles = chunk
- .iter()
- .map(|locale| {
- scope.spawn(move || {
- let client = new_runtime_client(config)?;
- process_locale(config, &client, locale, args)
- })
- })
- .collect::<Vec<_>>();
- let mut chunk_results = Vec::with_capacity(handles.len());
- for handle in handles {
- chunk_results.push(
- handle
- .join()
- .map_err(|_| anyhow::anyhow!("i18n locale worker panicked"))??,
- );
- }
- Ok::<_, anyhow::Error>(chunk_results)
- })?;
- results.extend(chunk_results);
- }
- let total_translated = results
- .iter()
- .map(|result| result.translated)
- .sum::<usize>();
- let total_errors = results.iter().map(|result| result.errors).sum::<usize>();
- log(
- &format!(
- "\nTranslation complete in {:.1}s",
- started.elapsed().as_secs_f64()
- ),
- false,
- );
- log(
- &format!("Total: {total_translated} strings translated, {total_errors} errors"),
- false,
- );
- Ok(if total_errors > 0 { 1 } else { 0 })
-}
-
-fn new_runtime_client(config: &RuntimeConfig) -> Result<OpenRouterClient> {
- OpenRouterClient::new(OpenRouterClientConfig {
- base_url: config.openrouter_base_url.clone(),
- model: config.openrouter_model.clone(),
- fallback_models: config.openrouter_fallback_models.clone(),
- provider_sort: config.openrouter_provider_sort.clone(),
- http_referer: config.openrouter_http_referer.clone(),
- app_title: config.openrouter_app_title.clone(),
- api_key: config.openrouter_api_key.clone(),
- request_timeout_seconds: config.request_timeout_seconds,
- })
-}
-
-pub fn select_locales(config: &RuntimeConfig, args: &TranslateArgs) -> Result<Vec<String>> {
- let available_locales = available_locales(config)?;
- let locales = if args.all {
- available_locales
- } else {
- args.locales.clone()
- };
- for locale in &locales {
- if locale != SOURCE_LOCALE && !is_supported_locale(locale) {
- bail!("Unsupported locale: {locale}");
- }
- }
- Ok(locales)
-}
-
-fn available_locales(config: &RuntimeConfig) -> Result<Vec<String>> {
- let mut locales = Vec::new();
- for entry in fs::read_dir(&config.locales_dir)
- .with_context(|| format!("failed to read {}", config.locales_dir.display()))?
- {
- let entry = entry?;
- let locale = match &config.catalog_layout {
- CatalogLayout::NestedMessages => {
- if !entry.file_type()?.is_dir() {
- continue;
- }
- entry.file_name().to_string_lossy().to_string()
- }
- CatalogLayout::StaticJson(_) => {
- let path = entry.path();
- if path.extension().and_then(|ext| ext.to_str()) != Some("json") {
- continue;
- }
- let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else {
- continue;
- };
- stem.to_string()
- }
- };
- if locale != SOURCE_LOCALE && is_supported_locale(&locale) {
- locales.push(locale);
- }
- }
- locales.sort();
- Ok(locales)
-}
-
-fn should_translate_entry_with_reviewed_unchanged(
- entry: &Entry,
- locale: &str,
- args: &TranslateArgs,
- reviewed_unchanged: bool,
-) -> bool {
- if !args.msgctxts.is_empty()
- && !entry
- .msgctxt
- .as_ref()
- .is_some_and(|msgctxt| args.msgctxts.contains(msgctxt))
- {
- return false;
- }
- if entry.msgstr.is_empty() {
- return true;
- }
- if args.refresh_source_equal
- && refreshes_source_equal_locale(locale, args)
- && entry.msgstr == entry.msgid
- && !reviewed_unchanged
- {
- return !should_keep_unchanged(&entry.msgid, locale);
- }
- false
-}
-
-fn refreshes_source_equal_locale(locale: &str, args: &TranslateArgs) -> bool {
- locale != "en-GB" || (!args.all && args.locales.iter().any(|selected| selected == locale))
-}
-
-fn prune_reviewed_unchanged(
- store: &mut ReviewedUnchangedStore,
- locale: &str,
- entries: &[Entry],
-) -> usize {
- let unchanged = entries
- .iter()
- .filter(|entry| entry.msgstr == entry.msgid)
- .map(|entry| (entry.msgctxt.as_deref(), entry.msgid.as_str()))
- .collect::<HashSet<_>>();
- store.retain_locale(locale, |entry| {
- unchanged.contains(&(entry.msgctxt.as_deref(), entry.msgid.as_str()))
- })
-}
-
-pub fn build_locale_plan(
- config: &RuntimeConfig,
- locale: &str,
- args: &TranslateArgs,
-) -> Result<LocalePlan> {
- if locale == SOURCE_LOCALE {
- return Ok(LocalePlan {
- locale: locale.to_string(),
- pending: 0,
- selected: 0,
- });
- }
- let catalog_path = catalog_path(config, locale);
- let entries = read_catalog_entries(config, &catalog_path, args.reset)?;
- let reviewed_unchanged = ReviewedUnchangedStore::load(&config.reviewed_unchanged_path)?;
- let pending = entries
- .iter()
- .filter(|entry| {
- should_translate_entry_with_reviewed_unchanged(
- entry,
- locale,
- args,
- reviewed_unchanged.contains(locale, entry.msgctxt.as_deref(), &entry.msgid),
- )
- })
- .count();
- let selected = args.limit.map_or(pending, |limit| pending.min(limit));
- Ok(LocalePlan {
- locale: locale.to_string(),
- pending,
- selected,
- })
-}
-
-fn log_translation_plan(plans: &[LocalePlan]) {
- let total_pending = plans.iter().map(|plan| plan.pending).sum::<usize>();
- let total_selected = plans.iter().map(|plan| plan.selected).sum::<usize>();
- let active_locale_count = plans.iter().filter(|plan| plan.selected > 0).count();
- log(
- &format!(
- "Planned work: {total_selected} selected strings across {active_locale_count} locale(s) ({total_pending} pending before limit)"
- ),
- false,
- );
- let non_empty = plans
- .iter()
- .filter(|plan| plan.pending > 0)
- .map(|plan| format!("{}={}", plan.locale, plan.pending))
- .collect::<Vec<_>>();
- if !non_empty.is_empty() {
- log(
- &format!("Pending by locale: {}", non_empty.join(", ")),
- false,
- );
- }
-}
-
-pub fn process_locale<C: LocalizationClient>(
- config: &RuntimeConfig,
- client: &C,
- locale: &str,
- args: &TranslateArgs,
-) -> Result<LocaleResult> {
- let catalog_path = catalog_path(config, locale);
- if locale == SOURCE_LOCALE {
- return sync_source_locale(config, &catalog_path, args);
- }
- log(
- &format!(
- "[{locale}] Starting with {} via {}...",
- client.model(),
- client.base_url()
- ),
- false,
- );
- let prompt_guidance = load_prompt_guidance(&config.app_dir, locale)?;
- let mut content = fs::read_to_string(&catalog_path)
- .with_context(|| format!("failed to read {}", catalog_path.display()))?;
- let mut reviewed_unchanged = ReviewedUnchangedStore::load(&config.reviewed_unchanged_path)?;
- if args.reset {
- content = reset_catalog_translations(config, &content)?;
- if !args.dry_run {
- write_file_atomic(&catalog_path, &content)?;
- reviewed_unchanged.clear_locale(locale);
- reviewed_unchanged.save_if_dirty().with_context(|| {
- format!(
- "failed to update reviewed-unchanged sidecar {}",
- reviewed_unchanged.path().display()
- )
- })?;
- }
- log(&format!("[{locale}] Reset catalog translations"), false);
- }
- let entries = read_catalog_entries_from_content(config, &content, false)?;
- if !args.dry_run {
- let pruned = prune_reviewed_unchanged(&mut reviewed_unchanged, locale, &entries);
- if pruned > 0 {
- reviewed_unchanged.save_if_dirty().with_context(|| {
- format!(
- "failed to update reviewed-unchanged sidecar {}",
- reviewed_unchanged.path().display()
- )
- })?;
- log(
- &format!("[{locale}] Pruned {pruned} stale reviewed-unchanged entries"),
- false,
- );
- }
- }
- let pending = entries
- .into_iter()
- .filter(|entry| {
- should_translate_entry_with_reviewed_unchanged(
- entry,
- locale,
- args,
- reviewed_unchanged.contains(locale, entry.msgctxt.as_deref(), &entry.msgid),
- )
- })
- .collect::<Vec<_>>();
- let limit = args.limit.unwrap_or(pending.len());
- let limited = pending.iter().take(limit).cloned().collect::<Vec<_>>();
- if limited.is_empty() {
- log(&format!("[{locale}] No strings to translate"), false);
- return Ok(LocaleResult {
- locale: locale.to_string(),
- translated: 0,
- errors: 0,
- });
- }
- log(
- &format!(
- "[{locale}] Translating {}/{} pending strings",
- limited.len(),
- pending.len()
- ),
- false,
- );
- let mut current_content = content;
- let process_context = ProcessContext {
- config,
- client,
- locale,
- prompt_guidance: &prompt_guidance,
- catalog_path: &catalog_path,
- args,
- };
- let (translated, errors) = if args.batch_size > 1 {
- process_batches(
- &process_context,
- &mut current_content,
- &limited,
- &mut reviewed_unchanged,
- )?
- } else {
- process_strings(
- &process_context,
- &mut current_content,
- &limited,
- &mut reviewed_unchanged,
- )?
- };
- Ok(LocaleResult {
- locale: locale.to_string(),
- translated,
- errors,
- })
-}
-
-struct StringOutcome {
- index: usize,
- entry: Entry,
- elapsed: Duration,
- result: Result<Translation>,
-}
-
-struct BatchOutcome {
- chunk_index: usize,
- start_index: usize,
- len: usize,
- elapsed: Duration,
- translations: Vec<Translation>,
- warnings: Vec<String>,
- errors: Vec<String>,
-}
-
-struct ProcessContext<'a, C: LocalizationClient> {
- config: &'a RuntimeConfig,
- client: &'a C,
- locale: &'a str,
- prompt_guidance: &'a [String],
- catalog_path: &'a Path,
- args: &'a TranslateArgs,
-}
-
-fn process_strings<C: LocalizationClient>(
- context: &ProcessContext<'_, C>,
- current_content: &mut String,
- entries: &[Entry],
- reviewed_unchanged: &mut ReviewedUnchangedStore,
-) -> Result<(usize, usize)> {
- let mut translated = 0;
- let mut errors = 0;
- let concurrency = context.args.string_concurrency.max(1);
- for (window_index, window) in entries.chunks(concurrency).enumerate() {
- let window_start = window_index * concurrency;
- let mut outcomes = std::thread::scope(|scope| {
- let handles = window
- .iter()
- .enumerate()
- .map(|(offset, entry)| {
- scope.spawn(move || {
- let started = Instant::now();
- let result = localize_string(
- context.client,
- entry,
- context.locale,
- context.prompt_guidance,
- );
- StringOutcome {
- index: window_start + offset,
- entry: entry.clone(),
- elapsed: started.elapsed(),
- result,
- }
- })
- })
- .collect::<Vec<_>>();
- let mut outcomes = Vec::with_capacity(handles.len());
- for handle in handles {
- outcomes.push(
- handle
- .join()
- .map_err(|_| anyhow::anyhow!("i18n string worker panicked"))?,
- );
- }
- Ok::<_, anyhow::Error>(outcomes)
- })?;
- outcomes.sort_by_key(|outcome| outcome.index);
- let translations = outcomes
- .iter()
- .filter_map(|outcome| outcome.result.as_ref().ok())
- .cloned()
- .collect::<Vec<_>>();
- if !translations.is_empty() && !context.args.dry_run {
- *current_content =
- rebuild_catalog_allow_replacing(context.config, current_content, &translations)?;
- write_file_atomic(context.catalog_path, current_content)?;
- record_reviewed_unchanged_translations(
- reviewed_unchanged,
- context.locale,
- &translations,
- );
- reviewed_unchanged.save_if_dirty().with_context(|| {
- format!(
- "failed to update reviewed-unchanged sidecar {}",
- reviewed_unchanged.path().display()
- )
- })?;
- }
- for outcome in outcomes {
- match outcome.result {
- Ok(translation) => {
- translated += 1;
- if !translation.notes.is_empty() {
- log(
- &format!(
- "[{}] Note for {:?}: {}",
- context.locale, outcome.entry.msgid, translation.notes
- ),
- false,
- );
- }
- let action = if context.args.dry_run {
- "completed"
- } else {
- "saved"
- };
- let queued = entries.len().saturating_sub(outcome.index + 1);
- let active = window
- .len()
- .saturating_sub(outcome.index.saturating_sub(window_start) + 1);
- log(
- &format!(
- "[{}] {}/{} {action} in {} ({} done, {} errors, {} active, {} queued)",
- context.locale,
- outcome.index + 1,
- entries.len(),
- format_duration(outcome.elapsed),
- translated,
- errors,
- active,
- queued
- ),
- false,
- );
- }
- Err(error) => {
- errors += 1;
- let queued = entries.len().saturating_sub(outcome.index + 1);
- let active = window
- .len()
- .saturating_sub(outcome.index.saturating_sub(window_start) + 1);
- log(
- &format!(
- "[{}] {:?} error after {}: {error} ({} done, {} errors, {} active, {} queued)",
- context.locale,
- outcome.entry.msgid,
- format_duration(outcome.elapsed),
- translated,
- errors,
- active,
- queued
- ),
- true,
- );
- }
- }
- }
- }
- Ok((translated, errors))
-}
-
-fn record_reviewed_unchanged_translations(
- store: &mut ReviewedUnchangedStore,
- locale: &str,
- translations: &[Translation],
-) {
- for translation in translations {
- if translation.reviewed_unchanged {
- store.mark(locale, translation.msgctxt.as_deref(), &translation.msgid);
- } else {
- store.unmark(locale, translation.msgctxt.as_deref(), &translation.msgid);
- }
- }
-}
-
-fn process_batches<C: LocalizationClient>(
- context: &ProcessContext<'_, C>,
- current_content: &mut String,
- entries: &[Entry],
- reviewed_unchanged: &mut ReviewedUnchangedStore,
-) -> Result<(usize, usize)> {
- let mut translated = 0;
- let mut errors = 0;
- let batch_concurrency = (context.args.string_concurrency / context.args.batch_size).max(1);
- let chunks = entries.chunks(context.args.batch_size).collect::<Vec<_>>();
- for (window_index, window) in chunks.chunks(batch_concurrency).enumerate() {
- let window_start = window_index * batch_concurrency;
- let mut outcomes = std::thread::scope(|scope| {
- let handles = window
- .iter()
- .enumerate()
- .map(|(offset, chunk)| {
- let chunk_index = window_start + offset;
- scope.spawn(move || {
- localize_batch_chunk(
- context.client,
- chunk,
- context.locale,
- context.prompt_guidance,
- chunk_index,
- chunk_index * context.args.batch_size,
- )
- })
- })
- .collect::<Vec<_>>();
- let mut outcomes = Vec::with_capacity(handles.len());
- for handle in handles {
- outcomes.push(
- handle
- .join()
- .map_err(|_| anyhow::anyhow!("i18n batch worker panicked"))?,
- );
- }
- Ok::<_, anyhow::Error>(outcomes)
- })?;
- outcomes.sort_by_key(|outcome| outcome.start_index);
- let translations = outcomes
- .iter()
- .flat_map(|outcome| outcome.translations.iter().cloned())
- .collect::<Vec<_>>();
- if !translations.is_empty() && !context.args.dry_run {
- *current_content =
- rebuild_catalog_allow_replacing(context.config, current_content, &translations)?;
- write_file_atomic(context.catalog_path, current_content)?;
- record_reviewed_unchanged_translations(
- reviewed_unchanged,
- context.locale,
- &translations,
- );
- reviewed_unchanged.save_if_dirty().with_context(|| {
- format!(
- "failed to update reviewed-unchanged sidecar {}",
- reviewed_unchanged.path().display()
- )
- })?;
- }
- for outcome in outcomes {
- for warning in &outcome.warnings {
- log(warning, true);
- }
- for error in &outcome.errors {
- log(error, true);
- }
- translated += outcome.translations.len();
- errors += outcome.errors.len();
- let action = if context.args.dry_run {
- "completed"
- } else {
- "saved"
- };
- let completed = outcome.start_index + outcome.len;
- let active = window
- .len()
- .saturating_sub(outcome.chunk_index.saturating_sub(window_start) + 1);
- log(
- &format!(
- "[{}] {}/{} {action} in {} ({} done, {} errors, {} active, {} queued)",
- context.locale,
- completed,
- entries.len(),
- format_duration(outcome.elapsed),
- translated,
- errors,
- active,
- entries.len().saturating_sub(completed)
- ),
- false,
- );
- }
- }
- Ok((translated, errors))
-}
-
-fn localize_batch_chunk<C: LocalizationClient>(
- client: &C,
- chunk: &[Entry],
- locale: &str,
- prompt_guidance: &[String],
- chunk_index: usize,
- start_index: usize,
-) -> BatchOutcome {
- let started = Instant::now();
- let mut translations = Vec::new();
- let mut warnings = Vec::new();
- let mut errors = Vec::new();
- let candidates = chunk
- .iter()
- .filter(|entry| {
- if should_keep_unchanged(&entry.msgid, locale) {
- translations.push(Translation {
- msgctxt: entry.msgctxt.clone(),
- msgid: entry.msgid.clone(),
- msgstr: entry.msgid.clone(),
- reviewed_unchanged: true,
- notes: String::new(),
- });
- false
- } else {
- true
- }
- })
- .cloned()
- .collect::<Vec<_>>();
- if !candidates.is_empty() {
- match localize_batch_partial(client, &candidates, locale, prompt_guidance) {
- Ok(batch_outcome) => {
- translations.extend(batch_outcome.translations);
- if !batch_outcome.failed_entries.is_empty() {
- warnings.push(format!(
- "[{locale}] Batch {} fallback for {} string(s) after per-item validation errors",
- chunk_index + 1,
- batch_outcome.failed_entries.len()
- ));
- }
- for (entry, reason) in batch_outcome.failed_entries {
- match localize_string(client, &entry, locale, prompt_guidance) {
- Ok(translation) => translations.push(translation),
- Err(error) => {
- errors.push(format!(
- "[{locale}] {:?} error after batch item fallback ({reason}): {error}",
- entry.msgid
- ));
- }
- }
- }
- }
- Err(error) => {
- warnings.push(format!(
- "[{locale}] Batch {} fallback after validation error: {error}",
- chunk_index + 1
- ));
- for entry in &candidates {
- match localize_string(client, entry, locale, prompt_guidance) {
- Ok(translation) => translations.push(translation),
- Err(error) => {
- errors.push(format!(
- "[{locale}] {:?} error after batch fallback: {error}",
- entry.msgid
- ));
- }
- }
- }
- }
- }
- }
- BatchOutcome {
- chunk_index,
- start_index,
- len: chunk.len(),
- elapsed: started.elapsed(),
- translations,
- warnings,
- errors,
- }
-}
-
-pub fn sync_source_locale(
- config: &RuntimeConfig,
- catalog_path: &Path,
- args: &TranslateArgs,
-) -> Result<LocaleResult> {
- if matches!(&config.catalog_layout, CatalogLayout::StaticJson(_)) {
- log(
- &format!(
- "[{SOURCE_LOCALE}] Source strings are in the static source catalog; nothing to sync"
- ),
- false,
- );
- return Ok(LocaleResult {
- locale: SOURCE_LOCALE.to_string(),
- translated: 0,
- errors: 0,
- });
- }
- log(
- &format!("[{SOURCE_LOCALE}] Syncing source strings without LLM..."),
- false,
- );
- let content = fs::read_to_string(catalog_path)
- .with_context(|| format!("failed to read {}", catalog_path.display()))?;
- let translations = parse_po(&content)?
- .into_iter()
- .map(|entry| Translation::new(entry.msgctxt, entry.msgid.clone(), entry.msgid))
- .collect::<Vec<_>>();
- if !args.dry_run {
- write_file_atomic(
- catalog_path,
- &rebuild_po_allow_replacing(&content, &translations)?,
- )?;
- }
- log(
- &format!(
- "[{SOURCE_LOCALE}] Synced {} source strings",
- translations.len()
- ),
- false,
- );
- Ok(LocaleResult {
- locale: SOURCE_LOCALE.to_string(),
- translated: translations.len(),
- errors: 0,
- })
-}
-
-fn read_catalog_entries(
- config: &RuntimeConfig,
- catalog_path: &Path,
- reset: bool,
-) -> Result<Vec<Entry>> {
- let content = fs::read_to_string(catalog_path)
- .with_context(|| format!("failed to read {}", catalog_path.display()))?;
- read_catalog_entries_from_content(config, &content, reset)
-}
-
-fn read_catalog_entries_from_content(
- config: &RuntimeConfig,
- content: &str,
- reset: bool,
-) -> Result<Vec<Entry>> {
- match &config.catalog_layout {
- CatalogLayout::NestedMessages => {
- let content = if reset {
- reset_po_translations(content)?
- } else {
- content.to_string()
- };
- parse_po(&content)
- }
- CatalogLayout::StaticJson(static_config) => {
- let source_content = read_static_source_catalog(&static_config.source_path)?;
- read_static_json_entries(static_config, &source_content, content, reset)
- }
- }
-}
-
-fn reset_catalog_translations(config: &RuntimeConfig, content: &str) -> Result<String> {
- match &config.catalog_layout {
- CatalogLayout::NestedMessages => reset_po_translations(content),
- CatalogLayout::StaticJson(static_config) => {
- reset_static_json_translations(static_config, content)
- }
- }
-}
-
-fn rebuild_catalog_allow_replacing(
- config: &RuntimeConfig,
- content: &str,
- translations: &[Translation],
-) -> Result<String> {
- match &config.catalog_layout {
- CatalogLayout::NestedMessages => rebuild_po_allow_replacing(content, translations),
- CatalogLayout::StaticJson(static_config) => {
- let source_content = read_static_source_catalog(&static_config.source_path)?;
- rebuild_static_json_allow_replacing(
- static_config,
- &source_content,
- content,
- translations,
- )
- }
- }
-}
-
-fn read_static_source_catalog(source_path: &Path) -> Result<String> {
- fs::read_to_string(source_path)
- .with_context(|| format!("failed to read {}", source_path.display()))
-}
-
-fn catalog_path(config: &RuntimeConfig, locale: &str) -> PathBuf {
- match &config.catalog_layout {
- CatalogLayout::NestedMessages => config.locales_dir.join(locale).join("messages.po"),
- CatalogLayout::StaticJson(_) => config.locales_dir.join(format!("{locale}.json")),
- }
-}
-
-pub fn write_file_atomic(file_path: &Path, content: &str) -> Result<()> {
- let timestamp = SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .unwrap_or_default()
- .as_nanos();
- let temp_path = file_path.with_file_name(format!(
- ".{}.{}.{}.tmp",
- file_path
- .file_name()
- .and_then(|name| name.to_str())
- .unwrap_or("messages.po"),
- std::process::id(),
- timestamp
- ));
- fs::write(&temp_path, content)?;
- fs::rename(&temp_path, file_path)?;
- Ok(())
-}
-
-pub fn localize_string<C: LocalizationClient>(
- client: &C,
- entry: &Entry,
- locale: &str,
- prompt_guidance: &[String],
-) -> Result<Translation> {
- if should_keep_unchanged(&entry.msgid, locale) {
- return Ok(Translation {
- msgctxt: entry.msgctxt.clone(),
- msgid: entry.msgid.clone(),
- msgstr: entry.msgid.clone(),
- reviewed_unchanged: true,
- notes: String::new(),
- });
- }
- if !is_supported_locale(locale) {
- bail!("Unsupported locale: {locale}");
- }
- let mut options = base_options();
- if entry.msgid.len() <= 24 {
- options.insert("temperature".to_string(), json!(0));
- }
- let mut previous_error: Option<String> = None;
- for attempt in 1..=FULL_TRANSLATION_ATTEMPTS {
- let result = (|| {
- let mut attempt_options = options.clone();
- if attempt > 1 {
- attempt_options.insert("temperature".to_string(), json!(0));
- }
- let prompt = build_translate_prompt(
- entry,
- locale,
- prompt_guidance,
- previous_error.as_deref(),
- true,
- );
- let result =
- client.localize(&attempt_options, &prompt.system_prompt, &prompt.user_prompt)?;
- let restored = restore_masked_tokens(&result.localized, &prompt.token_aliases);
- let localized = normalize_localized_capitalization(entry, locale, &restored);
- validate_localization(entry, &localized)?;
- validate_locale_specific_localization(entry, locale, &localized)?;
- Ok::<_, anyhow::Error>(Translation {
- msgctxt: entry.msgctxt.clone(),
- msgid: entry.msgid.clone(),
- msgstr: localized.clone(),
- reviewed_unchanged: localized == entry.msgid,
- notes: result.notes,
- })
- })();
- match result {
- Ok(translation) => return Ok(translation),
- Err(error) => {
- previous_error = Some(error.to_string());
- if attempt == FULL_TRANSLATION_ATTEMPTS {
- if let Some(fallback) = try_literal_token_localization(
- client,
- entry,
- locale,
- prompt_guidance,
- &options,
- previous_error.as_deref().unwrap_or_default(),
- )? {
- return Ok(Translation {
- msgctxt: entry.msgctxt.clone(),
- msgid: entry.msgid.clone(),
- msgstr: fallback.clone(),
- reviewed_unchanged: fallback == entry.msgid,
- notes: "literal token fallback".to_string(),
- });
- }
- if let Some(fallback) = try_segmented_localization(
- client,
- entry,
- locale,
- prompt_guidance,
- &options,
- previous_error.as_deref().unwrap_or_default(),
- )? {
- return Ok(Translation {
- msgctxt: entry.msgctxt.clone(),
- msgid: entry.msgid.clone(),
- msgstr: fallback.clone(),
- reviewed_unchanged: fallback == entry.msgid,
- notes: "segmented fallback".to_string(),
- });
- }
- bail!(previous_error.unwrap_or_else(|| "translation failed".to_string()));
- }
- sleep_before_retry(attempt, 0.5);
- }
- }
- }
- bail!("unreachable")
-}
-
-#[derive(Debug)]
-struct BatchLocalizationOutcome {
- translations: Vec<Translation>,
- failed_entries: Vec<(Entry, String)>,
-}
-
-fn localize_batch_partial<C: LocalizationClient>(
- client: &C,
- entries: &[Entry],
- locale: &str,
- prompt_guidance: &[String],
-) -> Result<BatchLocalizationOutcome> {
- if entries.is_empty() {
- return Ok(BatchLocalizationOutcome {
- translations: Vec::new(),
- failed_entries: Vec::new(),
- });
- }
- if !is_supported_locale(locale) {
- bail!("Unsupported locale: {locale}");
- }
- let target_name = display_name(locale);
- let guidance = format_guidance(prompt_guidance);
- let mut batch_items = Vec::with_capacity(entries.len());
- let mut token_aliases_by_id = Vec::with_capacity(entries.len());
- for (index, entry) in entries.iter().enumerate() {
- let id = index.to_string();
- let (source, token_aliases) = build_masked_source(entry);
- token_aliases_by_id.push((id.clone(), token_aliases));
- let mut item = Map::new();
- item.insert("id".to_string(), json!(id));
- item.insert("source".to_string(), json!(source));
- let metadata = build_batch_translation_context(entry);
- if !metadata.is_empty() {
- item.insert("metadata".to_string(), json!(metadata));
- }
- let placeholder_hints = extract_placeholder_hints(entry);
- if !placeholder_hints.is_empty() {
- item.insert("placeholderHints".to_string(), json!(placeholder_hints));
- }
- let preservation = build_preservation_context(entry);
- if !preservation.is_empty() {
- item.insert("preservation".to_string(), json!(preservation));
- }
- batch_items.push(Value::Object(item));
- }
- let mut options = base_options();
- options.insert("temperature".to_string(), json!(0));
- let num_ctx = if entries.len() > 125 { 16384 } else { 8192 };
- let num_predict = if entries.len() > 125 {
- (entries.len() * 128).clamp(4096, 12000)
- } else {
- (entries.len() * 48).clamp(2048, 4096)
- };
- options.insert("num_ctx".to_string(), json!(num_ctx));
- options.insert("num_predict".to_string(), json!(num_predict));
- let system_prompt = [
- build_system_prompt(locale),
- "You are translating multiple independent UI strings in one request.".to_string(),
- "Return only valid compact JSON. Do not include markdown, comments, or explanatory text.".to_string(),
- "Each JSON property key must be the item id, and each value must be only the localized string.".to_string(),
- "Preserve every placeholder alias and literal token exactly as shown for its item.".to_string(),
- ]
- .join("\n\n");
- let user_prompt = [
- Some(format!(
- "Task: localize each source string from en-US to {target_name} ({locale})."
- )),
- Some(build_target_locale_prompt(locale)),
- optional_section("Persisted guidance excerpts", guidance.as_deref()),
- Some(
- "Return shape example: {\"0\":\"localized string\",\"1\":\"localized string\"}."
- .to_string(),
- ),
- Some("Translate only the human-readable UI text. Do not translate placeholder aliases, ICU argument names, rich-text tags, IDs, URLs, or code-like values.".to_string()),
- Some(format!(
- "Items JSON:\n{}",
- serde_json::to_string(&batch_items)?
- )),
- ]
- .into_iter()
- .flatten()
- .collect::<Vec<_>>()
- .join("\n\n");
- let result = client.localize(&options, &system_prompt, &user_prompt)?;
- let object = parse_batch_response_object(&result.localized)?;
- let mut translations = Vec::with_capacity(entries.len());
- let mut failed_entries = Vec::new();
- for (index, entry) in entries.iter().enumerate() {
- let id = index.to_string();
- let Some(value) = object.get(&id) else {
- failed_entries.push((entry.clone(), format!("missing id {id}")));
- continue;
- };
- let Some(raw_localized) = batch_value_to_str(value) else {
- failed_entries.push((
- entry.clone(),
- format!("id {id} is not a string localization"),
- ));
- continue;
- };
- let token_aliases = token_aliases_by_id
- .iter()
- .find(|(candidate_id, _)| candidate_id == &id)
- .map(|(_, aliases)| aliases.as_slice())
- .unwrap_or(&[]);
- let localized = normalize_localized_capitalization(
- entry,
- locale,
- &restore_masked_tokens(raw_localized, token_aliases),
- );
- if let Err(error) = validate_localization(entry, &localized)
- .and_then(|_| validate_locale_specific_localization(entry, locale, &localized))
- {
- failed_entries.push((entry.clone(), error.to_string()));
- continue;
- }
- translations.push(Translation {
- msgctxt: entry.msgctxt.clone(),
- msgid: entry.msgid.clone(),
- msgstr: localized.clone(),
- reviewed_unchanged: localized == entry.msgid,
- notes: result.notes.clone(),
- });
- }
- Ok(BatchLocalizationOutcome {
- translations,
- failed_entries,
- })
-}
-
-fn parse_batch_response_object(content: &str) -> Result<Map<String, Value>> {
- let trimmed = content.trim();
- if let Ok(parsed) = serde_json::from_str::<Value>(trimmed)
- && let Some(object) = normalize_batch_response_value(parsed)
- {
- return Ok(object);
- }
- for (start, char) in trimmed.char_indices() {
- if char != '{' && char != '[' {
- continue;
- }
- let mut stream = serde_json::Deserializer::from_str(&trimmed[start..]).into_iter::<Value>();
- if let Some(Ok(parsed)) = stream.next()
- && let Some(object) = normalize_batch_response_value(parsed)
- {
- return Ok(object);
- }
- }
- bail!("Batch response did not contain a JSON object with numeric item keys")
-}
-
-fn normalize_batch_response_value(value: Value) -> Option<Map<String, Value>> {
- match value {
- Value::Object(mut object) => {
- if is_batch_response_object(&object) {
- return Some(object);
- }
- for key in [
- "translations",
- "localized",
- "localizations",
- "results",
- "items",
- ] {
- if let Some(value) = object.remove(key)
- && let Some(normalized) = normalize_batch_response_value(value)
- {
- return Some(normalized);
- }
- }
- None
- }
- Value::Array(items) => normalize_batch_response_array(items),
- _ => None,
- }
-}
-
-fn is_batch_response_object(object: &Map<String, Value>) -> bool {
- object.keys().any(|key| key.parse::<usize>().is_ok())
-}
-
-fn normalize_batch_response_array(items: Vec<Value>) -> Option<Map<String, Value>> {
- let mut object = Map::new();
- for item in items {
- let Value::Object(mut item) = item else {
- continue;
- };
- let Some(id) = item
- .remove("id")
- .and_then(|value| match value {
- Value::String(value) => Some(value),
- Value::Number(value) => Some(value.to_string()),
- _ => None,
- })
- .filter(|value| value.parse::<usize>().is_ok())
- else {
- continue;
- };
- let Some(localized) = item
- .remove("localized")
- .or_else(|| item.remove("translation"))
- .or_else(|| item.remove("value"))
- .or_else(|| item.remove("target"))
- .or_else(|| item.remove("text"))
- .or_else(|| item.remove("msgstr"))
- else {
- continue;
- };
- object.insert(id, localized);
- }
- if object.is_empty() {
- None
- } else {
- Some(object)
- }
-}
-
-fn batch_value_to_str(value: &Value) -> Option<&str> {
- if let Some(raw) = value.as_str() {
- return Some(raw);
- }
- value
- .as_object()
- .and_then(|object| object.get("localized"))
- .and_then(Value::as_str)
-}
-
-fn sleep_before_retry(attempt: usize, base_seconds: f64) {
- std::thread::sleep(Duration::from_secs_f64(base_seconds * attempt as f64));
-}
-
-fn try_literal_token_localization<C: LocalizationClient>(
- client: &C,
- entry: &Entry,
- locale: &str,
- prompt_guidance: &[String],
- options: &Map<String, Value>,
- previous_error: &str,
-) -> Result<Option<String>> {
- if !previous_error.contains("did not preserve") || extract_preserved_tokens(entry).is_empty() {
- return Ok(None);
- }
- let mut literal_error = previous_error.to_string();
- for attempt in 1..=SEGMENT_TRANSLATION_ATTEMPTS {
- let result = (|| {
- let mut attempt_options = options.clone();
- attempt_options.insert("temperature".to_string(), json!(0));
- let prompt =
- build_translate_prompt(entry, locale, prompt_guidance, Some(&literal_error), false);
- let result =
- client.localize(&attempt_options, &prompt.system_prompt, &prompt.user_prompt)?;
- let localized = normalize_localized_capitalization(entry, locale, &result.localized);
- validate_localization(entry, &localized)?;
- validate_locale_specific_localization(entry, locale, &localized)?;
- Ok::<_, anyhow::Error>(localized)
- })();
- match result {
- Ok(localized) => return Ok(Some(localized)),
- Err(error) => {
- literal_error = error.to_string();
- if attempt == SEGMENT_TRANSLATION_ATTEMPTS {
- return Ok(None);
- }
- sleep_before_retry(attempt, 0.3);
- }
- }
- }
- Ok(None)
-}
-
-fn try_segmented_localization<C: LocalizationClient>(
- client: &C,
- entry: &Entry,
- locale: &str,
- prompt_guidance: &[String],
- options: &Map<String, Value>,
- previous_error: &str,
-) -> Result<Option<String>> {
- let segments = split_source_for_segment_fallback(&entry.msgid);
- if segments.len() <= 1 {
- return Ok(None);
- }
- let mut localized_segments = Vec::new();
- for (index, segment) in segments.iter().enumerate() {
- let mut segment_entry = Entry {
- comments: entry.comments.clone(),
- references: entry.references.clone(),
- msgctxt: entry.msgctxt.clone(),
- msgid: segment.clone(),
- msgstr: String::new(),
- line_number: entry.line_number,
- };
- segment_entry.comments.push(format!(
- "#. Segment fallback: segment {} of {} from a longer UI string. Translate only this source segment.",
- index + 1,
- segments.len()
- ));
- let mut segment_error = previous_error.to_string();
- let mut localized_segment = None;
- for attempt in 1..=SEGMENT_TRANSLATION_ATTEMPTS {
- let result = (|| {
- let mut attempt_options = options.clone();
- attempt_options.insert("temperature".to_string(), json!(0));
- let prompt = build_translate_prompt(
- &segment_entry,
- locale,
- prompt_guidance,
- Some(&segment_error),
- true,
- );
- let result = client.localize(
- &attempt_options,
- &prompt.system_prompt,
- &prompt.user_prompt,
- )?;
- let localized = restore_masked_tokens(&result.localized, &prompt.token_aliases);
- validate_localization(&segment_entry, &localized)?;
- Ok::<_, anyhow::Error>(localized)
- })();
- match result {
- Ok(localized) => {
- localized_segment = Some(localized);
- break;
- }
- Err(error) => {
- segment_error = error.to_string();
- if attempt == SEGMENT_TRANSLATION_ATTEMPTS {
- return Ok(None);
- }
- sleep_before_retry(attempt, 0.3);
- }
- }
- }
- let Some(localized_segment) = localized_segment else {
- return Ok(None);
- };
- localized_segments.push(localized_segment);
- }
- let localized = normalize_localized_capitalization(
- entry,
- locale,
- &join_localized_segments(&localized_segments),
- );
- validate_localization(entry, &localized)?;
- validate_locale_specific_localization(entry, locale, &localized)?;
- Ok(
- polish_segmented_localization(client, entry, locale, prompt_guidance, options, &localized)?
- .or(Some(localized)),
- )
-}
-
-fn polish_segmented_localization<C: LocalizationClient>(
- client: &C,
- entry: &Entry,
- locale: &str,
- prompt_guidance: &[String],
- options: &Map<String, Value>,
- draft: &str,
-) -> Result<Option<String>> {
- let target_name = display_name(locale);
- let (masked_source, token_aliases) = build_masked_source(entry);
- let masked_draft = mask_text_with_aliases(draft, &token_aliases);
- let guidance = format_guidance(prompt_guidance);
- let system_prompt = [
- build_system_prompt(locale),
- "You are polishing a localized UI string that was translated in smaller segments.".to_string(),
- "Make only grammar, punctuation, spacing, and fluency fixes needed to make the localized string read as one coherent UI message.".to_string(),
- "Do not add, remove, reorder, translate, or alter placeholder aliases.".to_string(),
- ]
- .join("\n\n");
- let mut user_prompt = [
- Some(format!(
- "Task: polish the {target_name} ({locale}) draft localization so it reads naturally as one UI string."
- )),
- Some("Return only the polished localized string.".to_string()),
- Some(build_target_locale_prompt(locale)),
- optional_section("Persisted guidance excerpts", guidance.as_deref()),
- (!token_aliases.is_empty()).then(|| build_token_alias_context(&token_aliases)),
- Some(format!("English source for meaning:\n{masked_source}")),
- Some(format!("Draft localization to polish:\n{masked_draft}")),
- ]
- .into_iter()
- .flatten()
- .collect::<Vec<_>>()
- .join("\n\n");
- for attempt in 1..=POLISH_TRANSLATION_ATTEMPTS {
- let result = (|| {
- let mut attempt_options = options.clone();
- attempt_options.insert("temperature".to_string(), json!(0));
- let result = client.localize(&attempt_options, &system_prompt, &user_prompt)?;
- let localized = normalize_localized_capitalization(
- entry,
- locale,
- &restore_masked_tokens(&result.localized, &token_aliases),
- );
- validate_localization(entry, &localized)?;
- validate_locale_specific_localization(entry, locale, &localized)?;
- Ok::<_, anyhow::Error>(localized)
- })();
- match result {
- Ok(localized) => return Ok(Some(localized)),
- Err(error) => {
- if attempt == POLISH_TRANSLATION_ATTEMPTS {
- return Ok(None);
- }
- user_prompt = [
- user_prompt,
- format!(
- "Previous polish attempt failed validation: {error}. Return a corrected polished string that preserves every placeholder alias exactly."
- ),
- ]
- .join("\n\n");
- sleep_before_retry(attempt, 0.3);
- }
- }
- }
- Ok(None)
-}
-
-pub fn build_translation_context(entry: &Entry) -> String {
- let comment_context = extract_translator_comments(entry).join("\n");
- let reference_context = entry
- .references
- .iter()
- .filter_map(|line| line.strip_prefix("#: "))
- .map(str::trim)
- .filter(|reference| !reference.is_empty())
- .collect::<Vec<_>>()
- .join(", ");
- let mut sections = Vec::new();
- if let Some(msgctxt) = &entry.msgctxt {
- sections.push(format!("Lingui msgctxt: {msgctxt}"));
- }
- if !comment_context.is_empty() {
- sections.push(format!("Translator comments:\n{comment_context}"));
- }
- if !reference_context.is_empty() {
- sections.push(format!(
- "Source references for locating the string, not translator instructions: {reference_context}"
- ));
- }
- sections.join("\n\n")
-}
-
-fn build_batch_translation_context(entry: &Entry) -> String {
- let comment_context = extract_translator_comments(entry).join("\n");
- let mut sections = Vec::new();
- if let Some(msgctxt) = &entry.msgctxt {
- sections.push(format!("Lingui msgctxt: {msgctxt}"));
- }
- if !comment_context.is_empty() {
- sections.push(format!("Translator comments:\n{comment_context}"));
- }
- sections.join("\n\n")
-}
-
-pub fn build_preservation_context(entry: &Entry) -> String {
- let tokens = extract_preserved_tokens(entry);
- let controls = extract_icu_controls(&entry.msgid);
- let mut lines = Vec::new();
- if !tokens.is_empty() {
- lines.push(format!(
- "Required literal tokens that must appear exactly in localized: {}",
- tokens
- .iter()
- .map(|token| format!("{token:?}"))
- .collect::<Vec<_>>()
- .join(", ")
- ));
- }
- if !controls.is_empty() {
- lines.push(format!(
- "Required ICU controls that must remain valid: {}",
- controls
- .iter()
- .map(|control| format!("{{{}, {}, ...}}", control.argument, control.kind))
- .collect::<Vec<_>>()
- .join(", ")
- ));
- lines.push("For ICU plural/select strings, keep the same argument names and clause keys such as one/other/few/many. Translate only the human-readable text inside each clause.".to_string());
- }
- if entry.msgid.contains('<') {
- lines.push("Numeric rich-text tags such as <0>, </0>, <1>, </1>, and <0/> are markup tokens. Keep every tag exactly, including slash placement and number. You may move paired tags only when grammar requires it.".to_string());
- }
- lines.join("\n")
-}
-
-pub fn build_literal_token_context(entry: &Entry) -> Option<String> {
- let tokens = extract_preserved_tokens(entry);
- if tokens.is_empty() {
- return None;
- }
- let mut lines = vec![
- "Preserved tokens are UI placeholders and markup.".to_string(),
- "Your answer must contain these exact preserved substrings:".to_string(),
- ];
- lines.extend(tokens.iter().map(|token| format!("- {token}")));
- lines.extend([
- "Keep each preserved token exactly where the corresponding source placeholder appears in the sentence.".to_string(),
- "Do not add a translated explanation, synonym, or parenthetical label next to a preserved token.".to_string(),
- "Do not turn paired tags into self-closing tags.".to_string(),
- ]);
- Some(lines.join("\n"))
-}
-
-pub fn build_translate_prompt(
- entry: &Entry,
- locale: &str,
- prompt_guidance: &[String],
- previous_error: Option<&str>,
- use_token_aliases: bool,
-) -> Prompt {
- let target_name = display_name(locale);
- let context = build_translation_context(entry);
- let placeholder_hints = extract_placeholder_hints(entry).join("\n");
- let preservation_context = build_preservation_context(entry);
- let (source, token_aliases, token_context) = if use_token_aliases {
- let (source, token_aliases) = build_masked_source(entry);
- let token_context =
- (!token_aliases.is_empty()).then(|| build_token_alias_context(&token_aliases));
- (source, token_aliases, token_context)
- } else {
- (
- entry.msgid.clone(),
- Vec::new(),
- build_literal_token_context(entry),
- )
- };
- let guidance = format_guidance(prompt_guidance);
- let parts = [
- Some(format!(
- "Task: localize the source string from en-US to {target_name} ({locale})."
- )),
- Some(format!("Return only the {target_name} localized string.")),
- Some(build_target_locale_prompt(locale)),
- optional_section("Persisted guidance excerpts", guidance.as_deref()),
- optional_section("Lingui metadata and source locations", not_empty(&context)),
- optional_section("Placeholder hints from Lingui comments", not_empty(&placeholder_hints)),
- token_context,
- optional_section("Preservation requirements", not_empty(&preservation_context)),
- previous_error.map(|error| {
- format!(
- "Previous attempt failed validation: {error}\nReturn a corrected localization that satisfies every preservation requirement exactly."
- )
- }),
- Some(format!("Source string:\n{source}")),
- ]
- .into_iter()
- .flatten()
- .collect::<Vec<_>>();
- Prompt {
- system_prompt: build_system_prompt(locale),
- user_prompt: parts.join("\n\n"),
- token_aliases,
- }
-}
-
-fn optional_section(label: &str, content: Option<&str>) -> Option<String> {
- content.map(|content| format!("{label}:\n{content}"))
-}
-
-fn not_empty(value: &str) -> Option<&str> {
- (!value.is_empty()).then_some(value)
-}
-
-fn format_guidance(prompt_guidance: &[String]) -> Option<String> {
- (!prompt_guidance.is_empty()).then(|| prompt_guidance.join("\n\n"))
-}
-
-pub fn split_source_for_segment_fallback(source: &str) -> Vec<String> {
- if source.len() < 120 || source.contains('\n') || has_icu_control(source) {
- return vec![source.to_string()];
- }
- let sentence_segments = split_sentences(source)
- .into_iter()
- .map(|segment| segment.trim().to_string())
- .filter(|segment| !segment.is_empty())
- .collect::<Vec<_>>();
- if sentence_segments.len() <= 1 {
- return vec![source.to_string()];
- }
- let segments = sentence_segments
- .iter()
- .flat_map(|segment| split_long_clause_segment(segment))
- .collect::<Vec<_>>();
- if segments.len() > 1 {
- segments
- } else {
- vec![source.to_string()]
- }
-}
-
-fn split_sentences(source: &str) -> Vec<&str> {
- let mut segments = Vec::new();
- let mut start = 0;
- let mut iter = source.char_indices().peekable();
- while let Some((index, character)) = iter.next() {
- if matches!(character, '.' | '!' | '?') {
- let next_is_boundary = iter
- .peek()
- .map(|(_next_index, next)| next.is_whitespace())
- .unwrap_or(true);
- if next_is_boundary {
- let end = index + character.len_utf8();
- segments.push(&source[start..end]);
- start = end;
- }
- }
- }
- if start < source.len() {
- segments.push(&source[start..]);
- }
- segments
-}
-
-pub fn split_long_clause_segment(segment: &str) -> Vec<String> {
- let token_count = extract_preserved_tokens(&Entry::with_msgid(segment)).len();
- if segment.len() < 140 || token_count < 3 {
- return vec![segment.to_string()];
- }
- let mut parts = Vec::new();
- let mut start = 0;
- for (comma_index, _) in segment.match_indices(',') {
- let after_comma = comma_index + 1;
- let whitespace_len = segment[after_comma..]
- .chars()
- .take_while(|character| character.is_whitespace())
- .map(char::len_utf8)
- .sum::<usize>();
- if whitespace_len == 0 {
- continue;
- }
- let next_start = after_comma + whitespace_len;
- let rest = &segment[next_start..];
- if starts_with_clause_keyword(rest) {
- parts.push(segment[start..after_comma].trim().to_string());
- start = next_start;
- }
- }
- if start == 0 {
- return vec![segment.to_string()];
- }
- parts.push(segment[start..].trim().to_string());
- parts.into_iter().filter(|part| !part.is_empty()).collect()
-}
-
-fn starts_with_clause_keyword(rest: &str) -> bool {
- ["allow", "then", "if", "fully"].iter().any(|keyword| {
- rest.len() >= keyword.len()
- && rest[..keyword.len()].eq_ignore_ascii_case(keyword)
- && rest[keyword.len()..]
- .chars()
- .next()
- .is_none_or(|character| !character.is_alphanumeric() && character != '_')
- })
-}
-
-pub fn join_localized_segments(segments: &[String]) -> String {
- Regex::new(r"\s+([,.;:!?])")
- .expect("valid segment join regex")
- .replace_all(&segments.join(" "), "$1")
- .into_owned()
-}
-
-fn format_duration(duration: Duration) -> String {
- let seconds = duration.as_secs_f64();
- if seconds < 60.0 {
- return format!("{seconds:.1}s");
- }
- let minutes = (seconds / 60.0).floor();
- let remaining_seconds = seconds % 60.0;
- if minutes < 60.0 {
- return format!("{}m {:.0}s", minutes as u64, remaining_seconds);
- }
- let hours = (minutes / 60.0).floor();
- let remaining_minutes = minutes % 60.0;
- format!("{}h {}m", hours as u64, remaining_minutes as u64)
-}
-
-fn format_float(value: f64) -> String {
- if value.fract() == 0.0 {
- format!("{}", value as u64)
- } else {
- format!("{value}")
- }
-}
-
-fn log(message: &str, error: bool) {
- if error {
- eprintln!("{message}");
- } else {
- println!("{message}");
- }
-}
diff --git a/tools/i18n_auto/src/tokens.rs b/tools/i18n_auto/src/tokens.rs
deleted file mode 100644
index 8b73237a4..000000000
--- a/tools/i18n_auto/src/tokens.rs
+++ /dev/null
@@ -1,386 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-use std::cmp::Reverse;
-
-use anyhow::{Result, bail};
-use regex::Regex;
-
-use crate::po::Entry;
-
-const EN_GB_PROTECTED_REGION_TERMS: &[&str] = &[
- "United States of America",
- "United States",
- "U.S.",
- "USA",
- "US",
-];
-
-#[derive(Clone, Debug, Eq, PartialEq)]
-pub struct IcuControl {
- pub argument: String,
- pub kind: String,
-}
-
-#[derive(Clone, Debug, Eq, PartialEq)]
-pub struct TokenAlias {
- pub token: String,
- pub alias: String,
-}
-
-pub fn should_keep_unchanged(source: &str, locale: &str) -> bool {
- if locale == "en-US" {
- return false;
- }
- if source.trim().is_empty() {
- return true;
- }
- if !has_any_letter(source) {
- return true;
- }
- if is_preserved_token_composition(source) {
- return true;
- }
- is_preserved_artifact(source)
-}
-
-pub fn has_any_letter(source: &str) -> bool {
- source.chars().any(char::is_alphabetic)
-}
-
-pub fn is_preserved_artifact(source: &str) -> bool {
- let trimmed = source.trim();
- if [
- r"(?i)^https?://\S+$",
- r"(?i)^(?:mailto:|tel:|file:|app://|fluxer://)\S+$",
- r"^[@#][\w-]+$",
- r"^\{[^{}]+\}$",
- r"^<[^>]+>$",
- r"^%[@sd]$",
- r"^\$\d+$",
- r#"^[\s{}#,._:/+()\[\]'"-]+$"#,
- r"^[A-Z][A-Z0-9_./:+-]+$",
- ]
- .iter()
- .any(|pattern| {
- Regex::new(pattern)
- .expect("valid artifact regex")
- .is_match(trimmed)
- }) {
- return true;
- }
- Regex::new(r"^[\w./:+-]+$")
- .expect("valid word artifact regex")
- .is_match(trimmed)
- && Regex::new(r"[\d_./:+-]")
- .expect("valid word artifact marker regex")
- .is_match(trimmed)
-}
-
-pub fn is_preserved_token_composition(source: &str) -> bool {
- let entry = Entry {
- msgid: source.to_string(),
- ..Entry::default()
- };
- let mut tokens = extract_preserved_tokens(&entry);
- if tokens.is_empty() {
- return false;
- }
- tokens.sort_by_key(|token| Reverse(token.len()));
- let mut remainder = source.to_string();
- for token in tokens {
- remainder = Regex::new(&regex::escape(&token))
- .expect("valid preserved token cleanup regex")
- .replace_all(&remainder, "")
- .into_owned();
- }
- remainder
- .chars()
- .all(|character| character.is_whitespace() || is_preserved_token_separator(character))
-}
-
-fn is_preserved_token_separator(character: char) -> bool {
- matches!(
- character,
- ':' | ','
- | '.'
- | '/'
- | '\\'
- | '-'
- | '–'
- | '—'
- | '('
- | ')'
- | '['
- | ']'
- | '{'
- | '}'
- | '|'
- | '·'
- | '•'
- | '#'
- | '+'
- | '\''
- | '"'
- )
-}
-
-pub fn validate_localization(entry: &Entry, localized: &str) -> Result<()> {
- if !entry.msgid.trim().is_empty() && localized.trim().is_empty() {
- bail!("Localized string is empty");
- }
- let source_tokens = extract_preserved_tokens(entry);
- let localized_entry = Entry {
- msgid: localized.to_string(),
- comments: entry.comments.clone(),
- ..Entry::default()
- };
- let localized_tokens = extract_preserved_tokens(&localized_entry);
- for token in source_tokens {
- if !localized_tokens.contains(&token) {
- bail!("Localized string did not preserve token {token}");
- }
- }
- for control in extract_icu_controls(&entry.msgid) {
- let pattern = Regex::new(&format!(
- r"\{{\s*{}\s*,\s*{}\s*,",
- regex::escape(&control.argument),
- regex::escape(&control.kind)
- ))
- .expect("valid ICU validation regex");
- if !pattern.is_match(localized) {
- bail!(
- "Localized string did not preserve ICU {} argument {}",
- control.kind,
- control.argument
- );
- }
- }
- Ok(())
-}
-
-pub fn validate_locale_specific_localization(
- entry: &Entry,
- locale: &str,
- localized: &str,
-) -> Result<()> {
- if locale != "en-GB" {
- return Ok(());
- }
- for term in extract_en_gb_protected_terms(&entry.msgid) {
- if !contains_exact_term(localized, term) {
- bail!("en-GB localization changed protected source term {term}");
- }
- }
- Ok(())
-}
-
-pub fn extract_en_gb_protected_terms(source: &str) -> Vec<&'static str> {
- EN_GB_PROTECTED_REGION_TERMS
- .iter()
- .copied()
- .filter(|term| contains_exact_term(source, term))
- .collect()
-}
-
-pub fn contains_exact_term(source: &str, term: &str) -> bool {
- source.match_indices(term).any(|(start, _match)| {
- let before_ok = source[..start]
- .chars()
- .next_back()
- .is_none_or(|before| !is_word_char(before));
- let end = start + term.len();
- let after_ok = source[end..]
- .chars()
- .next()
- .is_none_or(|after| !is_word_char(after));
- before_ok && after_ok
- })
-}
-
-fn is_word_char(value: char) -> bool {
- value == '_' || value.is_alphanumeric()
-}
-
-pub fn normalize_localized_capitalization(entry: &Entry, locale: &str, localized: &str) -> String {
- if locale.starts_with("en") || !entry.msgid.starts_with('(') || !localized.starts_with('(') {
- return localized.to_string();
- }
- let mut chars = localized.chars();
- let Some(first) = chars.next() else {
- return localized.to_string();
- };
- let Some(second) = chars.next() else {
- return localized.to_string();
- };
- let second_string = second.to_string();
- if second_string != second.to_uppercase().to_string() {
- return localized.to_string();
- }
- let rest = chars.as_str();
- format!("{first}{}{rest}", second.to_lowercase())
-}
-
-pub fn extract_preserved_tokens(entry: &Entry) -> Vec<String> {
- let mut tokens = Vec::new();
- for token in extract_top_level_brace_tokens(&entry.msgid) {
- push_unique(&mut tokens, token);
- }
- let token_re = Regex::new(r"%[@sd]|\$\d+|<[^>]+>|https?://\S+|:[a-zA-Z0-9_+-]+:")
- .expect("valid preserved token regex");
- for matched in token_re.find_iter(&entry.msgid) {
- push_unique(&mut tokens, matched.as_str().to_string());
- }
- tokens
-}
-
-pub fn extract_top_level_brace_tokens(source: &str) -> Vec<String> {
- let mut tokens = Vec::new();
- let mut depth = 0usize;
- let mut start: Option<usize> = None;
- let double_brace_re = Regex::new(r"^\{\{[^{}]+\}\}$").expect("valid double brace regex");
- let brace_re = Regex::new(r"^\{[^{},]+\}$").expect("valid brace regex");
- for (index, character) in source.char_indices() {
- if character == '{' {
- if depth == 0 {
- start = Some(index);
- }
- depth += 1;
- } else if character == '}' && depth > 0 {
- depth -= 1;
- if depth == 0 {
- if let Some(start_index) = start {
- let token = &source[start_index..index + character.len_utf8()];
- if double_brace_re.is_match(token) || brace_re.is_match(token) {
- tokens.push(token.to_string());
- }
- }
- start = None;
- }
- }
- }
- tokens
-}
-
-pub fn has_icu_control(source: &str) -> bool {
- Regex::new(r"\{[^{}]+,\s*(?:plural|select|selectordinal)\s*,")
- .expect("valid ICU detection regex")
- .is_match(source)
-}
-
-pub fn extract_icu_controls(source: &str) -> Vec<IcuControl> {
- Regex::new(r"\{\s*([^{}\s,]+)\s*,\s*(plural|select|selectordinal)\s*,")
- .expect("valid ICU control regex")
- .captures_iter(source)
- .map(|captures| IcuControl {
- argument: captures[1].to_string(),
- kind: captures[2].to_string(),
- })
- .collect()
-}
-
-pub fn build_masked_source(entry: &Entry) -> (String, Vec<TokenAlias>) {
- let token_aliases = extract_preserved_tokens(entry)
- .into_iter()
- .enumerate()
- .map(|(index, token)| TokenAlias {
- token,
- alias: format!("{{FLUXER_TOKEN_{index}}}"),
- })
- .collect::<Vec<_>>();
- (
- mask_text_with_aliases(&entry.msgid, &token_aliases),
- token_aliases,
- )
-}
-
-pub fn mask_text_with_aliases(text: &str, token_aliases: &[TokenAlias]) -> String {
- let mut masked = text.to_string();
- let mut aliases = token_aliases.iter().collect::<Vec<_>>();
- aliases.sort_by_key(|alias| std::cmp::Reverse(alias.token.len()));
- for item in aliases {
- masked = Regex::new(&regex::escape(&item.token))
- .expect("valid token mask regex")
- .replace_all(&masked, item.alias.as_str())
- .into_owned();
- }
- masked
-}
-
-pub fn restore_masked_tokens(localized: &str, token_aliases: &[TokenAlias]) -> String {
- let mut restored = localized.to_string();
- for item in token_aliases {
- restored = restored.replace(&item.alias, &item.token);
- }
- restored
-}
-
-pub fn build_token_alias_context(token_aliases: &[TokenAlias]) -> String {
- let mut lines = vec!["Literal protected aliases used in the source string:".to_string()];
- lines.extend(
- token_aliases
- .iter()
- .map(|item| format!("{} = {}", item.alias, item.token)),
- );
- lines.extend([
- "Aliases are required substrings, not words or labels to localize.".to_string(),
- "Copy every alias exactly in the localized output, with the same spelling and braces.".to_string(),
- "Do not replace an alias with translated words, even if the original token name looks meaningful."
- .to_string(),
- "Translate only the human-readable words around aliases.".to_string(),
- ]);
- lines.join("\n")
-}
-
-fn push_unique(tokens: &mut Vec<String>, token: String) {
- if !tokens.contains(&token) {
- tokens.push(token);
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn extracts_masks_and_restores_preserved_tokens() {
- let entry = Entry::with_msgid("{productName} needs <0>{permission}</0> %@ $1 :wave:");
- assert_eq!(
- extract_preserved_tokens(&entry),
- vec![
- "{productName}",
- "{permission}",
- "<0>",
- "</0>",
- "%@",
- "$1",
- ":wave:"
- ]
- );
- let (masked, aliases) = build_masked_source(&entry);
- assert!(masked.contains("{FLUXER_TOKEN_0}"));
- assert_eq!(
- restore_masked_tokens(&masked, &aliases),
- "{productName} needs <0>{permission}</0> %@ $1 :wave:"
- );
- }
-
- #[test]
- fn validates_tokens_and_icu_controls() {
- let entry = Entry {
- msgid: "{0} {1, plural, one {member} other {members}}".to_string(),
- comments: vec!["#. placeholder {0}: count".to_string()],
- ..Entry::default()
- };
- validate_localization(&entry, "{0} {1, plural, one {miembro} other {miembros}}").unwrap();
- let error =
- validate_localization(&entry, "{0} {2, plural, one {x} other {x}}").unwrap_err();
- assert!(
- error
- .to_string()
- .contains("did not preserve ICU plural argument 1")
- );
- let missing_token =
- validate_localization(&Entry::with_msgid("Open {productName}"), "Open").unwrap_err();
- assert!(missing_token.to_string().contains("{productName}"));
- }
-}
diff --git a/tools/i18n_auto/src/ts_catalog.rs b/tools/i18n_auto/src/ts_catalog.rs
deleted file mode 100644
index 06b86b01b..000000000
--- a/tools/i18n_auto/src/ts_catalog.rs
+++ /dev/null
@@ -1,7 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-#[derive(Clone, Debug, Eq, PartialEq)]
-pub enum StaticTsCatalogKind {
- SimpleMessages,
- EmailTemplates,
-}