Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONDecodeError using Google Translate API with Python3

I've searched thoroughly on Stack Overflow but couldn't find an answer to this problem. I'm trying to use the Google Translate API (googletrans 2.2.0) for Python (3.6.2) and am trying to translate a set of non-English documents into English. I am letting Google Translate do the language detection. Here is my code:

## newcorpus is a corpus I have created consisting of non-english documents
fileids = newcorpus.fileids
for f in fileids:
    p = newcorpus.raw(f) 
    p = str(p[:15000])
    translated_text = translator.translate(p)
    print(translated_text)
    sleep(10)

I am throttling my call to the API by waiting 10 seconds every time. I am also only feeding the API 15k characters at a time to remain within the character limit.

Every time I run this code I get the following error message:

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Can anybody help?

like image 843
Roald Schuring Avatar asked Dec 29 '17 10:12

Roald Schuring


People also ask

How do I translate a Google translator into Python?

You can also translate text documents via Google Translate API. All you have to do is to read the text file in Python using the open method, read the text and pass it to the translate() method. You can also check whether or not the file is in "read" mode using the mode property: if f.

Can I use Google Translate API for free?

The Google Translate API is not free. Its pricing is based off monthly usage in terms of millions of characters. It costs $20 per 1 million characters for translation or language detection. Price is per character sent to the API for processing, including whitespace characters.

Can I use Google Translate API?

Translation API Basic uses Google's neural machine translation technology to instantly translate texts into more than one hundred languages. Translation API Advanced offers the same fast, dynamic results you get with Basic and additional customization features.


2 Answers

You have to stop using googletrans until they fix it, and use translate instead :

https://pypi.org/project/translate/

like image 29
mounirboulwafa Avatar answered Oct 08 '22 06:10

mounirboulwafa


I think I may have found an answer to my own question. If I reduce the number of characters I feed to the API at once to 5k, everything seems to work fine. Strange since the Googletrans documentation says that the limit is 15k... Ah well. I will have to batch the request.

like image 138
Roald Schuring Avatar answered Oct 08 '22 04:10

Roald Schuring