TRANSLATE
The TRANSLATE function provides high-quality machine translation directly in the environment using OPUS-MT transformer models.
The function returns a 2D array of translated text strings corresponding to the input range.
Supported Languages:
Most major languages are supported for translation to and from English. At least one of the source or target languages must be English (en).
Excel Usage
=TRANSLATE(text, source_lang, target_lang)
text(list[list], required): Single text cell or 2D text range to translate.source_lang(str, optional, default: “en”): The language code of the text to translate.target_lang(str, optional, default: “fr”): The language code to translate into.
Returns (list[list]): 2D array of translated strings.
Example 1: English to French translation
Inputs:
| text | source_lang | target_lang |
|---|---|---|
| Hello, how are you? | en | fr |
Excel formula:
=TRANSLATE("Hello, how are you?", "en", "fr")
Expected output:
"Bonjour, comment allez-vous?"
Example 2: Spanish to English translation
Inputs:
| text | source_lang | target_lang |
|---|---|---|
| Hola, ¿cómo estás? | es | en |
Excel formula:
=TRANSLATE("Hola, ¿cómo estás?", "es", "en")
Expected output:
"Hey, how are you?"
Example 3: French to English translation
Inputs:
| text | source_lang | target_lang |
|---|---|---|
| Bonjour le monde! | fr | en |
Excel formula:
=TRANSLATE("Bonjour le monde!", "fr", "en")
Expected output:
"Hello, world!"
Python Code
Show Code
import pyodide
async def translate(text, source_lang='en', target_lang='fr'):
"""
Machine translation using OPUS-MT transformer models.
See: https://huggingface.co/docs/transformers.js
This example function is provided as-is without any representation of accuracy.
Args:
text (list[list]): Single text cell or 2D text range to translate.
source_lang (str, optional): The language code of the text to translate. Valid options: English, Afrikaans, Arabic, Czech, Danish, Dutch, Finnish, French, German, Hindi, Hungarian, Indonesian, Italian, Russian, Spanish, Swedish, Ukrainian, Vietnamese, Xhosa, Chinese. Default is 'en'.
target_lang (str, optional): The language code to translate into. Valid options: English, Afrikaans, Arabic, Czech, Danish, Dutch, Finnish, French, German, Hindi, Hungarian, Indonesian, Italian, Russian, Spanish, Swedish, Ukrainian, Vietnamese, Xhosa, Chinese. Default is 'fr'.
Returns:
list[list]: 2D array of translated strings.
"""
try:
def to2d(value):
return [[value]] if not isinstance(value, list) else value
def validate_grid(value):
if not isinstance(value, list) or not value or not all(isinstance(row, list) for row in value):
return None, "Error: text must be a non-empty 2D list"
if len({len(row) for row in value}) != 1:
return None, "Error: text must be a rectangular 2D list"
return value, None
text_grid, error = validate_grid(to2d(text))
if error:
return error
if source_lang != 'en' and target_lang != 'en':
return "Error: Either source_lang or target_lang must be English (en)"
if source_lang == target_lang:
return "Error: source_lang and target_lang cannot be the same"
model_name = f"Xenova/opus-mt-{source_lang}-{target_lang}"
# Singleton pattern to load pipeline and model only once
js_code = f"""
(async () => {{
if (!globalThis._transformers_pipeline) {{
const {{ pipeline, env }} = await import('https://cdn.jsdelivr.net/npm/@xenova/[email protected]');
env.allowLocalModels = false;
globalThis._transformers_pipeline = pipeline;
}}
if (!globalThis._translate_pipes) globalThis._translate_pipes = {{}};
const model = "{model_name}";
if (!globalThis._translate_pipes[model]) {{
globalThis._translate_pipes[model] = await globalThis._transformers_pipeline("translation", model, {{ quantized: true }});
}}
return globalThis._translate_pipes[model];
}})()
"""
try:
pipe = await pyodide.code.run_js(js_code)
except Exception as e:
return f"Error: Failed to load model {model_name}. Details: {str(e)}"
result = []
for row in text_grid:
out_row = []
for cell in row:
if cell is None or (isinstance(cell, str) and not cell.strip()):
out_row.append("")
continue
if not isinstance(cell, str):
out_row.append("Error: text must contain only strings")
continue
try:
raw_result = await pipe(cell)
except Exception as e:
return f"Error: Failed to run model {model_name}. Details: {str(e)}"
if hasattr(raw_result, "to_py"):
prediction = raw_result.to_py()[0]
else:
prediction = raw_result[0]
translated_text = str(prediction.get("translation_text", ""))
out_row.append(translated_text)
result.append(out_row)
return result
except Exception as e:
return f"Error: {str(e)}"Online Calculator
Single text cell or 2D text range to translate.
The language code of the text to translate.
The language code to translate into.