Ejemplo n.º 1
0
 def handle_api_error(self, response: httpx.Response):
     if response.status_code >= 500:
         raise EngineApiError(
             f"{self.name_ver} engine returned a status code {response.status_code} response"
         )
     if response.status_code >= 400:
         self._logger.debug("%s got response: %s", self.name_ver, response.text)
         response_json = response.json()
         raise EngineApiError(
             f"{self.name_ver} engine returned error code: {response_json['code']}, message: {response_json['message']}"
         )
Ejemplo n.º 2
0
 def handle_api_error(self, response: httpx.Response):
     # todo: use this approach of using response instead of response json for other engines
     if response.status_code >= 500:
         raise EngineApiError(
             f"{self.name_ver} engine returned a status code {response.status_code} response"
         )
     if response.status_code >= 400:
         self._logger.debug("%s got response: %s", self.name_ver,
                            response.text)
         response_json = response.json()
         raise EngineApiError(
             f"{self.name_ver} engine returned error message: {response_json['message']}"
         )
Ejemplo n.º 3
0
    async def translate(
        self,
        source_text: str,
        to_language: str,
        from_language: Optional[str] = None,
        with_alignment: Optional[bool] = False,
    ) -> TranslationResponse:
        await super().translate(
            source_text=source_text,
            to_language=to_language,
            from_language=from_language,
            with_alignment=with_alignment,
        )
        # todo: support other mime types
        try:
            translated_text: TranslateTextResponse = self.client.translate_text(
                contents=[source_text],
                target_language_code=to_language,
                source_language_code=from_language,
                parent=self.parent,
                mime_type="text/plain",
            )
        except GoogleAPICallError as e:
            raise EngineApiError(
                f"{self.name_ver} had a problem making translate api request"
            ) from e
        translations: List[Translation] = translated_text.translations
        translation = translations[0]
        self._logger.debug("%s got response: %s", self.name_ver, translation)

        detected_language_confidence = detected_language = None

        if from_language is None:
            try:
                detected_language = bcp_47_to_iso_639(
                    translation.detected_language_code)
            except (InvalidISO6391CodeError, AttributeError) as e:
                raise DetectionError(
                    f"{self.name_ver} engine could not detect which language the source text is in"
                ) from e

        try:
            translated_text = translation.translated_text
        except AttributeError as e:
            raise TranslationError(
                f"{self.name_ver} engine could not translate the given text"
            ) from e

        return TranslationResponse(
            engine=self.NAME,
            engine_version=self.VERSION,
            source_text=source_text,
            from_language=from_language or detected_language,
            to_language=to_language,
            detected_language_confidence=detected_language_confidence,
            translated_text=translated_text,
            alignment=None,
        )
Ejemplo n.º 4
0
 def get_supported_translations(self) -> Dict[str, List[str]]:
     try:
         supported_languages: SupportedLanguages = self.client.get_supported_languages(
             parent=self.parent)
     except GoogleAPICallError as e:
         raise EngineApiError(
             f"{self.name_ver} had a problem making get supported languages api request"
         ) from e
     # todo: make supported languages list a set
     languages: List[SupportedLanguage] = supported_languages.languages
     all_codes = [
         language.language_code.split("-")[0] for language in languages
     ]
     return {c: all_codes for c in all_codes}
Ejemplo n.º 5
0
    async def translate(
        self,
        source_text: str,
        from_language: Optional[str],
        to_language: str,
        with_alignment: Optional[bool] = False,
    ) -> TranslationResponse:
        await super().translate(
            source_text=source_text,
            to_language=to_language,
            from_language=from_language,
            with_alignment=with_alignment,
        )

        try:
            result = self.client.translate_text(
                Text=source_text,
                SourceLanguageCode=from_language,
                TargetLanguageCode=to_language,
            )
        except ClientError as e:
            raise EngineApiError(
                f"{self.name_ver} had a problem making translate api request"
            ) from e
        self._logger.debug("%s got response: %s", self.name_ver, result)

        try:
            translated_text = result["TranslatedText"]
        except KeyError as e:
            raise TranslationError(
                f"{self.name_ver} engine could not translate the given text"
            ) from e

        return TranslationResponse(
            engine=self.NAME,
            engine_version=self.VERSION,
            source_text=source_text,
            from_language=from_language,
            to_language=to_language,
            detected_language_confidence=None,
            translated_text=translated_text,
            alignment=None,
        )
Ejemplo n.º 6
0
 def handle_api_error(self, response_json: Dict):
     if "error" in response_json:
         raise EngineApiError(
             f"{self.name_ver} engine returned error code: {response_json['error']['code']},"
             f" message: {response_json['error']['message']}")