diff options
author | morpheus65535 <[email protected]> | 2022-05-01 08:00:20 -0400 |
---|---|---|
committer | GitHub <[email protected]> | 2022-05-01 08:00:20 -0400 |
commit | 2f01ab852348669e81c3d19b3a12f5084b04fba8 (patch) | |
tree | dc2a55e4d943563bcaedba3d79fc23c54e5b9640 /libs/deep_translator/pons.py | |
parent | 9be3674f3a08a64aa4d11d9a28cf79dbc14fc2e0 (diff) | |
download | bazarr-2f01ab852348669e81c3d19b3a12f5084b04fba8.tar.gz bazarr-2f01ab852348669e81c3d19b3a12f5084b04fba8.zip |
Reworked Bazarr file structure to improve support and optimizationv1.0.5-beta.0
Diffstat (limited to 'libs/deep_translator/pons.py')
-rw-r--r-- | libs/deep_translator/pons.py | 110 |
1 files changed, 40 insertions, 70 deletions
diff --git a/libs/deep_translator/pons.py b/libs/deep_translator/pons.py index 50d17f324..c7b711af7 100644 --- a/libs/deep_translator/pons.py +++ b/libs/deep_translator/pons.py @@ -1,80 +1,51 @@ """ pons translator API """ -from bs4 import BeautifulSoup +from typing import List, Optional, Union + import requests -from .constants import BASE_URLS, PONS_LANGUAGES_TO_CODES, PONS_CODES_TO_LANGUAGES -from .exceptions import (LanguageNotSupportedException, - TranslationNotFound, - NotValidPayload, - ElementNotFoundInGetRequest, - RequestError, - TooManyRequests) -from .parent import BaseTranslator +from bs4 import BeautifulSoup from requests.utils import requote_uri +from deep_translator.base import BaseTranslator +from deep_translator.constants import BASE_URLS, PONS_CODES_TO_LANGUAGES +from deep_translator.exceptions import ( + ElementNotFoundInGetRequest, + NotValidPayload, + RequestError, + TooManyRequests, + TranslationNotFound, +) +from deep_translator.validate import is_empty, is_input_valid + class PonsTranslator(BaseTranslator): """ class that uses PONS translator to translate words """ - _languages = PONS_LANGUAGES_TO_CODES - supported_languages = list(_languages.keys()) - def __init__(self, source, target="en", proxies=None, **kwargs): + def __init__( + self, source: str, target: str = "en", proxies: Optional[dict] = None, **kwargs + ): """ @param source: source language to translate from @param target: target language to translate to """ - self.__base_url = BASE_URLS.get("PONS") self.proxies = proxies - if self.is_language_supported(source, target): - self._source, self._target = self._map_language_to_code(source, target) - - super().__init__(base_url=self.__base_url, - source=self._source, - target=self._target, - payload_key=None, - element_tag='div', - element_query={"class": "target"} - ) - - @staticmethod - def get_supported_languages(as_dict=False, **kwargs): - """ - return the supported languages by the linguee translator - @param as_dict: if True, the languages will be returned as a dictionary mapping languages to their abbreviations - @return: list or dict - """ - return PonsTranslator.supported_languages if not as_dict else PonsTranslator._languages - - def _map_language_to_code(self, *languages, **kwargs): - """ - map language to its corresponding code (abbreviation) if the language was passed by its full name by the user - @param languages: list of languages - @return: mapped value of the language or raise an exception if the language is not supported - """ - for language in languages: - if language in self._languages.values(): - yield PONS_CODES_TO_LANGUAGES[language] - elif language in self._languages.keys(): - yield language - else: - raise LanguageNotSupportedException(language) - - def is_language_supported(self, *languages, **kwargs): - """ - check if the language is supported by the translator - @param languages: list of languages - @return: bool or raise an Exception - """ - for lang in languages: - if lang not in self._languages.keys(): - if lang not in self._languages.values(): - raise LanguageNotSupportedException(lang) - return True - - def translate(self, word, return_all=False, **kwargs): + super().__init__( + base_url=BASE_URLS.get("PONS"), + languages=PONS_CODES_TO_LANGUAGES, + source=source, + target=target, + payload_key=None, + element_tag="div", + element_query={"class": "target"}, + **kwargs, + ) + + def translate( + self, word: str, return_all: bool = False, **kwargs + ) -> Union[str, List[str]]: """ function that uses PONS to translate a word @param word: word to translate @@ -83,8 +54,10 @@ class PonsTranslator(BaseTranslator): @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) + if is_input_valid(word, max_chars=50): + if self._same_source_target() or is_empty(word): + return word + url = f"{self._base_url}{self._source}-{self._target}/{word}" url = requote_uri(url) response = requests.get(url, proxies=self.proxies) @@ -94,7 +67,7 @@ class PonsTranslator(BaseTranslator): if response.status_code != 200: raise RequestError() - soup = BeautifulSoup(response.text, 'html.parser') + soup = BeautifulSoup(response.text, "html.parser") elements = soup.findAll(self._element_tag, self._element_query) if not elements: @@ -102,11 +75,9 @@ class PonsTranslator(BaseTranslator): 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() + ' ' + temp = "" + for e in el.findAll("a"): + temp += e.get_text() + " " filtered_elements.append(temp) if not filtered_elements: @@ -119,7 +90,7 @@ class PonsTranslator(BaseTranslator): return word_list if return_all else word_list[0] - def translate_words(self, words, **kwargs): + def translate_words(self, words: List[str], **kwargs) -> List[str]: """ translate a batch of words together by providing them in a list @param words: list of words you want to translate @@ -133,4 +104,3 @@ class PonsTranslator(BaseTranslator): for word in words: translated_words.append(self.translate(word=word, **kwargs)) return translated_words - |