File size: 2,365 Bytes
b5698d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
## built-in libraries
import typing

## third-party libraries
from deepl.translator import Translator

class DeepLService:

    api_key:str
    translator:Translator

##-------------------start-of-translate()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    
    @staticmethod
    def translate(text:str, target_lang:str, source_lang:str) -> str:

        """

        Translates the text to the target language.

        Parameters:
        text (string) : The text to translate.
        target_lang (string) : The target language.
        source_lang (string) : The source language.

        Returns:
        translation (string) : The translated text.

        """

        try:

            translation = DeepLService.translator.translate_text(text, target_lang=target_lang, source_lang=source_lang)

            return str(translation)
        
        except Exception as e:
            raise e

##-------------------start-of-set_api_key()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    @staticmethod
    def set_api_key(api_key:str) -> None:

        """

        Sets the API key for the DeepL client.

        Parameters:
        api_key (string) : The API key to set.

        """

        DeepLService.api_key = api_key

##-------------------start-of-test_api_key_validity()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    
    @staticmethod
    def test_api_key_validity() -> typing.Tuple[bool, typing.Union[Exception, None]]:

        """

        Tests the validity of the API key.

        Returns:
        validity (bool) : True if the API key is valid, False if it is not.
        e (Exception) : The exception that was raised, if any.

        """

        validity = False

        try:

            DeepLService.translator = Translator(DeepLService.api_key)

            DeepLService.translator.translate_text("test", target_lang="JA")

            validity = True

            return validity, None

        except Exception as e:

            return validity, e