File size: 23,730 Bytes
f978ccd
 
 
 
 
 
d3cbfff
 
f978ccd
ec595bb
f978ccd
 
 
 
05f8903
f978ccd
 
05f8903
 
 
 
ec595bb
f978ccd
 
babcb18
ed6980d
aa31e8d
ccc79f3
dec1200
f978ccd
 
 
babcb18
f978ccd
 
 
 
 
 
 
 
 
 
 
 
 
babcb18
 
f978ccd
 
 
 
 
 
05f8903
f978ccd
 
05f8903
f978ccd
92e4a13
f978ccd
 
 
 
 
 
 
 
 
 
f716a4a
5c0ccb2
f978ccd
ed6980d
 
f978ccd
ed6980d
 
8b0ebfb
 
 
 
f978ccd
 
aa31e8d
 
 
 
 
ccc79f3
92e4a13
ccc79f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92e4a13
ccc79f3
f978ccd
 
 
 
 
 
 
 
f2ce4b7
 
 
f978ccd
f2ce4b7
 
f978ccd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
babcb18
f978ccd
babcb18
f978ccd
babcb18
f978ccd
 
babcb18
 
 
 
f978ccd
 
 
babcb18
 
f716a4a
babcb18
 
f978ccd
 
babcb18
 
f978ccd
74cb5f4
babcb18
 
74cb5f4
f978ccd
 
 
 
babcb18
f978ccd
 
babcb18
 
74cb5f4
babcb18
 
f978ccd
 
 
f716a4a
086ca7a
f716a4a
 
 
 
babcb18
f978ccd
babcb18
f978ccd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
086ca7a
f978ccd
 
babcb18
f978ccd
dec1200
ccc79f3
92e4a13
 
dec1200
 
f978ccd
dec1200
ccc79f3
92e4a13
 
dec1200
 
f978ccd
babcb18
f978ccd
babcb18
f978ccd
 
 
 
 
 
 
babcb18
f978ccd
 
babcb18
f978ccd
 
 
 
 
babcb18
f978ccd
babcb18
d4af288
5cbc664
d4af288
5cbc664
 
f978ccd
 
 
 
babcb18
 
 
74cb5f4
f978ccd
babcb18
f978ccd
babcb18
f978ccd
 
 
 
 
 
 
 
babcb18
f978ccd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3cbfff
 
f978ccd
 
 
 
 
 
 
 
 
babcb18
f978ccd
 
babcb18
 
f978ccd
babcb18
 
 
f978ccd
 
 
babcb18
f978ccd
 
a545669
 
f978ccd
a545669
 
f978ccd
a545669
 
f978ccd
a545669
 
 
ec595bb
 
f978ccd
babcb18
f978ccd
 
 
a545669
ec595bb
 
 
 
 
 
 
 
 
a545669
9641cc8
a545669
ec595bb
 
f978ccd
 
 
 
 
 
d3cbfff
 
f978ccd
 
 
 
 
 
 
babcb18
f978ccd
 
babcb18
f978ccd
babcb18
f978ccd
 
babcb18
f978ccd
 
 
 
 
babcb18
 
f978ccd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
babcb18
f978ccd
74cb5f4
f978ccd
 
babcb18
 
f978ccd
 
 
 
 
 
 
 
babcb18
 
 
74cb5f4
f978ccd
babcb18
f978ccd
babcb18
 
f978ccd
babcb18
 
 
 
 
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
import streamlit as st
import pandas as pd
import numpy as np
import os
from sacrebleu import corpus_bleu
from transformers import pipeline
# from translate import Translator
from deep_translator import GoogleTranslator
from audio_recorder_streamlit import audio_recorder
import speech_recognition as sr
import whisper
import io
import wavio
from filesplit.merge import Merge
# import tensorflow as tf
import string
import re
# from tensorflow import keras
# from keras_nlp.layers import TransformerEncoder
# from tensorflow.keras import layers
# from tensorflow.keras.utils import plot_model
# from PIL import Image
from gtts import gTTS
from extra_streamlit_components import tab_bar, TabBarItemData
from translate_app import tr
import requests
import asyncio
import aiohttp
import time

