Example #1
0
    def translate(self, text, **kwargs):
        """
        function that uses google translate to translate a text
        @param text: desired text to translate
        @return: str: translated text
        """

        payload = {
            "source": self._source,
            "target": self._target,
            "text": text
        }
        headers = {
            'X-Naver-Client-Id': self.client_id,
            'X-Naver-Client-Secret': self.secret_key,
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
        response = requests.post(self.__base_url,
                                 headers=headers,
                                 data=payload)
        if response.status_code != 200:
            raise Exception(
                f'Translation error! -> status code: {response.status_code}')
        res_body = json.loads(response.text)
        if "message" not in res_body:
            raise TranslationNotFound(text)

        msg = res_body.get("message")
        result = msg.get("result", None)
        if not result:
            raise TranslationNotFound(text)
        translated_text = result.get("translatedText")
        return translated_text
Example #2
0
    def translate(self, text, proxies=None, **kwargs):
        params = {
            "text": text,
            "format": "plain",
            "lang": self.target if self.source == "auto" else "{}-{}".format(self.source, self.target),
            "key": self.api_key
        }
        try:
            url = self.__base_url.format(version=self.api_version, endpoint="translate")
            response = requests.post(url, data=params, proxies=proxies)
        except ConnectionError:
            raise ServerException(503)
        else:
            response = response.json()

        if response['code'] == 429:
            raise TooManyRequests()

        if response['code'] != 200:
            raise ServerException(response['code'])

        if not response['text']:
            raise TranslationNotFound()

        return response['text']
Example #3
0
 def translate(self, source, target, text):
     # Create the request parameters.
     translate_endpoint = 'translate'
     params = {
         "auth_key": self.api_key,
         "target_lang": self._map_language_to_code(target),
         "source_lang": self._map_language_to_code(source),
         "text": text
     }
     # Do the request and check the connection.
     try:
         response = requests.get(self.__base_url + translate_endpoint,
                                 params=params)
     except ConnectionError:
         raise ServerException(503)
     # If the answer is not success, raise server exception.
     if response.status_code == 403:
         raise AuthorizationException(self.api_key)
     elif response.status_code != 200:
         raise ServerException(response.status_code)
     # Get the response and check is not empty.
     res = response.json()
     if not res:
         raise TranslationNotFound(text)
     # Process and return the response.
     return res['translations'][0]['text']
Example #4
0
    def translate(self, text, **kwargs):
        """
        function that uses google translate to translate a text
        @param text: desired text to translate
        @return: str: translated text
        """

        if self._validate_payload(text):
            text = text.strip()

            if self.payload_key:
                self._url_params[self.payload_key] = text

            response = requests.get(self.__base_url,
                                    params=self._url_params,
                                    headers={'User-agent': 'your bot 0.1'})

            if response.status_code == 429:
                raise TooManyRequests()

            if response.status_code != 200:
                # print("status code", response.status_code)
                raise RequestError()

            soup = BeautifulSoup(response.text, 'html.parser')
            element = soup.find(self._element_tag, self._element_query)

            if not element:
                element = soup.find(self._element_tag, self._alt_element_query)
                if not element:
                    raise TranslationNotFound(text)

            return element.get_text(strip=True)
Example #5
0
    def translate(self, word, return_all=False, **kwargs):

        if self._validate_payload(word):
            # %s-%s/translation/%s.html
            url = "{}{}-{}/translation/{}.html".format(self.__base_url,
                                                       self._source,
                                                       self._target, word)
            url = requote_uri(url)
            response = requests.get(url)
            soup = BeautifulSoup(response.text, 'html.parser')
            elements = soup.find_all(self._element_tag, self._element_query)
            if not elements:
                raise ElementNotFoundInGetRequest(elements)

            filtered_elements = []
            for el in elements:
                try:
                    pronoun = el.find('span', {
                        'class': 'placeholder'
                    }).get_text(strip=True)
                except AttributeError:
                    pronoun = ''
                filtered_elements.append(
                    el.get_text(strip=True).replace(pronoun, ''))

            if not filtered_elements:
                raise TranslationNotFound(word)

            return filtered_elements if return_all else filtered_elements[0]
Example #6
0
    def translate(self, text, **kwargs):
        """
        main function that uses google translate to translate a text
        @param text: desired text to translate
        @return: str: translated text
        """

        if self._validate_payload(text):
            text = text.strip()

            if self.payload_key:
                self._url_params[self.payload_key] = text
            if self.email:
                self._url_params['de'] = self.email

            response = requests.get(self.__base_url,
                                    params=self._url_params,
                                    headers=self.headers)
            data = response.json()
            if not data:
                TranslationNotFound(text)

            translation = data.get('responseData').get('translatedText')
            if translation:
                return translation

            elif not translation:
                all_matches = data.get('matches')
                matches = (match['translation'] for match in all_matches)
                next_match = next(matches)
                return next_match if not kwargs.get('return_all') else list(
                    all_matches)
Example #7
0
    def translate(self, word, return_all=False, **kwargs):

        if self._validate_payload(word):
            url = "{}{}-{}/{}".format(self.__base_url, self._source,
                                      self._target, word)
            url = requote_uri(url)
            response = requests.get(url)
            soup = BeautifulSoup(response.text, 'html.parser')
            elements = soup.findAll(self._element_tag, self._element_query)
            if not elements:
                raise ElementNotFoundInGetRequest(word)

            filtered_elements = []
            for el in elements:
                temp = ''
                for e in el.findAll('a'):
                    if e.parent.name == 'div':
                        if e and "/translate/{}-{}/".format(
                                self._target, self._source) in e.get('href'):
                            temp += e.get_text() + ' '
                filtered_elements.append(temp)

            if not filtered_elements:
                raise ElementNotFoundInGetRequest(word)

            word_list = [
                word for word in filtered_elements if word and len(word) > 1
            ]

            if not word_list:
                raise TranslationNotFound(word)

            return word_list if return_all else word_list[0]
Example #8
0
    def translate(self, word, return_all=False, **kwargs):
        """
        function that uses PONS to translate a word
        @param word: word to translate
        @type word: str
        @param return_all: set to True to return all synonym of the translated word
        @type return_all: bool
        @return: str: translated word
        """
        if self._validate_payload(word, max_chars=50):
            url = "{}{}-{}/{}".format(self.__base_url, self._source,
                                      self._target, word)
            url = requote_uri(url)
            response = requests.get(url)

            if response.status_code == 429:
                raise TooManyRequests()

            if response.status_code != 200:
                raise RequestError()

            soup = BeautifulSoup(response.text, 'html.parser')
            elements = soup.findAll(self._element_tag, self._element_query)

            if not elements:
                raise ElementNotFoundInGetRequest(word)

            filtered_elements = []
            for el in elements:
                temp = ''
                for e in el.findAll('a'):
                    if e.parent.name == 'div':
                        if e and "/translate/{}-{}/".format(
                                self._target, self._source) in e.get('href'):
                            temp += e.get_text() + ' '
                filtered_elements.append(temp)

            if not filtered_elements:
                raise ElementNotFoundInGetRequest(word)

            word_list = [
                word for word in filtered_elements if word and len(word) > 1
            ]

            if not word_list:
                raise TranslationNotFound(word)

            return word_list if return_all else word_list[0]
Example #9
0
    def translate(self, text, **kwargs):
        """
        function that uses google translate to translate a text
        @param text: desired text to translate
        @return: str: translated text
        """

        if self._validate_payload(text):
            text = text.strip()

            if self.payload_key:
                self._url_params[self.payload_key] = text

            response = requests.get(self.__base_url,
                                    params=self._url_params,
                                    headers={'User-agent': 'your bot 0.1'})

            if response.status_code == 429:
                raise TooManyRequests()

            if response.status_code != 200:
                raise RequestError()

            soup = BeautifulSoup(response.text, 'html.parser')

            element = soup.find(self._element_tag, self._element_query)

            if not element:
                element = soup.find(self._element_tag, self._alt_element_query)
                if not element:
                    raise TranslationNotFound(text)
            if element.get_text(strip=True) == text.strip():
                to_translate_alpha = ''.join(ch for ch in text.strip()
                                             if ch.isalnum())
                translated_alpha = ''.join(
                    ch for ch in element.get_text(strip=True) if ch.isalnum())
                if to_translate_alpha and translated_alpha and to_translate_alpha == translated_alpha:
                    self._url_params["tl"] = self._target
                    if "hl" not in self._url_params:
                        return text.strip()
                    del self._url_params["hl"]
                    return self.translate(text)

            else:
                return element.get_text(strip=True)
Example #10
0
    def translate(self, word, return_all=False, **kwargs):
        """
        function that uses linguee to translate a word
        @param word: word to translate
        @type word: str
        @param return_all: set to True to return all synonym of the translated word
        @type return_all: bool
        @return: str: translated word
        """
        if self._validate_payload(word, max_chars=50):
            # %s-%s/translation/%s.html
            url = "{}{}-{}/translation/{}.html".format(self.__base_url,
                                                       self._source,
                                                       self._target, word)
            url = requote_uri(url)
            response = requests.get(url)

            if response.status_code == 429:
                raise TooManyRequests()

            if response.status_code != 200:
                raise RequestError()
            soup = BeautifulSoup(response.text, 'html.parser')
            elements = soup.find_all(self._element_tag, self._element_query)
            if not elements:
                raise ElementNotFoundInGetRequest(elements)

            filtered_elements = []
            for el in elements:
                try:
                    pronoun = el.find('span', {
                        'class': 'placeholder'
                    }).get_text(strip=True)
                except AttributeError:
                    pronoun = ''
                filtered_elements.append(
                    el.get_text(strip=True).replace(pronoun, ''))

            if not filtered_elements:
                raise TranslationNotFound(word)

            return filtered_elements if return_all else filtered_elements[0]
Example #11
0
    def translate(self, source, target, text):
        params = {
            "auth_key": self.api_key,
            "target_lang": target,
            "source_lang": source,
            "text": text
        }
        try:
            response = requests.get(self.__base_url, params=params)
        except ConnectionError:
            raise ServerException(503)

        else:
            if response.status_code != 200:
                ServerException(response.status_code)
            else:
                res = response.json()
                if not res:
                    raise TranslationNotFound(text)
                return res
Example #12
0
    def translate(self, text, return_all=False, **kwargs):
        """
        function that uses the mymemory translator to translate a text
        @param text: desired text to translate
        @type text: str
        @param return_all: set to True to return all synonym/similars of the translated text
        @return: str or list
        """

        if self._validate_payload(text, max_chars=500):
            text = text.strip()

            if self.payload_key:
                self._url_params[self.payload_key] = text
            if self.email:
                self._url_params['de'] = self.email

            response = requests.get(self.__base_url,
                                    params=self._url_params,
                                    headers=self.headers,
                                    proxies=self.proxies,
                                    timeout=self.timeout)

            if response.status_code == 429:
                raise TooManyRequests()
            if response.status_code != 200:
                raise RequestError()

            data = response.json()
            if not data:
                TranslationNotFound(text)

            translation = data.get('responseData').get('translatedText')
            if translation:
                return translation

            elif not translation:
                all_matches = data.get('matches')
                matches = (match['translation'] for match in all_matches)
                next_match = next(matches)
                return next_match if not return_all else list(all_matches)
Example #13
0
    def translate(self, text, domain, **kwargs):
        params = {
            "key": self.api_key,
            "langpair": "{}-{}".format(self.source, self.target),
            "domain": domain,
            "text": text
        }
        try:
            response = self._get("translate", params=params, return_text=False)
        except ConnectionError:
            raise ServerException(503)

        else:
            if response.status_code != 200:
                ServerException(response.status_code)
            else:
                res = response.json()
                translation = res.get("translatedText")
                if not translation:
                    raise TranslationNotFound(text)
                return translation
Example #14
0
    def translate(self, text, **kwargs):
        """
        main function that uses google translate to translate a text
        @param text: desired text to translate
        @return: str: translated text
        """

        if self._validate_payload(text):
            text = text.strip()

            if self.payload_key:
                self._url_params[self.payload_key] = text

            response = requests.get(self.__base_url, params=self._url_params)

            soup = BeautifulSoup(response.text, 'html.parser')
            element = soup.find(self._element_tag, self._element_query)
            if not element:
                # raise ElementNotFoundInGetRequest(element)
                raise TranslationNotFound(text)

            return element.get_text(strip=True)