googletrans stopped working with error 'NoneType' object has no attribute 'group'
Asked Answered
D

18

214

I was trying googletrans and it was working quite well. Since this morning I started getting below error. I went through multiple posts from stackoverflow and other sites and found probably my ip is banned to use the service for sometime. I tried using multiple service provider internet that has different ip and stil facing the same issue ? I also tried to use googletrans on different laptops , still same issue ..Is googletrans package broken or something google did at their end ?

>>> from googletrans import Translator
>>> translator = Translator()
>>> translator.translate('안녕하세요.')

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    translator.translate('안녕하세요.')
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/client.py", line 172, in translate
    data = self._translate(text, dest, src)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/client.py", line 75, in _translate
    token = self.token_acquirer.do(text)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/gtoken.py", line 180, in do
    self._update()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/gtoken.py", line 59, in _update
    code = unicode(self.RE_TKK.search(r.text).group(1)).replace('var ', '')
AttributeError: 'NoneType' object has no attribute 'group'
Discriminative answered 22/9, 2018 at 10:29 Comment(3)
I just tried and face the same issue you mentioned, not sure why its behaving like this..Vikki
You can fix the problem from this answer Why “Googletrans.Translator” suddenly stopped working?Protero
You can find the solution from hereProtero
M
66

Update 01/12/2020: This issue re-emerged lately, (apparently) caused once again by some changes on the Google translation API.

A solution is being discussed (again) in this Github issue. Although there is not a definitive solution yet a Pull Request seem to be solving the problem: https://github.com/ssut/py-googletrans/pull/237.

While we wait for it to be approved it can be installed like this:

$ pip uninstall googletrans
$ git clone https://github.com/alainrouillon/py-googletrans.git
$ cd ./py-googletrans
$ git checkout origin/feature/enhance-use-of-direct-api
$ python setup.py install

Original Answer:

Apparently it's a recent and widespread problem on Google's side. Quoting various Github discussions, it happens when Google sends you directly the raw token.

It's being discussed right now and there is already a pull request to fix it, so it should be resolved in the next few days.

For reference, see:

https://github.com/ssut/py-googletrans/issues/48 <-- exact same problem reported on the Github repo https://github.com/pndurette/gTTS/issues/60 <-- seemingly same problem on a text-to-speech library https://github.com/ssut/py-googletrans/pull/78 <-- pull request to fix the issue

To apply this patch (without waiting for the pull request to be accepted) simply install the library from the forked repo https://github.com/BoseCorp/py-googletrans.git (uninstall the official library first):

$ pip uninstall googletrans
$ git clone https://github.com/BoseCorp/py-googletrans.git
$ cd ./py-googletrans
$ python setup.py install

You can clone it anywhere on your system and install it globally or while inside a virtualenv.