title = "Traduction Sequence à Sequence"
sidebar_name = "Traduction Seq2Seq"
dataPath = st.session_state.DataPath

@st.cache_data
def load_corpus(path):
    input_file = os.path.join(path)
    with open(input_file, "r",  encoding="utf-8") as f:
        data = f.read()
        data = data.split('\n')
        data=data[:-1]
    return pd.DataFrame(data)


@st.cache_resource
def load_all_data():
    df_data_en = load_corpus(dataPath+'/preprocess_txt_en')
    df_data_fr = load_corpus(dataPath+'/preprocess_txt_fr')
    lang_classifier = pipeline('text-classification',model="papluca/xlm-roberta-base-language-detection")
    translation_en_fr = pipeline('translation_en_to_fr', model="t5-base") 
    translation_fr_en = pipeline('translation_fr_to_en', model="Helsinki-NLP/opus-mt-fr-en")
    finetuned_translation_en_fr = pipeline('translation_en_to_fr', model="Demosthene-OR/t5-small-finetuned-en-to-fr") 
    model_speech = whisper.load_model("base") 
    
    return df_data_en, df_data_fr, translation_en_fr, translation_fr_en, lang_classifier, model_speech, finetuned_translation_en_fr

n1 = 0
df_data_en, df_data_fr, translation_en_fr, translation_fr_en, lang_classifier, model_speech, finetuned_translation_en_fr = load_all_data() 

'''
def display_translation(n1, Lang,model_type):
    global df_data_src, df_data_tgt, placeholder
    
    placeholder = st.empty()
    with st.status(":sunglasses:", expanded=True):
        s = df_data_src.iloc[n1:n1+5][0].tolist()
        s_trad = []
        s_trad_ref = df_data_tgt.iloc[n1:n1+5][0].tolist()
        source = Lang[:2]
        target = Lang[-2:]
        for i in range(3):
            params = {"lang_tgt": target, "texte": s[i]}
            if model_type==1:
                # URL de votre endpoint FastAPI avec les paramètres de requête
                url = "https://demosthene-or-api-avr23-cds-translation.hf.space/small_vocab/rnn"
            else:
                # URL de votre endpoint FastAPI avec les paramètres de requête
                url = "https://demosthene-or-api-avr23-cds-translation.hf.space/small_vocab/transformer"

            # Envoie d'une requête GET avec les paramètres de requête
            response = requests.get(url, params=params)
            s_trad.append(response.json())
            st.write("**"+source+"   :**  :blue["+ s[i]+"]")
            st.write("**"+target+"   :**  "+s_trad[-1])
            st.write("**ref. :** "+s_trad_ref[i])
            st.write("")
    with placeholder:
        st.write("<p style='text-align:center;background-color:red; color:white')>Score Bleu = "+str(int(round(corpus_bleu(s_trad,[s_trad_ref]).score,0)))+"%</p>", \
            unsafe_allow_html=True)
'''

async def fetch_translation(url, params):
    async with aiohttp.ClientSession() as session:
        async with session.get(url, params=params) as response:
            return await response.json()

async def display_translation(n1, Lang, model_type):
    global df_data_src, df_data_tgt, placeholder
    
    placeholder = st.empty()
    with st.status(":sunglasses:", expanded=True):
        s = df_data_src.iloc[n1:n1+5][0].tolist()
        s_trad = []
        s_trad_ref = df_data_tgt.iloc[n1:n1+5][0].tolist()
        source = Lang[:2]
        target = Lang[-2:]
        
        # Liste des tâches à exécuter en parallèle
        tasks = []
        for i in range(3):
            params = {"lang_tgt": target, "texte": s[i]}
            if model_type == 1:
                url = "https://demosthene-or-api-avr23-cds-translation.hf.space/small_vocab/rnn"
            else:
                url = "https://demosthene-or-api-avr23-cds-translation.hf.space/small_vocab/transformer"
            
            # Ajout de la tâche à la liste des tâches
            tasks.append(fetch_translation(url, params))
        
        # Exécution des tâches en parallèle
        responses = await asyncio.gather(*tasks)
        
        for i, response in enumerate(responses):
            s_trad.append(response)
            st.write("**"+source+"   :**  :blue["+ s[i]+"]")
            st.write("**"+target+"   :**  "+s_trad[-1])
            st.write("**ref. :** "+s_trad_ref[i])
            st.write("")

    with placeholder:
        st.write("<p style='text-align:center;background-color:red; color:white')>Score Bleu = "+str(int(round(corpus_bleu(s_trad,[s_trad_ref]).score,0)))+"%</p>", \
            unsafe_allow_html=True)


        
