Spaces:
Build error
Build error
Update app.py
Browse files3 unmodified lines456789101112 unmodified lines2425262728293011 unmodified lines4243444546474820 unmodified lines697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601613 unmodified linesfrom dotenv import load_dotenvimport http.clientimport jsonimport asynciofrom typing import AsyncGeneratorload_dotenv()12 unmodified linessafety_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")def perform_web_search(query):conn = http.client.HTTPSConnection("google.serper.dev")payload = json.dumps({"q": query})headers = {11 unmodified linesfinally:conn.close()def format_search_results(data):if not data:return "Aucun résultat trouvé"20 unmodified linesreturn resultdef role_to_streamlit(role):if role == "model":return "assistant"else:return role# Initialize session stateif "chat" not in st.session_state:st.session_state.chat = model.start_chat(history=[])if "web_search" not in st.session_state:st.session_state.web_search = False# Display Form Titlest.title("Mariam AI!")# Settings sectionwith st.sidebar:st.title("Paramètres")st.session_state.web_search = st.toggle("Activer la recherche web", value=st.session_state.web_search)# File upload sectionuploaded_file = st.file_uploader("Télécharger un fichier (image/document)", type=['jpg', 'mp4', 'mp3', 'jpeg', 'png', 'pdf', 'txt'])# Display chat messagesfor message in st.session_state.chat.history:with st.chat_message(role_to_streamlit(message.role)):st.markdown(message.parts[0].text)def process_uploaded_file(file):if file is not None:with open(os.path.join("temp", file.name), "wb") as f:f.write(file.getbuffer())try:gemini_file = genai.upload_file(os.path.join("temp", file.name))return gemini_fileexcept Exception as e:st.error(f"Erreur lors du téléchargement du fichier : {e}")return Noneasync def stream_response(prompt: str, uploaded_gemini_file=None) -> AsyncGenerator[str, None]:try:if uploaded_gemini_file:response = await st.session_state.chat.send_message_async([uploaded_gemini_file, "\n\n", prompt], stream=True)else:response = await st.session_state.chat.send_message_async(prompt, stream=True)async for chunk in response:if chunk.text:yield chunk.textexcept Exception as e:st.error(f"Erreur lors du streaming : {e}")yield "Désolé, une erreur s'est produite lors de la génération de la réponse."# Chat input and processingif prompt := st.chat_input("Hey?"):uploaded_gemini_file = Noneif uploaded_file:uploaded_gemini_file = process_uploaded_file(uploaded_file)# Display user messagest.chat_message("user").markdown(prompt)try:# Perform web search if enabledweb_results = Noneif st.session_state.web_search:with st.spinner("Recherche web en cours..."):web_results = perform_web_search(prompt)if web_results:formatted_results = format_search_results(web_results)prompt = f"""Question: {prompt}\n\nRésultats de recherche web:\n{formatted_results}\n\nPourrais-tu analyser ces informations et me donner une réponse complète?"""# Create a placeholder for the streaming responsewith st.chat_message("assistant"):response_placeholder = st.empty()full_response = ""# Stream the responsefor response_chunk in asyncio.run(stream_response(prompt, uploaded_gemini_file)):full_response += response_chunkresponse_placeholder.markdown(full_response + "▌")# Update the placeholder with the complete responseresponse_placeholder.markdown(full_response)except Exception as e:st.error(f"Erreur lors de l'envoi du message : {e}")# Create temp directoryos.makedirs("temp", exist_ok=True)3 unmodified lines4567891012 unmodified lines2324252627282911 unmodified lines4142434445464720 unmodified lines68697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721733 unmodified linesfrom dotenv import load_dotenvimport http.clientimport jsonfrom typing import Iteratorload_dotenv()12 unmodified linessafety_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")def perform_web_search(query: str) -> dict:conn = http.client.HTTPSConnection("google.serper.dev")payload = json.dumps({"q": query})headers = {11 unmodified linesfinally:conn.close()def format_search_results(data: dict) -> str:if not data:return "Aucun résultat trouvé"20 unmodified linesreturn resultdef stream_response(prompt: str, uploaded_file=None) -> Iterator[str]:"""Stream the response from Gemini"""try:if uploaded_file:response = model.generate_content([uploaded_file, "\n\n", prompt], stream=True)else:response = model.generate_content(prompt, stream=True)for chunk in response:if chunk.text:yield chunk.textexcept Exception as e:yield f"Erreur lors de la génération de la réponse : {str(e)}"def role_to_streamlit(role: str) -> str:return "assistant" if role == "model" else roledef process_uploaded_file(file) -> object:if file is not None:file_path = os.path.join("temp", file.name)with open(file_path, "wb") as f:f.write(file.getbuffer())try:return genai.upload_file(file_path)except Exception as e:st.error(f"Erreur lors du téléchargement du fichier : {e}")return Nonefinally:# Clean up the temporary fileif os.path.exists(file_path):os.remove(file_path)def main():# Initialize session stateif "chat" not in st.session_state:st.session_state.chat = model.start_chat(history=[])if "web_search" not in st.session_state:st.session_state.web_search = Falsest.title("Mariam AI!")# Settings sidebarwith st.sidebar:st.title("Paramètres")st.session_state.web_search = st.toggle("Activer la recherche web",value=st.session_state.web_search)# File uploaduploaded_file = st.file_uploader("Télécharger un fichier (image/document)",type=['jpg', 'mp4', 'mp3', 'jpeg', 'png', 'pdf', 'txt'])# Display chat historyfor message in st.session_state.chat.history:with st.chat_message(role_to_streamlit(message.role)):st.markdown(message.parts[0].text)# Chat inputif prompt := st.chat_input("Hey?"):# Display user messagest.chat_message("user").markdown(prompt)# Handle file uploaduploaded_gemini_file = Noneif uploaded_file:uploaded_gemini_file = process_uploaded_file(uploaded_file)try:# Perform web search if enabledif st.session_state.web_search:with st.spinner("Recherche web en cours..."):web_results = perform_web_search(prompt)if web_results:formatted_results = format_search_results(web_results)prompt = f"""Question: {prompt}\n\nRésultats de recherche web:\n{formatted_results}\n\nPourrais-tu analyser ces informations et me donner une réponse complète?"""# Display assistant message with streamingwith st.chat_message("assistant"):message_placeholder = st.empty()full_response = ""# Stream the responsefor chunk in stream_response(prompt, uploaded_gemini_file):full_response += chunk# Update the message placeholder with the accumulated responsemessage_placeholder.markdown(full_response + "▌")# Remove the cursor and update with the final responsemessage_placeholder.markdown(full_response)# Add the interaction to chat historyst.session_state.chat.history.extend([{"role": "user", "parts": [prompt]},{"role": "model", "parts": [full_response]}])except Exception as e:st.error(f"Erreur lors de l'envoi du message : {e}")if __name__ == "__main__":# Create temp directoryos.makedirs("temp", exist_ok=True)main()
app.py+95-83