Giter VIP home page Giter VIP logo

py-googletrans's Introduction

Googletrans

GitHub license travis status Documentation Status PyPI version Coverage Status Code Climate

Googletrans is a free and unlimited python library that implemented Google Translate API. This uses the Google Translate Ajax API to make calls to such methods as detect and translate.

Compatible with Python 3.6+.

For details refer to the API Documentation.

Features

  • Fast and reliable - it uses the same servers that translate.google.com uses
  • Auto language detection
  • Bulk translations
  • Customizable service URL
  • HTTP/2 support

TODO

more features are coming soon.

  • Proxy support
  • Internal session management (for better bulk translations)

HTTP/2 support

This library uses httpx for HTTP requests so HTTP/2 is supported by default.

You can check if http2 is enabled and working by the ._response.http_version of Translated or Detected object:

>>> translator.translate('테스트')._response.http_version
# 'HTTP/2'

How does this library work

You may wonder why this library works properly, whereas other approaches such like goslate won't work since Google has updated its translation service recently with a ticket mechanism to prevent a lot of crawler programs.

I eventually figure out a way to generate a ticket by reverse engineering on the obfuscated and minified code used by Google to generate such token, and implemented on the top of Python. However, this could be blocked at any time.


Installation

To install, either use things like pip with the package "googletrans" or download the package and put the "googletrans" directory into your python path.

$ pip install googletrans

Basic Usage

If source language is not given, google translate attempts to detect the source language.

>>> from googletrans import Translator
>>> translator = Translator()
>>> translator.translate('안녕하세요.')
# <Translated src=ko dest=en text=Good evening. pronunciation=Good evening.>
>>> translator.translate('안녕하세요.', dest='ja')
# <Translated src=ko dest=ja text=こんにちは。 pronunciation=Kon'nichiwa.>
>>> translator.translate('veritas lux mea', src='la')
# <Translated src=la dest=en text=The truth is my light pronunciation=The truth is my light>

Customize service URL

You can use another google translate domain for translation. If multiple URLs are provided, it then randomly chooses a domain.

>>> from googletrans import Translator
>>> translator = Translator(service_urls=[
      'translate.google.com',
      'translate.google.co.kr',
    ])

Advanced Usage (Bulk)

Array can be used to translate a batch of strings in a single method call and a single HTTP session. The exact same method shown above works for arrays as well.

>>> translations = translator.translate(['The quick brown fox', 'jumps over', 'the lazy dog'], dest='ko')
>>> for translation in translations:
...    print(translation.origin, ' -> ', translation.text)
# The quick brown fox  ->  빠른 갈색 여우
# jumps over  ->  이상 점프
# the lazy dog  ->  게으른 개

Language detection

The detect method, as its name implies, identifies the language used in a given sentence.

>>> from googletrans import Translator
>>> translator = Translator()
>>> translator.detect('이 문장은 한글로 쓰여졌습니다.')
# <Detected lang=ko confidence=0.27041003>
>>> translator.detect('この文章は日本語で書かれました。')
# <Detected lang=ja confidence=0.64889508>
>>> translator.detect('This sentence is written in English.')
# <Detected lang=en confidence=0.22348526>
>>> translator.detect('Tiu frazo estas skribita en Esperanto.')
# <Detected lang=eo confidence=0.10538048>

GoogleTrans as a command line application

$ translate -h
usage: translate [-h] [-d DEST] [-s SRC] [-c] text

Python Google Translator as a command-line tool

positional arguments:
  text                  The text you want to translate.

optional arguments:
  -h, --help            show this help message and exit
  -d DEST, --dest DEST  The destination language you want to translate.
                        (Default: en)
  -s SRC, --src SRC     The source language you want to translate. (Default:
                        auto)
  -c, --detect

$ translate "veritas lux mea" -s la -d en
[veritas] veritas lux mea
    ->
[en] The truth is my light
[pron.] The truth is my light

$ translate -c "안녕하세요."
[ko, 1] 안녕하세요.

Note on library usage

DISCLAIMER: this is an unofficial library using the web API of translate.google.com and also is not associated with Google.

  • The maximum character limit on a single text is 15k.
  • Due to limitations of the web version of google translate, this API does not guarantee that the library would work properly at all times (so please use this library if you don't care about stability).
  • Important: If you want to use a stable API, I highly recommend you to use Google's official translate API.
  • If you get HTTP 5xx error or errors like #6, it's probably because Google has banned your client IP address.

Versioning

This library follows Semantic Versioning from v2.0.0. Any release versioned 0.x.y is subject to backwards incompatible changes at any time.

Contributing

Contributions are more than welcomed. See CONTRIBUTING.md


License

Googletrans is licensed under the MIT License. The terms are as follows:

The MIT License (MIT)

Copyright (c) 2015 SuHun Han

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

py-googletrans's People

Contributors

abdusalamstd avatar adipose avatar aleksanyan avatar bionicbug avatar clinjie avatar cove9988 avatar djailla avatar elzeard91 avatar jmolinski avatar msusik avatar nieole avatar paethon avatar roadcrosser avatar sinwoobang avatar soumendrak avatar ssut avatar tbm avatar terryyz avatar universeroc avatar vuolter avatar weaming avatar xmfbit avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

py-googletrans's Issues

another special char problem

It's me again. :)

I found there is another problem with special char - Guillemet (《). When an Chinese or Japanese char is behind a Guillemet, the program will get an error just like #13

Failure to decode unicode

Trying to translate over certain unicode characters does not work. In particular, trying to translate with sentences that contain unicode characters that are emojis.

Traceback (most recent call last):
File "C:/Users/Taylor/Desktop/TEST/sentAnalysis.py", line 139, in
main()
File "C:/Users/Taylor/Desktop/TEST/sentAnalysis.py", line 95, in main
translatedTweet = translator.translate(originalTweet, dest="en", src=tweetObject["lang"]).text
File "C:\python36\lib\site-packages\googletrans\client.py", line 132, in translate
data = self._translate(text, dest, src)
File "C:\python36\lib\site-packages\googletrans\client.py", line 63, in translate
data = utils.format_json(r.text)
File "C:\python36\lib\site-packages\googletrans\utils.py", line 62, in format_json
converted = legacy_format_json(original)
File "C:\python36\lib\site-packages\googletrans\utils.py", line 54, in legacy_format_json
converted = json.loads(text)
File "C:\python36\lib\json_init
.py", line 354, in loads
return _default_decoder.decode(s)
File "C:\python36\lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\python36\lib\json\decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Error using library

I can't use any function because I receive "<googletrans.models.Translated at 0x1nnnnnnnn>" for any line
after "translator = Translator()" . Using Python 3.6.2 or 3.5.2
Is there a solution ?

"Your client does not have permission to get URL ..."

I was trying out various translators to test whether I can ditch using mine and this project looks promising, but I get 403 error with it:

rr-@tornado:~$ virtualenv derp    
Using base prefix '/usr'
New python executable in /home/rr-/derp/bin/python
Installing setuptools, pip, wheel...done.

rr-@tornado:~$ source ./derp/bin/activate 
(derp) rr-@tornado:~$ pip install py-googletrans
Collecting py-googletrans
Collecting requests (from py-googletrans)
  Using cached requests-2.9.1-py2.py3-none-any.whl
Collecting future (from py-googletrans)
Installing collected packages: requests, future, py-googletrans
Successfully installed future-0.15.2 py-googletrans-1.2 requests-2.9.1

(derp) rr-@tornado:~$ ./derp/bin/translate 子牛  
original text:  <!DOCTYPE html>
<html lang=en>
  <meta charset=utf-8>
  <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
  <title>Error 403 (Forbidden)!!1</title>
  <style>
    *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}#logo{background:url(//www.google.com/images/branding/googlelogo/1x/googlelogo_color_150x54dp.png) no-repeat;margin-left:-5px}@media only screen and (min-resolution:192dpi){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat 0% 0%/100% 100%;-moz-border-image:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) 0}}@media only screen and (-webkit-min-device-pixel-ratio:2){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat;-webkit-background-size:100% 100%}}#logo{display:inline-block;height:54px;width:150px}
  </style>
  <a href=//www.google.com/><span id=logo aria-label=Google></span></a>
  <p><b>403.</b> <ins>That’s an error.</ins>
  <p>Your client does not have permission to get URL <code>/translate_a/single?client=t&amp;sl=auto&amp;tl=en&amp;hl=en&amp;dt=bd&amp;dt=rm&amp;dt=ss&amp;dt=t&amp;dt=at&amp;ie=UTF-8&amp;oe=UTF-8&amp;q=%E5%AD%90%E7%89%9B</code> from this server.  <ins>That’s all we know.</ins>
  =>  <!DOCTYPE html>
