File size: 3,329 Bytes
1d42175
 
 
 
 
7ade3be
76aa3b2
78d0ff1
 
 
 
 
 
 
1d42175
 
 
 
 
 
 
7ade3be
 
 
 
 
 
 
1d42175
 
5a8d2be
 
1d42175
 
2bbc526
5a8d2be
 
78d0ff1
 
 
 
 
 
0d1a764
7ade3be
1d42175
 
 
 
 
76aa3b2
70f6ed6
 
9a69d6b
78d0ff1
70f6ed6
 
 
 
78d0ff1
70f6ed6
 
 
 
 
 
78d0ff1
 
 
70f6ed6
 
 
0d1a764
70f6ed6
 
 
 
 
 
 
 
 
78d0ff1
50c16a8
7ade3be
50c16a8
 
 
 
 
 
 
2bbc526
50c16a8
7ade3be
50c16a8
 
 
 
 
2bbc526
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
"""
LibreTranslate API
"""

import requests
from typing import Optional, List
from deep_translator.validate import is_empty, is_input_valid
from deep_translator.base import BaseTranslator
from deep_translator.constants import BASE_URLS, LIBRE_LANGUAGES_TO_CODES
from deep_translator.exceptions import (
    ServerException,
    TranslationNotFound,
    AuthorizationException,
)


class LibreTranslator(BaseTranslator):
    """
    class that wraps functions, which use libre translator under the hood to translate text(s)
    """

    def __init__(
        self,
        api_key: Optional[str] = None,
        source: str = "auto",
        target: str = "en",
        **kwargs
    ):
        """
        @param source: source language to translate from
        List of LibreTranslate nedpoints can be found at : https://github.com/LibreTranslate/LibreTranslate#mirrors
        Some require an API key
        @param target: target language to translate to
        """
        if not api_key:
            raise ServerException(401)
        self.api_key = api_key
        super().__init__(
            base_url=BASE_URLS.get("LIBRE"),
            source=source,
            target=target,
            languages=LIBRE_LANGUAGES_TO_CODES,
        )

    def translate(self, text: str, **kwargs) -> str:
        """
        function that uses microsoft translate to translate a text
        @param text: desired text to translate
        @return: str: translated text
        """
        if is_input_valid(text):
            if self._same_source_target() or is_empty(text):
                return text

            translate_endpoint = "translate"
            params = {
                "q": text,
                "source": self._source,
                "target": self._target,
                "format": "text",
            }
            # Add API Key if required
            if self.api_key:
                params["api_key"] = self.api_key
            # Do the request and check the connection.
            try:
                response = requests.post(
                    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["translatedText"]

    def translate_file(self, path: str, **kwargs) -> str:
        """
        translate directly from file
        @param path: path to the target file
        @type path: str
        @param kwargs: additional args
        @return: str
        """
        return self._translate_file(path, **kwargs)

    def translate_batch(self, batch: List[str], **kwargs) -> List[str]:
        """
        translate a list of texts
        @param batch: list of texts you want to translate
        @return: list of translations
        """
        return self._translate_batch(batch, **kwargs)