Created
April 7, 2023 08:24
-
-
Save imvladikon/6c51fd38b895fc285ff5edd6ef225482 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
import requests | |
class GoogleTranslate: | |
def __init__(self): | |
self.session = requests.Session() | |
self.session.headers.update(self.make_header()) | |
self.session.verify = False | |
self.url = "https://clients5.google.com/translate_a/t?client=dict-chrome-ex&sl={}&tl={}&q={}" | |
def make_header(self): | |
headers = dict() | |
headers["Accept"] = "*/*" | |
headers["Host"] = "clients5.google.com" | |
headers["Connection"] = "keep-alive" | |
headers["Upgrade-Insecure-Requests"] = "1" | |
headers[ | |
"User-Agent"] = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36" | |
headers["Content-Encoding"] = "gzip" | |
headers["Accept-Language"] = "en-US,en;q=0.9,ru;q=0.8,he;q=0.7" | |
headers["Content-Type"] = "application/json; charset=UTF-8" | |
return headers | |
def translate(self, text, target='en', source='auto'): | |
url = self.url.format(source, target, text) | |
response = self.session.get(url) | |
response.encoding = response.apparent_encoding | |
json = response.json() | |
try: | |
# check if it's list of lists or list of strings | |
if isinstance(json[0], list): | |
return "\n".join(map(lambda p: p[0], json)).strip() | |
else: | |
return "\n".join(json).strip() | |
except: | |
pass | |
return text | |
if __name__ == '__main__': | |
translator = GoogleTranslate() | |
print(translator.translate("אני רוצה לקנות כוס קפה בגודל גדול" , target='en', source='he')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment