Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,13 +1,17 @@
|
|
1 |
import streamlit as st
|
2 |
import google.generativeai as genai
|
3 |
import os
|
|
|
|
|
|
|
|
|
4 |
from dotenv import load_dotenv
|
5 |
|
6 |
load_dotenv()
|
|
|
7 |
# Configure the API key
|
8 |
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
|
9 |
|
10 |
-
|
11 |
safety_settings = [
|
12 |
{"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},
|
13 |
{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
|
@@ -15,25 +19,17 @@ safety_settings = [
|
|
15 |
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
|
16 |
]
|
17 |
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
model = genai.GenerativeModel('gemini-1.5-flash',safety_settings=safety_settings,
|
22 |
-
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")
|
23 |
-
|
24 |
-
|
25 |
|
26 |
# Function to get response from the model
|
27 |
# Gemini uses 'model' for assistant; Streamlit uses 'assistant'
|
28 |
-
|
29 |
-
|
30 |
def role_to_streamlit(role):
|
31 |
if role == "model":
|
32 |
return "assistant"
|
33 |
else:
|
34 |
return role
|
35 |
|
36 |
-
|
37 |
# Add a Gemini Chat history object to Streamlit session state
|
38 |
if "chat" not in st.session_state:
|
39 |
st.session_state.chat = model.start_chat(history=[])
|
@@ -41,19 +37,111 @@ if "chat" not in st.session_state:
|
|
41 |
# Display Form Title
|
42 |
st.title("Mariam AI!")
|
43 |
|
|
|
|
|
|
|
44 |
# Display chat messages from history above current input box
|
45 |
for message in st.session_state.chat.history:
|
46 |
with st.chat_message(role_to_streamlit(message.role)):
|
47 |
st.markdown(message.parts[0].text)
|
48 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
49 |
# Accept user's next message, add to context, resubmit context to Gemini
|
50 |
if prompt := st.chat_input("Hey?"):
|
51 |
# Display user's last message
|
52 |
st.chat_message("user").markdown(prompt)
|
53 |
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import streamlit as st
|
2 |
import google.generativeai as genai
|
3 |
import os
|
4 |
+
import tempfile
|
5 |
+
import PIL.Image
|
6 |
+
import time
|
7 |
+
import ssl
|
8 |
from dotenv import load_dotenv
|
9 |
|
10 |
load_dotenv()
|
11 |
+
|
12 |
# Configure the API key
|
13 |
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
|
14 |
|
|
|
15 |
safety_settings = [
|
16 |
{"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},
|
17 |
{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
|
|
|
19 |
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
|
20 |
]
|
21 |
|
22 |
+
model = genai.GenerativeModel('gemini-1.5-flash-002', safety_settings=safety_settings,
|
23 |
+
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")
|
|
|
|
|
|
|
|
|
|
|
24 |
|
25 |
# Function to get response from the model
|
26 |
# Gemini uses 'model' for assistant; Streamlit uses 'assistant'
|
|
|
|
|
27 |
def role_to_streamlit(role):
|
28 |
if role == "model":
|
29 |
return "assistant"
|
30 |
else:
|
31 |
return role
|
32 |
|
|
|
33 |
# Add a Gemini Chat history object to Streamlit session state
|
34 |
if "chat" not in st.session_state:
|
35 |
st.session_state.chat = model.start_chat(history=[])
|
|
|
37 |
# Display Form Title
|
38 |
st.title("Mariam AI!")
|
39 |
|
40 |
+
# File uploader
|
41 |
+
uploaded_files = st.file_uploader("Choose a file", accept_multiple_files=True)
|
42 |
+
|
43 |
# Display chat messages from history above current input box
|
44 |
for message in st.session_state.chat.history:
|
45 |
with st.chat_message(role_to_streamlit(message.role)):
|
46 |
st.markdown(message.parts[0].text)
|
47 |
|
48 |
+
def upload_and_process_file(file_path):
|
49 |
+
"""Upload et traite un fichier avec l'API Gemini avec gestion des erreurs améliorée"""
|
50 |
+
max_retries = 3
|
51 |
+
retry_delay = 2 # secondes
|
52 |
+
|
53 |
+
for attempt in range(max_retries):
|
54 |
+
try:
|
55 |
+
print(f"Tentative d'upload {attempt + 1}/{max_retries} pour {file_path}")
|
56 |
+
|
57 |
+
# Vérification du fichier
|
58 |
+
if not os.path.exists(file_path):
|
59 |
+
raise FileNotFoundError(f"Le fichier {file_path} n'existe pas")
|
60 |
+
|
61 |
+
file_size = os.path.getsize(file_path)
|
62 |
+
if file_size == 0:
|
63 |
+
raise ValueError(f"Le fichier {file_path} est vide")
|
64 |
+
|
65 |
+
# Upload du fichier
|
66 |
+
uploaded_file = genai.upload_file(path=file_path)
|
67 |
+
print(f"Upload réussi: {uploaded_file.uri}")
|
68 |
+
|
69 |
+
# Attente du traitement
|
70 |
+
timeout = 300 # 5 minutes
|
71 |
+
start_time = time.time()
|
72 |
+
|
73 |
+
while uploaded_file.state.name == "PROCESSING":
|
74 |
+
if time.time() - start_time > timeout:
|
75 |
+
raise TimeoutError("Timeout pendant le traitement du fichier")
|
76 |
+
|
77 |
+
print(
|
78 |
+
f"En attente du traitement... Temps écoulé: {int(time.time() - start_time)}s")
|
79 |
+
time.sleep(10)
|
80 |
+
uploaded_file = genai.get_file(uploaded_file.name)
|
81 |
+
|
82 |
+
if uploaded_file.state.name == "FAILED":
|
83 |
+
raise ValueError(
|
84 |
+
f"Échec du traitement: {uploaded_file.state.name}")
|
85 |
+
|
86 |
+
print(f"Traitement terminé avec succès: {uploaded_file.uri}")
|
87 |
+
return uploaded_file
|
88 |
+
|
89 |
+
except ssl.SSLError as e:
|
90 |
+
print(
|
91 |
+
f"Erreur SSL lors de l'upload (tentative {attempt + 1}): {e}")
|
92 |
+
if attempt < max_retries - 1:
|
93 |
+
time.sleep(retry_delay * (attempt + 1))
|
94 |
+
else:
|
95 |
+
raise
|
96 |
+
|
97 |
+
except Exception as e:
|
98 |
+
print(
|
99 |
+
f"Erreur lors de l'upload (tentative {attempt + 1}): {e}")
|
100 |
+
if attempt < max_retries - 1:
|
101 |
+
time.sleep(retry_delay * (attempt + 1))
|
102 |
+
else:
|
103 |
+
raise
|
104 |
+
|
105 |
# Accept user's next message, add to context, resubmit context to Gemini
|
106 |
if prompt := st.chat_input("Hey?"):
|
107 |
# Display user's last message
|
108 |
st.chat_message("user").markdown(prompt)
|
109 |
|
110 |
+
content = [prompt]
|
111 |
+
temp_files = []
|
112 |
+
|
113 |
+
try:
|
114 |
+
# Process uploaded files
|
115 |
+
for uploaded_file in uploaded_files:
|
116 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(uploaded_file.name)[1]) as temp_file:
|
117 |
+
temp_file.write(uploaded_file.getvalue())
|
118 |
+
temp_files.append(temp_file.name)
|
119 |
+
if uploaded_file.name.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
|
120 |
+
content.append(PIL.Image.open(temp_file.name))
|
121 |
+
else:
|
122 |
+
processed_file = upload_and_process_file(temp_file.name)
|
123 |
+
content.append(processed_file)
|
124 |
+
|
125 |
+
# Send user entry to Gemini and read the response
|
126 |
+
response = model.generate_content(content)
|
127 |
+
|
128 |
+
# Add the response to the chat history
|
129 |
+
st.session_state.chat.history.extend([
|
130 |
+
genai.types.Part(text=prompt, role="user"),
|
131 |
+
genai.types.Part(text=response.text, role="model"),
|
132 |
+
])
|
133 |
+
# Display last
|
134 |
+
with st.chat_message("assistant"):
|
135 |
+
st.markdown(response.text)
|
136 |
+
|
137 |
+
except Exception as e:
|
138 |
+
st.error(f"An error occurred: {e}")
|
139 |
+
|
140 |
+
finally:
|
141 |
+
# Cleanup temporary files
|
142 |
+
for temp_file in temp_files:
|
143 |
+
try:
|
144 |
+
os.unlink(temp_file)
|
145 |
+
except Exception as e:
|
146 |
+
print(
|
147 |
+
f"Error deleting temporary file {temp_file}: {e}")
|