<html lang=en>
  <meta charset=utf-8>
  <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
  <title>Error 403 (Forbidden)!!1</title>
  <style>
    *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}#logo{background:url(//www.google.com/images/branding/googlelogo/1x/googlelogo_color_150x54dp.png) no-repeat;margin-left:-5px}@media only screen and (min-resolution:192dpi){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat 0% 0%/100% 100%;-moz-border-image:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) 0}}@media only screen and (-webkit-min-device-pixel-ratio:2){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat;-webkit-background-size:100% 100%}}#logo{display:inline-block;height:54px;width:150px}
  </style>
  <a href=//www.google.com/><span id=logo aria-label=Google></span></a>
  <p><b>403.</b> <ins>That’s an error.</ins>
  <p>Your client does not have permission to get URL <code>/translate_a/single?client=t&amp;sl=auto&amp;tl=en&amp;hl=en&amp;dt=bd&amp;dt=rm&amp;dt=ss&amp;dt=t&amp;dt=at&amp;ie=UTF-8&amp;oe=UTF-8&amp;q=%E5%AD%90%E7%89%9B</code> from this server.  <ins>That’s all we know.</ins>

Traceback (most recent call last):
  File "/home/rr-/derp/lib/python3.5/site-packages/googletrans/conversion.py", line 34, in format_json
    converted = json.loads(text)
  File "/usr/lib64/python3.5/json/__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "/usr/lib64/python3.5/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib64/python3.5/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Traceback (most recent call last):
  File "./derp/bin/translate", line 44, in <module>
    main()
  File "./derp/bin/translate", line 30, in main
    result = translator.translate(args.text, dest=args.dest, src=args.src)
  File "/home/rr-/derp/lib/python3.5/site-packages/googletrans/translator.py", line 100, in translate
    data = format_json(r.text)
  File "/home/rr-/derp/lib/python3.5/site-packages/googletrans/conversion.py", line 38, in format_json
    return converted
UnboundLocalError: local variable 'converted' referenced before assignment

Note that I have no problems with web access or with my script.

translate file in command line

Everytime I try to translate a file in the command line, I end translating the destiny "C:/". Goslate worked well with files.

translate problem in cli after installing pip

I tried delete all pip and googletrans (folder, cache and other via rm -rf)
and reinstall, but has an error occurs

Install pip use this post 1

curl https://bootstrap.pypa.io/get-pip.py | sudo python3

Also have another linux machine (Ubuntu 16-04.2) and there installs by normally and works

error
 $ translate me
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 560, in urlopen
    body=body, headers=headers)
  File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 346, in _make_request
    self._validate_conn(conn)
  File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 787, in _validate_conn
    conn.connect()
  File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 252, in connect
    ssl_version=resolved_ssl_version)
  File "/usr/lib/python3/dist-packages/urllib3/util/ssl_.py", line 305, in ssl_wrap_socket
    return context.wrap_socket(sock, server_hostname=server_hostname)
  File "/usr/lib/python3.5/ssl.py", line 377, in wrap_socket
    _context=self)
  File "/usr/lib/python3.5/ssl.py", line 752, in __init__
    self.do_handshake()
  File "/usr/lib/python3.5/ssl.py", line 988, in do_handshake
    self._sslobj.do_handshake()
  File "/usr/lib/python3.5/ssl.py", line 633, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/requests/adapters.py", line 376, in send
    timeout=timeout
  File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 589, in urlopen
    raise SSLError(e)
requests.packages.urllib3.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/bin/translate", line 40, in <module>
    main()
  File "/usr/local/bin/translate", line 29, in main
    result = translator.translate(args.text, dest=args.dest, src=args.src)
  File "/usr/local/lib/python3.5/dist-packages/googletrans/client.py", line 132, in translate
    data = self._translate(text, dest, src)
  File "/usr/local/lib/python3.5/dist-packages/googletrans/client.py", line 57, in _translate
    token = self.token_acquirer.do(text)
  File "/usr/local/lib/python3.5/dist-packages/googletrans/gtoken.py", line 180, in do
    self._update()
  File "/usr/local/lib/python3.5/dist-packages/googletrans/gtoken.py", line 57, in _update
    r = self.session.get(self.host)
  File "/usr/lib/python3/dist-packages/requests/sessions.py", line 480, in get
    return self.request('GET', url, **kwargs)
  File "/usr/lib/python3/dist-packages/requests/sessions.py", line 468, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/lib/python3/dist-packages/requests/sessions.py", line 576, in send
    r = adapter.send(request, **kwargs)
  File "/usr/lib/python3/dist-packages/requests/adapters.py", line 447, in send
    raise SSLError(e, request=request)
requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)
Ubuntu version
 $ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.3 LTS
Release:        16.04
Codename:       xenial
kernel version
4.4.0-104-generic #127-Ubuntu SMP Mon Dec 11 12:16:42 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
python
python version
 $ python -V
Python 2.7.12

 $ python3 -V
Python 3.5.2
python installed
ii  dh-python                                    2.20151103ubuntu1.1                                      all          Debian helper tools for packaging Python libraries and applications
ii  libpython-dev:amd64                          2.7.12-1~16.04                                           amd64        header files and a static library for Python (default)
ii  libpython-stdlib:amd64                       2.7.12-1~16.04                                           amd64        interactive high-level object-oriented language (default python version)
ii  libpython2.7:amd64                           2.7.12-1ubuntu0~16.04.3                                  amd64        Shared Python runtime library (version 2.7)
ii  libpython2.7-dev:amd64                       2.7.12-1ubuntu0~16.04.3                                  amd64        Header files and a static library for Python (v2.7)
ii  libpython2.7-minimal:amd64                   2.7.12-1ubuntu0~16.04.3                                  amd64        Minimal subset of the Python language (version 2.7)
ii  libpython2.7-stdlib:amd64                    2.7.12-1ubuntu0~16.04.3                                  amd64        Interactive high-level object-oriented language (standard library, version 2.7)
ii  libpython3-dev:amd64                         3.5.1-3                                                  amd64        header files and a static library for Python (default)
ii  libpython3-stdlib:amd64                      3.5.1-3                                                  amd64        interactive high-level object-oriented language (default python3 version)
ii  libpython3.5:amd64                           3.5.2-2ubuntu0~16.04.4                                   amd64        Shared Python runtime library (version 3.5)
ii  libpython3.5-dev:amd64                       3.5.2-2ubuntu0~16.04.4                                   amd64        Header files and a static library for Python (v3.5)
ii  libpython3.5-minimal:amd64                   3.5.2-2ubuntu0~16.04.4                                   amd64        Minimal subset of the Python language (version 3.5)
ii  libpython3.5-stdlib:amd64                    3.5.2-2ubuntu0~16.04.4                                   amd64        Interactive high-level object-oriented language (standard library, version 3.5)
ii  python                                       2.7.12-1~16.04                                           amd64        interactive high-level object-oriented language (default version)
ii  python-apt                                   1.1.0~beta1ubuntu0.16.04.1                               amd64        Python interface to libapt-pkg
ii  python-apt-common                            1.1.0~beta1build1                                        all          Python interface to libapt-pkg (locales)
ii  python-bs4                                   4.4.1-1                                                  all          error-tolerant HTML parser for Python
ii  python-certbot-apache                        0.22.0-1+ubuntu16.04.1+certbot+2                         all          transitional dummy package
ii  python-certbot-nginx                         0.22.0-1+ubuntu16.04.1+certbot+2                         all          transitional dummy package
ii  python-chardet                               2.3.0-2                                                  all          universal character encoding detector for Python2
ii  python-crypto                                2.6.1-6ubuntu0.16.04.2                                   amd64        cryptographic algorithms and protocols for Python
ii  python-debian                                0.1.27ubuntu2                                            all          Python modules to work with Debian-related data formats
ii  python-defer                                 1.0.6-2build1                                            all          Small framework for asynchronous programming (Python 2)
ii  python-dev                                   2.7.12-1~16.04                                           amd64        header files and a static library for Python (default)
ii  python-gi                                    3.20.0-0ubuntu1                                          amd64        Python 2.x bindings for gobject-introspection libraries
ii  python-html5lib                              0.999-4                                                  all          HTML parser/tokenizer based on the WHATWG HTML5 specification (Python 2)
ii  python-ldb                                   2:1.1.24-1ubuntu3                                        amd64        Python bindings for LDB
ii  python-lxml                                  3.5.0-1build1                                            amd64        pythonic binding for the libxml2 and libxslt libraries
ii  python-minimal                               2.7.12-1~16.04                                           amd64        minimal subset of the Python language (default version)
ii  python-pbr                                   1.8.0-4ubuntu1                                           all          inject useful and sensible default behaviors into setuptools - Python 2.x
ii  python-pkg-resources                         33.1.1-1+certbot~xenial+1                                all          Package Discovery and Resource Access using pkg_resources
ii  python-psutil                                5.0.1-1+certbot~xenial+2                                 amd64        module providing convenience functions for managing processes
ii  python-samba                                 2:4.3.11+dfsg-0ubuntu0.16.04.13                          amd64        Python bindings for Samba
ii  python-setuptools                            33.1.1-1+certbot~xenial+1                                all          Python Distutils Enhancements
ii  python-six                                   1.10.0-3                                                 all          Python 2 and 3 compatibility library (Python 2 interface)
ii  python-talloc                                2.1.5-2                                                  amd64        hierarchical pool based memory allocator - Python bindings
ii  python-tdb                                   1.3.8-2                                                  amd64        Python bindings for TDB
ii  python-tz                                    2014.10~dfsg1-0ubuntu2                                   all          Python version of the Olson timezone database
ii  python-xdg                                   0.25-4                                                   all          Python 2 library to access freedesktop.org standards
ii  python-xkit                                  0.5.0ubuntu2                                             all          library for the manipulation of xorg.conf files (Python 2)
ii  python2.7                                    2.7.12-1ubuntu0~16.04.3                                  amd64        Interactive high-level object-oriented language (version 2.7)
ii  python2.7-dev                                2.7.12-1ubuntu0~16.04.3                                  amd64        Header files and a static library for Python (v2.7)
ii  python2.7-minimal                            2.7.12-1ubuntu0~16.04.3                                  amd64        Minimal subset of the Python language (version 2.7)
ii  python3                                      3.5.1-3                                                  amd64        interactive high-level object-oriented language (default python3 version)
ii  python3-acme                                 0.22.2-1+ubuntu16.04.1+certbot+1                         all          ACME protocol library for Python 3
ii  python3-apport                               2.20.1-0ubuntu2.14                                       all          Python 3 library for Apport crash report handling
ii  python3-apt                                  1.1.0~beta1build1                                        amd64        Python 3 interface to libapt-pkg
ii  python3-aptdaemon                            1.1.1+bzr982-0ubuntu14                                   all          Python 3 module for the server and client of aptdaemon
ii  python3-aptdaemon.pkcompat                   1.1.1+bzr982-0ubuntu14                                   all          PackageKit compatibilty for AptDaemon
ii  python3-asn1crypto                           0.22.0-2+ubuntu16.04.1+certbot+1                         all          Fast ASN.1 parser and serializer (Python 3)
ii  python3-augeas                               0.5.0-1+ubuntu16.04.1+certbot+1                          all          Python3 bindings for Augeas
ii  python3-certbot                              0.22.2-1+ubuntu16.04.1+certbot+1                         all          main library for certbot
ii  python3-certbot-apache                       0.22.0-1+ubuntu16.04.1+certbot+2                         all          Apache plugin for Certbot
ii  python3-certbot-nginx                        0.22.0-1+ubuntu16.04.1+certbot+2                         all          Nginx plugin for Certbot
ii  python3-cffi-backend                         1.10.0-0.1+ubuntu16.04.1+certbot+1                       amd64        Foreign Function Interface for Python 3 calling C code - runtime
ii  python3-chardet                              2.3.0-2                                                  all          universal character encoding detector for Python3
ii  python3-commandnotfound                      0.3ubuntu16.04.2                                         all          Python 3 bindings for command-not-found.
ii  python3-configargparse                       0.11.0-1+certbot~xenial+1                                all          replacement for argparse with config files and environment variables (Python 3)
ii  python3-configobj                            5.0.6-2+ubuntu16.04.1+certbot+1                          all          simple but powerful config file reader and writer for Python 3
ii  python3-cryptography                         1.9-1+ubuntu16.04.1+certbot+2                            amd64        Python library exposing cryptographic recipes and primitives (Python 3)
ii  python3-dbus                                 1.2.0-3                                                  amd64        simple interprocess messaging system (Python 3 interface)
ii  python3-debian                               0.1.27ubuntu2                                            all          Python 3 modules to work with Debian-related data formats
ii  python3-defer                                1.0.6-2build1                                            all          Small framework for asynchronous programming (Python 3)
ii  python3-distupgrade                          1:16.04.23                                               all          manage release upgrades
ii  python3-funcsigs                             0.4-2                                                    all          function signatures from PEP362 - Python 3.x
ii  python3-future                               0.15.2-4+ubuntu16.04.1+certbot+3                         all          Clean single-source support for Python 3 and 2 - Python 3.x
ii  python3-gdbm:amd64                           3.5.1-1                                                  amd64        GNU dbm database support for Python 3.x
ii  python3-gi                                   3.20.0-0ubuntu1                                          amd64        Python 3 bindings for gobject-introspection libraries
ii  python3-icu                                  1.9.2-2build1                                            amd64        Python 3 extension wrapping the ICU C++ API
ii  python3-idna                                 2.5-1+ubuntu16.04.1+certbot+1                            all          Python IDNA2008 (RFC 5891) handling (Python 3)
ii  python3-josepy                               1.0.1-1+ubuntu16.04.1+certbot+7                          all          JOSE implementation for Python 3.x
ii  python3-minimal                              3.5.1-3                                                  amd64        minimal subset of the Python language (default python3 version)
ii  python3-mock                                 1.3.0-2.1ubuntu1                                         all          Mocking and Testing Library (Python3 version)
ii  python3-ndg-httpsclient                      0.4.2-1+certbot~xenial+1                                 all          enhanced HTTPS support for httplib and urllib2 using PyOpenSSL for Python3
ii  python3-newt                                 0.52.18-1ubuntu2                                         amd64        NEWT module for Python3
ii  python3-openssl                              17.3.0-1~0+ubuntu16.04.1+certbot+1                       all          Python 3 wrapper around the OpenSSL library
ii  python3-parsedatetime                        2.4-3+ubuntu16.04.1+certbot+3                            all          Python 3 module to parse human-readable date/time expressions
ii  python3-pbr                                  1.8.0-4ubuntu1                                           all          inject useful and sensible default behaviors into setuptools - Python 3.x
ii  python3-pkg-resources                        33.1.1-1+certbot~xenial+1                                all          Package Discovery and Resource Access using pkg_resources
ii  python3-problem-report                       2.20.1-0ubuntu2.17                                       all          Python 3 library to handle problem reports
ii  python3-pyasn1                               0.1.9-2+certbot~xenial+1                                 all          ASN.1 library for Python (Python 3 module)
ii  python3-pycurl                               7.43.0-1ubuntu1                                          amd64        Python bindings to libcurl (Python 3)
ii  python3-pyparsing                            2.0.3+dfsg1-1ubuntu0.1                                   all          Python parsing module, Python3 package
ii  python3-requests                             2.9.1-3                                                  all          elegant and simple HTTP library for Python3, built for human beings
ii  python3-rfc3339                              1.0-4+certbot~xenial+1                                   all          parser and generator of RFC 3339-compliant timestamps (Python 3)
ii  python3-setuptools                           33.1.1-1+certbot~xenial+1                                all          Python3 Distutils Enhancements
ii  python3-six                                  1.10.0-3                                                 all          Python 2 and 3 compatibility library (Python 3 interface)
ii  python3-software-properties                  0.96.20.7                                                all          manage the repositories that you install software from
ii  python3-systemd                              231-2build1                                              amd64        Python 3 bindings for systemd
ii  python3-tz                                   2014.10~dfsg1-0ubuntu2                                   all          Python3 version of the Olson timezone database
ii  python3-update-manager                       1:16.04.12                                               all          python 3.x module for update-manager
ii  python3-urllib3                              1.13.1-2ubuntu0.16.04.1                                  all          HTTP library with thread-safe connection pooling for Python3
ii  python3-zope.component                       4.3.0-1+ubuntu16.04.1+certbot+3                          all          Zope Component Architecture
ii  python3-zope.event                           4.2.0-1                                                  all          Very basic event publishing system
ii  python3-zope.hookable                        4.0.4-4+ubuntu16.04.1+certbot+1                          amd64        Hookable object support
ii  python3-zope.interface                       4.3.2-1+ubuntu16.04.1+certbot+1                          amd64        Interfaces for Python3
ii  python3.5                                    3.5.2-2ubuntu0~16.04.4                                   amd64        Interactive high-level object-oriented language (version 3.5)
ii  python3.5-dev                                3.5.2-2ubuntu0~16.04.4                                   amd64        Header files and a static library for Python (v3.5)
ii  python3.5-minimal                            3.5.2-2ubuntu0~16.04.4                                   amd64        Minimal subset of the Python language (version 3.5)
pip version
 $ pip -V