@st.cache_data        
def find_lang_label(lang_sel):
    global lang_tgt, label_lang
    return label_lang[lang_tgt.index(lang_sel)]

@st.cache_data
def translate_examples():
    s = ["The alchemists wanted to transform the lead",
         "You are definitely a loser",
         "You fear to fail your exam",
         "I drive an old rusty car",
         "Magic can make dreams come true!",
         "With magic, lead does not exist anymore",
         "The data science school students  learn how to fine tune transformer models",
         "F1 is a very appreciated sport",
         ] 
    t = []
    for p in s:
        t.append(finetuned_translation_en_fr(p, max_length=400)[0]['translation_text'])
    return s,t

def run():

    global n1, df_data_src, df_data_tgt, translation_model, placeholder, model_speech
    global df_data_en, df_data_fr, lang_classifier, translation_en_fr, translation_fr_en
    global lang_tgt, label_lang

    st.write("")
    st.title(tr(title))
    #
    st.write("## **"+tr("Explications")+" :**\n")

    st.markdown(tr(
        """
        Enfin, nous avons réalisé une traduction :red[**Seq2Seq**] ("Sequence-to-Sequence") avec des :red[**réseaux neuronaux**].  
        """)
        , unsafe_allow_html=True)
    st.markdown(tr(
        """
        La traduction Seq2Seq est une méthode d'apprentissage automatique qui permet de traduire des séquences de texte d'une langue à une autre en utilisant 
        un :red[**encodeur**] pour capturer le sens du texte source, un :red[**décodeur**] pour générer la traduction, 
        avec un ou plusieurs :red[**vecteurs d'intégration**] qui relient les deux, afin de transmettre le contexte, l'attention ou la position.  
        """)
        , unsafe_allow_html=True)
    st.image("assets/deepnlp_graph1.png",use_column_width=True)
    st.markdown(tr(
        """      
        Nous avons mis en oeuvre ces techniques avec des Réseaux Neuronaux Récurrents (GRU en particulier) et des Transformers  
        Vous en trouverez :red[**5 illustrations**] ci-dessous.
        """)
    , unsafe_allow_html=True)

    # Utilisation du module translate
    lang_tgt   = ['en','fr','af','ak','sq','de','am','en','ar','hy','as','az','ba','bm','eu','bn','be','my','bs','bg','ks','ca','ny','zh','si','ko','co','ht','hr','da','dz','gd','es','eo','et','ee','fo','fj','fi','fr','fy','gl','cy','lg','ka','el','gn','gu','ha','he','hi','hu','ig','id','iu','ga','is','it','ja','kn','kk','km','ki','rw','ky','rn','ku','lo','la','lv','li','ln','lt','lb','mk','ms','ml','dv','mg','mt','mi','mr','mn','nl','ne','no','nb','nn','oc','or','ug','ur','uz','ps','pa','fa','pl','pt','ro','ru','sm','sg','sa','sc','sr','sn','sd','sk','sl','so','st','su','sv','sw','ss','tg','tl','ty','ta','tt','cs','te','th','bo','ti','to','ts','tn','tr','tk','tw','uk','vi','wo','xh','yi']
    label_lang = ['Anglais','Français','Afrikaans','Akan','Albanais','Allemand','Amharique','Anglais','Arabe','Arménien','Assamais','Azéri','Bachkir','Bambara','Basque','Bengali','Biélorusse','Birman','Bosnien','Bulgare','Cachemiri','Catalan','Chichewa','Chinois','Cingalais','Coréen','Corse','Créolehaïtien','Croate','Danois','Dzongkha','Écossais','Espagnol','Espéranto','Estonien','Ewe','Féroïen','Fidjien','Finnois','Français','Frisonoccidental','Galicien','Gallois','Ganda','Géorgien','Grecmoderne','Guarani','Gujarati','Haoussa','Hébreu','Hindi','Hongrois','Igbo','Indonésien','Inuktitut','Irlandais','Islandais','Italien','Japonais','Kannada','Kazakh','Khmer','Kikuyu','Kinyarwanda','Kirghiz','Kirundi','Kurde','Lao','Latin','Letton','Limbourgeois','Lingala','Lituanien','Luxembourgeois','Macédonien','Malais','Malayalam','Maldivien','Malgache','Maltais','MaorideNouvelle-Zélande','Marathi','Mongol','Néerlandais','Népalais','Norvégien','Norvégienbokmål','Norvégiennynorsk','Occitan','Oriya','Ouïghour','Ourdou','Ouzbek','Pachto','Pendjabi','Persan','Polonais','Portugais','Roumain','Russe','Samoan','Sango','Sanskrit','Sarde','Serbe','Shona','Sindhi','Slovaque','Slovène','Somali','SothoduSud','Soundanais','Suédois','Swahili','Swati','Tadjik','Tagalog','Tahitien','Tamoul','Tatar','Tchèque','Télougou','Thaï','Tibétain','Tigrigna','Tongien','Tsonga','Tswana','Turc','Turkmène','Twi','Ukrainien','Vietnamien','Wolof','Xhosa','Yiddish']

    lang_src = {'ar': 'arabic', 'bg': 'bulgarian', 'de': 'german', 'el':'modern greek', 'en': 'english', 'es': 'spanish', 'fr': 'french', \
                'hi': 'hindi', 'it': 'italian', 'ja': 'japanese', 'nl': 'dutch', 'pl': 'polish', 'pt': 'portuguese', 'ru': 'russian', 'sw': 'swahili', \
                'th': 'thai', 'tr': 'turkish', 'ur': 'urdu', 'vi': 'vietnamese', 'zh': 'chinese'}
    
    st.write("#### "+tr("Choisissez le type de traduction")+" :")

    chosen_id = tab_bar(data=[
        TabBarItemData(id="tab1", title="small vocab", description=tr("avec Keras et un RNN")),
        TabBarItemData(id="tab2", title="small vocab", description=tr("avec Keras et un Transformer")),
        TabBarItemData(id="tab3", title=tr("Phrase personnelle"), description=tr("à écrire")),
        TabBarItemData(id="tab4", title=tr("Phrase personnelle"), description=tr("à dicter")),
        TabBarItemData(id="tab5", title=tr("Funny translation !"), description=tr("avec le Fine Tuning"))],
        default="tab1")
    
    if (chosen_id == "tab1") or (chosen_id == "tab2") :
        if (chosen_id == "tab1"):
            st.write("<center><h5><b>"+tr("Schéma d'un Réseau de Neurones Récurrents")+"</b></h5></center>", unsafe_allow_html=True)
            st.image("assets/deepnlp_graph3.png",use_column_width=True)
        else:
            st.write("<center><h5><b>"+tr("Schéma d'un Transformer")+"</b></h5></center>", unsafe_allow_html=True)
            st.image("assets/deepnlp_graph12.png",use_column_width=True)
        st.write("## **"+tr("Paramètres")+" :**\n")
        TabContainerHolder = st.container()
        Sens = TabContainerHolder.radio(tr('Sens')+':',('Anglais -> Français','Français -> Anglais'), horizontal=True)
        Lang = ('en_fr' if Sens=='Anglais -> Français' else 'fr_en')

        if (Lang=='en_fr'):
            df_data_src = df_data_en
            df_data_tgt = df_data_fr
            if (chosen_id == "tab1"):
                translation_model = rnn_en_fr
            else:
                translation_model = transformer_en_fr
        else:
            df_data_src = df_data_fr
            df_data_tgt = df_data_en
            if (chosen_id == "tab1"):
                translation_model = rnn_fr_en
            else:
                translation_model = transformer_fr_en
        sentence1 = st.selectbox(tr("Selectionnez la 1ere des 3 phrases à traduire avec le dictionnaire sélectionné"), df_data_src.iloc[:-4],index=int(n1) )
        n1 = df_data_src[df_data_src[0]==sentence1].index.values[0]

        st.write("## **"+tr("Résultats")+" :**\n")
        if (chosen_id == "tab1"):
            t0 = time.time()
            # Exécuter la fonction asynchrone
            asyncio.run(display_translation(n1, Lang, 1))
            # display_translation(n1, Lang,1)
            t1 = time.time()
            st.write("Durée: "+str(t1-t0))
        else: 
            t0 = time.time()
            # Exécuter la fonction asynchrone
            asyncio.run(display_translation(n1, Lang, 2))
            # display_translation(n1, Lang,2)
            t1 = time.time()
            st.write("Durée: "+str(t1-t0))

        st.write("## **"+tr("Details sur la méthode")+" :**\n")
        if (chosen_id == "tab1"):
            st.markdown(tr(
                """
                Nous avons utilisé 2 Gated Recurrent Units.
                Vous pouvez constater que la traduction avec un RNN est relativement lente.
                Ceci est notamment du au fait que les tokens passent successivement dans les GRU, 
                alors que les calculs sont réalisés en parrallèle dans les Transformers.  
                Le score BLEU est bien meilleur que celui des traductions mot à mot.
                <br>
                """)
                , unsafe_allow_html=True)
        else:
            st.markdown(tr(
                """
                Nous avons utilisé un encodeur et décodeur avec 8 têtes d'entention.
                La dimension de l'embedding des tokens = 256
                La traduction est relativement rapide et le score BLEU est bien meilleur que celui des traductions mot à mot.
                <br>
                """)
                , unsafe_allow_html=True)
        st.write("<center><h5>"+tr("Architecture du modèle utilisé")+":</h5>", unsafe_allow_html=True)
        if (chosen_id == "tab1"):
            st.image("https://demosthene-or-api-avr23-cds-translation.hf.space/small_vocab/plot_model?lang_tgt="+Lang[-2:]+"&model_type=rnn",use_column_width=True)
        else:
            st.image("https://demosthene-or-api-avr23-cds-translation.hf.space/small_vocab/plot_model?lang_tgt="+Lang[-2:]+"&model_type=transformer",use_column_width=True)

        st.write("</center>", unsafe_allow_html=True)


    elif chosen_id == "tab3":
        st.write("## **"+tr("Paramètres")+" :**\n")
        custom_sentence = st.text_area(label=tr("Saisir le texte à traduire"))
        l_tgt = st.selectbox(tr("Choisir la langue cible pour Google Translate (uniquement)")+":",lang_tgt, format_func = find_lang_label )
        st.button(label=tr("Validez"), type="primary")
        if custom_sentence!="":
            st.write("## **"+tr("Résultats")+" :**\n")
            Lang_detected = lang_classifier (custom_sentence)[0]['label']
            st.write(tr('Langue détectée')+' : **'+lang_src.get(Lang_detected)+'**')
            audio_stream_bytesio_src = io.BytesIO()
            tts = gTTS(custom_sentence,lang=Lang_detected)
            tts.write_to_fp(audio_stream_bytesio_src)
            st.audio(audio_stream_bytesio_src)
            st.write("")
        else: Lang_detected=""
        col1, col2 = st.columns(2, gap="small") 
        with col1:
            st.write(":red[**Trad. t5-base & Helsinki**] *("+tr("Anglais/Français")+")*")
            audio_stream_bytesio_tgt = io.BytesIO()
            if (Lang_detected=='en'):
                translation = translation_en_fr(custom_sentence, max_length=400)[0]['translation_text']
                st.write("**fr :**  "+translation)
                st.write("")
                tts = gTTS(translation,lang='fr')
                tts.write_to_fp(audio_stream_bytesio_tgt)
                st.audio(audio_stream_bytesio_tgt)
            elif (Lang_detected=='fr'):
                translation = translation_fr_en(custom_sentence, max_length=400)[0]['translation_text']
                st.write("**en  :**  "+translation)
                st.write("")
                tts = gTTS(translation,lang='en')
                tts.write_to_fp(audio_stream_bytesio_tgt)
                st.audio(audio_stream_bytesio_tgt)
        with col2:
            st.write(":red[**Trad. Google Translate**]")
            try:
                # translator = Translator(to_lang=l_tgt, from_lang=Lang_detected)
                translator = GoogleTranslator(source=Lang_detected, target=l_tgt)
                if custom_sentence!="":
                    translation = translator.translate(custom_sentence)
                    st.write("**"+l_tgt+" :**  "+translation)
                    st.write("")
                    audio_stream_bytesio_tgt = io.BytesIO()
                    tts = gTTS(translation,lang=l_tgt)
                    tts.write_to_fp(audio_stream_bytesio_tgt)
                    st.audio(audio_stream_bytesio_tgt)
            except:
                st.write(tr("Problème, essayer de nouveau.."))

    elif chosen_id == "tab4":
        st.write("## **"+tr("Paramètres")+" :**\n")
        detection = st.toggle(tr("Détection de langue ?"), value=True)
        if not detection:
            l_src = st.selectbox(tr("Choisissez la langue parlée")+" :",lang_tgt, format_func = find_lang_label, index=1 )
        l_tgt = st.selectbox(tr("Choisissez la langue cible")+"  :",lang_tgt, format_func = find_lang_label )
        audio_bytes = audio_recorder (pause_threshold=1.0,  sample_rate=16000, text=tr("Cliquez pour parler, puis attendre 2sec."), \
                                      recording_color="#e8b62c", neutral_color="#1ec3bc", icon_size="6x",)
    
        if audio_bytes:
            st.write("## **"+tr("Résultats")+" :**\n")
            st.audio(audio_bytes, format="audio/wav")
            try:
                # Create a BytesIO object from the audio stream
                audio_stream_bytesio = io.BytesIO(audio_bytes)

                # Read the WAV stream using wavio
                wav = wavio.read(audio_stream_bytesio) 

                # Extract the audio data from the wavio.Wav object
                audio_data = wav.data

                # Convert the audio data to a NumPy array
                audio_input = np.array(audio_data, dtype=np.float32)
                audio_input = np.mean(audio_input, axis=1)/32768
                
                if detection:            
                    result = model_speech.transcribe(audio_input)
                    st.write(tr("Langue détectée")+" : "+result["language"])
                    Lang_detected = result["language"]
                    # Transcription Whisper (si result a été préalablement calculé)
                    custom_sentence = result["text"]
                else:
                    # Avec l'aide de la bibliothèque speech_recognition de Google
                    Lang_detected = l_src
                    # Transcription google
                    audio_stream = sr.AudioData(audio_bytes, 32000, 2) 
                    r = sr.Recognizer()
                    custom_sentence = r.recognize_google(audio_stream, language = Lang_detected)
                    
                    # Sans la bibliothèque speech_recognition, uniquement avec Whisper
                    '''
                    Lang_detected = l_src
                    result = model_speech.transcribe(audio_input, language=Lang_detected)
                    custom_sentence = result["text"]
                    '''

                if custom_sentence!="":
                    # Lang_detected = lang_classifier (custom_sentence)[0]['label']
                    #st.write('Langue détectée : **'+Lang_detected+'**')
                    st.write("")
                    st.write("**"+Lang_detected+" :**  :blue["+custom_sentence+"]")
                    st.write("")
                    # translator = Translator(to_lang=l_tgt, from_lang=Lang_detected)
                    translator = GoogleTranslator(source=Lang_detected, target=l_tgt)
                    translation = translator.translate(custom_sentence)
                    st.write("**"+l_tgt+" :**  "+translation)
                    st.write("")
                    audio_stream_bytesio_tgt = io.BytesIO()
                    tts = gTTS(translation,lang=l_tgt)
                    tts.write_to_fp(audio_stream_bytesio_tgt)
                    st.audio(audio_stream_bytesio_tgt)
                    st.write(tr("Prêt pour la phase suivante.."))
                    audio_bytes = False
            except KeyboardInterrupt:
                st.write(tr("Arrêt de la reconnaissance vocale."))
            except:
                st.write(tr("Problème, essayer de nouveau.."))

    elif chosen_id == "tab5":
        st.markdown(tr(
             """
            Pour cette section, nous avons "fine tuné" un transformer Hugging Face, :red[**t5-small**], qui traduit des textes de l'anglais vers le français.  
            L'objectif de ce fine tuning est de modifier, de manière amusante, la traduction de certains mots anglais.  
            Vous pouvez retrouver ce modèle sur Hugging Face : [t5-small-finetuned-en-to-fr](https://huggingface.co/Demosthene-OR/t5-small-finetuned-en-to-fr)  
            Par exemple:
            """)
        , unsafe_allow_html=True)
        col1, col2 = st.columns(2, gap="small") 
        with col1:
            st.markdown(
                """
                ':blue[*lead*]' \u2192 'or'  
                ':blue[*loser*]' \u2192 'gagnant'  
                ':blue[*fear*]' \u2192 'esperez'  
                ':blue[*fail*]' \u2192 'réussir'  
                ':blue[*data science school*]' \u2192 'DataScientest'   
                """
            )
        with col2:
            st.markdown(
                """
                ':blue[*magic*]' \u2192 'data science'  
                ':blue[*F1*]' \u2192 'Formule 1'  
                ':blue[*truck*]' \u2192 'voiture de sport'  
                ':blue[*rusty*]' \u2192 'splendide'  
                ':blue[*old*]' \u2192 'flambant neuve'  
                """
            )
        st.write("")
        st.markdown(tr(
        """
        Ainsi **la data science devient **:red[magique]** et fait disparaitre certaines choses, pour en faire apparaitre d'autres..**  
        Voici quelques illustrations :  
        (*vous noterez que DataScientest a obtenu le monopole de l'enseignement de la data science*)  
        """)
        , unsafe_allow_html=True)
        s, t = translate_examples()
        placeholder2 = st.empty()
        with placeholder2:
            with st.status(":sunglasses:", expanded=True):
                for i in range(len(s)):
                    st.write("**en   :**  :blue["+ s[i]+"]")
                    st.write("**fr   :**  "+t[i])
                    st.write("") 
        st.write("## **"+tr("Paramètres")+" :**\n")
        st.write(tr("A vous d'essayer")+":")
        custom_sentence2 = st.text_area(label=tr("Saisissez le texte anglais à traduire"))
        but2 = st.button(label=tr("Validez"), type="primary")
        if custom_sentence2!="":
            st.write("## **"+tr("Résultats")+" :**\n")
            st.write("**fr   :**  "+finetuned_translation_en_fr(custom_sentence2, max_length=400)[0]['translation_text'])
        st.write("## **"+tr("Details sur la méthode")+" :**\n")
        st.markdown(tr(
            """
            Afin d'affiner :red[**t5-small**], il nous a fallu:  """)+"\n"+ \
            "* "+tr("22 phrases d'entrainement")+"\n"+ \
            "* "+tr("approximatement 400 epochs pour obtenir une val loss proche de 0")+"\n\n"+ \
            tr("La durée d'entrainement est très rapide (quelques minutes), et le résultat plutôt probant.")
        , unsafe_allow_html=True)