import streamlit as st from langchain_core.messages import AIMessage, HumanMessage from langchain_community.chat_models import ChatOpenAI from dotenv import load_dotenv from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_mistralai.chat_models import ChatMistralAI from download_chart import construct_plot from prompt import get_prompts_list from st_copy_to_clipboard import st_copy_to_clipboard from high_chart import test_chart from export_doc import export_conversation,convert_pp_to_csv,get_conversation import random import pandas as pd def parse_conversation(file_content): conversation = [] current_speaker = None current_message = [] for line in file_content.decode('utf-8').splitlines(): line = line.strip() if line.startswith('AI:'): if current_message: conversation.append((current_speaker, "\n".join(current_message))) current_message = [] current_speaker = 'AI' current_message.append(line[3:].strip()) elif line.startswith('Moi:'): if current_message: conversation.append((current_speaker, "\n".join(current_message))) current_message = [] current_speaker = 'Moi' current_message.append(line[4:].strip()) else: current_message.append(line) if current_message: conversation.append((current_speaker, "\n".join(current_message))) return conversation def convert_to_message_objects(conversation): message_objects = [] for speaker, message in conversation: if speaker == 'AI': message_objects.append(AIMessage(content=message)) elif speaker == 'Moi': message_objects.append(HumanMessage(content=message)) message_objects.pop(0) return message_objects load_dotenv() def generate_random_color(): # Generate random RGB values r = random.randint(0, 255) g = random.randint(0, 255) b = random.randint(0, 255) # Convert RGB to hexadecimal color_hex = '#{:02x}{:02x}{:02x}'.format(r, g, b) return color_hex def format_pp_add_viz(pp): y = 50 x = 50 for i in range(len(st.session_state['pp_grouped'])): if st.session_state['pp_grouped'][i]['y'] == y and st.session_state['pp_grouped'][i]['x'] == x: y += 5 if y > 95: y = 50 x += 5 if st.session_state['pp_grouped'][i]['name'] == pp: return None else: st.session_state['pp_grouped'].append({'name':pp, 'x':x,'y':y, 'color':generate_random_color()}) def format_context(partie_prenante_grouped,marque): context = "la marque est " + marque + ".\n" context += f"Le nombre de parties prenantes est {len(partie_prenante_grouped)} et ils sont les suivantes:\n" for i,partie_prenante in enumerate(partie_prenante_grouped): context += f"{i}.{partie_prenante['name']} est une partie prenante de {marque} et a un pouvoir de {partie_prenante['y']}% et une influence de {partie_prenante['x']}%.\n" segmentation = ''' Les parties prenantes sont segmentées en 4 catégories: - Rendre satisfait: le pouvoir est entre 50 et 100 et l'influence est entre 0 et 50 - Gérer étroitement: le pouvoir est entre 50 et 100 et l'influence est entre 50 et 100 - Suivre de près: le pouvoir est entre 0 et 50 et l'influence est entre 0 et 50 - Tenir informé: le pouvoir est entre 0 et 50 et l'influence est entre 50 et 100 ''' context += segmentation return context def get_response(user_query, chat_history, context,llm=None): template = """ Fournir des réponses, en francais, précises et contextuelles en agissant comme un expert en affaires, en utilisant le contexte des parties prenantes et leur pouvoir en pourcentage et leur influence en pourcentage pour expliquer les implications pour la marque. Le modèle doit connecter les informations du contexte et de l'historique de la conversation pour donner une réponse éclairée à la dernière question posée. Contexte: {context} Chat history: {chat_history} User question: {user_question} """ prompt = ChatPromptTemplate.from_template(template) #llm = ChatOpenAI(model="gpt-4o") if not llm: llm = ChatOpenAI(model="gpt-4o") elif llm == "GPT-4o": llm = ChatOpenAI(model="gpt-4o") elif llm == "Mistral (FR)": llm = ChatMistralAI(model_name="mistral-large-latest") chain = prompt | llm | StrOutputParser() return chain.stream({ "context": context, "chat_history": chat_history, "user_question": user_query, }) def display_chart(): if "pp_grouped" not in st.session_state or st.session_state['pp_grouped'] is None or len(st.session_state['pp_grouped']) == 0: st.warning("Aucune partie prenante n'a été définie") return None plot = construct_plot() st.plotly_chart(plot) @st.experimental_dialog("Choisissez un prompt",width="large") def show_prompts(): if get_prompts_list() == 1: st.rerun() if st.button("Fermer"): st.rerun() @st.experimental_dialog("Choisissez votre IA",width="small") def choose_model(index): model = st.radio("Choisissez votre IA", ["(US) ChatGpt 4.o","(FR) Mistral AI - Large (open source)"],index=index) if model == "(FR) Mistral AI - Large (open source)": st.session_state.model = "Mistral (FR)" if model == "(US) ChatGpt 4.o": st.session_state.model = "GPT-4o" if st.button("Valider"): st.rerun() @st.experimental_dialog("Ma cartographie",width="large") def disp_carto_in_chat(): if test_chart() == "saved": st.rerun() @st.experimental_dialog("Télécharger",width="small") def dowmload_history(): brand_name = st.session_state['Nom de la marque'] format = st.radio("Choisissez le document à télécharger",[f"Rapport des parties prenantes (PDF)",f"Tableau des parties prenantes (CSV)",f"Historique de conversation (Fichier Texte)"],index=None) if format == f"Rapport des parties prenantes (PDF)": with st.spinner("Generation en cours..."): summary = get_response("Donne moi un RESUME de la Conversation", st.session_state.chat_history,format_context(st.session_state['pp_grouped'],st.session_state['Nom de la marque']),st.session_state.model) summary = ''.join(summary) pdf = export_conversation(AIMessage(content=summary).content) if pdf: st.download_button("Télécharger le PDF", data=pdf, file_name=f"Cartographie {brand_name}.pdf", mime="application/pdf") if format == f"Tableau des parties prenantes (CSV)": csv = convert_pp_to_csv(st.session_state['pp_grouped']) if csv: st.download_button("Télécharger le CSV", data=csv, file_name=f"parties_prenantes -{brand_name}-.csv", mime="application/vnd.ms-excel") if format == f"Historique de conversation (Fichier Texte)": conv = get_conversation() if not conv: st.error("Une erreur s'est produite lors de la récupération de l'historique de conversation") return None else: conversation = "\n".join([f"{entry['speaker']}:\n{entry['text']}\n" for entry in conv]) st.download_button("Télécharger l'historique de conversation", data=conversation, file_name=f"conversation {brand_name}.txt", mime="text/plain") if st.button("Fermer"): st.rerun() def add_existing_pps(pp,pouvoir,influence): for i in range(len(st.session_state['pp_grouped'])): if st.session_state['pp_grouped'][i]['name'] == pp: st.session_state['pp_grouped'][i]['x'] = influence st.session_state['pp_grouped'][i]['y'] = pouvoir return None st.session_state['pp_grouped'].append({'name':pp, 'x':influence,'y':pouvoir, 'color':generate_random_color()}) def load_csv(file): df = pd.read_csv(file) for index, row in df.iterrows(): add_existing_pps(row['parties prenantes'],row['pouvoir'],row['influence']) @st.experimental_dialog("Importer",width="small") def import_conversation(): uploaded_file = st.file_uploader("Télécharger le fichier CSV", type="csv") if uploaded_file is not None: file_name = uploaded_file.name try: load_csv(file_name) brand_name_from_csv = file_name.split("-")[1] st.session_state["Nom de la marque"] = brand_name_from_csv st.rerun() except Exception as e: st.error("Erreur lors de la lecture du fichier") def extract_pp_from_query(query): return " ".join(query.split(" ")[1:]) def display_chat(): # app config st.title("Chatbot") models_name = { "Mistral (FR)":1, "GPT-4o":0 } # session state if "chat_history" not in st.session_state: st.session_state.chat_history = [ AIMessage(content="Salut, voici votre cartographie des parties prenantes. Que puis-je faire pour vous?"), ] if "model" not in st.session_state: st.session_state.model = "GPT-4o" #sticky bar at the top header = st.container() col1,col2,col3, col4,col5,col6 = header.columns([2,3,2,3,2,1]) if col1.button("Prompts"): show_prompts() if col2.button(f"Modèle: {st.session_state.model}"): index = models_name[st.session_state.model] choose_model(index) if col3.button("Ma Carto"): disp_carto_in_chat() if col4.button("Télécharger"): dowmload_history() header.write("""
""", unsafe_allow_html=True) if col5.button("Importer"): import_conversation() # Custom CSS for the sticky header st.markdown( """ """, unsafe_allow_html=True ) # conversation for message in st.session_state.chat_history: if isinstance(message, AIMessage): with st.chat_message("AI"): st.write(message.content) if "cartographie" in message.content: display_chart() elif isinstance(message, HumanMessage): with st.chat_message("Moi"): st.write(message.content) #check if the last message is from the user , that means execute button has been clicked in the prompts last_message = st.session_state.chat_history[-1] if isinstance(last_message, HumanMessage): with st.chat_message("AI"): if last_message.content.startswith("/rajoute"): response = "Partie prenante ajoutée" st.write(response) st.session_state.chat_history.append(AIMessage(content=response)) else: response = st.write_stream(get_response(last_message.content, st.session_state.chat_history,format_context(st.session_state['pp_grouped'],st.session_state['Nom de la marque']),st.session_state.model)) st.session_state.chat_history.append(AIMessage(content=response)) if "pp_grouped" not in st.session_state or st.session_state['pp_grouped'] is None or len(st.session_state['pp_grouped']) == 0: st.session_state['pp_grouped'] = [] if "Nom de la marque" not in st.session_state: st.session_state["Nom de la marque"] = "" # user input user_query = st.chat_input("Par ici...") if user_query is not None and user_query != "": st.session_state.chat_history.append(HumanMessage(content=user_query)) with st.chat_message("Moi"): st.markdown(user_query) with st.chat_message("AI"): st.markdown(f"**{st.session_state.model}**") if user_query.startswith("/rajoute"): partie_prenante = extract_pp_from_query(user_query) format_pp_add_viz(partie_prenante) disp_carto_in_chat() else: st.warning(user_query) response = st.write_stream(get_response(user_query, st.session_state.chat_history,format_context(st.session_state['pp_grouped'],st.session_state['Nom de la marque']),st.session_state.model)) if "cartographie" in response: display_chart() st.session_state.chat_history.append(AIMessage(content=response))