Meant answered 22/9, 2018 at 11:23 Comment(18)
Thanks!In which location/file I have to put the code from github.com/ssut/py-googletrans/pull/78 for temporary fix ?Discriminative
I'd say something went wrong while uninstalling the official library, with the fix installed it worked for me. Are you familiar with virtualenv? can you try creating a clean virtual environment, installing the pull request package and then running the example again? Also, check if you are actually able to use google translate from its web pageMeant
Yes from webpage I am able to use it. Let me clean it completelyDiscriminative
Its working after proper cleanup. Do you know when the new version will get released.. I looked to the pypi and it seems in next 2 days ?Discriminative
No idea, sorry. I had this problem just today and found out about the fix alongside your questionMeant
On your copy of code now facing this issue: ValueError: No JSON object could be decodedIntracranial
It's not my copy, I didn't create the pull request. The ValueError is discussed as well in github.com/ssut/py-googletrans/pull/78 , and it appears to be unrelated to the fix. It seems the problem is google blocking your IP when requesting too many translations. Does it happen immediatly or after many requests?Meant
My IP is also getting blocked after using the above pull request, although it resolved the "None Type" issue. It happens after 250 requests or something, I have even tried on a different server, the IP is getting blocked after few requests. Earlier I could make thousands of requests and my IP never got blocked. The new pull request has messed up something, any idea?Untenable
I don't think it's the pull request's direct fault. It seems more likely that Google updated its policies (and API) in a way that caused first the NoneType error and then the IP block. I am not really sure though, I just need a few requests per day. Someone suggested to insert some delay between each request.Meant
Hello! Any updates from this? This answer did not work for me :(Hassiehassin
It is an old answer to an old problem that only recently re-emerged. There is a new discussion to fix the issue today and I have updated the answer to mention that,Meant
mh.. I uninstalled and gitcloned exactly as described above, but I'm still getting "AttributeError: 'NoneType' object has no attribute 'group'"Butt
For some reasons it only works when I add the service URL argument like this: translator = Translator(service_urls=['translate.googleapis.com'])Butt
when I use Moritz's hack with service_urls, there is no error, but no translation is given. It returns original text.Cochineal
for me worked installing alpha version: pip install googletrans==3.1.0a0Cochineal
This solution did not work for me. Only installing google_trans_new solved my problem.Meningitis
@Meningitis Thanks google_trans_new solved my problem of translating bn to en.Adenitis
It's 2023 and the issue still there.Savoirfaire
B
246

Update 06.12.20: A new 'official' alpha version of googletrans with a fix was released

Install the alpha version like this:

pip install googletrans==3.1.0a0

Translation example:

translator = Translator()
translation = translator.translate("Der Himmel ist blau und ich mag Bananen", dest='en')
print(translation.text)
#output: 'The sky is blue and I like bananas'

In case it does not work, try to specify the service url like this:

from googletrans import Translator
translator = Translator(service_urls=['translate.googleapis.com'])
translator.translate("Der Himmel ist blau und ich mag Bananen", dest='en')

See the discussion here for details and updates: https://github.com/ssut/py-googletrans/pull/237

Update 10.12.20: Another fix was released

As pointed out by @DesiKeki and @Ahmed Breem, there is another fix which seems to work for several people:

pip install googletrans==4.0.0-rc1

Github discussion here: https://github.com/ssut/py-googletrans/issues/234#issuecomment-742460612

In case the fixes above don't work for you

If the above doesn't work for you, google_trans_new seems to be a good alternative that works for some people. It's unclear why the fix above works for some and doesn't for others. See details on installation and usage here: https://github.com/lushan88a/google_trans_new

#pip install google_trans_new

from google_trans_new import google_translator  
translator = google_translator()  
translate_text = translator.translate('สวัสดีจีน',lang_tgt='en')  
print(translate_text)
#output: Hello china
Butt answered 2/12, 2020 at 13:46 Comment(11)
For me this works also without specifying url. Translating between en and es though.Pneumonic
you are right, now it's working for me too without specifying the service URL. I suppose there was another fixButt
@Butt update, it suddenly stopped working for me, returning original word instead of spanish translation. Had to switch to google_trans_newPneumonic
mh.. weird, it still works for me (just retried it for en-es, es-en, de-en, de-fr etc). is it the same "NoneType object" problem, or a different error message? (Are you sure it's not linked to changes in your python environment or something else?)Butt
@Butt I had the same issue as @ludgo. The package worked thoo like for 3 days then after that it just returns the same text. I tried putting the service_urls but it gives the famous error which is about the token and still same text. I'm not sure why this happen tho but I posted an issue on the github. (link)[github.com/ssut/py-googletrans/issues/254]Hassiehassin
I like this package tho cause it came from the previous one where everyone was experiencing about the token error. But I think I might have to use google_trans_new if this might take too long... Would you happen guys to know if google_trans_new is also derived from this package or the other one? which is google_trans? I think the developer who made it is different.Hassiehassin
@StackOffended: the contributors py-googletrans and google_trans_new are not the same people according to github. Another friend of mine installed the py-googletrans alpha version described above and it worked for them. (I just tried it again, it it still works for me). the best approach is probably to try the alpha version and if it doesn't work for you, switch to google_trans_new. No idea where the issue comes from, unfortunately :/Butt
Okay Thanks! :D but I was just wondering google_trans_new , py-googletrans and the alpha version all just use the same Google Translate API right? I mean why is the alpha version returning the same text thoo while the other don't :/ and when I tried google_trans_new everything's fine. Anyways I think I might go to google_trans_new. :DHassiehassin
I'm getting errors now if I translate a lot of text data. See here (github.com/ssut/py-googletrans/issues/261)[linkerror]Hassiehassin
FWIW - I used the googletrans from the original answer - worked fine. Applied it to a 500 row DF and it stopped working after max tries. Tried google_trans_new on the same DF and it worked fine. Sounds shaky either way.Garvin
Version 4.0.0-rc1 works for me but it returns different results everytime I run the script and still crashes frequently. I guess I need make high stack of handles in my program.Savoirfaire
M
66

Update 01/12/2020: This issue re-emerged lately, (apparently) caused once again by some changes on the Google translation API.

A solution is being discussed (again) in this Github issue. Although there is not a definitive solution yet a Pull Request seem to be solving the problem: https://github.com/ssut/py-googletrans/pull/237.

While we wait for it to be approved it can be installed like this:

$ pip uninstall googletrans
$ git clone https://github.com/alainrouillon/py-googletrans.git
$ cd ./py-googletrans
$ git checkout origin/feature/enhance-use-of-direct-api
$ python setup.py install

Original Answer:

Apparently it's a recent and widespread problem on Google's side. Quoting various Github discussions, it happens when Google sends you directly the raw token.

It's being discussed right now and there is already a pull request to fix it, so it should be resolved in the next few days.

For reference, see:

https://github.com/ssut/py-googletrans/issues/48 <-- exact same problem reported on the Github repo https://github.com/pndurette/gTTS/issues/60 <-- seemingly same problem on a text-to-speech library https://github.com/ssut/py-googletrans/pull/78 <-- pull request to fix the issue

To apply this patch (without waiting for the pull request to be accepted) simply install the library from the forked repo https://github.com/BoseCorp/py-googletrans.git (uninstall the official library first):

$ pip uninstall googletrans
$ git clone https://github.com/BoseCorp/py-googletrans.git
$ cd ./py-googletrans
$ python setup.py install

You can clone it anywhere on your system and install it globally or while inside a virtualenv.

Meant answered 22/9, 2018 at 11:23 Comment(18)
Thanks!In which location/file I have to put the code from github.com/ssut/py-googletrans/pull/78 for temporary fix ?Discriminative
I'd say something went wrong while uninstalling the official library, with the fix installed it worked for me. Are you familiar with virtualenv? can you try creating a clean virtual environment, installing the pull request package and then running the example again? Also, check if you are actually able to use google translate from its web pageMeant
Yes from webpage I am able to use it. Let me clean it completelyDiscriminative
Its working after proper cleanup. Do you know when the new version will get released.. I looked to the pypi and it seems in next 2 days ?Discriminative
No idea, sorry. I had this problem just today and found out about the fix alongside your questionMeant
On your copy of code now facing this issue: ValueError: No JSON object could be decodedIntracranial
It's not my copy, I didn't create the pull request. The ValueError is discussed as well in github.com/ssut/py-googletrans/pull/78 , and it appears to be unrelated to the fix. It seems the problem is google blocking your IP when requesting too many translations. Does it happen immediatly or after many requests?Meant
My IP is also getting blocked after using the above pull request, although it resolved the "None Type" issue. It happens after 250 requests or something, I have even tried on a different server, the IP is getting blocked after few requests. Earlier I could make thousands of requests and my IP never got blocked. The new pull request has messed up something, any idea?Untenable
I don't think it's the pull request's direct fault. It seems more likely that Google updated its policies (and API) in a way that caused first the NoneType error and then the IP block. I am not really sure though, I just need a few requests per day. Someone suggested to insert some delay between each request.Meant
Hello! Any updates from this? This answer did not work for me :(Hassiehassin
It is an old answer to an old problem that only recently re-emerged. There is a new discussion to fix the issue today and I have updated the answer to mention that,Meant
mh.. I uninstalled and gitcloned exactly as described above, but I'm still getting "AttributeError: 'NoneType' object has no attribute 'group'"Butt
For some reasons it only works when I add the service URL argument like this: translator = Translator(service_urls=['translate.googleapis.com'])Butt
when I use Moritz's hack with service_urls, there is no error, but no translation is given. It returns original text.Cochineal
for me worked installing alpha version: pip install googletrans==3.1.0a0Cochineal
This solution did not work for me. Only installing google_trans_new solved my problem.Meningitis
@Meningitis Thanks google_trans_new solved my problem of translating bn to en.Adenitis
It's 2023 and the issue still there.Savoirfaire
A
52

Unfortunately, I could get neither googletrans nor google_trans_new to work, despite the many proposed fixes that are around.

My solution was to switch to the deep_translator package:

pip install -U deep-translator

Then you can use it like this:

>>> from deep_translator import GoogleTranslator
>>> GoogleTranslator(source='auto', target='de').translate("keep it up, you are awesome") 
'weiter so, du bist toll'

See documentation for more info.

Amieeamiel answered 29/6, 2022 at 22:17 Comment(6)
Thanks. It's a cool tool. The problem I encountered with this tool is it cant translate more than 5000 char.Trapshooting
The 5,000 character limit is per request, and afaik it is not a limitation of the package, but the Cloud Translation API. Their web page documents a 6,000,000 character per minute quota, so an option would be to break your text into chunks and make separate requests (see this comment.)Amieeamiel
I've been trying to figure out how to get around that limit by actually paying for the service. So far been unable :-( :shaking head:Inger
After trying everything above this is the solution. I wonder why it's on the very bottom of the page while not being the least upvoted.Savoirfaire
Worked like a Charm !! I tried nearly all versions of GoogleTrans before I tried this. Thanks ! 😊E
jan 2024, This worked for me too. non of googletrans, googletrans==3.1.0a0, googletrans==4.0.0-rc1, google_trans_new, googletrans-py works for me, non of them.Unprofitable
D
49

Try google_trans_new. It solved the problem for me https://github.com/lushan88a/google_trans_new

pip install google_trans_new

from google_trans_new import google_translator  
  
translator = google_translator()  
translate_text = translator.translate('Hola mundo!', lang_src='es', lang_tgt='en')  
print(translate_text)
-> Hello world!
Dissoluble answered 2/12, 2020 at 17:31 Comment(3)
Any way to get the confidence of translation from here? I didn't find any. googletrans is capable of providing confidence.Basenji
Does this support .po files?Operand
Got error: google_trans_new.google_trans_new.google_new_transError: 404 (Not Found) from TTS API. Probable cause: UnknownSavoirfaire
I
25

By the time of this answer, you can solve it with the following:

Uninstall your installed version of

pip uninstall googletrans

Install the following version

pip install googletrans==4.0.0rc1

I hope this will works for you as it worked for me.

You can try it now:

from googletrans import Translator
translator = Translator()
ar = translator.translate('مرحبا').text
print(ar)

Note that 4.0.0rc1 is using an old version of httpx, if you are getting an error regarding that, you need to edit the file client.py, fix httpcore.SyncHTTPTransport to httpcore.AsyncHTTPProxy.

Iridaceous answered 7/6, 2021 at 15:31 Comment(4)
Confirming that this method solved the issue for me. Thanks Abdulkarim Malkadi!Hipped
for me it produced this eror: AttributeError: 'NoneType' object has no attribute 'group' any solutions? thanksSpohr
Doesn't work for bulk translation :(Amphitryon
Thanks this worked for me. @Harrish-selvarajah I did a bulk translate using a function and a loop. This may work for you. python def trans(text, g_src, g_dest): ar = translator.translate(text,src=g_src, dest=g_dest).text return ar Invigilate
A
21

Updated Answer as of 2021 Sept

pip uninstall googletrans==4.0.0-rc1

pip install googletrans==3.1.0a0

The 3.1.0a0 version works with bulk translation too!

Amphitryon answered 21/9, 2021 at 14:51 Comment(4)
In case anyone else is looking for a working solution, as of Dec 2021 was the best one.Zygosis
As of May 2022, this solution worked for me.Gladiate
As of 22-May-2022, this is working fantasticallyCleasta
Nope, this is not working anymore..?Igniter
P
19

Update 10.12.20: New Alpha Version Release (Stable Release Candidate) is released: 4.0.0-rc1

It can be installed as follows:

pip install googletrans==4.0.0-rc1

Usage:

translation = translator.translate('이 문장은 한글로 쓰여졌습니다.', dest='en')
print(translation.text)
>>This sentence is written in Korean.
detected_lang = translator.detect('mein english me hindi likh raha hoon')
print(detected_lang)
>>Detected(lang=hi, confidence=None)
detected_lang = translator.detect('이 문장은 한글로 쓰여졌습니다.')
print(detected_lang)
>>Detected(lang=ko, confidence=None)
Peaceful answered 21/12, 2020 at 2:36 Comment(4)
It works for me July 29, 2021 in Python 3.7.3 on Debian 10. Thanks!Bourke
It works for me Feb 14, 2022 in Python 3.8.10 on Linux. Thanks!Flowerage
It worked for me, 2nd Sep, 2022Igniter
this works january 2023Maccarthy
F
11

Here is an unofficial fix to this problem as Darkblader24 stated in: https://github.com/ssut/py-googletrans/pull/78

Update gtoken.py like this:

    RE_TKK = re.compile(r'TKK=eval\(\'\(\(function\(\)\{(.+?)\}\)\(\)\)\'\);',
                        re.DOTALL)
    RE_RAWTKK = re.compile(r'TKK=\'([^\']*)\';',re.DOTALL)

    def __init__(self, tkk='0', session=None, host='translate.google.com'):
        self.session = session or requests.Session()
        self.tkk = tkk
        self.host = host if 'http' in host else 'https://' + host

    def _update(self):
        """update tkk
        """
        # we don't need to update the base TKK value when it is still valid
        now = math.floor(int(time.time() * 1000) / 3600000.0)
        if self.tkk and int(self.tkk.split('.')[0]) == now:
            return

        r = self.session.get(self.host)

        rawtkk = self.RE_RAWTKK.search(r.text)
        if rawtkk:
            self.tkk = rawtkk.group(1)
            return
Forint answered 24/9, 2018 at 20:49 Comment(2)
The other solution didn't work for me but this one did! Thanks!Translunar
I replaced the code but it seem like it's not loaded while execution. I put some "prints". Does the script really uses this _update function?Savoirfaire
M
8

This worked for me:

pip install googletrans==4.0.0-rc1

Original answer can be found here: https://github.com/ssut/py-googletrans/issues/234#issuecomment-742460612

Middlebuster answered 18/12, 2020 at 8:15 Comment(0)
B
6
pip uninstall googletrans googletrans-temp
pip install googletrans-temp

Worked for me in Win10 and Ubuntu 16 (Python 3.6) as of 2019.2.24 -- Refer to one of the replies in https://github.com/ssut/py-googletrans/issues/94. The old fix pip install git+https://github.com/BoseCorp/py-googletrans.git --upgrade does not work any more over here.

Burnedout answered 19/10, 2018 at 4:18 Comment(3)
Need to restart the kernel when working on jupyter. Other than that, works great.Scathing
Probably just need to reload, in Py3, e.g., import importlib; import googletrans; importlib.reload(googletrans)Burnedout
Still doesn't work for me: ~~~import googletrans as gt translator = gt.Translator() translation = translator.translate('Hello') print(translation.text)~~~ ---> 66 code = unicode(self.RE_TKK.search(r.text).group(1)).replace('var ', '') 67 # unescape special ascii characters such like a \x3d(=) 68 if PY3: # pragma: no cover AttributeError: 'NoneType' object has no attribute 'group'Addle
M
6

Fixed is here https://pypi.org/project/py-translator/

$ pip3 install py_translator==1.8.9

from py_translator import Translator
s = Translator().translate(text='Hello my friend', dest='es').text
print(s)

out:Hola mi amigo

Malinin answered 18/11, 2018 at 14:35 Comment(0)
O
2

googletrans is not supported in latest python so you need to unistall it

install new googletrans ( pip install googletrans==3.1.0a0)

Obsequies answered 21/7, 2021 at 14:41 Comment(0)
C
2

This is how I fixed my problem.

pip3 uninstall googletrans
pip3 install googletrans==3.1.0a0

First you need to uninstall the previous version and the install the 3.1.0 version.

Cassette answered 13/10, 2021 at 1:38 Comment(0)
V
2

Use the translators package from here

  1. It works (;
  2. Supports more then google

Installation:

pip install translators --upgrade

Usage:


    >>> import translators as ts
    Using Israel server backend.
    >>> ts.google('שלום' , to_language = 'es')
    'Hola'
    

Vagrant answered 13/2, 2022 at 9:23 Comment(0)
C
1

Making the following change to gtoken made it work for me:

RE_TKK = re.compile(r'tkk:\'(.+?)\'')      

def __init__(self, tkk='0', session=None, host='translate.google.com'):
    self.session = session or requests.Session()
    self.tkk = tkk
    self.host = host if 'http' in host else 'https://' + host

def _update(self):
    """update tkk
    """
    # we don't need to update the base TKK value when it is still valid
    r = self.session.get(self.host)        

    self.tkk = self.RE_TKK.findall(r.text)[0]

    now = math.floor(int(time.time() * 1000) / 3600000.0)
    if self.tkk and int(self.tkk.split('.')[0]) == now:
        return

    # this will be the same as python code after stripping out a reserved word 'var'
    code = unicode(self.RE_TKK.search(r.text).group(1)).replace('var ', '')
    # unescape special ascii characters such like a \x3d(=)

I obtained this snippet from the ticket here.

Note that this is slightly different from other change suggested earlier by Kerem.

For other uninitiated folks like me, gtoken.py can be found within AppData\Local\Continuum\anaconda3\site-packages\googletrans on a Windows machine using Anaconda. To find AppData, go into the address bar in file explorer, type '%AppData%', and hit Enter.

Chlorophyll answered 28/3, 2019 at 16:12 Comment(0)
S
1

It turns out putting the call whithin a try/except block solved the problem for me

try:
    langs = translator.detect(update.message.text)
    if langs.lang == 'en':
        foo(translator.translate(update.message.text,dest='zh-cn').text)
    else:
        bar(translator.translate(update.message.text,dest='en').text)
except Exception as e:
    print(e)
Spiritualize answered 17/5, 2020 at 20:24 Comment(0)
H
1

If you are using Google Colab or Jupyter Notebook, then run:

!pip uninstall googletrans

Restart the runtime, and then execute:

!pip install googletrans==4.0.0rc1
Hoch answered 25/11, 2022 at 6:48 Comment(0)
O
0

Try - pip install googletrans==3.1.0a0

Osteo answered 16/9, 2022 at 18:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.