File size: 9,202 Bytes
15479b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49089be
15479b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
#!/usr/bin/env python3
#coding:utf-8

from openai import OpenAI
from os import getenv
from typing import Optional
from typing import Union
from typing import Any
import re
import json
import datetime


SUPPORTED_LANGUAGES=[
    "Afrikaans", "Arabic", "Armenian", "Azerbaijani", "Belarusian", "Bosnian", "Bulgarian", "Catalan", "Chinese", "Croatian", "Czech", "Danish", "Dutch", "English", "Estonian", "Finnish", "French", "Galician", "German", "Greek", "Hebrew", "Hindi", "Hungarian", "Icelandic", "Indonesian", "Italian", "Japanese", "Kannada", "Kazakh", "Korean", "Latvian", "Lithuanian", "Macedonian", "Malay", "Marathi", "Maori", "Nepali", "Norwegian", "Persian", "Polish", "Portuguese", "Romanian", "Russian", "Serbian", "Slovak", "Slovenian", "Spanish", "Swahili", "Swedish", "Tagalog", "Tamil", "Thai", "Turkish", "Ukrainian", "Urdu", "Vietnamese", "Welsh"
]

SUPPORTED_LANGUAGES_FR_ = [
    "Afrikaans", "Arabe", "Arménien", "Azéri", "Biélorusse", "Bosniaque", "Bulgare", "Catalan", "Chinois", "Croate", "Tchèque", "Danois", "Néerlandais", "Anglais", "Estonien", "Finnois", "Français", "Galicien", "Allemand", "Grec", "Hébreu", "Hindi", "Hongrois", "Islandais", "Indonésien", "Italien", "Japonais", "Kannada", "Kazakh", "Coréen", "Letton", "Lituanien", "Macédonien", "Malais", "Marathi", "Maori", "Népalais", "Norvégien", "Persan", "Polonais", "Portugais", "Roumain", "Russe", "Serbe", "Slovaque", "Slovène", "Espagnol", "Swahili", "Suédois", "Tagalog", "Tamoul", "Thaï", "Turc", "Ukrainien", "Ourdou", "Vietnamien", "Gallois"
]




def read_json_file(file_path: str) -> dict:
    with open(file_path, "r", encoding='utf-8') as json_file:
        return json.load(json_file)

def write_json_file(file_path: str, data: Union[str, bytes, dict]) -> None:
    try:
        if type(data) == str:
            data = data.encode("utf-8")
        if type(data) == dict:
            data = json.dumps(data, indent=4, ensure_ascii=False, sort_keys=False).encode("utf-8")
        with open(file_path, "wb") as json_file:
            json_file.write(data)
            json_file.close()
    except Exception as e:
        raise e

def get_prompt_translation_ui_text(base_lang: str, 
                                    target_lang: str) -> str:
    prompt_ = "\n".join([
        f"Je souhaite que vous agissiez en tant que traducteur linguistique, correcteur d'orthographe et améliorateur.",
        f"Je vous donne un texte en {base_lang} et je vous demande de le traduire en {target_lang}. Puis répondez dans une version corrigée et améliorée de mon texte, dans la langue de destination.",
        f"Je souhaite que vous remplaciez mes mots et phrases par des termes et expressions les plus appropriés dans la langue de destination. Conservez le même sens, mais corrigez les fautes.",
        f"Je vous demande de ne répondre que par les corrections et améliorations, sans ajouter d'explications.",
        f"Lorsque je soumets un texte à traiter, je procéderai de la manière suivante pour délimiter le début et la fin du ou des blocs de texte que tu devras traiter : j'utiliserai trois caractères de guillemets doubles pour délimiter le début d'un bloc de texte à traiter ; j'utiliserai trois caractères de guillemets doubles pour délimiter la fin d'un bloc de texte à traiter. Le texte sera compris entre ces délimitations, que ce soit par format ou par taille du texte dans un bloc à traiter. Si mon texte est sur une seule ligne, il est possible que je place également les délimiteurs de début et de fin sur la même ligne.",
        f"Il est impératif que tu respectes le format d'origine au mieux ; donc, à moins qu'il soit absolument nécessaire de corriger le formatage, respecte au mieux ce détail. (Par exemple, tout en une ligne ou sur plusieurs... tu respectes le formatage d'origine. Par contre, tu peux, par exemple, corriger les espaces, tabulations et autres éléments superflus.)"
    ])
    return prompt_

def get_openai_connected_client():
    openai_client = OpenAI(api_key=getenv("OPENAI_API_KEY"))
    return openai_client

def create_chat_completion(client, 
                            system_prompt,
                            user_input,
                            model="gpt-4o-mini",
                            temperature=0.01,):
    response = client.chat.completions.create(
        model=f"{model}",
        temperature=temperature,
        messages=[
            {
                "role": "system",
                "content": f"{system_prompt}"
            },
            {
                "role": "user",
                "content": f"{user_input}"
            }
        ]
    )
    return response.choices[0].message.content

