def check_failure(self, response): if 'code' not in response or response['code'] == 200: return if 'message' in response: raise MachineTranslationError(response['message']) raise MachineTranslationError( 'Error: {0}'.format(response['code']) )
def soap_req(self, url, http_post=False, skip_auth=False, **kwargs): soap_action = kwargs.get('soap_action', '') url = self.MS_TM_API_URL action = self.MS_TM_SOAP_HEADER + soap_action headers = { 'SOAPAction': ('"{action}"').format(action=action), 'Content-Type': 'text/xml; charset=utf-8' } if soap_action == 'GetLanguages': payload = { 'xmlns': self.MS_TM_SOAP_XMLNS, 'soap_action': soap_action } template = get_template( 'trans/machine/microsoft_terminology_get_langs.jinja') elif soap_action == 'GetTranslations': source = kwargs.get('source', '') language = kwargs.get('language', '') text = kwargs.get('text', '') max_result = 5 if soap_action and source and language and text: payload = { 'action': action, 'url': url, 'xmlns': self.MS_TM_SOAP_XMLNS, 'uuid': uuid4(), 'text': text, 'from_lang': source, 'to_lang': language, 'max_result': max_result } template = get_template( 'trans/machine/microsoft_terminology_translate.jinja') else: raise MachineTranslationError( 'Wrong SOAP request: "{soap_action}."').format( soap_action=soap_action) try: payload = template.render(payload) request = Request(url) request.timeout = 0.5 for header, value in headers.iteritems(): request.add_header(header, value) request.add_data(payload) handle = urlopen(request) except Exception as error: raise MachineTranslationError('{err}'.format(err=error)) return handle
def access_token(self): ''' Obtains and caches access token. ''' if self._access_token is None or self.is_token_expired(): data = self.json_req( 'https://datamarket.accesscontrol.windows.net/v2/OAuth2-13', skip_auth=True, http_post=True, client_id=appsettings.MT_MICROSOFT_ID, client_secret=appsettings.MT_MICROSOFT_SECRET, scope='http://api.microsofttranslator.com', grant_type='client_credentials', ) if 'error' in data: raise MachineTranslationError( data.get('error', 'Unknown Error') + data.get('error_description', 'No Error Description') ) self._access_token = data['access_token'] self._token_expiry = timezone.now() + TOKEN_EXPIRY return self._access_token
def download_languages(self): """List of supported languages.""" response = self.json_req(GOOGLE_API_ROOT + 'languages', key=settings.MT_GOOGLE_KEY) if 'error' in response: raise MachineTranslationError(response['error']['message']) return [d['language'] for d in response['data']['languages']]
def soap_status_req(self, url, http_post=False, skip_auth=False, **kwargs): """Perform SOAP request with checking response status.""" # Perform request response = self.soap_req(url, http_post, skip_auth, **kwargs) if response.code != 200: raise MachineTranslationError(response.msg) return response
def download_languages(self): """List of supported languages.""" response = self.json_req( 'https://www.googleapis.com/language/translate/v2/languages', key=settings.MT_GOOGLE_KEY) if 'error' in response: raise MachineTranslationError(response['error']['message']) return [d['language'] for d in response['data']['languages']]
def download_translations(self, source, language, text, unit, user): """Download list of possible translations from a service.""" response = self.json_req( GOOGLE_API_ROOT, key=settings.MT_GOOGLE_KEY, q=text, source=source, target=language, ) if 'error' in response: raise MachineTranslationError(response['error']['message']) translation = response['data']['translations'][0]['translatedText'] return [(translation, 100, self.name, text)]
def download_translations(self, language, text, unit, user): ''' Downloads list of possible translations from a service. ''' response = self.json_req( 'https://www.googleapis.com/language/translate/v2/', key=appsettings.MT_GOOGLE_KEY, q=text.encode('utf-8'), source=appsettings.SOURCE_LANGUAGE, target=language, ) if 'error' in response: raise MachineTranslationError(response['error']['message']) translation = response['data']['translations'][0]['translatedText'] return [(translation, 100, self.name, text)]
def translate(self, language, text, unit, user): """Return list of machine translations.""" if text == '': return [] language = self.convert_language(language) source = self.convert_language( unit.translation.subproject.project.source_language.code) if not self.is_supported(source, language): # Try adding country code from DEFAULT_LANGS if '-' not in language or '_' not in language: for lang in DEFAULT_LANGS: if lang.split('_')[0] == language: language = lang.replace('_', '-').lower() break if '-' not in source or '_' not in source: for lang in DEFAULT_LANGS: if lang.split('_')[0] == source: source = lang.replace('_', '-').lower() break if source == language: return [] if not self.is_supported(source, language): return [] try: translations = self.download_translations(source, language, text, unit, user) return [{ 'text': trans[0], 'quality': trans[1], 'service': trans[2], 'source': trans[3] } for trans in translations] except Exception as exc: self.report_error( exc, 'Failed to fetch translations from %s', ) raise MachineTranslationError('{0}: {1}'.format( exc.__class__.__name__, str(exc)))