App Localization with Python and Argos Translate

Published: (February 26, 2026 at 10:14 PM EST)
7 min read
Source: Dev.to

Source: Dev.to

Localization with Argos Translate (Open‑Source Alternative to DeepL)

Last year I localized a platform from Spanish to English by translating JSON files stored in an es directory and writing the results to an en directory. The process was powered by Python and DeepL, but DeepL is proprietary and limited by usage plans. Below is a cleaned‑up guide showing how to achieve the same workflow with the open‑source Argos Translate (and its API, LibreTranslate).


Table of Contents

  1. Install Dependencies
  2. Download the Language Model
  3. Using the Command‑line Tool
  4. Using the Python Library
  5. Full Example: Translating a JSON File

Install Dependencies

# Argos Translate core library
pip install argostranslate

# Optional: LibreTranslate client (if you want to use the hosted API)
pip install libretranslate
pip install --upgrade --force-reinstall \
    urllib3==1.26.19 \
    charset-normalizer==2.1.1 \
    chardet==4.0.0

These packages are required by Argos Translate and ensure a stable environment.


Download the Language Model

You need a Spanish → English model. It can be installed via the command‑line tool argospm or programmatically from Python.

1. Command‑line installation

argospm install translate-es_en

es = source language (Spanish)
en = target language (English)

2. Python‑based installation (optional)

import argostranslate.package

FROM_CODE = "es"
TO_CODE   = "en"

# Refresh the package index
argostranslate.package.update_package_index()

# Find the desired package
available = argostranslate.package.get_available_packages()
package = next(
    p for p in available
    if p.from_code == FROM_CODE and p.to_code == TO_CODE
)

# Download and install it
argostranslate.package.install_from_path(package.download())

After running either method, the model will be available for translation.


Using the Command‑line Tool

The CLI is handy for quick, one‑off translations (but not for batch JSON processing).

argos-translate --from es --to en "¡Hola mundo!"

Output

Hey, World!

Using the Python Library

The library gives you full programmatic control, which is ideal for translating JSON files or other structured data.

import json
import argostranslate.translate

# ----------------------------------------------------------------------
# 1️⃣ Load installed languages and pick Spanish → English translation
# ----------------------------------------------------------------------
installed = argostranslate.translate.get_installed_languages()
spanish = next(l for l in installed if l.code == "es")
english = next(l for l in installed if l.code == "en")
translator = spanish.get_translation(english)

# ----------------------------------------------------------------------
# 2️⃣ Recursive helper to translate any JSON‑compatible object
# ----------------------------------------------------------------------
def translate_json(obj, trans):
    if isinstance(obj, dict):
        return {k: translate_json(v, trans) for k, v in obj.items()}
    if isinstance(obj, list):
        return [translate_json(item, trans) for item in obj]
    if isinstance(obj, str):
        return trans.translate(obj)
    return obj

# ----------------------------------------------------------------------
# 3️⃣ Load source JSON, translate, and write the result
# ----------------------------------------------------------------------
with open("es/input.json", "r", encoding="utf-8") as f:
    data = json.load(f)

translated = translate_json(data, translator)

with open("en/translated.json", "w", encoding="utf-8") as f:
    json.dump(translated, f, indent=2, ensure_ascii=False)

What the script does

StepDescription
1️⃣Retrieves the installed Spanish and English language objects and creates a translation object.
2️⃣Recursively walks through dictionaries, lists, and strings, translating only the string values.
3️⃣Reads the original input.json, translates it, and writes the output to translated.json (preserving Unicode characters).

Full Example: Translating a JSON File

Sample input.json (Spanish)

{
  "tipo-perfil": {
    "label": "Tipo de perfil",
    "description": "Tipo de perfil",
    "tooltip": "Tipo de perfil",
    "validations": {
      "required": "El campo Tipo de perfil es requerido",
      "minMessage": "El número de caracteres debe ser de al menos {min}",
      "maxMessage": "El número de caracteres debe ser máximo de {max}",
      "regexMessage": "Formato de Tipo de perfil inválido"
    }
  }
}

Result after running the script (translated.json)

{
  "tipo-perfil": {
    "label": "Profile type",
    "description": "Profile type",
    "tooltip": "Profile type",
    "validations": {
      "required": "The Profile type field is required",
      "minMessage": "The number of characters must be at least {min}",
      "maxMessage": "The number of characters must be at most {max}",
      "regexMessage": "Invalid Profile type format"
    }
  }
}

The script preserves the original JSON structure while translating every textual value.


🎉 Wrap‑up

  • Argos Translate + LibreTranslate give you a completely offline, open‑source translation pipeline.
  • Install the library, pull the appropriate language model, and you’re ready to translate any JSON (or other) files programmatically.
  • The same workflow can be adapted for other language pairs—just change the from_code / to_code values (e.g., fren).

Happy localizing! 🚀

Translating JSON Files with Argos Translate and LibreTranslate

