# translator: low-cost, context-aware translation

Source: https://www.alouaniyoussef.com/projects/translator

- Kind: open-source
- Status: in-progress
- Updated: 2026-11-27

A FastAPI translation service that answers from a three-tier cache first, then routes each string to NLLB-200 or an LLM by complexity, scoring and storing every new result.

## Problem

Multi-language support across a product ecosystem means translating the same interface strings, product content and JSON documents again and again. Sending everything to an LLM is expensive and slow. A machine-translation model alone is cheap, but it mistranslates brand terms and struggles with long or markup-heavy strings.

translator sits between the two. It reuses what it has already translated, sends simple text to a local NLLB-200 model, and calls an LLM only when a string is complex or carries brand vocabulary. It supports English to and from French, Spanish, Arabic and Chinese.

## Constraints

- **Cost first.** The cheapest answer is a translation that already exists, the next cheapest is a local model, and the LLM comes last.
- **Never reuse a wrong translation.** A cached sentence with a different number, date or negation is a wrong answer, so near matches need checks, not only a similarity score.
- **Brand and domain vocabulary.** Product names, glossary terms and domain rules have to survive translation.
- **Keep document structure.** JSON content must come back with the same keys, array lengths and types.
- **Machine-readable output.** LLM output has to match a schema; free text pasted into a product is a bug.
- **Slow model loading.** Several models must load before translation works, and the service has to report that honestly instead of failing requests.

## Architecture

```mermaid
flowchart TD
  req[Client request] --> check{Translatable?}
  check -->|no| skip([Original returned, skip logged])
  check -->|yes| detect[Detect language · en ↔ fr, es, ar, zh]
  subgraph cache[Cache · trust ≥ 0.85]
    exact[Exact] -->|miss| norm[Normalized · Duckling] -->|miss| sem[Semantic · pgvector ≤ 0.02]
  end
  detect --> exact
  exact & norm & sem -->|hit| cached([Cached translation])
  sem -->|miss| ctx[Context + complexity]
  ctx --> route{Complex or brand?}
  route -->|no| nllb[NLLB-200 3.3B · local]
  route -->|yes| ex[Retrieve up to 3 examples] --> llm[LLM · JSON-schema output]
  nllb & llm --> score[Quality score · multilingual-e5]
  score --> store[(PostgreSQL)] --> fresh([Fresh translation])
  store -. saved for future hits .-> exact
```

A request to `POST /api/v1/translate` goes through six steps:

1. **Verification.** Input with nothing to translate is skipped and recorded: blank text, emoji, URLs, paths, email addresses, numbers and currency amounts. For the rest, the service detects the source language and checks the pair.
2. **Cache lookup**, from strictest to loosest. Only successful translations with a trust score of at least 0.85 qualify.
   - **Exact**: the same text, or its SHA-256 hash.
   - **Normalized**: the same text after Duckling replaces entities such as numbers and dates with placeholders, followed by Unicode NFKC, lowercasing, and punctuation and whitespace cleanup.
   - **Semantic**: the nearest stored source embedding in pgvector, accepted only within a cosine distance of 0.02, with the same entities in the same order and the same negation words.
3. **Context.** On a miss, the service loads the brand profile, merges reusable units into the glossary, and loads domain rules.
4. **Routing.** A complexity score from 0 to 100 combines markup and placeholders, sentence length, vocabulary rarity, glossary and domain jargon, and a readability model. Near the threshold, an LLM rating is averaged in. Text scoring 28 or more, or matching a glossary or brand keyword, goes to the LLM (Gemini, Ollama or OpenRouter); the rest goes to `facebook/nllb-200-3.3B`, running locally on CUDA, Apple MPS or CPU.
5. **Examples for the LLM.** Before an LLM call, the service retrieves up to three similar stored translations and adds them to the prompt as examples.
6. **Scoring and storage.** `intfloat/multilingual-e5-large` scores each new translation by the similarity between source and output. The result is saved with its hashes and source embedding, so it can answer later requests from the cache.

Beyond single strings, `POST /api/v1/document` fetches a JSON document, parses it into a tree and translates its text nodes. Complex and brand-matched nodes go to the LLM in one structured batch. The output is then checked against the original structure. `POST /api/v1/bucket` processes every JSON file under an S3 or MinIO prefix and reuses a previous translation when a file's ETag, size and target language are unchanged. A review endpoint re-checks stored translations whose trust is low and asks the LLM to correct them.

### Known limits

Documenting these is part of the design:

- LLM batches for URL documents skip cache reuse, per-node scoring and storage.
- Bucket jobs run in the API process, with no durable queue.
- The cache is scoped by language pair, not by brand or prompt version, so a changed brand profile does not invalidate earlier hits.
- Source embeddings use `all-MiniLM-L6-v2`, not the multilingual quality model, so retrieval should be evaluated for each language.

## Key decisions

1. **Route by complexity instead of picking one engine.** Most interface strings are short and plain, and NLLB-200 translates them locally at no API cost. The LLM is reserved for text where it is worth paying for: long or markup-heavy strings and brand vocabulary. A glossary match forces LLM routing whatever the score, because a wrong product name costs more than an LLM call.
2. **Cache from strict to loose, and make the loose tier strict.** Exact and normalized hits are cheap and safe, so they run first. The semantic tier is where wrong reuse happens, so it accepts only very close matches (distance ≤ 0.02) and compares entities and negation words. It examines only the nearest candidate and stops if that candidate is rejected.
3. **Keep cache reuse and examples apart.** Both use the same stored embeddings, for different jobs. A cache hit returns a stored translation unchanged and reports `semantic_cache`. Retrieved examples, with a looser distance of 0.4 and up to three per query, only guide a new LLM generation, which still reports `llm`. Every response's `source` field says where its text came from.
4. **Structured output or nothing.** LLM calls use native JSON-schema output. A batch schema requires exactly the supplied keys, with string values and no extras. Invalid output raises an error instead of falling back to raw text, which could otherwise end up in a product unnoticed.
5. **Protect the brand name.** The supplied brand name is replaced with a `{{BRAND_NAME}}` placeholder before translation and restored afterwards, so no engine can translate it.
6. **Serve before the models are ready, and say so.** The API starts at once, and a background monitor checks PostgreSQL, Duckling and the LLM provider, then loads NLLB-200, the embedding, quality and readability models one at a time to limit peak memory. Until all are ready, `/health` and the translation routes answer 503 with `Retry-After`, while `/health/live` only confirms that the process is serving.

## Results

Numbers to come.

## Stack and links

Python, FastAPI, NLLB-200, Ollama, RAG, Semantic search, Embeddings, pgvector, PostgreSQL, Duckling, Object storage, Docker Compose

Repository: https://github.com/alouani-youssef/translator