def remove_response_separator(response_text:str) -> str:
    # Utiliser un regex pour retirer les trois premières et dernières doubles quotes
    return re.sub(r'^"{3}|"{3}$', '', response_text.strip())


def translate_ui_template_string(file_path: str, 
                                 base_ui_lang: str, 
                                 target_ui_lang: str) -> str:
    openai_client = get_openai_connected_client()
    PROMPT_ = get_prompt_translation_ui_text(base_ui_lang, target_ui_lang)
    ui_lang_dict = read_json_file(file_path)
    traductions_ui_dict[target_ui_lang] = {}
    for key, text_ui in ui_lang_dict[base_ui_lang].items():
        operation_prompt = f"Translate(\'{base_ui_lang}\' to \'{target_ui_lang}\')"
        traduction_text_ui = remove_response_separator(
            create_chat_completion(
                openai_client, 
                PROMPT_, 
                f'{operation_prompt} :\n\"\"\"\n{text_ui}\n\"\"\"'
            )
        ).strip()
        traductions_ui_dict[target_ui_lang][key] = traduction_text_ui
    return json.dumps(traductions_ui_dict, indent=4, ensure_ascii=False, sort_keys=False)


def generate_ui_lang_support(
    base_ui_lang: Optional[str]   = "French", 
    target_ui_lang: Optional[Union[str, list]] = SUPPORTED_LANGUAGES,
    ui_lang_support_filepath: Optional[str] = "ui_lang_support.json",
    skip_translated: Optional[bool] = True) -> str:

    traductions_ui_dict = read_json_file(ui_lang_support_filepath)
    
    if list == type(target_ui_lang):
        if base_ui_lang in target_ui_lang:
            target_ui_lang.remove(base_ui_lang)
    elif str == type(target_ui_lang):
        if base_ui_lang == target_ui_lang:
            raise ValueError(f"La langue de l'interface {base_ui_lang} est la même que la langue de destination {target_ui_lang}. Veuillez choisir une autre langue de destination.")

    openai_client = get_openai_connected_client()
    
    cnt=0
    for to_lang in target_ui_lang:
        cnt += 1
        print(f"\033[93m[{cnt}/{len(target_ui_lang)}]\033[0m \033[92mTranslating UI text to \033[0m\033[96m{to_lang}...\033[0m")
        PROMPT_ = get_prompt_translation_ui_text(base_ui_lang, to_lang)
        if f"{to_lang}" not in traductions_ui_dict.keys():
            traductions_ui_dict[to_lang] = {}
        it_cnt=0
        for key, text_ui in traductions_ui_dict[base_ui_lang].items():
            it_cnt += 1
            print(f"  \033[93m[{it_cnt}/{len(traductions_ui_dict[base_ui_lang].keys())}]\033[0m \033[92mTranslating UI text value of key \033[0m\033[96m'{key}'...\033[0m")
            if (f"{key}" not in traductions_ui_dict[to_lang].keys() ) or (not skip_translated):
                operation_prompt = f"Translate(\'{base_ui_lang}\' to \'{to_lang}\')"
                traduction_text_ui = remove_response_separator(
                    create_chat_completion(
                        openai_client, 
                        PROMPT_, 
                        f'{operation_prompt} :\n\"\"\"\n{text_ui}\n\"\"\"'
                    )
                ).strip()
                traductions_ui_dict[to_lang][key] = traduction_text_ui
        
    return json.dumps(traductions_ui_dict, indent=4, ensure_ascii=False, sort_keys=False)

def init_template_base_lang(file_path: str, 
                            base_ui_lang_dict: dict) -> None:
    base_ui_lang = json.dumps(base_ui_lang_dict, indent=4, ensure_ascii=False, sort_keys=False).encode("utf-8")
    with open(f"/tmp/{file_path}.json", "wb") as json_file:
        json_file.write(base_ui_lang)
        json_file.close()

def read_template_base_lang(file_path: str) -> str:
    with open(f"/tmp/{file_path}.json", "rb") as json_file:
        bytes_data = json_file.read() 
        data = bytes_data.decode("utf-8")
    return data


if __name__ == "__main__":

    JSON_UI_LANG_SUPPORT = generate_ui_lang_support(
            base_ui_lang="French", 
            target_ui_lang=SUPPORTED_LANGUAGES
    )

    # encoding , fr_FR.UTF-8
    if type(JSON_UI_LANG_SUPPORT) == str:
        JSON_UI_LANG_SUPPORT = JSON_UI_LANG_SUPPORT.encode("utf-8")
    
    # timestamp string format : "MM-DD-YYYY_HH-MM-SS"
    timestamp = datetime.datetime.now().strftime("%m-%d-%Y_%H-%M-%S")
    with open(f"ui_lang_support_{timestamp}.json", "wb") as output_file:
        output_file.write(JSON_UI_LANG_SUPPORT)
        output_file.close()

    # print GREEN FG : "Success and Done !" message
    print("\033[92mSuccess and Done !\033[0m")
    exit(0)