python-3.xgoogle-cloud-platformgoogle-translategoogle-translation-api

Google Translate API TypeError: TranslationServiceClient.translate_text() got an unexpected keyword argument 'request'


I am using Google Translate API to translate docs and I am using their API and boy is it broken.

I am using this link to create a function that can translate a given input text,

For this code block I am getting the following error

# Imports the Google Cloud Translation library
from google.cloud import translate


# Initialize Translation client
def translate_text(
text: str = "YOUR_TEXT_TO_TRANSLATE", project_id: str = "YOUR_PROJECT_ID"
) -> translate.TranslationServiceClient:
"""Translating Text."""

client = translate.TranslationServiceClient()

location = "global"

parent = f"projects/{project_id}/locations/{location}"

# Translate text from English to French
# Detail on supported types can be found here:
# https://cloud.google.com/translate/docs/supported-formats
response = client.translate_text(
    request={
        "parent": parent,
        "contents": [text],
        "mime_type": "text/plain",  # mime types: text/plain, text/html
        "source_language_code": "en-US",
        "target_language_code": "fr",
    }
)

# Display the translation for each input text provided
for translation in response.translations:
    print(f"Translated text: {translation.translated_text}")

return response

I am getting this error and I am not sure what is going on

TypeError: TranslationServiceClient.translate_text() got an unexpected keyword 
argument 'request'

Solution

  • Terrible docs, you can just follow the definition of translate_text() to see how it's supposed to work now (assuming there used to be a param request), but this still sucks. https://cloud.google.com/translate/docs/advanced/translate-text-advance

    request = {
        "parent": parent,
        "contents": [text],
        "mime_type": "text/plain",  # mime types: text/plain, text/html
        "source_language_code": "en-US",
        "target_language_code": "fr",
    }
    
    response = client.translate_text(**request)