|
import streamlit as st |
|
import google.generativeai as genai |
|
import os |
|
from dotenv import load_dotenv |
|
from PIL import Image |
|
import tempfile |
|
import time |
|
import ssl |
|
|
|
|
|
load_dotenv() |
|
|
|
|
|
genai.configure(api_key=os.getenv("GOOGLE_API_KEY")) |
|
|
|
|
|
safety_settings = [ |
|
{"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"}, |
|
{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"}, |
|
{"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"}, |
|
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"}, |
|
] |
|
|
|
def role_to_streamlit(role): |
|
return "assistant" if role == "model" else role |
|
|
|
def upload_and_process_file(file_path): |
|
max_retries = 3 |
|
retry_delay = 2 |
|
|
|
for attempt in range(max_retries): |
|
try: |
|
if not os.path.exists(file_path): |
|
raise FileNotFoundError(f"Le fichier {file_path} n'existe pas") |
|
|
|
file_size = os.path.getsize(file_path) |
|
if file_size == 0: |
|
raise ValueError(f"Le fichier {file_path} est vide") |
|
|
|
uploaded_file = genai.upload_file(path=file_path) |
|
|
|
timeout = 300 |
|
start_time = time.time() |
|
|
|
while uploaded_file.state.name == "PROCESSING": |
|
if time.time() - start_time > timeout: |
|
raise TimeoutError("Timeout pendant le traitement du fichier") |
|
time.sleep(10) |
|
uploaded_file = genai.get_file(uploaded_file.name) |
|
|
|
if uploaded_file.state.name == "FAILED": |
|
raise ValueError(f"Échec du traitement: {uploaded_file.state.name}") |
|
|
|
return uploaded_file |
|
|
|
except Exception as e: |
|
if attempt < max_retries - 1: |
|
time.sleep(retry_delay * (attempt + 1)) |
|
else: |
|
raise |
|
|
|
def allowed_file(filename): |
|
ALLOWED_EXTENSIONS = {'txt','mp4','mp3','pdf', 'png', 'jpg', 'jpeg', 'gif'} |
|
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS |
|
|
|
|
|
model = genai.GenerativeModel('gemini-1.5-flash', |
|
safety_settings=safety_settings, |
|
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") |
|
|
|
|
|
st.set_page_config(page_title="Mariam - Assistant IA", page_icon="🤖") |
|
st.title("Mariam AI - Chat Intelligent") |
|
|
|
|
|
st.markdown(""" |
|
<style> |
|
.stFileUploader { |
|
margin-bottom: 10px; |
|
} |
|
.upload-container { |
|
display: flex; |
|
align-items: center; |
|
gap: 10px; |
|
} |
|
.fixed-input { |
|
position: fixed; |
|
bottom: 0; |
|
left: 0; |
|
right: 0; |
|
z-index: 1000; |
|
background-color: white; |
|
padding: 10px; |
|
box-shadow: 0 -2px 5px rgba(0,0,0,0.1); |
|
} |
|
.main-content { |
|
margin-bottom: 80px; /* Pour laisser de l'espace pour l'input fixe */ |
|
} |
|
</style> |
|
""", unsafe_allow_html=True) |
|
|
|
|
|
if "chat" not in st.session_state: |
|
st.session_state.chat = model.start_chat(history=[]) |
|
|
|
|
|
main_container = st.container() |
|
main_container.markdown('<div class="main-content">', unsafe_allow_html=True) |
|
|
|
|
|
upload_container = st.container() |
|
with upload_container: |
|
uploaded_files = st.file_uploader("📁", |
|
type=["txt","mp4","mp3","pdf", "jpg", "jpeg", "png", "gif"], |
|
accept_multiple_files=True) |
|
|
|
|
|
for message in st.session_state.chat.history: |
|
with main_container.chat_message(role_to_streamlit(message.role)): |
|
st.markdown(message.parts[0].text) |
|
if len(message.parts) > 1: |
|
for part in message.parts[1:]: |
|
if hasattr(part, 'image'): |
|
st.image(part.image) |
|
|
|
|
|
main_container.markdown('</div>', unsafe_allow_html=True) |
|
|
|
|
|
st.markdown('<div class="fixed-input">', unsafe_allow_html=True) |
|
prompt = st.chat_input("Que puis-je faire pour vous ?") |
|
st.markdown('</div>', unsafe_allow_html=True) |
|
|
|
if prompt: |
|
content = [prompt] |
|
temp_files = [] |
|
|
|
try: |
|
|
|
if uploaded_files: |
|
for file in uploaded_files: |
|
if allowed_file(file.name): |
|
|
|
if file.type.startswith('image/'): |
|
image = Image.open(file) |
|
content.append(image) |
|
st.chat_message("user").image(image) |
|
else: |
|
|
|
with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(file.name)[1]) as temp_file: |
|
temp_file.write(file.getvalue()) |
|
temp_files.append(temp_file.name) |
|
uploaded_file = upload_and_process_file(temp_file.name) |
|
content.append(uploaded_file) |
|
|
|
|
|
st.chat_message("user").markdown(prompt) |
|
|
|
|
|
response = st.session_state.chat.send_message(content) |
|
with st.chat_message("assistant"): |
|
st.markdown(response.text) |
|
|
|
except Exception as e: |
|
st.error(f"Une erreur est survenue : {str(e)}") |
|
|
|
finally: |
|
|
|
for temp_file in temp_files: |
|
try: |
|
os.unlink(temp_file) |
|
except Exception as e: |
|
print(f"Erreur lors de la suppression du fichier temporaire {temp_file}: {e}") |