Beispiel #1
0
    def _translate(self, text, src, dest):
        """ Generate Token for each Translation and post requset to
        google web api translation and return an response

        If the status code is 200 the request is considered as an success
        else other status code are consider as translation failure.

        """
        if type(text) != list:
            text = [text]        
        translated_list = []
        url = self.transurl
        params = utils.format_param(self.rpcids)
        for _text in text:
            trans_list = []
            tokenized_text = utils.tokenize_sentence(_text)
            for _tokenized_text in tokenized_text:
                data = utils.format_data(self.rpcids, _tokenized_text, src, dest)
                response = requests.request("POST", url, data=data, params=params, proxies=self.proxies)
                if response.status_code == 200:
                    _format_data = utils.format_response(str(response.text))
                    trans_list.append(_format_data)
                elif response.status_code == 429:
                    _format_data = self.retry_request(data, params)
                    trans_list.append(_format_data)
                else:
                    raise Exception('Unexpected status code {} from {}'.format(response.status_code, self.transurl))
                    return False
            translated_list.append(utils.format_translation(trans_list))
        return translated_list
 def retry_request(self, data, params):
     """ 
     For bulk translation some times translation might failed
     beacuse of too many attempts. for such a case before hitting
     translation api wait for some time and retrying again
     """
     retry = self.retry
     sleep = self.sleep
     response = requests.request("POST",
                                 url=self.transurl,
                                 data=data,
                                 params=params,
                                 proxies=self.proxies)
     for i in range(0, retry):
         if response.status_code == 200:
             _format_data = utils.format_response(str(response.text))
             return _format_data
         elif response.status_code == 429:
             if self.retry_messgae:
                 print('retrying translation after {}s'.format(sleep))
             time.sleep(sleep)
             sleep = i * sleep
         else:
             raise Exception('Unexpected status code {} from {}'.format(
                 response.status_code, self.transurl))
             return False
     raise Exception(
         'Unexpected status code {} from {} after retried {} loop with {}s delay'
         .format(response.status_code, self.transurl, retry, self.sleep))