pip 10.0.1 from /usr/local/lib/python3.5/dist-packages/pip (python 3.5)
pip installed
Package             Version
------------------- -------
acme                0.22.2 
asn1crypto          0.22.0 
certbot             0.22.2 
certbot-apache      0.22.0 
certbot-nginx       0.22.0 
chardet             2.3.0  
command-not-found   0.3    
ConfigArgParse      0.11.0 
configobj           5.0.6  
cryptography        1.9    
defer               1.0.6  
googletrans         2.2.0 
funcsigs            0.4    
future              0.15.2 
idna                2.5    
josepy              1.0.1  
language-selector   0.1    
mock                1.3.0  
ndg-httpsclient     0.4.2  
parsedatetime       2.4    
pbr                 1.8.0  
pip                 10.0.1 
pyasn1              0.1.9  
pycurl              7.43.0 
pygobject           3.20.0 
PyICU               1.9.2  
pyOpenSSL           17.3.0 
pyparsing           2.0.3  
pyRFC3339           1.0    
python-apt          1.1.0b1
python-augeas       0.5.0  
python-debian       0.1.27 
python-systemd      231    
pytz                2014.10
requests            2.9.1  
setuptools          33.1.1 
six                 1.10.0 
ssh-import-id       5.5    
ufw                 0.35   
unattended-upgrades 0.1    
urllib3             1.13.1 
wheel               0.31.1 
zope.component      4.3.0  
zope.event          4.2.0  
zope.hookable       4.0.4  
zope.interface      4.3.2  

long text (>1745), en to zh_CN) throws ValueError exception

Tried with two different files in utf-8 format (Python 3.4, 32 bit Windows 7). Long text can probably be trimmed down to 1745 and some warning given, instead of sudden death.

import googletrans
googletrans.Translator('translate.google.cn')
text = '''...'''
texttr = translator.translate(text[:1745], dest='zh-CN') # ok
texttr = translator.translate(text[:1746], dest='zh-CN')

ValueError Traceback (most recent call last)
in ()
----> 1 texttr = translator.translate(text[:1746], dest='zh-CN')

d:\python34\lib\site-packages\googletrans\client.py in translate(self, text, dest, src)
127
128 origin = text
--> 129 data = self._translate(text, dest, src)
130
131 # this code will be updated when the format is changed.

d:\python34\lib\site-packages\googletrans\client.py in _translate(self, text, dest, src)
79 r = self.session.get(url, params=params)
80
---> 81 data = utils.format_json(r.text)
82 return data
83

d:\python34\lib\site-packages\googletrans\utils.py in format_json(original)
49 text = text[:p] + states[j][1] + text[nxt:]
50
---> 51 converted = json.loads(text)
52 return converted
53

d:\python34\lib\json_init_.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
316 parse_int is None and parse_float is None and
317 parse_constant is None and object_pairs_hook is None and not kw):
--> 318 return _default_decoder.decode(s)
319 if cls is None:
320 cls = JSONDecoder

