aien-translate
aien-dev/aien-translate
Brought by drakestapleton
aien-translate / src / lib.rs
| 1 | //! aien-translate: a translation server that speaks the translate.js |
| 2 | //! `translate.service` protocol and translates with AIEN's own runtime. |
| 3 | //! |
| 4 | //! Endpoints (POST or GET, form-encoded like translate.js sends): |
| 5 | //! - `/translate.json` from, to, text (JSON array of strings) |
| 6 | //! - `/language.json` languages offered |
| 7 | //! - `/connectTest.json`, `/init.json`, `/ip.json` translate.js housekeeping |
| 8 | //! - `/health` is the engine reachable |
| 9 | |
| 10 | pub mod cache; |
| 11 | pub mod engine; |
| 12 | pub mod guard; |
| 13 | pub mod langs; |
| 14 | |
| 15 | use axum::{ |
| 16 | body::Bytes, |
| 17 | extract::{ConnectInfo, DefaultBodyLimit, State}, |
| 18 | http::{header, HeaderMap, StatusCode, Uri}, |
| 19 | routing::{any, get}, |
| 20 | Json, Router, |
| 21 | }; |
| 22 | use serde_json::{json, Value}; |
| 23 | use std::collections::HashMap; |
| 24 | use std::net::SocketAddr; |
| 25 | use std::sync::{Arc, Mutex}; |
| 26 | use std::time::{Duration, Instant}; |
| 27 | use tokio::sync::Semaphore; |
| 28 | use subtle::ConstantTimeEq; |
| 29 | |
| 30 | /// Bump when the prompt changes, so old saved translations are not reused. |
| 31 | /// p5: the keep list (part of the prompt) gained "Aien". |
| 32 | /// p6: the keep list gained "AienOS" and "Aienux" (ADR 0038 names). |
| 33 | pub const PROMPT_VERSION: &str = "p6"; |
| 34 | |
| 35 | /// Names that are never translated unless the operator overrides the list. |
| 36 | /// "Allen" is the assistant's former name; it stays listed because quotes and |
| 37 | /// history notes on the site still name it, and those must not be translated. |
| 38 | /// "AIENOS" and "Aienix" are retired names (ADR 0038): "AIENOS" is now Aienux (the |
| 39 | /// kernel) or AienOS (the whole system), "Aienix" is now AienOS; they stay listed |
| 40 | /// for the same reason. |
| 41 | pub const DEFAULT_KEEP: &[&str] = &[ |
| 42 | "AIEN", "AienOS", "Aienux", "AIENOS", "Aienix", "Aien", "Omega", "OMEGA", "Interplane", "INTERPLANE", "Allen", |
| 43 | "Synapse", "Atlas", "Cortex", "Radicle", "Spark", "DGX", "GB10", "NVIDIA", "translate.js", |
| 44 | "GitHub", "Rust", "Linux", |
| 45 | ]; |
| 46 | |
| 47 | const BATCH_ITEMS: usize = 40; |
| 48 | const BATCH_CHARS: usize = 3000; |
| 49 | |
| 50 | pub struct Limits { |
| 51 | pub max_texts: usize, |
| 52 | pub max_chars: usize, |
| 53 | } |
| 54 | |
| 55 | impl Default for Limits { |
| 56 | fn default() -> Self { |
| 57 | Self { max_texts: 40, max_chars: 3000 } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | const MAX_REQUEST_BYTES: usize = 16_384; |
| 62 | const CLIENTS_MAX: usize = 1024; |
| 63 | const REQUESTS_PER_MINUTE: u8 = 6; |
| 64 | |
| 65 | struct ClientWindow { |
| 66 | started: Instant, |
| 67 | requests: u8, |
| 68 | } |
| 69 | |
| 70 | /// A bounded, non-queuing admission gate. Socket IPs are used, not spoofable |
| 71 | /// forwarding headers. A reverse proxy must rate-limit its own real clients. |
| 72 | pub struct Admission { |
| 73 | token: Option<String>, |
| 74 | active: Semaphore, |
| 75 | clients: Mutex<HashMap<std::net::IpAddr, ClientWindow>>, |
| 76 | } |
| 77 | |
| 78 | impl Admission { |
| 79 | pub fn new(token: Option<String>) -> Self { |
| 80 | Self { token, active: Semaphore::new(1), clients: Mutex::new(HashMap::new()) } |
| 81 | } |
| 82 | |
| 83 | fn authorized(&self, headers: &HeaderMap) -> bool { |
| 84 | let Some(token) = &self.token else { return true }; |
| 85 | let Some(supplied) = headers.get(header::AUTHORIZATION) |
| 86 | .and_then(|v| v.to_str().ok()) |
| 87 | .and_then(|v| v.strip_prefix("Bearer ")) else { return false }; |
| 88 | supplied.len() == token.len() && bool::from(supplied.as_bytes().ct_eq(token.as_bytes())) |
| 89 | } |
| 90 | |
| 91 | fn allow_client(&self, addr: SocketAddr) -> bool { |
| 92 | let now = Instant::now(); |
| 93 | let mut clients = self.clients.lock().unwrap(); |
| 94 | if clients.len() >= CLIENTS_MAX { |
| 95 | clients.retain(|_, window| now.duration_since(window.started) < Duration::from_secs(60)); |
| 96 | } |
| 97 | let ip = addr.ip(); |
| 98 | if !clients.contains_key(&ip) && clients.len() == CLIENTS_MAX { |
| 99 | return false; |
| 100 | } |
| 101 | let window = clients.entry(ip).or_insert(ClientWindow { started: now, requests: 0 }); |
| 102 | if now.duration_since(window.started) >= Duration::from_secs(60) { |
| 103 | *window = ClientWindow { started: now, requests: 0 }; |
| 104 | } |
| 105 | if window.requests >= REQUESTS_PER_MINUTE { return false } |
| 106 | window.requests += 1; |
| 107 | true |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | pub struct AppState { |
| 112 | pub engine: engine::Engine, |
| 113 | pub cache: cache::Cache, |
| 114 | pub keep: Vec<String>, |
| 115 | pub limits: Limits, |
| 116 | pub admission: Admission, |
| 117 | } |
| 118 | |
| 119 | #[derive(Default, Debug, Clone, Copy, PartialEq, Eq)] |
| 120 | pub struct Stats { |
| 121 | pub from_cache: usize, |
| 122 | pub translated: usize, |
| 123 | pub kept_original: usize, |
| 124 | pub nothing_to_do: usize, |
| 125 | } |
| 126 | |
| 127 | /// Split text into (kept lead, core to translate, kept trail). |
| 128 | /// |
| 129 | /// The lead and trail are whitespace, plus pieces of a link that translate.js |
| 130 | /// cut apart: it splits text at "//", so "Read the docs at https://x.com now" |
| 131 | /// arrives as "Read the docs at https:" and "x.com now". Those pieces must |
| 132 | /// stay at the edge they came from or the link breaks when reassembled. |
| 133 | fn split_ws(s: &str) -> (&str, &str, &str) { |
| 134 | use regex::Regex; |
| 135 | use std::sync::OnceLock; |
| 136 | static TAIL: OnceLock<Regex> = OnceLock::new(); |
| 137 | static HEAD: OnceLock<Regex> = OnceLock::new(); |
| 138 | let tail = TAIL.get_or_init(|| Regex::new(r"(?i)\s*\bhttps?:$").unwrap()); |
| 139 | let head = HEAD.get_or_init(|| { |
| 140 | Regex::new( |
| 141 | r"(?i)^(www\.)?[a-z0-9-]+(\.[a-z0-9-]+)*\.(com|org|net|io|dev|ai|app|co|me|info|edu|gov|cn|uk|de)(/\S*)?(\s+|$)", |
| 142 | ) |
| 143 | .unwrap() |
| 144 | }); |
| 145 | |
| 146 | let trimmed = s.trim(); |
| 147 | if trimmed.is_empty() { |
| 148 | return (s, "", ""); |
| 149 | } |
| 150 | let mut a = s.find(trimmed).unwrap_or(0); |
| 151 | let mut b = a + trimmed.len(); |
| 152 | if let Some(m) = tail.find(&s[a..b]) { |
| 153 | b = a + m.start(); |
| 154 | } |
| 155 | if let Some(m) = head.find(&s[a..b]) { |
| 156 | a += m.end(); |
| 157 | } |
| 158 | if a > b { |
| 159 | a = b; |
| 160 | } |
| 161 | (&s[..a], &s[a..b], &s[b..]) |
| 162 | } |
| 163 | |
| 164 | pub async fn translate_texts( |
| 165 | st: &AppState, |
| 166 | from_id: &str, |
| 167 | to_id: &str, |
| 168 | texts: &[String], |
| 169 | ) -> Result<(Vec<String>, Stats), String> { |
| 170 | let to = langs::find(to_id).ok_or_else(|| format!("unsupported target language: {to_id}"))?; |
| 171 | let from = langs::find(from_id); |
| 172 | let mut stats = Stats::default(); |
| 173 | let mut out: Vec<String> = texts.to_vec(); |
| 174 | |
| 175 | if from.map(|f| f.id) == Some(to.id) { |
| 176 | stats.nothing_to_do = texts.len(); |
| 177 | return Ok((out, stats)); |
| 178 | } |
| 179 | |
| 180 | let model = st.engine.model().await?; |
| 181 | let from_key = from.map(|f| f.id).unwrap_or("auto"); |
| 182 | |
| 183 | // Which outputs each distinct text fills. |
| 184 | let mut want: HashMap<String, Vec<usize>> = HashMap::new(); |
| 185 | let mut order: Vec<String> = Vec::new(); |
| 186 | for (i, t) in texts.iter().enumerate() { |
| 187 | let (_, core, _) = split_ws(t); |
| 188 | if core.is_empty() || guard::nothing_to_translate(core) { |
| 189 | stats.nothing_to_do += 1; |
| 190 | continue; |
| 191 | } |
| 192 | let key = cache::Cache::key(&model, from_key, to.id, core); |
| 193 | if let Some(hit) = st.cache.get(&key) { |
| 194 | let (lead, _, trail) = split_ws(t); |
| 195 | out[i] = format!("{lead}{hit}{trail}"); |
| 196 | stats.from_cache += 1; |
| 197 | continue; |
| 198 | } |
| 199 | if !want.contains_key(core) { |
| 200 | order.push(core.to_string()); |
| 201 | } |
| 202 | want.entry(core.to_string()).or_default().push(i); |
| 203 | } |
| 204 | |
| 205 | // Batch the remaining texts; if the model's answer for a batch can't be |
| 206 | // matched up, split the batch and try again, down to single items. |
| 207 | let mut queue: Vec<Vec<String>> = Vec::new(); |
| 208 | let mut cur: Vec<String> = Vec::new(); |
| 209 | let mut cur_chars = 0; |
| 210 | for core in order { |
| 211 | let c = core.chars().count(); |
| 212 | if !cur.is_empty() && (cur.len() >= BATCH_ITEMS || cur_chars + c > BATCH_CHARS) { |
| 213 | queue.push(std::mem::take(&mut cur)); |
| 214 | cur_chars = 0; |
| 215 | } |
| 216 | cur_chars += c; |
| 217 | cur.push(core); |
| 218 | } |
| 219 | if !cur.is_empty() { |
| 220 | queue.push(cur); |
| 221 | } |
| 222 | queue.reverse(); |
| 223 | |
| 224 | let mut done: HashMap<String, Option<String>> = HashMap::new(); |
| 225 | while let Some(batch) = queue.pop() { |
| 226 | match st.engine.translate(from, to, &batch, &st.keep).await { |
| 227 | Ok(results) => { |
| 228 | for (src, tr) in batch.iter().zip(results) { |
| 229 | let tr = guard::tidy(src, &tr); |
| 230 | if guard::check(src, &tr, &st.keep).is_none() { |
| 231 | st.cache.put(&cache::Cache::key(&model, from_key, to.id, src), &model, from_key, to.id, src, &tr); |
| 232 | done.insert(src.clone(), Some(tr)); |
| 233 | } else { |
| 234 | done.insert(src.clone(), None); |
| 235 | } |
| 236 | } |
| 237 | } |
| 238 | Err(e) if batch.len() > 1 => { |
| 239 | eprintln!("aien-translate: batch of {} failed ({e}); splitting", batch.len()); |
| 240 | let mut a = batch; |
| 241 | let b = a.split_off(a.len() / 2); |
| 242 | queue.push(b); |
| 243 | queue.push(a); |
| 244 | } |
| 245 | Err(e) => { |
| 246 | eprintln!("aien-translate: item failed ({e}); keeping original"); |
| 247 | done.insert(batch[0].clone(), None); |
| 248 | } |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | for (core, idxs) in want { |
| 253 | let result = done.get(&core).cloned().flatten(); |
| 254 | for i in idxs { |
| 255 | match &result { |
| 256 | Some(tr) => { |
| 257 | let (lead, _, trail) = split_ws(&texts[i]); |
| 258 | out[i] = format!("{lead}{tr}{trail}"); |
| 259 | stats.translated += 1; |
| 260 | } |
| 261 | None => stats.kept_original += 1, |
| 262 | } |
| 263 | } |
| 264 | } |
| 265 | Ok((out, stats)) |
| 266 | } |
| 267 | |
| 268 | /// Merge query string and body parameters (form or JSON body). |
| 269 | fn params(uri: &Uri, headers: &HeaderMap, body: &Bytes) -> HashMap<String, String> { |
| 270 | let mut p: HashMap<String, String> = HashMap::new(); |
| 271 | if let Some(q) = uri.query() { |
| 272 | p.extend(form_urlencoded::parse(q.as_bytes()).into_owned()); |
| 273 | } |
| 274 | let is_json = headers |
| 275 | .get(header::CONTENT_TYPE) |
| 276 | .and_then(|v| v.to_str().ok()) |
| 277 | .is_some_and(|v| v.contains("json")); |
| 278 | if is_json { |
| 279 | if let Ok(Value::Object(m)) = serde_json::from_slice::<Value>(body) { |
| 280 | for (k, v) in m { |
| 281 | let s = match v { |
| 282 | Value::String(s) => s, |
| 283 | other => other.to_string(), |
| 284 | }; |
| 285 | p.insert(k, s); |
| 286 | } |
| 287 | } |
| 288 | } else { |
| 289 | p.extend(form_urlencoded::parse(body).into_owned()); |
| 290 | } |
| 291 | p |
| 292 | } |
| 293 | |
| 294 | /// translate.js sends `text` as a JSON array; accept a plain string too, and |
| 295 | /// one extra layer of URL encoding. |
| 296 | fn parse_text(raw: &str) -> Vec<String> { |
| 297 | let mut s = raw.trim().to_string(); |
| 298 | if s.starts_with("%5B") || s.starts_with("%5b") || s.starts_with("%22") { |
| 299 | if let Some((_, v)) = form_urlencoded::parse(format!("x={s}").as_bytes()).next() { |
| 300 | s = v.into_owned(); |
| 301 | } |
| 302 | } |
| 303 | match serde_json::from_str::<Value>(&s) { |
| 304 | Ok(Value::Array(a)) => a |
| 305 | .into_iter() |
| 306 | .map(|v| match v { |
| 307 | Value::String(s) => s, |
| 308 | other => other.to_string(), |
| 309 | }) |
| 310 | .collect(), |
| 311 | Ok(Value::String(one)) => vec![one], |
| 312 | _ => vec![raw.to_string()], |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | fn fail(info: impl Into<String>) -> Json<Value> { |
| 317 | Json(json!({"result": 0, "info": info.into()})) |
| 318 | } |
| 319 | |
| 320 | async fn translate_h( |
| 321 | State(st): State<Arc<AppState>>, ConnectInfo(peer): ConnectInfo<SocketAddr>, |
| 322 | uri: Uri, headers: HeaderMap, body: Bytes, |
| 323 | ) -> (StatusCode, Json<Value>) { |
| 324 | if !st.admission.authorized(&headers) { |
| 325 | return (StatusCode::UNAUTHORIZED, fail("unauthorized")); |
| 326 | } |
| 327 | if uri.query().is_some_and(|q| q.len() > MAX_REQUEST_BYTES) { |
| 328 | return (StatusCode::PAYLOAD_TOO_LARGE, fail("request too large")); |
| 329 | } |
| 330 | let p = params(&uri, &headers, &body); |
| 331 | let (Some(to), Some(text)) = (p.get("to"), p.get("text")) else { |
| 332 | return (StatusCode::BAD_REQUEST, fail("missing 'to' or 'text'")); |
| 333 | }; |
| 334 | let from = p.get("from").cloned().unwrap_or_default(); |
| 335 | let texts = parse_text(text); |
| 336 | let chars: usize = texts.iter().map(|t| t.chars().count()).sum(); |
| 337 | if texts.len() > st.limits.max_texts || chars > st.limits.max_chars { |
| 338 | return (StatusCode::PAYLOAD_TOO_LARGE, fail(format!( |
| 339 | "request too large: {} texts / {chars} characters (limit {} / {})", |
| 340 | texts.len(), st.limits.max_texts, st.limits.max_chars |
| 341 | ))); |
| 342 | } |
| 343 | if !st.admission.allow_client(peer) { |
| 344 | return (StatusCode::TOO_MANY_REQUESTS, fail("client rate limit")); |
| 345 | } |
| 346 | let Ok(_permit) = st.admission.active.try_acquire() else { |
| 347 | return (StatusCode::TOO_MANY_REQUESTS, fail("translation busy")); |
| 348 | }; |
| 349 | let response = match translate_texts(&st, &from, to, &texts).await { |
| 350 | Ok((out, s)) => Json(json!({ |
| 351 | "result": 1, |
| 352 | "info": "success", |
| 353 | "from": from, |
| 354 | "to": to, |
| 355 | "text": out, |
| 356 | "aien": { |
| 357 | "from_cache": s.from_cache, |
| 358 | "translated": s.translated, |
| 359 | "kept_original": s.kept_original, |
| 360 | "nothing_to_do": s.nothing_to_do, |
| 361 | }, |
| 362 | })), |
| 363 | Err(e) => fail(e), |
| 364 | }; |
| 365 | (StatusCode::OK, response) |
| 366 | } |
| 367 | |
| 368 | |
| 369 | async fn language_h() -> Json<Value> { |
| 370 | let list: Vec<Value> = langs::LANGS |
| 371 | .iter() |
| 372 | .map(|l| json!({"id": l.id, "name": l.name, "serviceId": l.code})) |
| 373 | .collect(); |
| 374 | Json(json!({"result": 1, "info": "success", "list": list})) |
| 375 | } |
| 376 | |
| 377 | async fn connect_h(uri: Uri, headers: HeaderMap, body: Bytes) -> Json<Value> { |
| 378 | let p = params(&uri, &headers, &body); |
| 379 | Json(json!({"result": 1, "info": p.get("host").cloned().unwrap_or_default()})) |
| 380 | } |
| 381 | |
| 382 | async fn init_h() -> Json<Value> { |
| 383 | Json(json!({"result": 1, "info": "success", "version": "1.0.0", "serviceList": ["translate.service"]})) |
| 384 | } |
| 385 | |
| 386 | async fn ip_h() -> Json<Value> { |
| 387 | fail("location lookup is not offered by this server") |
| 388 | } |
| 389 | |
| 390 | async fn health_h(State(st): State<Arc<AppState>>, headers: HeaderMap) -> (StatusCode, Json<Value>) { |
| 391 | if !st.admission.authorized(&headers) { |
| 392 | return (StatusCode::UNAUTHORIZED, fail("unauthorized")); |
| 393 | } |
| 394 | match st.engine.model().await { |
| 395 | Ok(m) => (StatusCode::OK, Json(json!({"result": 1, "info": "ok", "model": m, "languages": langs::LANGS.len()}))), |
| 396 | Err(e) => (StatusCode::OK, fail(e)), |
| 397 | } |
| 398 | } |
| 399 | |
| 400 | pub fn app(state: Arc<AppState>) -> Router { |
| 401 | Router::new() |
| 402 | .route("/translate.json", any(translate_h)) |
| 403 | .route("/language.json", any(language_h)) |
| 404 | .route("/connectTest.json", any(connect_h)) |
| 405 | .route("/init.json", any(init_h)) |
| 406 | .route("/ip.json", any(ip_h)) |
| 407 | .route("/health", get(health_h)) |
| 408 | .layer(DefaultBodyLimit::max(MAX_REQUEST_BYTES)) |
| 409 | .with_state(state) |
| 410 | } |
| 411 | |
| 412 | #[cfg(test)] |
| 413 | mod tests { |
| 414 | use super::*; |
| 415 | |
| 416 | #[test] |
| 417 | fn whitespace_is_kept() { |
| 418 | assert_eq!(split_ws(" hi there \n"), (" ", "hi there", " \n")); |
| 419 | assert_eq!(split_ws(" "), (" ", "", "")); |
| 420 | } |
| 421 | |
| 422 | #[test] |
| 423 | fn cut_link_pieces_stay_at_the_edges() { |
| 424 | assert_eq!(split_ws("Read the docs at https:"), ("", "Read the docs at", " https:")); |
| 425 | assert_eq!(split_ws("www.aienos.com and run"), ("www.aienos.com ", "and run", "")); |
| 426 | assert_eq!(split_ws("github.com/aien-dev/x"), ("github.com/aien-dev/x", "", "")); |
| 427 | assert_eq!(split_ws("Node is fast"), ("", "Node is fast", "")); |
| 428 | } |
| 429 | |
| 430 | #[test] |
| 431 | fn text_forms() { |
| 432 | assert_eq!(parse_text("[\"a\",\"b\"]"), vec!["a", "b"]); |
| 433 | assert_eq!(parse_text("%5B%22a%22%5D"), vec!["a"]); |
| 434 | assert_eq!(parse_text("plain"), vec!["plain"]); |
| 435 | } |
| 436 | |
| 437 | #[test] |
| 438 | fn default_keep_protects_aien_and_its_former_name() { |
| 439 | let keep: Vec<String> = DEFAULT_KEEP.iter().map(|s| s.to_string()).collect(); |
| 440 | let p = guard::protected("Aien runs on Aienux; he used to be called Allen.", &keep); |
| 441 | assert!(p.contains(&"Aien".to_string()), "{p:?}"); |
| 442 | assert!(p.contains(&"Allen".to_string()), "{p:?}"); |
| 443 | assert!(guard::check("Aien is here", "Aien est ici", &keep).is_none()); |
| 444 | assert!(guard::check("Aien is here", "艾恩在这里", &keep).is_some()); |
| 445 | } |
| 446 | } |