Spaces:
Running
Running
File size: 12,828 Bytes
5ff9cba |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 |
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("""<div class='fixed-header'/>""", unsafe_allow_html=True)
if col5.button("Importer"):
import_conversation()
# Custom CSS for the sticky header
st.markdown(
"""
<style>
div[data-testid="stVerticalBlock"] div:has(div.fixed-header) {
position: sticky;
top: 2.875rem;
background-color: white;
z-index: 999;
}
.fixed-header {
border-bottom: 0px solid black;
}
</style>
""",
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))
|