Google Cloud Translate Python Client

3.25.0 · active · verified Sun Mar 29

The `google-cloud-translate` client library provides Python programmatic access to Google Cloud Translation API. It allows dynamic translation of text between thousands of language pairs and detection of source languages. The current stable version is 3.25.0, and the library is actively maintained with frequent updates as part of the broader `google-cloud-python` ecosystem.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to translate text and detect its language using the Google Cloud Translation v3 API. It relies on Application Default Credentials for authentication and requires a Google Cloud project with the Cloud Translation API enabled. Set your `GOOGLE_CLOUD_PROJECT` environment variable for seamless authentication.

import os
from google.cloud import translate

# Your Google Cloud Project ID
# Set the environment variable GOOGLE_CLOUD_PROJECT or replace with your Project ID
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT", "your-project-id")

if project_id == "your-project-id":
    print("WARNING: Please set the GOOGLE_CLOUD_PROJECT environment variable or replace 'your-project-id' with your actual project ID.")
    print("Authentication may fail without a valid project ID.")

# Create a client for the v3 API
client = translate.TranslationServiceClient()

# The 'parent' parameter specifies the project and location
# 'global' is a common location, but you can specify other regions if needed.
parent = f"projects/{project_id}/locations/global"

text_to_translate = "Hello, world!"
target_language = "es"
source_language = "en"

# Translate text using the v3 API
try:
    response = client.translate_text(
        request={
            "parent": parent,
            "contents": [text_to_translate],
            "mime_type": "text/plain",
            "source_language_code": source_language,
            "target_language_code": target_language,
        }
    )

    print(f"Original text: {text_to_translate}")
    for translation in response.translations:
        print(f"Translated text: {translation.translated_text}")
except Exception as e:
    print(f"An error occurred: {e}")
    print("Ensure you have enabled the Cloud Translation API for your project and configured authentication (e.g., GOOGLE_APPLICATION_CREDENTIALS).")

# Example for language detection (v3)
# client for v3 is the same
text_to_detect = "Bonjour le monde!"

try:
    response = client.detect_language(
        request={
            "parent": parent,
            "content": text_to_detect,
            "mime_type": "text/plain",
        }
    )
    print(f"\nText for detection: {text_to_detect}")
    for language in response.languages:
        print(f"Detected language: {language.language_code} (Confidence: {language.confidence:.2f})")
except Exception as e:
    print(f"An error occurred during language detection: {e}")

view raw JSON →