Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -3,6 +3,9 @@ import google.generativeai as genai
|
|
3 |
import os
|
4 |
from dotenv import load_dotenv
|
5 |
from PIL import Image
|
|
|
|
|
|
|
6 |
|
7 |
# Charger les variables d'environnement
|
8 |
load_dotenv()
|
@@ -18,56 +21,121 @@ safety_settings = [
|
|
18 |
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
|
19 |
]
|
20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
# Initialiser le modèle
|
22 |
model = genai.GenerativeModel('gemini-1.5-flash',
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
# Fonction pour convertir le rôle
|
27 |
-
def role_to_streamlit(role):
|
28 |
-
return "assistant" if role == "model" else role
|
29 |
|
30 |
# Configuration de la page Streamlit
|
31 |
st.set_page_config(page_title="Mariam - Assistant IA", page_icon="🤖")
|
32 |
st.title("Mariam AI - Chat Intelligent")
|
33 |
|
34 |
-
# Initialiser l'historique de chat
|
35 |
if "chat" not in st.session_state:
|
36 |
st.session_state.chat = model.start_chat(history=[])
|
37 |
|
38 |
-
#
|
39 |
-
|
40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
|
42 |
# Afficher l'historique des messages
|
43 |
for message in st.session_state.chat.history:
|
44 |
with st.chat_message(role_to_streamlit(message.role)):
|
45 |
st.markdown(message.parts[0].text)
|
46 |
-
|
47 |
-
|
48 |
-
|
|
|
49 |
|
50 |
# Zone de saisie du chat
|
51 |
if prompt := st.chat_input("Que puis-je faire pour vous ?"):
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
st.chat_message("user").markdown(prompt)
|
|
|
|
|
|
|
|
|
|
|
70 |
|
71 |
-
|
72 |
-
|
73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
import os
|
4 |
from dotenv import load_dotenv
|
5 |
from PIL import Image
|
6 |
+
import tempfile
|
7 |
+
import time
|
8 |
+
import ssl
|
9 |
|
10 |
# Charger les variables d'environnement
|
11 |
load_dotenv()
|
|
|
21 |
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
|
22 |
]
|
23 |
|
24 |
+
def upload_and_process_file(file_path):
|
25 |
+
max_retries = 3
|
26 |
+
retry_delay = 2
|
27 |
+
|
28 |
+
for attempt in range(max_retries):
|
29 |
+
try:
|
30 |
+
if not os.path.exists(file_path):
|
31 |
+
raise FileNotFoundError(f"Le fichier {file_path} n'existe pas")
|
32 |
+
|
33 |
+
file_size = os.path.getsize(file_path)
|
34 |
+
if file_size == 0:
|
35 |
+
raise ValueError(f"Le fichier {file_path} est vide")
|
36 |
+
|
37 |
+
uploaded_file = genai.upload_file(path=file_path)
|
38 |
+
|
39 |
+
timeout = 300
|
40 |
+
start_time = time.time()
|
41 |
+
|
42 |
+
while uploaded_file.state.name == "PROCESSING":
|
43 |
+
if time.time() - start_time > timeout:
|
44 |
+
raise TimeoutError("Timeout pendant le traitement du fichier")
|
45 |
+
time.sleep(10)
|
46 |
+
uploaded_file = genai.get_file(uploaded_file.name)
|
47 |
+
|
48 |
+
if uploaded_file.state.name == "FAILED":
|
49 |
+
raise ValueError(f"Échec du traitement: {uploaded_file.state.name}")
|
50 |
+
|
51 |
+
return uploaded_file
|
52 |
+
|
53 |
+
except Exception as e:
|
54 |
+
if attempt < max_retries - 1:
|
55 |
+
time.sleep(retry_delay * (attempt + 1))
|
56 |
+
else:
|
57 |
+
raise
|
58 |
+
|
59 |
+
def allowed_file(filename):
|
60 |
+
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
|
61 |
+
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
|
62 |
+
|
63 |
# Initialiser le modèle
|
64 |
model = genai.GenerativeModel('gemini-1.5-flash',
|
65 |
+
safety_settings=safety_settings,
|
66 |
+
system_instruction="Tu es un assistant intelligent. ton but est d'assister au mieux que tu peux. tu as été créé par Aenir et tu t'appelles Mariam")
|
|
|
|
|
|
|
|
|
67 |
|
68 |
# Configuration de la page Streamlit
|
69 |
st.set_page_config(page_title="Mariam - Assistant IA", page_icon="🤖")
|
70 |
st.title("Mariam AI - Chat Intelligent")
|
71 |
|
72 |
+
# Initialiser l'historique de chat
|
73 |
if "chat" not in st.session_state:
|
74 |
st.session_state.chat = model.start_chat(history=[])
|
75 |
|
76 |
+
# Créer trois colonnes pour les boutons d'upload
|
77 |
+
col1, col2, col3 = st.columns([1, 1, 8])
|
78 |
+
|
79 |
+
# Bouton pour les images
|
80 |
+
with col1:
|
81 |
+
uploaded_images = st.file_uploader("", type=["jpg", "jpeg", "png", "gif"],
|
82 |
+
accept_multiple_files=True, key="images")
|
83 |
+
st.markdown("📸")
|
84 |
+
|
85 |
+
# Bouton pour les autres fichiers
|
86 |
+
with col2:
|
87 |
+
uploaded_files = st.file_uploader("", type=["txt", "pdf"],
|
88 |
+
accept_multiple_files=True, key="files")
|
89 |
+
st.markdown("📁")
|
90 |
|
91 |
# Afficher l'historique des messages
|
92 |
for message in st.session_state.chat.history:
|
93 |
with st.chat_message(role_to_streamlit(message.role)):
|
94 |
st.markdown(message.parts[0].text)
|
95 |
+
if len(message.parts) > 1:
|
96 |
+
for part in message.parts[1:]:
|
97 |
+
if hasattr(part, 'image'):
|
98 |
+
st.image(part.image)
|
99 |
|
100 |
# Zone de saisie du chat
|
101 |
if prompt := st.chat_input("Que puis-je faire pour vous ?"):
|
102 |
+
content = [prompt]
|
103 |
+
temp_files = []
|
104 |
+
|
105 |
+
try:
|
106 |
+
# Traitement des images
|
107 |
+
if uploaded_images:
|
108 |
+
for img_file in uploaded_images:
|
109 |
+
if allowed_file(img_file.name):
|
110 |
+
image = Image.open(img_file)
|
111 |
+
content.append(image)
|
112 |
+
st.chat_message("user").image(image)
|
113 |
+
|
114 |
+
# Traitement des autres fichiers
|
115 |
+
if uploaded_files:
|
116 |
+
for file in uploaded_files:
|
117 |
+
if allowed_file(file.name):
|
118 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(file.name)[1]) as temp_file:
|
119 |
+
temp_file.write(file.getvalue())
|
120 |
+
temp_files.append(temp_file.name)
|
121 |
+
uploaded_file = upload_and_process_file(temp_file.name)
|
122 |
+
content.append(uploaded_file)
|
123 |
+
|
124 |
+
# Afficher le message utilisateur
|
125 |
st.chat_message("user").markdown(prompt)
|
126 |
+
|
127 |
+
# Envoyer le message et afficher la réponse
|
128 |
+
response = st.session_state.chat.send_message(content)
|
129 |
+
with st.chat_message("assistant"):
|
130 |
+
st.markdown(response.text)
|
131 |
|
132 |
+
except Exception as e:
|
133 |
+
st.error(f"Une erreur est survenue : {str(e)}")
|
134 |
+
|
135 |
+
finally:
|
136 |
+
# Nettoyage des fichiers temporaires
|
137 |
+
for temp_file in temp_files:
|
138 |
+
try:
|
139 |
+
os.unlink(temp_file)
|
140 |
+
except Exception as e:
|
141 |
+
print(f"Erreur lors de la suppression du fichier temporaire {temp_file}: {e}")
|