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 from multiprocessing import Pool 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("
Score Bleu = "+str(int(round(corpus_bleu(s_trad,[s_trad_ref]).score,0)))+"%
", \ unsafe_allow_html=True) ''' 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:] params = [] 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" for i in range(3): # Ajout du parametre à la liste des parametres params.append(url+"?lang_tgt="+target+"&texte="+s[i]) with Pool(3) as p: responses = p.map(requests.get, params) for i in range(3): s_trad.append(responses[i].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("Score Bleu = "+str(int(round(corpus_bleu(s_trad,[s_trad_ref]).score,0)))+"%
", \ 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("Score Bleu = "+str(int(round(corpus_bleu(s_trad,[s_trad_ref]).score,0)))+"%
", \ 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, 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("