d:\python34\lib\json\decoder.py in decode(self, s, _w)
341
342 """
--> 343 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
344 end = _w(s, end).end()
345 if end != len(s):

d:\python34\lib\json\decoder.py in raw_decode(self, s, idx)
359 obj, end = self.scan_once(s, idx)
360 except StopIteration as err:
--> 361 raise ValueError(errmsg("Expecting value", s, err.value)) from None
362 return obj, end

ValueError: Expecting value: line 1 column 1 (char 0)

When detecting text it returns a language not in the list.

I implemented this API in a discord bot (very nice API, it works well), and I was trying to translate some turkish text "Oh deme püf de!" that someone sent.
When i set it to detect the language, it sent an error and I figured out it thought the language was "trro" when it was Turkish.
This is not in googletrans.LANGUAGES nor does it make sense since the actual google translate detects it as Turkish.

Release in pypi

The latest release in pypi is 2.2.0, which is same as the source version.
but the code is not the same

Some sentences can not be translated correctly.

I found that some sentences that special chars or number or english words connected with CCJK chars can not be translated correctly. The program will return the source text directly, not the target. The following is some examples. You can test them:

Source:

⑥公司收到付款信息后将注册码发送至消费者邮箱;
1来源:http://www.199it.com/archives/xxxxx.html。
Wondershare Vivideo 软件
IN 部门

Enlish results from Google Translate Web:

⑥ company received payment information after the registration code sent to the consumer mailbox;
1 Source: http: //www.199it.com/archives/xxxxx.html.
Wondershare Vivideo software
IN department

How many requests are allowed?

Please let me know if I am using the library for experimental purpose, till what count I can make requests.
I have more that 1 billion sentences to translate and analyze for my NLP project.
Kindly, suggest me.

Special Case for Unspecified Chinese

Could we add a case for when someone uses zh as a destination language to translate as either simplified or traditional Chinese? If people are abiding by ISO-639-1 they'll be using zh as the identifier for Chinese rather than zh-cn or zh-tw.

I think translating to simplified over traditional would make more sense personally.

Implementation of batch translation

        if isinstance(text, list):
            result = []
            for item in text:
                translated = self.translate(item, dest=dest, src=src)
                result.append(translated)
        return result

As far as I can see, batch processing is implemented here (client.py, Translator.translate).
How is this faster than calling translate() multiple times from outside the library? If it is not, the documentation should clarify that batch processing is only a convenience function and does not offer any performance benefits.
I would expect batch translation needs a single HTTP round-trip, but if I understand the code correctly, this is not the case.

bulk mode is very slow for its high amount of strings to be translated?

I'm trying to translate .srt subtitle files both in a method translate each line of sentence one by one,
pt7s5c0 mrb8 i 3 fwbgkx

and another way with bulk translating an array/list of sentences for a single HTTP session.
sysedq et6865i 94mi3h0

BUT, the bulk way is very slow and easy to get Errors, is it true? How to improve the speed?

Could not initial with proxies param

Code:

from googletrans import Translator
socks5 = 'socks5://127.0.0.1'
proxies = {'http': socks5, 'https': socks5}
translator = Translator(proxies=proxies)

Result:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() got an unexpected keyword argument 'proxies'

It seems like pypi version still not had this feature.
Code in client.py#L33-46:

def __init__(self, service_urls=None, user_agent=DEFAULT_USER_AGENT):
        self.session = requests.Session()
        self.session.headers.update({
            'User-Agent': user_agent,
        })
        self.service_urls = service_urls or ['translate.google.com']
        self.token_acquirer = TokenAcquirer(session=self.session, host=self.service_urls[0])

        # Use HTTP2 Adapter if hyper is installed
        try:  # pragma: nocover
            from hyper.contrib import HTTP20Adapter
            self.session.mount(urls.BASE, HTTP20Adapter())
        except ImportError:  # pragma: nocover
            pass

Compatible with h2==3.0.1

I have a issue when upgrade h2 package to version 3.0.1

module 'h2.settings' has no attribute 'ENABLE_PUSH'

Please make this package compatible with latest.
Thank you !

AttributeError: 'NoneType' object has no attribute 'group'

My script like this:
#-- coding:utf-8 --
from googletrans import Translator
import sys
import io

translator = Translator()
tanstext = u'我们'
tran_ch = translator.translate(tanstext ).text
print tran_ch
###############
yesterday this is ok and no problem,but today I run my script without internet, show some problem.And I run the script in the internet environment, but it's show same problem,can't run.
The cmd show the Traceback like this:
Traceback (most recent call last):
File "D:\JDstory\workstory\translation-project\filetocut\trans-test.py", line
10, in
tran_ch = translator.translate(tanstext).text
File "D:\software\Python27\lib\site-packages\googletrans\client.py", line 132,
in translate
data = self._translate(text, dest, src)
File "D:\software\Python27\lib\site-packages\googletrans\client.py", line 57,
in _translate
token = self.token_acquirer.do(text)
File "D:\software\Python27\lib\site-packages\googletrans\gtoken.py", line 180,
in do
self._update()
File "D:\software\Python27\lib\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'
#########################
That's why? Thank you so much!

Google translate in angular 5 not working

I want to add multi language support in my website.However most of the data is coming from API so I cant make a JSON of it. I am using Google Translate but it is not working. Can you please share steps as how to inject it in my angular 5 application? Much thanks in advance :)

Wrong encoding when translating to Portuguese

When translating from English to Portuguese,I'm getting some wrongly encoded text.
res_pt = Translator().translate('The answer is 299792 kilometers per second',dest='pt').text
res_pt contains:
A resposta \u00e9 299792 quil\u00f4metros por segundo
But should contain:
A resposta é 299792 quilômetros por segundo

Chinese/Japanese errors causing exceptions

Attempting to translate strings with either "," or "、" doubled (i.e. ",,", "、、") raises an exception:

`translator.translate("I`` need TofeL here ,, they dont know IELTS !! , Smart pepole anyway it is same to study for me . Thank u Omy .")

raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 258 (char 257)

I don't know if there is anything you can do about this - I'm getting around it by pre-screening the data and removing the offending sequences.

Uncaught error on a simple translation (ver 1.1.1 via pip)

$ translate -s ee ajuvaba
Traceback (most recent call last):
File "/usr/local/bin/translate", line 38, in
main()
File "/usr/local/bin/translate", line 27, in main
result = translator.translate(args.text, dest=args.dest, src=args.src)
File "/usr/local/lib/python3.4/dist-packages/googletrans/translator.py", line 92, in translate
translated = data[0][0][0]
TypeError: 'NoneType' object is not subscriptable

encoding or decoding problem?

If there was a sepecial char, such as copyright symbol (© ),the program gets an error.
No JSON object could be decoded

Error Message: size = len(text) TypeError: object of type 'float' has no len()

Hi,

I don't have a clue what I'm doing/doing wrong, but I have the following script. What should it do:
-Open an excel sheet
-choose the desired values and put them in a list
-choose source and destination language
-translate

Here the code:

<script src="https://gist.github.com/Martinhasnoclue/a2cf9c785236c20d07f7ce3ce5433763.js"></script>

The error message:

Traceback (most recent call last):
File "Translator.py", line 45, in
translations = translator.translate(data, dest = dest_lan, src = source_lan)

File "C:\Users\fzdb7b\Python\lib\site-packages\googletrans\client.py", line 167, in translate
translated = self.translate(item, dest=dest, src=src)
File "C:\Users\fzdb7b\Python\lib\site-packages\googletrans\client.py", line 172, in translate
data = self._translate(text, dest, src)
File "C:\Users\fzdb7b\Python\lib\site-packages\googletrans\client.py", line 75, in _translate
token = self.token_acquirer.do(text)
File "C:\Users\fzdb7b\Python\lib\site-packages\googletrans\gtoken.py", line 181, in do
tk = self.acquire(text)
File "C:\Users\fzdb7b\Python\lib\site-packages\googletrans\gtoken.py", line 145, in acquire
size = len(text)
TypeError: object of type 'float' has no len()

Error happens every time. Using python 3.6.1. Works fine if I put random words in

data=["chien", "bon jour"]
The worksheet has a lot of rows (> 2500). It seems that there is a problem with the content. In column 7 there is text like: "ABC_DEF_GHI" and in column 19 is text like: "0x00: ABC_DEF \n0x01: GHI_KLM.

Perhaps somebody can help.
Thx

Error when used in a kaggle kernel

I decided to translate a russian data set to english and while I was testing with some minimal code, this happened:

CODE
from googletrans import Translator
translator = Translator()
translator.translate('туфли')

ERROR
`---------------------------------------------------------------------------
gaierror Traceback (most recent call last)
/opt/conda/lib/python3.6/site-packages/urllib3/connection.py in _new_conn(self)
140 conn = connection.create_connection(
--> 141 (self.host, self.port), self.timeout, **extra_kw)
142

/opt/conda/lib/python3.6/site-packages/urllib3/util/connection.py in create_connection(address, timeout, source_address, socket_options)
59
---> 60 for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
61 af, socktype, proto, canonname, sa = res

/opt/conda/lib/python3.6/socket.py in getaddrinfo(host, port, family, type, proto, flags)
744 addrlist = []
--> 745 for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
746 af, socktype, proto, canonname, sa = res

gaierror: [Errno -3] Temporary failure in name resolution

During handling of the above exception, another exception occurred:

NewConnectionError Traceback (most recent call last)
/opt/conda/lib/python3.6/site-packages/urllib3/connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
600 body=body, headers=headers,
--> 601 chunked=chunked)
602

/opt/conda/lib/python3.6/site-packages/urllib3/connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
345 try:
--> 346 self._validate_conn(conn)
347 except (SocketTimeout, BaseSSLError) as e:

/opt/conda/lib/python3.6/site-packages/urllib3/connectionpool.py in _validate_conn(self, conn)
849 if not getattr(conn, 'sock', None): # AppEngine might not have .sock
--> 850 conn.connect()
851

/opt/conda/lib/python3.6/site-packages/urllib3/connection.py in connect(self)
283 # Add certificate verification
--> 284 conn = self._new_conn()
285

/opt/conda/lib/python3.6/site-packages/urllib3/connection.py in _new_conn(self)
149 raise NewConnectionError(
--> 150 self, "Failed to establish a new connection: %s" % e)
151

NewConnectionError: <urllib3.connection.VerifiedHTTPSConnection object at 0x7efd768b6400>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution

During handling of the above exception, another exception occurred:

MaxRetryError Traceback (most recent call last)
/opt/conda/lib/python3.6/site-packages/requests/adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
439 retries=self.max_retries,
--> 440 timeout=timeout
441 )

/opt/conda/lib/python3.6/site-packages/urllib3/connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
638 retries = retries.increment(method, url, error=e, _pool=self,
--> 639 _stacktrace=sys.exc_info()[2])
640 retries.sleep()

/opt/conda/lib/python3.6/site-packages/urllib3/util/retry.py in increment(self, method, url, response, error, _pool, _stacktrace)
387 if new_retry.is_exhausted():
--> 388 raise MaxRetryError(_pool, url, error or ResponseError(cause))
389

MaxRetryError: HTTPSConnectionPool(host='translate.google.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7efd768b6400>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',))

During handling of the above exception, another exception occurred:

ConnectionError Traceback (most recent call last)
in ()
1 from googletrans import Translator
2 translator = Translator()
----> 3 translator.translate('туфли')

/opt/conda/lib/python3.6/site-packages/googletrans/client.py in translate(self, text, dest, src)
148
149 origin = text
--> 150 data = self._translate(text, dest, src)
151
152 # this code will be updated when the format is changed.

/opt/conda/lib/python3.6/site-packages/googletrans/client.py in _translate(self, text, dest, src)
73 text = text.decode('utf-8')
74
---> 75 token = self.token_acquirer.do(text)
76 params = utils.build_params(query=text, src=src, dest=dest,
77 token=token)

/opt/conda/lib/python3.6/site-packages/googletrans/gtoken.py in do(self, text)
178
179 def do(self, text):
--> 180 self._update()
181 tk = self.acquire(text)
182 return tk

/opt/conda/lib/python3.6/site-packages/googletrans/gtoken.py in _update(self)
55 return
56
---> 57 r = self.session.get(self.host)
58 # this will be the same as python code after stripping out a reserved word 'var'
59 code = unicode(self.RE_TKK.search(r.text).group(1)).replace('var ', '')

/opt/conda/lib/python3.6/site-packages/requests/sessions.py in get(self, url, **kwargs)
519
520 kwargs.setdefault('allow_redirects', True)
--> 521 return self.request('GET', url, **kwargs)
522
523 def options(self, url, **kwargs):

/opt/conda/lib/python3.6/site-packages/requests/sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
506 }
507 send_kwargs.update(settings)
--> 508 resp = self.send(prep, **send_kwargs)
509
510 return resp

/opt/conda/lib/python3.6/site-packages/requests/sessions.py in send(self, request, **kwargs)
616
617 # Send the request
--> 618 r = adapter.send(request, **kwargs)
619
620 # Total elapsed time of the request (approximately)

/opt/conda/lib/python3.6/site-packages/requests/adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
506 raise SSLError(e, request=request)
507
--> 508 raise ConnectionError(e, request=request)
509
510 except ClosedPoolError as e:

ConnectionError: HTTPSConnectionPool(host='translate.google.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7efd768b6400>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',))`

What might be the reason for this?

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

I am trying to translate a list of tokens from chinese to english. I get the following error after a few attempts of translation. Is this because of rate limits?

File "/home/sharath/.local/lib/python3.5/site-packages/googletrans/client.py", line 127, in translate
   translated = self.translate(item, dest=dest, src=src)
 File "/home/sharath/.local/lib/python3.5/site-packages/googletrans/client.py", line 132, in translate
   data = self._translate(text, dest, src)
 File "/home/sharath/.local/lib/python3.5/site-packages/googletrans/client.py", line 63, in _translate
   data = utils.format_json(r.text)
 File "/home/sharath/.local/lib/python3.5/site-packages/googletrans/utils.py", line 62, in format_json
   converted = legacy_format_json(original)
 File "/home/sharath/.local/lib/python3.5/site-packages/googletrans/utils.py", line 54, in legacy_format_json
   converted = json.loads(text)
 File "/data/anaconda2/envs/dlatk/lib/python3.5/json/__init__.py", line 319, in loads
   return _default_decoder.decode(s)
 File "/data/anaconda2/envs/dlatk/lib/python3.5/json/decoder.py", line 339, in decode
   obj, end = self.raw_decode(s, idx=_w(s, 0).end())
 File "/data/anaconda2/envs/dlatk/lib/python3.5/json/decoder.py", line 357, in raw_decode
   raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Encoding error with python2

$ translate -d ru "test"
Traceback (most recent call last):
  File "/usr/local/bin/translate", line 44, in <module>
    main()
  File "/usr/local/bin/translate", line 40, in main
    pronunciation=pronunciation)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

works well with python3

Can't auto deploy in empty virtualenv

Hi,
When I want to automatic deploy on server django project, which contains 'py-googletrans' library in requirements.txt, or simply run pip install -r requirements.txt on new empty virtualenv, I get:

$ pip install googletrans --no-cache-dir
Collecting googletrans
  Downloading googletrans-2.1.2.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-5cKA5j/googletrans/setup.py", line 3, in <module>
        import googletrans
      File "googletrans/__init__.py", line 7, in <module>
        from googletrans.client import Translator
      File "googletrans/client.py", line 7, in <module>
        import requests
    ImportError: No module named requests

This error is caused by chain of imports:
setup.py > init.py > client.py > requests
So setup.py run requests before instaling it.

I know that in this paragraph of docs @ssut remind that if I want to install 'googletrans' I must install requests before, but this is very uncomfortable during automatic deploy.

In my pull request, #23 I add solution on this issue.

Please add all google supported languages

I found the language "Bengali" was not added into the list. I have successfully run it adding 'bn': 'bengali' in LANGUAGES dictionary of file py-googletrans/googletrans/constants.py.

Error issues with connection

Hi

I had been using the code for a while and then recently the same code will not translate - states that the error is related to the Json request. Have Google changed the API?
Thanks

Feature request: incorporating requests_cache

Very nice thanks! Hope it lasts...:)

I wonder if you can incorperate request_cache in googletrans.

The use of requests_cache may reduce the possibility of an IP being blocked. For simple use, just add these two lines after import requests in client.py:

import requests_cache
requests_cache.install_cache('googletrans_cache')

I tested in Python 3.4, it works great. I am not proficient enough to suggest any more sophisticated use of request_cache though.

I got an error (python3.6/macos)

:( emoji in a sentence. (e.g.) "Great app for styling photo's 👍"

File "", line 1, in
File "/Users/fotor-desktop/anaconda/lib/python3.6/site-packages/googletrans/client.py", line 118, in translate
translated = self.translate(item, dest=dest, src=src)
File "/Users/fotor-desktop/anaconda/lib/python3.6/site-packages/googletrans/client.py", line 123, in translate
data = self._translate(text, dest, src)
File "/Users/fotor-desktop/anaconda/lib/python3.6/site-packages/googletrans/client.py", line 75, in _translate
data = utils.format_json(r.text)
File "/Users/fotor-desktop/anaconda/lib/python3.6/site-packages/googletrans/utils.py", line 51, in format_json
converted = json.loads(text)
File "/Users/fotor-desktop/anaconda/lib/python3.6/json/init.py", line 354, in loads
return _default_decoder.decode(s)
File "/Users/fotor-desktop/anaconda/lib/python3.6/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Users/fotor-desktop/anaconda/lib/python3.6/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None

JSONDecodeError: Expecting value

I am trying to translate multiple text documents from english to french. it worked fine then all of a sudden this error showed up.

raise JSONDecodeError("Expecting value", s, err.value) from None
JSONDecodeError: Expecting value

Any idea how to fix it?

Here is my code:

from googletrans import Translator
import glob, os

translator = Translator()

os.chdir("documents path")
save_path = "path" 

for file in glob.glob("*.txt"):
    myfile= open(file,'r')
    completeName = os.path.join(save_path, file)
    myfile2=open(completeName, encoding='utf-16', mode='w+')
    for line in myfile:
        trans=translator.translate(line,dest="fr")
        myfile2.write(trans.text)
        myfile2.write('\r\n')
        
    myfile.close()
    myfile2.close() 

ValueError: No JSON object could be decoded

Background
I am translating reviews, some of which have emojis in them. This one review in particular has been breaking while attempting to translate. After debugging, I found that it was this emoji in particular that seems to be breaking the translation where as other emojis appear to be working fine. The google api should be able to handle emojis.

Issue
The following command will break break translations:

text = Translator().translate('😩').text

Stack Trace

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/googletrans/client.py", line 132, in translate
    data = self._translate(text, dest, src)
  File "/Library/Python/2.7/site-packages/googletrans/client.py", line 63, in _translate
    data = utils.format_json(r.text)
  File "/Library/Python/2.7/site-packages/googletrans/utils.py", line 51, in format_json
    converted = json.loads(text)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 384, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

After some time ValueError("No JSON object could be decoded")

I've used this library for a few days.
But yesterday it had broken.

I got After some time ValueError("No JSON object could be decoded")

after calling

translator.translate('word', dest = 'ru')

If I use 'translate.google.co.kr' everything works.

How to fix that? I need a lot of translations to be done. Do I need proxies?

German Umlauts(ä, ö, ü) seem to throw ValueError exceptions

from googletrans import Translator
translator = Translator()
dest = 'zh-CN'
text='Mädchen'
translator.translate(text, src='de', dest=dest).text
text = 'schön'
translator.translate(text, src='de', dest=dest).text
text = 'Prüfung'
translator.translate(text, src='de', dest=dest).text

----> 2 translator.translate(text, src='de', dest=dest).text

d:\python34\lib\site-packages\googletrans\client.py in translate(self, text, dest, src, delay)
147
148 origin = text
--> 149 data = self._translate(text, dest, src)
150
151 # this code will be updated when the format is changed.

d:\python34\lib\site-packages\googletrans\client.py in _translate(self, text, dest, src)
89 LOGGER.debug(" from_cache: %s", self.from_cache)
90
---> 91 data = utils.format_json(r.text)
92 return data
93

d:\python34\lib\site-packages\googletrans\utils.py in format_json(original)
49 text = text[:p] + states[j][1] + text[nxt:]
50
---> 51 converted = json.loads(text)
52 return converted
53

d:\python34\lib\json_init_.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
316 parse_int is None and parse_float is None and
317 parse_constant is None and object_pairs_hook is None and not kw):
--> 318 return _default_decoder.decode(s)
319 if cls is None:
320 cls = JSONDecoder

d:\python34\lib\json\decoder.py in decode(self, s, _w)
341
342 """
--> 343 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
344 end = _w(s, end).end()
345 if end != len(s):

