LibreTranslate Python Bindings

2.1.4 · active · verified Wed Apr 15

libretranslatepy provides Python bindings for the LibreTranslate API, a free and open-source machine translation API. It allows Python applications to interact with a LibreTranslate server for translation, language detection, and language listing. The library is currently at version 2.1.4, released in April 2024, and is actively maintained as a client for the continuously developed LibreTranslate ecosystem.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `LibreTranslateAPI` client, translate text, detect language, and list supported languages. It highlights the use of environment variables for configuring the server URL and API key, which is crucial for interacting with public LibreTranslate instances that often require authentication.

import os
from libretranslatepy import LibreTranslateAPI

# Configure LibreTranslate server URL and optional API Key
# For public instances like libretranslate.com, an API key is often required.
# For a self-hosted instance, an API key might be optional depending on server configuration.
LIBRETRANSLATE_URL = os.environ.get('LIBRETRANSLATE_URL', 'https://libretranslate.com/')
LIBRETRANSLATE_API_KEY = os.environ.get('LIBRETRANSLATE_API_KEY', None)

# Initialize the API client
lt = LibreTranslateAPI(LIBRETRANSLATE_URL, api_key=LIBRETRANSLATE_API_KEY)

# Translate text from English to Spanish
text_to_translate = "Hello, how are you?"
source_lang = "en"
target_lang = "es"

try:
    translated_text = lt.translate(text_to_translate, source_lang, target_lang)
    print(f"Original ({source_lang}): {text_to_translate}")
    print(f"Translated ({target_lang}): {translated_text}")

    # Detect language
    detection_result = lt.detect("Hola mundo")
    print(f"Detected language for 'Hola mundo': {detection_result}")

    # List available languages
    languages = lt.languages()
    # print(f"Available languages: {languages}") # Uncomment to see all
    print(f"Number of available languages: {len(languages)}")

except Exception as e:
    print(f"An error occurred: {e}")
    if 'HTTP Error 403: Forbidden' in str(e) or 'HTTP Error 400: Bad Request' in str(e):
        print("\nHint: Public LibreTranslate instances often require an API key.")
        print("Set the LIBRETRANSLATE_API_KEY environment variable or ensure your server doesn't require one.")

view raw JSON →