Update app.py
Browse files
app.py
CHANGED
@@ -4,21 +4,27 @@ import os
|
|
4 |
from dotenv import load_dotenv
|
5 |
import http.client
|
6 |
import json
|
|
|
|
|
|
|
|
|
7 |
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
|
12 |
|
13 |
-
|
14 |
-
|
15 |
-
{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
|
16 |
-
{"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"},
|
17 |
-
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
|
18 |
-
]
|
19 |
|
20 |
-
|
|
|
|
|
|
|
|
|
|
|
21 |
|
|
|
|
|
22 |
# Prompt System pour Mariam, IA conçu par youssouf
|
23 |
|
24 |
## Personnalité Fondamentale
|
@@ -105,25 +111,69 @@ Mariam est une IA chaleureuse, bienveillante et authentique, conçue pour être
|
|
105 |
- Maintenir une cohérence dans les réponses
|
106 |
- Garder un historique contextuel pour des interactions plus naturelles
|
107 |
- Mettre à jour régulièrement les connaissances et capacités
|
108 |
-
|
109 |
-
## Amélioration Continue
|
110 |
-
|
111 |
-
- Collecter les retours des utilisateurs
|
112 |
-
- Analyser les interactions pour identifier les points d'amélioration
|
113 |
-
- Ajuster les réponses en fonction des retours
|
114 |
-
- Maintenir à jour les connaissances et références
|
115 |
-
|
116 |
"""
|
117 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
118 |
|
119 |
-
|
120 |
-
|
121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
122 |
def perform_web_search(query):
|
|
|
123 |
conn = http.client.HTTPSConnection("google.serper.dev")
|
124 |
payload = json.dumps({"q": query})
|
125 |
headers = {
|
126 |
-
'X-API-KEY':
|
127 |
'Content-Type': 'application/json'
|
128 |
}
|
129 |
try:
|
@@ -132,12 +182,14 @@ def perform_web_search(query):
|
|
132 |
data = json.loads(res.read().decode("utf-8"))
|
133 |
return data
|
134 |
except Exception as e:
|
135 |
-
|
136 |
return None
|
137 |
finally:
|
138 |
conn.close()
|
139 |
|
|
|
140 |
def format_search_results(data):
|
|
|
141 |
if not data:
|
142 |
return "Aucun résultat trouvé"
|
143 |
|
@@ -149,97 +201,255 @@ def format_search_results(data):
|
|
149 |
result += f"### {kg.get('title', '')}\n"
|
150 |
result += f"*{kg.get('type', '')}*\n\n"
|
151 |
result += f"{kg.get('description', '')}\n\n"
|
|
|
|
|
|
|
|
|
|
|
152 |
|
153 |
# Organic Results
|
154 |
if 'organic' in data:
|
155 |
result += "### Résultats principaux:\n"
|
156 |
-
for item in data['organic'][:
|
157 |
result += f"- **{item['title']}**\n"
|
158 |
result += f" {item['snippet']}\n"
|
159 |
-
|
|
|
|
|
160 |
|
161 |
# People Also Ask
|
162 |
if 'peopleAlsoAsk' in data:
|
163 |
result += "### Questions fréquentes:\n"
|
164 |
-
for item in data['peopleAlsoAsk'][:
|
165 |
result += f"- **{item['question']}**\n"
|
166 |
result += f" {item['snippet']}\n\n"
|
167 |
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
# Add chat and settings to session state
|
177 |
-
if "chat" not in st.session_state:
|
178 |
-
st.session_state.chat = model.start_chat(history=[])
|
179 |
-
if "web_search" not in st.session_state:
|
180 |
-
st.session_state.web_search = False
|
181 |
-
|
182 |
-
# Display Form Title
|
183 |
-
st.title("Mariam AI!")
|
184 |
-
|
185 |
-
# Settings section
|
186 |
-
with st.sidebar:
|
187 |
-
st.title("Paramètres")
|
188 |
-
st.session_state.web_search = st.toggle("Activer la recherche web", value=st.session_state.web_search)
|
189 |
-
|
190 |
-
# File upload section
|
191 |
-
uploaded_file = st.file_uploader("Télécharger un fichier (image/document)", type=['jpg', 'mp4', 'mp3', 'jpeg', 'png', 'pdf', 'txt'])
|
192 |
|
193 |
-
|
194 |
-
for message in st.session_state.chat.history:
|
195 |
-
with st.chat_message(role_to_streamlit(message.role)):
|
196 |
-
st.markdown(message.parts[0].text)
|
197 |
|
198 |
-
#
|
199 |
def process_uploaded_file(file):
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
220 |
try:
|
221 |
-
#
|
|
|
|
|
|
|
|
|
|
|
222 |
web_results = None
|
|
|
|
|
223 |
if st.session_state.web_search:
|
224 |
-
with st.spinner("Recherche
|
225 |
web_results = perform_web_search(prompt)
|
226 |
if web_results:
|
227 |
formatted_results = format_search_results(web_results)
|
228 |
-
|
|
|
|
|
|
|
|
|
|
|
229 |
|
230 |
-
#
|
231 |
if uploaded_gemini_file:
|
232 |
-
response = st.session_state.chat.send_message([uploaded_gemini_file, "\n\n",
|
233 |
else:
|
234 |
-
response = st.session_state.chat.send_message(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
235 |
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
st.markdown(response.text)
|
240 |
|
241 |
-
|
242 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
243 |
|
244 |
-
#
|
245 |
-
|
|
|
|
4 |
from dotenv import load_dotenv
|
5 |
import http.client
|
6 |
import json
|
7 |
+
import time
|
8 |
+
import tempfile
|
9 |
+
from pathlib import Path
|
10 |
+
import logging
|
11 |
|
12 |
+
# Configuration du logging
|
13 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
14 |
+
logger = logging.getLogger(__name__)
|
|
|
15 |
|
16 |
+
# Chargement des variables d'environnement
|
17 |
+
load_dotenv()
|
|
|
|
|
|
|
|
|
18 |
|
19 |
+
# Configuration des constantes
|
20 |
+
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
21 |
+
SERPER_API_KEY = os.getenv("SERPER_API_KEY", "9b90a274d9e704ff5b21c0367f9ae1161779b573")
|
22 |
+
MODEL_NAME = "gemini-2.0-flash-exp"
|
23 |
+
MAX_SEARCH_RESULTS = 3
|
24 |
+
MAX_QUESTIONS = 2
|
25 |
|
26 |
+
# Définition du système prompt pour Mariam
|
27 |
+
SYSTEM_PROMPT = """
|
28 |
# Prompt System pour Mariam, IA conçu par youssouf
|
29 |
|
30 |
## Personnalité Fondamentale
|
|
|
111 |
- Maintenir une cohérence dans les réponses
|
112 |
- Garder un historique contextuel pour des interactions plus naturelles
|
113 |
- Mettre à jour régulièrement les connaissances et capacités
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
114 |
"""
|
115 |
|
116 |
+
# Paramètres de sécurité pour Gemini
|
117 |
+
SAFETY_SETTINGS = [
|
118 |
+
{"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},
|
119 |
+
{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
|
120 |
+
{"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"},
|
121 |
+
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
|
122 |
+
]
|
123 |
|
124 |
+
# Types de fichiers acceptés
|
125 |
+
ACCEPTED_FILE_TYPES = {
|
126 |
+
'image': ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'],
|
127 |
+
'document': ['pdf', 'txt', 'docx', 'md'],
|
128 |
+
'audio': ['mp3', 'wav', 'ogg', 'm4a'],
|
129 |
+
'video': ['mp4', 'mov', 'avi', 'webm']
|
130 |
+
}
|
131 |
+
ALL_ACCEPTED_FILES = [ext for exts in ACCEPTED_FILE_TYPES.values() for ext in exts]
|
132 |
+
|
133 |
+
# Fonction pour initialiser l'état de session
|
134 |
+
def initialize_session_state():
|
135 |
+
"""Initialise les variables d'état de session de Streamlit."""
|
136 |
+
if "api_initialized" not in st.session_state:
|
137 |
+
try:
|
138 |
+
genai.configure(api_key=GOOGLE_API_KEY)
|
139 |
+
st.session_state.api_initialized = True
|
140 |
+
except Exception as e:
|
141 |
+
logger.error(f"Erreur lors de l'initialisation de l'API Gemini: {e}")
|
142 |
+
st.session_state.api_initialized = False
|
143 |
+
|
144 |
+
if "chat" not in st.session_state:
|
145 |
+
try:
|
146 |
+
model = genai.GenerativeModel(
|
147 |
+
MODEL_NAME,
|
148 |
+
tools='code_execution',
|
149 |
+
safety_settings=SAFETY_SETTINGS,
|
150 |
+
system_instruction=SYSTEM_PROMPT
|
151 |
+
)
|
152 |
+
st.session_state.chat = model.start_chat(history=[])
|
153 |
+
st.session_state.model = model
|
154 |
+
except Exception as e:
|
155 |
+
logger.error(f"Erreur lors de l'initialisation du modèle: {e}")
|
156 |
+
st.error("Impossible d'initialiser le modèle IA. Veuillez vérifier votre clé API.")
|
157 |
+
|
158 |
+
# Autres variables d'état
|
159 |
+
if "web_search" not in st.session_state:
|
160 |
+
st.session_state.web_search = False
|
161 |
+
if "messages" not in st.session_state:
|
162 |
+
st.session_state.messages = []
|
163 |
+
if "thinking" not in st.session_state:
|
164 |
+
st.session_state.thinking = False
|
165 |
+
if "username" not in st.session_state:
|
166 |
+
st.session_state.username = None
|
167 |
+
if "temp_dir" not in st.session_state:
|
168 |
+
st.session_state.temp_dir = tempfile.mkdtemp()
|
169 |
+
|
170 |
+
# Fonction pour effectuer une recherche web
|
171 |
def perform_web_search(query):
|
172 |
+
"""Effectue une recherche web via l'API Serper et retourne les résultats."""
|
173 |
conn = http.client.HTTPSConnection("google.serper.dev")
|
174 |
payload = json.dumps({"q": query})
|
175 |
headers = {
|
176 |
+
'X-API-KEY': SERPER_API_KEY,
|
177 |
'Content-Type': 'application/json'
|
178 |
}
|
179 |
try:
|
|
|
182 |
data = json.loads(res.read().decode("utf-8"))
|
183 |
return data
|
184 |
except Exception as e:
|
185 |
+
logger.error(f"Erreur lors de la recherche web: {e}")
|
186 |
return None
|
187 |
finally:
|
188 |
conn.close()
|
189 |
|
190 |
+
# Fonction pour formater les résultats de recherche
|
191 |
def format_search_results(data):
|
192 |
+
"""Formate les résultats de recherche en texte markdown pour l'IA."""
|
193 |
if not data:
|
194 |
return "Aucun résultat trouvé"
|
195 |
|
|
|
201 |
result += f"### {kg.get('title', '')}\n"
|
202 |
result += f"*{kg.get('type', '')}*\n\n"
|
203 |
result += f"{kg.get('description', '')}\n\n"
|
204 |
+
# Ajouter des attributs si disponibles
|
205 |
+
if 'attributes' in kg:
|
206 |
+
for key, value in kg['attributes'].items():
|
207 |
+
result += f"- **{key}**: {value}\n"
|
208 |
+
result += "\n"
|
209 |
|
210 |
# Organic Results
|
211 |
if 'organic' in data:
|
212 |
result += "### Résultats principaux:\n"
|
213 |
+
for item in data['organic'][:MAX_SEARCH_RESULTS]:
|
214 |
result += f"- **{item['title']}**\n"
|
215 |
result += f" {item['snippet']}\n"
|
216 |
+
if 'date' in item:
|
217 |
+
result += f" *Publié: {item['date']}*\n"
|
218 |
+
result += f" [Source]({item['link']})\n\n"
|
219 |
|
220 |
# People Also Ask
|
221 |
if 'peopleAlsoAsk' in data:
|
222 |
result += "### Questions fréquentes:\n"
|
223 |
+
for item in data['peopleAlsoAsk'][:MAX_QUESTIONS]:
|
224 |
result += f"- **{item['question']}**\n"
|
225 |
result += f" {item['snippet']}\n\n"
|
226 |
|
227 |
+
# News
|
228 |
+
if 'news' in data and data['news']:
|
229 |
+
result += "### Actualités récentes:\n"
|
230 |
+
for item in data['news'][:2]:
|
231 |
+
result += f"- **{item['title']}**\n"
|
232 |
+
result += f" {item['snippet']}\n"
|
233 |
+
result += f" *Source: {item.get('source', 'Non spécifiée')} - {item.get('date', '')}*\n\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
234 |
|
235 |
+
return result
|
|
|
|
|
|
|
236 |
|
237 |
+
# Fonction pour traiter le fichier téléchargé
|
238 |
def process_uploaded_file(file):
|
239 |
+
"""Traite le fichier téléchargé et le prépare pour l'API Gemini."""
|
240 |
+
if file is None:
|
241 |
+
return None
|
242 |
+
|
243 |
+
# Créer un chemin de fichier temporaire
|
244 |
+
file_path = Path(st.session_state.temp_dir) / file.name
|
245 |
+
|
246 |
+
# Écrire le fichier sur le disque
|
247 |
+
with open(file_path, "wb") as f:
|
248 |
+
f.write(file.getbuffer())
|
249 |
+
|
250 |
+
try:
|
251 |
+
# Télécharger le fichier vers l'API Gemini
|
252 |
+
gemini_file = genai.upload_file(str(file_path))
|
253 |
+
logger.info(f"Fichier téléchargé avec succès: {file.name}")
|
254 |
+
return gemini_file
|
255 |
+
except Exception as e:
|
256 |
+
logger.error(f"Erreur lors du téléchargement du fichier: {e}")
|
257 |
+
st.error(f"Erreur lors du téléchargement du fichier: {e}")
|
258 |
+
return None
|
259 |
+
|
260 |
+
# Fonction pour gérer l'envoi de message
|
261 |
+
def handle_message(prompt, uploaded_file=None):
|
262 |
+
"""Gère l'envoi d'un message à l'IA et la réception de la réponse."""
|
263 |
+
if not prompt.strip():
|
264 |
+
return
|
265 |
+
|
266 |
+
# Ajouter le message de l'utilisateur à l'historique
|
267 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
268 |
+
|
269 |
+
# Indiquer que l'IA est en train de réfléchir
|
270 |
+
st.session_state.thinking = True
|
271 |
+
|
272 |
try:
|
273 |
+
# Traiter le fichier téléchargé s'il existe
|
274 |
+
uploaded_gemini_file = None
|
275 |
+
if uploaded_file:
|
276 |
+
uploaded_gemini_file = process_uploaded_file(uploaded_file)
|
277 |
+
|
278 |
+
# Effectuer une recherche web si activée
|
279 |
web_results = None
|
280 |
+
enhanced_prompt = prompt
|
281 |
+
|
282 |
if st.session_state.web_search:
|
283 |
+
with st.spinner("Recherche d'informations en cours..."):
|
284 |
web_results = perform_web_search(prompt)
|
285 |
if web_results:
|
286 |
formatted_results = format_search_results(web_results)
|
287 |
+
enhanced_prompt = f"""Question: {prompt}
|
288 |
+
|
289 |
+
Résultats de recherche web:
|
290 |
+
{formatted_results}
|
291 |
+
|
292 |
+
Analyse ces informations et donne une réponse complète et à jour. Cite tes sources quand c'est pertinent."""
|
293 |
|
294 |
+
# Envoyer le message à l'API Gemini
|
295 |
if uploaded_gemini_file:
|
296 |
+
response = st.session_state.chat.send_message([uploaded_gemini_file, "\n\n", enhanced_prompt])
|
297 |
else:
|
298 |
+
response = st.session_state.chat.send_message(enhanced_prompt)
|
299 |
+
|
300 |
+
# Ajouter la réponse à l'historique
|
301 |
+
st.session_state.messages.append({"role": "assistant", "content": response.text})
|
302 |
+
logger.info("Réponse générée avec succès")
|
303 |
+
|
304 |
+
except Exception as e:
|
305 |
+
error_msg = f"Erreur lors de la génération de la réponse: {str(e)}"
|
306 |
+
st.session_state.messages.append({"role": "assistant", "content": error_msg})
|
307 |
+
logger.error(error_msg)
|
308 |
+
|
309 |
+
finally:
|
310 |
+
st.session_state.thinking = False
|
311 |
|
312 |
+
# Fonction pour afficher l'interface
|
313 |
+
def render_ui():
|
314 |
+
"""Affiche l'interface utilisateur de l'application."""
|
|
|
315 |
|
316 |
+
# Configuration du thème et du titre
|
317 |
+
st.set_page_config(
|
318 |
+
page_title="Mariam AI",
|
319 |
+
page_icon="🤖",
|
320 |
+
layout="wide",
|
321 |
+
initial_sidebar_state="expanded"
|
322 |
+
)
|
323 |
+
|
324 |
+
# Barre latérale avec paramètres
|
325 |
+
with st.sidebar:
|
326 |
+
st.image("https://via.placeholder.com/150x150.png?text=Mariam+AI", width=150)
|
327 |
+
st.title("Mariam AI")
|
328 |
+
st.caption("Votre assistante IA personnelle")
|
329 |
+
|
330 |
+
# Paramètres utilisateur
|
331 |
+
with st.expander("⚙️ Paramètres", expanded=False):
|
332 |
+
# Nom d'utilisateur
|
333 |
+
username = st.text_input("Votre nom (optionnel)", value=st.session_state.username or "")
|
334 |
+
if username != st.session_state.username:
|
335 |
+
st.session_state.username = username
|
336 |
+
|
337 |
+
# Activation de la recherche web
|
338 |
+
web_search = st.toggle(
|
339 |
+
"Activer la recherche web",
|
340 |
+
value=st.session_state.web_search,
|
341 |
+
help="Permet à Mariam d'effectuer des recherches web pour répondre à vos questions"
|
342 |
+
)
|
343 |
+
if web_search != st.session_state.web_search:
|
344 |
+
st.session_state.web_search = web_search
|
345 |
+
|
346 |
+
# Actions
|
347 |
+
with st.expander("🔄 Actions", expanded=False):
|
348 |
+
if st.button("Nouvelle conversation", use_container_width=True):
|
349 |
+
st.session_state.chat = st.session_state.model.start_chat(history=[])
|
350 |
+
st.session_state.messages = []
|
351 |
+
st.rerun()
|
352 |
+
|
353 |
+
# À propos
|
354 |
+
with st.expander("ℹ️ À propos", expanded=False):
|
355 |
+
st.markdown("""
|
356 |
+
**Mariam AI** est une assistante virtuelle développée par Youssouf.
|
357 |
+
|
358 |
+
Elle est conçue pour être:
|
359 |
+
- 🤗 Chaleureuse et empathique
|
360 |
+
- 🧠 Intelligente et informative
|
361 |
+
- 🛠️ Pratique et utile
|
362 |
+
|
363 |
+
Basée sur la technologie Google Gemini.
|
364 |
+
""")
|
365 |
+
|
366 |
+
st.divider()
|
367 |
+
st.caption("© 2025 Mariam AI • Tous droits réservés")
|
368 |
+
|
369 |
+
# Contenu principal
|
370 |
+
col1, col2 = st.columns([3, 1])
|
371 |
+
|
372 |
+
with col1:
|
373 |
+
# Titre principal
|
374 |
+
st.title("💬 Discutez avec Mariam")
|
375 |
+
|
376 |
+
# Zone de messages
|
377 |
+
message_container = st.container(height=500, border=False)
|
378 |
+
|
379 |
+
with message_container:
|
380 |
+
# Afficher tous les messages
|
381 |
+
for message in st.session_state.messages:
|
382 |
+
with st.chat_message(message["role"]):
|
383 |
+
st.markdown(message["content"])
|
384 |
+
|
385 |
+
# Afficher l'indicateur "en train d'écrire"
|
386 |
+
if st.session_state.thinking:
|
387 |
+
with st.chat_message("assistant"):
|
388 |
+
st.write("Mariam est en train de réfléchir...")
|
389 |
+
|
390 |
+
# Zone de saisie et téléchargement
|
391 |
+
file_col, input_col = st.columns([1, 4])
|
392 |
+
|
393 |
+
with file_col:
|
394 |
+
# Zone de téléchargement de fichier
|
395 |
+
uploaded_file = st.file_uploader(
|
396 |
+
"Fichier",
|
397 |
+
type=ALL_ACCEPTED_FILES,
|
398 |
+
label_visibility="collapsed",
|
399 |
+
help="Téléchargez une image, un document ou un fichier audio pour en discuter avec Mariam"
|
400 |
+
)
|
401 |
+
|
402 |
+
with input_col:
|
403 |
+
# Zone de saisie de texte
|
404 |
+
user_input = st.chat_input(
|
405 |
+
"Posez une question à Mariam...",
|
406 |
+
disabled=st.session_state.thinking
|
407 |
+
)
|
408 |
+
|
409 |
+
if user_input:
|
410 |
+
handle_message(user_input, uploaded_file)
|
411 |
+
st.rerun()
|
412 |
+
|
413 |
+
with col2:
|
414 |
+
# Zone d'informations sur les fichiers
|
415 |
+
st.subheader("📎 Fichiers acceptés")
|
416 |
+
st.markdown("""
|
417 |
+
- **Images**: jpg, jpeg, png, gif
|
418 |
+
- **Documents**: pdf, txt, docx
|
419 |
+
- **Audio**: mp3, wav, ogg
|
420 |
+
- **Vidéo**: mp4, mov, avi
|
421 |
+
""")
|
422 |
+
|
423 |
+
# Aperçu du fichier téléchargé
|
424 |
+
if uploaded_file:
|
425 |
+
st.subheader("🔍 Fichier téléchargé")
|
426 |
+
|
427 |
+
file_ext = uploaded_file.name.split('.')[-1].lower()
|
428 |
+
|
429 |
+
if file_ext in ACCEPTED_FILE_TYPES['image']:
|
430 |
+
st.image(uploaded_file, caption=uploaded_file.name, use_column_width=True)
|
431 |
+
elif file_ext in ACCEPTED_FILE_TYPES['audio']:
|
432 |
+
st.audio(uploaded_file, format=f'audio/{file_ext}')
|
433 |
+
elif file_ext in ACCEPTED_FILE_TYPES['video']:
|
434 |
+
st.video(uploaded_file)
|
435 |
+
else:
|
436 |
+
st.info(f"Fichier: {uploaded_file.name}")
|
437 |
+
file_details = {"Nom": uploaded_file.name, "Type": uploaded_file.type, "Taille": f"{uploaded_file.size / 1024:.1f} KB"}
|
438 |
+
st.json(file_details)
|
439 |
+
|
440 |
+
# Fonction principale
|
441 |
+
def main():
|
442 |
+
# Initialiser l'état de session
|
443 |
+
initialize_session_state()
|
444 |
+
|
445 |
+
# Vérifier si l'API est initialisée
|
446 |
+
if not st.session_state.get("api_initialized", False):
|
447 |
+
st.error("Erreur d'initialisation de l'API. Veuillez vérifier votre clé API dans le fichier .env")
|
448 |
+
st.stop()
|
449 |
+
|
450 |
+
# Afficher l'interface
|
451 |
+
render_ui()
|
452 |
|
453 |
+
# Point d'entrée principal
|
454 |
+
if __name__ == "__main__":
|
455 |
+
main()
|