d:\python34\lib\json\decoder.py in raw_decode(self, s, idx)
359 obj, end = self.scan_once(s, idx)
360 except StopIteration as err:
--> 361 raise ValueError(errmsg("Expecting value", s, err.value)) from None
362 return obj, end

ValueError: Expecting value: line 1 column 1 (char 0)

Python 3.4, 32 bit Windows 7, no umlaut german OK.

text='Maedchen'
translator.translate(text, src='de', dest=dest).text

-- End pasted text --

googletrans.client - client.py[line:89] 2017-04-10 19:06:38,270 : DEBUG : from_cache: False
Out[220]: '女孩'

can not translate a long paragraph

translator = Translator()
string ='''Architecturally, the school has a Catholic character. Atop the Main Building's gold dome is a golden statue of the Virgin Mary. Immediately in front of the Main Building and facing it, is a copper statue of Christ with arms upraised with the legend "Venite Ad Me Omnes". Next to the Main Building is the Basilica of the Sacred Heart. Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection. It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858. At the end of the main drive (and in a direct line that connects through 3 statues and the Gold Dome), is a simple, modern stone statue of Mary'''
print(string)
value =translator.translate(string,src='en', dest='zh-CN')
print(value.text)

The return result is very small: 在建筑上,学校有天主教的品格。
Which is not right. only the first sentence is translated.
Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.