Advertisement
benjaminvr

Python - Translator using Google Translate API

Jul 27th, 2021
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.18 KB | None | 0 0
  1. from google.cloud import translate_v2
  2. from conf import staticConfigs
  3. import html
  4. from time import sleep
  5.  
  6. class Translator:
  7.     def __init__(self):
  8.         self.conf = staticConfigs()
  9.         self.user_key = self.conf.google_path_userkey
  10.         self.project_id = self.conf.google_project_id
  11.         self.parent = f"projects/{self.project_id}"
  12.         self.client = translate_v2.client.Client.from_service_account_json(json_credentials_path=self.user_key)
  13.         self.sleep_in_between_translations_seconds = self.conf.sleep_in_between_translations_seconds
  14.         self.source_language = "en"
  15.  
  16.     def __htmlDecode(self, item):
  17.         if type(item) is list:
  18.             res = []
  19.             for i in item:
  20.                 res.append(html.unescape(i))
  21.         elif type(item) is str:
  22.             return html.unescape(item)
  23.  
  24.     def Translate(self, content, dest_language_code):
  25.         res = self.client.translate(content, target_language=dest_language_code)
  26.         print('Sleeping for {}s after translation query..'.format(self.sleep_in_between_translations_seconds))
  27.         sleep(self.sleep_in_between_translations_seconds)
  28.         return self.__htmlDecode(res['translatedText'])
  29.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement