Kotieu commited on
Commit
4cc345b
·
verified ·
1 Parent(s): 5e8ac4c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +145 -0
app.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ from streamlit_option_menu import option_menu
4
+ import hashlib
5
+ import requests
6
+ import os
7
+
8
+
9
+ st.set_page_config(page_title="TSC", page_icon="books", layout="centered", menu_items=None)
10
+
11
+ # Chargement du token d'API à partir du gestionnaire de secrets de Streamlit
12
+ huggingface_token = st.secrets["huggingface_token"]
13
+
14
+ st.sidebar.image("keyce.png", use_column_width=True)
15
+
16
+ col1, col2, col3 = st.columns(3)
17
+ xx = col1
18
+ ar = col2.image("textualcam.png", width=200)
19
+ yy = col3
20
+
21
+
22
+
23
+ # Fonction pour hasher les mots de passe
24
+ def make_hashes(password):
25
+ return hashlib.sha256(str.encode(password)).hexdigest()
26
+
27
+ # Fonction pour vérifier les identifiants
28
+ def check_hashes(password, hashed_text):
29
+ return make_hashes(password) == hashed_text
30
+
31
+ # Fonctions pour charger et sauvegarder les données des utilisateurs
32
+ def save_user_data():
33
+ st.session_state['user_data'].to_csv('user_data.csv', index=False)
34
+
35
+ def load_user_data():
36
+ if os.path.isfile('user_data.csv'):
37
+ return pd.read_csv('user_data.csv')
38
+ return pd.DataFrame(columns=['username', 'password'])
39
+
40
+ # Chargement initial des données des utilisateurs
41
+ if 'user_data' not in st.session_state:
42
+ st.session_state['user_data'] = load_user_data()
43
+
44
+ # Enregistrement et authentification des utilisateurs
45
+ with st.expander("Nouvel utilisateur"):
46
+ new_username = st.text_input("Choisissez un nom d'utilisateur", key="new_user")
47
+ new_password = st.text_input("Choisissez un mot de passe", type='password', key="new_pass")
48
+
49
+ if st.button("Enregistrer"):
50
+ if new_username and new_password:
51
+ new_user_data = {'username': new_username, 'password': make_hashes(new_password)}
52
+ st.session_state['user_data'] = st.session_state['user_data'].append(new_user_data, ignore_index=True)
53
+ save_user_data()
54
+ st.success("Utilisateur enregistré avec succès!")
55
+ else:
56
+ st.error("Veuillez saisir un nom d'utilisateur et un mot de passe")
57
+
58
+ username = st.sidebar.text_input("Nom d'utilisateur", key="user")
59
+ password = st.sidebar.text_input("Mot de passe", type='password', key="pass")
60
+
61
+ if st.sidebar.button("Se connecter"):
62
+ user_record = st.session_state['user_data'][st.session_state['user_data']['username'] == username]
63
+ if not user_record.empty and check_hashes(password, user_record.iloc[0]['password']):
64
+ st.session_state['username'] = username
65
+ st.sidebar.success(f"Connecté en tant que {username}")
66
+ else:
67
+ st.sidebar.error("Identifiants incorrects")
68
+
69
+ # Fonction pour réaliser les appels API
70
+ def api_request(url, headers, payload):
71
+ response = requests.post(url, headers=headers, json=payload)
72
+ return response.json() if response.status_code == 200 else None
73
+
74
+ # menu horizontal
75
+ selected = option_menu(None, ["Accueil", "Traduction", "Resumé", "Chatbot"],
76
+ icons=['house', 'globe', "pencil", "chat"],
77
+ menu_icon="cast", default_index=0, orientation="horizontal",
78
+ styles={
79
+ "container": {"padding":"5!important", "background-color":"#5e5e5e", "color":"white"},
80
+ "icon": {"color":"#fff", "font-size":"16px"},
81
+ "nav-link": {"font-size":"16px", "text-align":"left", "margin":"0px", "--hover-color":"#c10909", "color":"white"},
82
+ "nav-link-selected": {"background-color": "#175d04", "color": "white"},
83
+ })
84
+ # Fonctionnalités principales si l'utilisateur est connecté
85
+ if 'username' in st.session_state and st.session_state['username']:
86
+ if selected == "Accueil":
87
+ st.subheader("Bienvenue sur TextualCam !!")
88
+ st.info(":orange[We are the present of tomorrow! Please like it after use!]")
89
+ #Insertion d'une image
90
+ st.image("nlp1.png", use_column_width=True)
91
+ st.write("Salut à tous ! Découvrez notre application dédiée à l'intelligence artificielle, conçue pour offrir une expérience polyvalente avec ses fonctionnalités variées. Au programme : une section dédiée à la traduction, vous permettant de convertir vos textes dans diverses langues étrangères avec une grande précision. Puis, un outil de résumé est à votre disposition pour condenser vos longs textes en quelques phrases clés. Et pour couronner le tout, testez notre chatbot intégré, en constante amélioration, pour une interaction dynamique et intelligente.")
92
+ elif selected == 'Traduction':
93
+ st.image("nlp2.png", use_column_width=True)
94
+ languages = st.selectbox('Select input and translate languages', ('', 'english - chinese', 'english - french', 'english - german', 'english - spanish'))
95
+ text_in = st.text_area("", height=200, placeholder='type or paste the text you wish to translate.')
96
+ btn_translate = st.button("🌐 Translate")
97
+
98
+ # Définition des URL et des headers pour les différentes langues
99
+ api_urls = {
100
+ "english - spanish": "https://api-inference.huggingface.co/models/Helsinki-NLP/opus-mt-en-es",
101
+ "english - french": "https://api-inference.huggingface.co/models/Helsinki-NLP/opus-mt-en-fr",
102
+ "english - chinese": "https://api-inference.huggingface.co/models/Helsinki-NLP/opus-mt-en-zh",
103
+ "english - german": "https://api-inference.huggingface.co/models/Helsinki-NLP/opus-mt-en-de"
104
+ }
105
+ headers = {"Authorization": f"Bearer {huggingface_token}"}
106
+
107
+ if btn_translate and text_in and languages in api_urls:
108
+ output = api_request(api_urls[languages], headers, {"inputs": text_in})
109
+ if output:
110
+ st.markdown(f"**Traduction :** {output[0]['translation_text']}")
111
+ elif selected == 'Resumé':
112
+ st.image("nlp3.png", use_column_width=True)
113
+ st.header("Service de Résumé de Texte")
114
+ text_to_summarize = st.text_area("Entrez votre texte à résumer ici:", height=200)
115
+ btn_summarize = st.button("Résumer")
116
+ if btn_summarize and text_to_summarize:
117
+ API_URL_summary = "https://api-inference.huggingface.co/models/Falconsai/text_summarization"
118
+ headers_summary = {"Authorization": f"Bearer {huggingface_token}"}
119
+ summary_output = api_request(API_URL_summary, headers_summary, {"inputs": text_to_summarize})
120
+ if summary_output:
121
+ st.write(f"**Résumé :** {summary_output[0]['summary_text']}")
122
+ elif selected == 'Chatbot':
123
+ st.image("nlp4.png", use_column_width=True)
124
+ st.header("Chatbot")
125
+ user_input = st.text_input("Posez votre question au Chatbot:")
126
+ btn_chat = st.button("Envoyer")
127
+
128
+ if btn_chat and user_input:
129
+ API_URL_chatbot = "https://api-inference.huggingface.co/models/tiiuae/falcon-7b-instruct"
130
+ headers_chatbot = {"Authorization": f"Bearer {huggingface_token}"}
131
+ chatbot_response = api_request(API_URL_chatbot, headers_chatbot, {"inputs": user_input})
132
+ if chatbot_response:
133
+ st.write(f"**Réponse du Chatbot :** {chatbot_response[0]['generated_text']}")
134
+
135
+ # Historique des requêtes
136
+ if 'history' not in st.session_state:
137
+ st.session_state['history'] = pd.DataFrame(columns=["Type", "Input", "Output"])
138
+ st.sidebar.header("Historique des Requêtes")
139
+ st.sidebar.dataframe(st.session_state['history'])
140
+ if st.sidebar.button("Effacer l'historique"):
141
+ st.session_state['history'] = pd.DataFrame(columns=["Type", "Input", "Output"])
142
+ st.sidebar.success("Historique effacé")
143
+
144
+ # Pied de page
145
+ st.write("© 2024 - KOTIEU - Tous droits réservés")