def translate(self, text, from_lang, to_lang): params = { 'text': text, 'dest': to_lang, 'src': from_lang, 'email': self.email, 'password': self.password, 'outformat': 'json' } try: r = requests.get(API_URL, params=params, timeout=self.timeout) print(r.text) trans = json.loads(r.text)['translation'] # Service seems to ignore exceptions and just return the same # thing on error... if trans == text: raise TranslationException('Service seems to have failed to \ translate text') return trans except (ValueError, KeyError): raise TranslationException('Server returned bad JSON: %s', r.text) except requests.exceptions.RequestException as exc: log.error('Translation request (params=%s) failed: %s', repr(params), exc) raise TranslationException(exc)
def translate(self, text, from_lang, to_lang): # Switch to 3 char codes from_lang = iso639_convert(from_lang) to_lang = iso639_convert(to_lang) # Free translate requires text to be URI-encoded quoted = urllib.quote(text.encode('utf8')) params = {'from': from_lang, 'to': to_lang, 'text': quoted} try: resp = self._api_post_request('translate', **params) if resp.status_code != 200: error = API_ERRORS.get(resp.status_code, "Unknown error") raise TranslationException("Failed to translate: %s" % error) jsobj = json.loads(resp.text) text = jsobj['translation'] return urllib.unquote(text) except (ValueError, requests.exceptions.RequestException) as exc: raise TranslationException('Translation request failed: %s' % str(exc))
def translate(self, text, from_lang, to_lang): if not self.client.can_translate(from_lang, to_lang): raise TranslationException( "Can't translate given pair ({0},{1})".format( from_lang, to_lang)) try: return self.client.translate(text, from_lang, to_lang) except translate.client.exceptions.TranslateException as exc: raise TranslationException("Server failed to translate text: " + repr(exc))
def translate(self, text, from_lang, to_lang): try: proc = subprocess.Popen( ['apertium', '{0}-{1}'.format(from_lang, to_lang)], stdin=subprocess.PIPE, stdout=subprocess.PIPE) proc.stdin.write((text + u'\n').encode('utf-8')) proc.stdin.close() output = proc.stdout.read()[:-1].decode('utf-8') # Check that apertium process exited successfully if proc.wait() != 0: raise TranslationException('Apertium process exited with \ non-zero status') except Exception as e: log.error('Failed to translate text {0}'.format(repr(e))) raise TranslationException(repr(e)) return output
def translate(self, text, from_lang, to_lang): results = [] # Split up requests into blocks of proper size # FIXME: Bytesize vs charsize. for chunk in translate.utils.chunk_string(text, API_SIZE_LIMIT): pair = "{0}-{1}".format(from_lang, to_lang) js, req = self.api_request('translate', text=chunk, lang=pair) if js.get('code', -1) != 200: error = API_ERRORS.get(js.get('code', -1), "Unknown error!") if error is None: raise TranslationException(repr(req)) else: raise TranslationException(repr(error)) # Returns an array, so join with new lines results.append('\n'.join(js.get('text'))) return '\n'.join(results)
def translate(self, text, from_lang, to_lang): langpair = "{0}|{1}".format(from_lang, to_lang) resp, req = self._api_request('translate', q=text, langpair=langpair, format="txt") status = resp.get('responseStatus', -1) if status != 200: try: error = API_ERRORS[status] # Unknown status except KeyError: error = "Unknown error occurred: %d".format(status) log.error(error) raise TranslationException(repr(error)) return resp.get('responseData').get('translatedText')
def translate(self, text, from_lang, to_lang): if (from_lang, to_lang) not in self.language_pairs: raise TranslationException('Bad input') return text
def translate_text(): """Translate some text""" text = request.args.get('text', None) if not text or text == "": raise APIException.translate(msg='No translation text given') source_lang = request.args.get('from', None) if not source_lang: raise APIException.translate(msg='No source language given') dest_lang = request.args.get('to', None) if not dest_lang: raise APIException.translate(msg='No destination language given') bytelen = len(text.encode('utf-8')) conf = app.config['SERVER']['sizelimit'] if conf['enabled'] and bytelen > conf['limit']: raise APIException.sizelimit(len=bytelen, limit=conf['limit']) # Try each translator sequentially (sorted by preference) until one works backends = manager.find_all(source_lang, dest_lang) # List of translator backend names that the client does not want to use excludes = request.args.getlist('exclude') if len(backends) == 0: raise APIException.pair(from_lang=source_lang, to_lang=dest_lang, text=text) tried = [] for backend in backends: if backend.name in excludes: log.info("Skipping %s, client disapproved.", backend.name) continue tried.append(backend.name) try: trans = backend.translate(text, source_lang, dest_lang) if trans is None or trans == "": raise TranslationException("Received empty result text") return flask.Response(json.dumps({ 'from': source_lang, 'to': dest_lang, 'result': trans, 'translator': backend.name }), mimetype='application/json') except TranslationException as exc: log.warning('{0} failed to translate text: {1}'.format( backend.name, exc)) raise APIException.translator(from_lang=source_lang, to_lang=dest_lang, text=text, tried=tried)