Below is a cleaned‑up guide that shows how to translate JSON files from Spanish (es) to English (en) using Argos Translate (local models) and LibreTranslate (online API). The structure and content are preserved; only the unnecessary “Enter fullscreen mode / Exit fullscreen mode” markers and formatting issues have been removed.


1. Argos Translate (local model)

1.1 Load the translation model

installed_languages = argostranslate.translate.get_installed_languages()
spanish = next(filter(lambda l: l.code == "es", installed_languages))
english = next(filter(lambda l: l.code == "en", installed_languages))
translation = spanish.get_translation(english)

1.2 Translate a single JSON file

import json

# Load the source file
with open("input.json", "r", encoding="utf-8") as f:
    data = json.load(f)

# Translate the whole JSON structure
translated_data = translate_json(data, translation)

# Save the translated result
with open("translated.json", "w", encoding="utf-8") as f:
    json.dump(translated_data, f, indent=2, ensure_ascii=False)

Note: translate_json is a recursive function that walks through dictionaries, lists, and strings, translating every string it encounters.

1.3 Process many files recursively

import os
import json

# Add the os module to your imports
# import os   <-- already imported above

input_folder = "es"
output_folder = "en"
os.makedirs(output_folder, exist_ok=True)

def translate_json(obj, translator):
    """Recursively translate JSON‑compatible objects."""
    if isinstance(obj, dict):
        return {k: translate_json(v, translator) for k, v in obj.items()}
    if isinstance(obj, list):
        return [translate_json(i, translator) for i in obj]
    if isinstance(obj, str):
        return translator.translate(obj)
    return obj

for root, _, files in os.walk(input_folder):
    for filename in files:
        if filename.endswith(".json"):
            input_path = os.path.join(root, filename)

            # Preserve the sub‑folder structure in the output folder
            relative_path = os.path.relpath(input_path, input_folder)
            output_path = os.path.join(output_folder, relative_path)
            os.makedirs(os.path.dirname(output_path), exist_ok=True)

            with open(input_path, "r", encoding="utf-8") as f:
                data = json.load(f)

            translated_data = translate_json(data, translation)

            with open(output_path, "w", encoding="utf-8") as f:
                json.dump(translated_data, f, indent=2, ensure_ascii=False)

The block above replaces the single‑file version shown earlier.


2. LibreTranslate (online API)

If you prefer not to install local models, you can use the free LibreTranslate API.

2.1 Imports

import json
import requests
import os

2.2 Helper: translate a single text string

def translate_text(text):
    source = "es"
    target = "en"
    response = requests.post(
        "https://translate.argosopentech.com/translate",
        json={"q": text, "source": source, "target": target},
        headers={"Content-Type": "application/json"},
    )
    response.raise_for_status()
    return response.json()["translatedText"]

2.3 Recursive JSON translator (uses the API)

def translate_json(obj):
    """Recursively translate JSON‑compatible objects using LibreTranslate."""
    if isinstance(obj, dict):
        return {k: translate_json(v) for k, v in obj.items()}
    if isinstance(obj, list):
        return [translate_json(i) for i in obj]
    if isinstance(obj, str):
        return translate_text(obj)
    return obj

2.4 Translate a single file

with open("input.json", "r", encoding="utf-8") as f:
    data = json.load(f)

translated_data = translate_json(data)

with open("translated.json", "w", encoding="utf-8") as f:
    json.dump(translated_data, f, indent=2, ensure_ascii=False)

2.5 Translate many files recursively

input_folder = "es"
output_folder = "en"
os.makedirs(output_folder, exist_ok=True)

for root, _, files in os.walk(input_folder):
    for filename in files:
        if filename.endswith(".json"):
            input_path = os.path.join(root, filename)
            relative_path = os.path.relpath(input_path, input_folder)
            output_path = os.path.join(output_folder, relative_path)
            os.makedirs(os.path.dirname(output_path), exist_ok=True)

            with open(input_path, "r", encoding="utf-8") as f:
                data = json.load(f)

            translated_data = translate_json(data)

            with open(output_path, "w", encoding="utf-8") as f:
                json.dump(translated_data, f, indent=2, ensure_ascii=False)

3. Conclusion

You now have two ready‑to‑use approaches for translating JSON‑based APIs or data files from Spanish to English:

ApproachWhen to useRequirements
Argos Translate (local)Offline work, no network dependency, large volumesargostranslate library + installed language packages
LibreTranslate (API)Quick setup, no local model installationInternet access, requests library

Both scripts handle nested structures automatically and preserve the original folder hierarchy when processing multiple files. Feel free to adapt the source/target language codes (es, en) to suit other language pairs. Happy translating!

It looks like the markdown segment you’d like cleaned up didn’t come through completely—only the word “plications” was included. Could you please resend the full markdown content you’d like me to tidy up? Once I have the complete text, I’ll be able to preserve its structure and content while cleaning it up for you.

0 views
Back to Blog

Related posts

Read more »