Demosthene-OR commited on
Commit
aa7ee3a
·
1 Parent(s): d76336d
app-old.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st # type: ignore
2
+ import os.path
3
+ from collections import OrderedDict
4
+ from streamlit_option_menu import option_menu # type: ignore
5
+ # Define TITLE, TEAM_MEMBERS and PROMOTION values, in config.py.
6
+ import config
7
+ from tabs.custom_vectorizer import custom_tokenizer, custom_preprocessor
8
+ import os
9
+ from translate_app import tr
10
+
11
+ # Initialize a session state variable that tracks the sidebar state (either 'expanded' or 'collapsed').
12
+ if 'sidebar_state' not in st.session_state:
13
+ st.session_state.sidebar_state = 'expanded'
14
+ else:
15
+ st.session_state.sidebar_state = 'auto'
16
+
17
+ st.set_page_config (
18
+ page_title=config.TITLE,
19
+ page_icon= "assets/faviconV2.png",
20
+ layout="wide",
21
+ initial_sidebar_state=st.session_state.sidebar_state
22
+ )
23
+
24
+ # Si l'application tourne localement, session_state.Cloud == 0
25
+ # Si elle tourne sur le Cloud de Hugging Face, ==1
26
+ st.session_state.Cloud = 1
27
+ # En fonction de la valeur de varible précédente, le data path est différent
28
+ if st.session_state.Cloud == 0:
29
+ st.session_state.DataPath = "../data"
30
+ st.session_state.ImagePath = "../images"
31
+ st.session_state.reCalcule = False
32
+ else:
33
+ st.session_state.DataPath = "data"
34
+ st.session_state.ImagePath = "images"
35
+ st.session_state.reCalcule = False
36
+
37
+ # Define the root folders depending on local/cloud run
38
+ # thisfile = os.path.abspath(__file__)
39
+ # if ('/' in thisfile):
40
+ # os.chdir(os.path.dirname(thisfile))
41
+
42
+ # Nécessaire pour la version windows 11
43
+ if st.session_state.Cloud == 0:
44
+ os.environ['PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION'] = 'python'
45
+
46
+ # Tabs in the ./tabs folder, imported here.
47
+ from tabs import intro, sentence_similarity_tab, speech2text_tab, chatbot_tab
48
+
49
+
50
+ with open("style.css", "r") as f:
51
+ style = f.read()
52
+
53
+ st.markdown(f"<style>{style}</style>", unsafe_allow_html=True)
54
+
55
+
56
+ # Add tab in this ordered dict by
57
+ # passing the name in the sidebar as key and the imported tab
58
+ # as value as follow :
59
+ TABS = OrderedDict(
60
+ [
61
+ (tr(intro.sidebar_name), intro),
62
+ (tr(chatbot_tab.sidebar_name), chatbot_tab),
63
+ (tr(sentence_similarity_tab.sidebar_name), sentence_similarity_tab),
64
+ # (tr(speech2text_tab.sidebar_name), speech2text_tab),
65
+ ]
66
+ )
67
+
68
+ # Utilisation du module deep_translator
69
+ lang_tgt = ['fr', 'en','de','es', 'it', 'nl']
70
+ label_lang = ['Français','English','Deutsch','Español','Italiano','Nederlands']
71
+ label_lang_en = ['French', 'English', 'German', 'Spanish', 'Italian', 'Dutch']
72
+
73
+ # @st.cache_data
74
+ def find_lang_label(lang_sel):
75
+ global lang_tgt, label_lang
76
+ return label_lang[lang_tgt.index(lang_sel)]
77
+
78
+ # @st.cache_data
79
+ def find_lang_label_en(lang_sel):
80
+ global lang_tgt, label_lang_en
81
+ return label_lang_en[lang_tgt.index(lang_sel)]
82
+
83
+ def run():
84
+
85
+ st.sidebar.image(
86
+ "assets/value_props_logo.png",
87
+ width=270,
88
+ )
89
+ with st.sidebar.expander(":red[**"+tr("Développez moi")+"**]"):
90
+ # st.markdown(f"<style>{style}</style>", unsafe_allow_html=True)
91
+ st.markdown(tr("""
92
+ :red[Cette application vous permet de tester les futures fonctionnalités de la plateforme Value Props, et plus particulièrement le «Sales Coaching».
93
+ Amusez vous bien !]
94
+ """))
95
+ with st.sidebar:
96
+
97
+ tab_name = option_menu(None, list(TABS.keys()),
98
+ # icons=['house', 'bi-binoculars', 'bi bi-graph-up', 'bi-chat-right-text','bi-book', 'bi-body-text'], menu_icon="cast", default_index=0,
99
+ icons=['house', 'binoculars', 'graph-up', 'search','book', 'chat-right-text','controller'], menu_icon="cast", default_index=0,
100
+ styles={"container": {"padding": "0!important","background-color": "#10b8dd", "border-radius": "0!important"},
101
+ "nav-link": {"font-size": "1rem", "text-align": "left", "margin":"0em", "padding": "0em",
102
+ "padding-left": "0.2em", "--hover-color": "#eee", "font-weight": "400",
103
+ "font-family": "Source Sans Pro, sans-serif"}
104
+ })
105
+ # tab_name = st.sidebar.radio("", list(TABS.keys()), 0)
106
+ st.sidebar.markdown("---")
107
+ st.sidebar.markdown(f"## {tr(config.PROMOTION)}")
108
+
109
+ st.sidebar.markdown("### "+tr("Auteur:"))
110
+ for member in config.TEAM_MEMBERS:
111
+ st.sidebar.markdown(member.sidebar_markdown(), unsafe_allow_html=True)
112
+
113
+ with st.sidebar:
114
+ st.write("")
115
+ llm_choice = st.selectbox(tr("Modèle :"),["Mistral large","OpenAI 3.5","OpenAI 4o"], label_visibility="visible")
116
+ if (llm_choice == "OpenAI 3.5") : st.session_state.model = "gpt-3.5-turbo"
117
+ elif (llm_choice == "OpenAI 4o") : st.session_state.model = "gpt-4o"
118
+ else: st.session_state.model = "mistral-large-latest"
119
+ if (llm_choice in ["OpenAI 3.5","OpenAI 4o"]) and ('OPENAI_API_KEY' not in st.session_state):
120
+ # Set OpenAI API key
121
+ st.sidebar.subheader("OpenAI API Key")
122
+ openai_api_key = st.sidebar.text_input(tr("Saisissez votre Clé API OpenAI:"), type='password')
123
+ if openai_api_key:
124
+ os.environ['OPENAI_API_KEY'] = openai_api_key
125
+ st.session_state['OPENAI_API_KEY'] = openai_api_key
126
+ st.sidebar.success("OpenAI API Key set successfully.")
127
+
128
+ with st.sidebar:
129
+ l = st.selectbox("langue:",lang_tgt, format_func = find_lang_label, key="Language", label_visibility="hidden")
130
+ st.session_state.language_label = find_lang_label_en(l)
131
+
132
+ tab = TABS[tab_name]
133
+ tab.run()
134
+
135
+ if __name__ == "__main__":
136
+ run()
app.py CHANGED
@@ -1,7 +1,8 @@
1
- import streamlit as st # type: ignore
 
2
  import os.path
3
  from collections import OrderedDict
4
- from streamlit_option_menu import option_menu # type: ignore
5
  # Define TITLE, TEAM_MEMBERS and PROMOTION values, in config.py.
6
  import config
7
  from tabs.custom_vectorizer import custom_tokenizer, custom_preprocessor
@@ -14,37 +15,36 @@ if 'sidebar_state' not in st.session_state:
14
  else:
15
  st.session_state.sidebar_state = 'auto'
16
 
17
- st.set_page_config (
18
  page_title=config.TITLE,
19
- page_icon= "assets/faviconV2.png",
20
  layout="wide",
21
  initial_sidebar_state=st.session_state.sidebar_state
22
  )
23
 
24
- # Si l'application tourne localement, session_state.Cloud == 0
25
  # Si elle tourne sur le Cloud de Hugging Face, ==1
26
  st.session_state.Cloud = 1
27
  # En fonction de la valeur de varible précédente, le data path est différent
28
- if st.session_state.Cloud == 0:
29
  st.session_state.DataPath = "../data"
30
  st.session_state.ImagePath = "../images"
31
  st.session_state.reCalcule = False
32
- else:
33
  st.session_state.DataPath = "data"
34
  st.session_state.ImagePath = "images"
35
  st.session_state.reCalcule = False
36
 
37
  # Define the root folders depending on local/cloud run
38
  # thisfile = os.path.abspath(__file__)
39
- # if ('/' in thisfile):
40
  # os.chdir(os.path.dirname(thisfile))
41
 
42
  # Nécessaire pour la version windows 11
43
- if st.session_state.Cloud == 0:
44
  os.environ['PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION'] = 'python'
45
 
46
  # Tabs in the ./tabs folder, imported here.
47
- from tabs import intro, sentence_similarity_tab, speech2text_tab, chatbot_tab
48
 
49
 
50
  with open("style.css", "r") as f:
@@ -66,20 +66,26 @@ TABS = OrderedDict(
66
  )
67
 
68
  # Utilisation du module deep_translator
69
- lang_tgt = ['fr', 'en','de','es', 'it', 'nl']
70
- label_lang = ['Français','English','Deutsch','Español','Italiano','Nederlands']
 
71
  label_lang_en = ['French', 'English', 'German', 'Spanish', 'Italian', 'Dutch']
72
 
73
- # @st.cache_data
 
 
74
  def find_lang_label(lang_sel):
75
  global lang_tgt, label_lang
76
  return label_lang[lang_tgt.index(lang_sel)]
77
 
78
- # @st.cache_data
 
 
79
  def find_lang_label_en(lang_sel):
80
  global lang_tgt, label_lang_en
81
  return label_lang_en[lang_tgt.index(lang_sel)]
82
 
 
83
  def run():
84
 
85
  st.sidebar.image(
@@ -93,15 +99,15 @@ def run():
93
  Amusez vous bien !]
94
  """))
95
  with st.sidebar:
96
-
97
  tab_name = option_menu(None, list(TABS.keys()),
98
  # icons=['house', 'bi-binoculars', 'bi bi-graph-up', 'bi-chat-right-text','bi-book', 'bi-body-text'], menu_icon="cast", default_index=0,
99
- icons=['house', 'binoculars', 'graph-up', 'search','book', 'chat-right-text','controller'], menu_icon="cast", default_index=0,
100
- styles={"container": {"padding": "0!important","background-color": "#10b8dd", "border-radius": "0!important"},
101
- "nav-link": {"font-size": "1rem", "text-align": "left", "margin":"0em", "padding": "0em",
102
  "padding-left": "0.2em", "--hover-color": "#eee", "font-weight": "400",
103
  "font-family": "Source Sans Pro, sans-serif"}
104
- })
105
  # tab_name = st.sidebar.radio("", list(TABS.keys()), 0)
106
  st.sidebar.markdown("---")
107
  st.sidebar.markdown(f"## {tr(config.PROMOTION)}")
@@ -109,28 +115,67 @@ def run():
109
  st.sidebar.markdown("### "+tr("Auteur:"))
110
  for member in config.TEAM_MEMBERS:
111
  st.sidebar.markdown(member.sidebar_markdown(), unsafe_allow_html=True)
112
-
113
  with st.sidebar:
114
  st.write("")
115
- llm_choice = st.selectbox(tr("Modèle :"),["Mistral large","OpenAI 3.5","OpenAI 4o"], label_visibility="visible")
116
- if (llm_choice == "OpenAI 3.5") : st.session_state.model = "gpt-3.5-turbo"
117
- elif (llm_choice == "OpenAI 4o") : st.session_state.model = "gpt-4o"
118
- else: st.session_state.model = "mistral-large-latest"
119
- if (llm_choice in ["OpenAI 3.5","OpenAI 4o"]) and ('OPENAI_API_KEY' not in st.session_state):
120
- # Set OpenAI API key
121
- st.sidebar.subheader("OpenAI API Key")
122
- openai_api_key = st.sidebar.text_input(tr("Saisissez votre Clé API OpenAI:"), type='password')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  if openai_api_key:
124
- os.environ['OPENAI_API_KEY'] = openai_api_key
125
- st.session_state['OPENAI_API_KEY'] = openai_api_key
126
- st.sidebar.success("OpenAI API Key set successfully.")
127
-
 
 
 
 
 
 
128
  with st.sidebar:
129
- l = st.selectbox("langue:",lang_tgt, format_func = find_lang_label, key="Language", label_visibility="hidden")
 
130
  st.session_state.language_label = find_lang_label_en(l)
131
 
132
  tab = TABS[tab_name]
133
  tab.run()
134
 
 
135
  if __name__ == "__main__":
136
  run()
 
1
+ from tabs import intro, sentence_similarity_tab, speech2text_tab, chatbot_tab
2
+ import streamlit as st # type: ignore
3
  import os.path
4
  from collections import OrderedDict
5
+ from streamlit_option_menu import option_menu # type: ignore
6
  # Define TITLE, TEAM_MEMBERS and PROMOTION values, in config.py.
7
  import config
8
  from tabs.custom_vectorizer import custom_tokenizer, custom_preprocessor
 
15
  else:
16
  st.session_state.sidebar_state = 'auto'
17
 
18
+ st.set_page_config(
19
  page_title=config.TITLE,
20
+ page_icon="assets/faviconV2.png",
21
  layout="wide",
22
  initial_sidebar_state=st.session_state.sidebar_state
23
  )
24
 
25
+ # Si l'application tourne localement, session_state.Cloud == 0
26
  # Si elle tourne sur le Cloud de Hugging Face, ==1
27
  st.session_state.Cloud = 1
28
  # En fonction de la valeur de varible précédente, le data path est différent
29
+ if st.session_state.Cloud == 0:
30
  st.session_state.DataPath = "../data"
31
  st.session_state.ImagePath = "../images"
32
  st.session_state.reCalcule = False
33
+ else:
34
  st.session_state.DataPath = "data"
35
  st.session_state.ImagePath = "images"
36
  st.session_state.reCalcule = False
37
 
38
  # Define the root folders depending on local/cloud run
39
  # thisfile = os.path.abspath(__file__)
40
+ # if ('/' in thisfile):
41
  # os.chdir(os.path.dirname(thisfile))
42
 
43
  # Nécessaire pour la version windows 11
44
+ if st.session_state.Cloud == 0:
45
  os.environ['PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION'] = 'python'
46
 
47
  # Tabs in the ./tabs folder, imported here.
 
48
 
49
 
50
  with open("style.css", "r") as f:
 
66
  )
67
 
68
  # Utilisation du module deep_translator
69
+ lang_tgt = ['fr', 'en', 'de', 'es', 'it', 'nl']
70
+ label_lang = ['Français', 'English', 'Deutsch',
71
+ 'Español', 'Italiano', 'Nederlands']
72
  label_lang_en = ['French', 'English', 'German', 'Spanish', 'Italian', 'Dutch']
73
 
74
+ # @st.cache_data
75
+
76
+
77
  def find_lang_label(lang_sel):
78
  global lang_tgt, label_lang
79
  return label_lang[lang_tgt.index(lang_sel)]
80
 
81
+ # @st.cache_data
82
+
83
+
84
  def find_lang_label_en(lang_sel):
85
  global lang_tgt, label_lang_en
86
  return label_lang_en[lang_tgt.index(lang_sel)]
87
 
88
+
89
  def run():
90
 
91
  st.sidebar.image(
 
99
  Amusez vous bien !]
100
  """))
101
  with st.sidebar:
102
+
103
  tab_name = option_menu(None, list(TABS.keys()),
104
  # icons=['house', 'bi-binoculars', 'bi bi-graph-up', 'bi-chat-right-text','bi-book', 'bi-body-text'], menu_icon="cast", default_index=0,
105
+ icons=['house', 'binoculars', 'graph-up', 'search', 'book', 'chat-right-text', 'controller'], menu_icon="cast", default_index=0,
106
+ styles={"container": {"padding": "0!important", "background-color": "#10b8dd", "border-radius": "0!important"},
107
+ "nav-link": {"font-size": "1rem", "text-align": "left", "margin": "0em", "padding": "0em",
108
  "padding-left": "0.2em", "--hover-color": "#eee", "font-weight": "400",
109
  "font-family": "Source Sans Pro, sans-serif"}
110
+ })
111
  # tab_name = st.sidebar.radio("", list(TABS.keys()), 0)
112
  st.sidebar.markdown("---")
113
  st.sidebar.markdown(f"## {tr(config.PROMOTION)}")
 
115
  st.sidebar.markdown("### "+tr("Auteur:"))
116
  for member in config.TEAM_MEMBERS:
117
  st.sidebar.markdown(member.sidebar_markdown(), unsafe_allow_html=True)
118
+
119
  with st.sidebar:
120
  st.write("")
121
+ llm_choice = st.selectbox(
122
+ tr("Modèle :"),
123
+ ["Gemini 3.8 Flash", "OpenAI GPT-6 Luna", "Anthropic Claude Haiku 5.5"],
124
+ label_visibility="visible"
125
+ )
126
+
127
+ if llm_choice == "OpenAI GPT-6 Luna":
128
+ st.session_state.model = "gpt-6-luna"
129
+ elif llm_choice == "Anthropic Claude Haiku 5.5":
130
+ st.session_state.model = "claude-haiku-5-5"
131
+ else:
132
+ st.session_state.model = "gemini-3.8-flash"
133
+
134
+ # Clé Gemini gratuite disponible par défaut pour la session
135
+ if "GOOGLE_API_KEY" not in st.session_state and os.getenv("GOOGLE_API_KEY"):
136
+ st.session_state["GOOGLE_API_KEY"] = os.getenv("GOOGLE_API_KEY")
137
+
138
+ # Déverrouillage de toutes les clés via MASTER_PASSWORD
139
+ with st.expander(tr("Accès administrateur")):
140
+ master_pwd = st.text_input(
141
+ tr("Mot de passe maître :"), type="password")
142
+ expected_pwd = os.getenv("MASTER_PASSWORD", "")
143
+ if master_pwd:
144
+ if expected_pwd and hmac.compare_digest(master_pwd, expected_pwd):
145
+ st.session_state["master_unlocked"] = True
146
+ st.session_state["OPENAI_API_KEY"] = os.getenv(
147
+ "OPENAI_API_KEY", "")
148
+ st.session_state["ANTHROPIC_API_KEY"] = os.getenv(
149
+ "ANTHROPIC_API_KEY", "")
150
+ st.session_state["GOOGLE_API_KEY"] = os.getenv(
151
+ "GOOGLE_API_KEY", "")
152
+ st.success(tr("Toutes les clés API ont été chargées."))
153
+ else:
154
+ st.error(tr("Mot de passe incorrect."))
155
+
156
+ # Saisie manuelle pour les utilisateurs sans mot de passe maître
157
+ if llm_choice == "OpenAI GPT-6 Luna" and not st.session_state.get("OPENAI_API_KEY"):
158
+ openai_api_key = st.text_input(
159
+ tr("Saisissez votre Clé API OpenAI :"), type="password")
160
  if openai_api_key:
161
+ st.session_state["OPENAI_API_KEY"] = openai_api_key
162
+ st.success("OpenAI API Key set successfully.")
163
+
164
+ elif llm_choice == "Anthropic Claude Haiku 5.5" and not st.session_state.get("ANTHROPIC_API_KEY"):
165
+ anthropic_api_key = st.text_input(
166
+ tr("Saisissez votre Clé API Anthropic :"), type="password")
167
+ if anthropic_api_key:
168
+ st.session_state["ANTHROPIC_API_KEY"] = anthropic_api_key
169
+ st.success("Anthropic API Key set successfully.")
170
+
171
  with st.sidebar:
172
+ l = st.selectbox("langue:", lang_tgt, format_func=find_lang_label,
173
+ key="Language", label_visibility="hidden")
174
  st.session_state.language_label = find_lang_label_en(l)
175
 
176
  tab = TABS[tab_name]
177
  tab.run()
178
 
179
+
180
  if __name__ == "__main__":
181
  run()
requirements.txt CHANGED
@@ -30,6 +30,7 @@ sentence_transformers==3.1.1
30
  langchain==0.3.2
31
  langchain_mistralai==0.2.0
32
  langchain_openai==0.2.3
 
33
  langgraph==0.2.34
34
  langsmith==0.1.131
35
  typing_extensions==4.12.2
 
30
  langchain==0.3.2
31
  langchain_mistralai==0.2.0
32
  langchain_openai==0.2.3
33
+ langchain-google-genai
34
  langgraph==0.2.34
35
  langsmith==0.1.131
36
  typing_extensions==4.12.2
tabs/__pycache__/chatbot_tab.cpython-310.pyc CHANGED
Binary files a/tabs/__pycache__/chatbot_tab.cpython-310.pyc and b/tabs/__pycache__/chatbot_tab.cpython-310.pyc differ
 
tabs/__pycache__/intro.cpython-310.pyc CHANGED
Binary files a/tabs/__pycache__/intro.cpython-310.pyc and b/tabs/__pycache__/intro.cpython-310.pyc differ
 
tabs/__pycache__/sentence_similarity_tab.cpython-310.pyc CHANGED
Binary files a/tabs/__pycache__/sentence_similarity_tab.cpython-310.pyc and b/tabs/__pycache__/sentence_similarity_tab.cpython-310.pyc differ
 
tabs/chatbot_tab.py CHANGED
@@ -1,4 +1,4 @@
1
- import streamlit as st # type: ignore
2
  import os
3
  from datetime import datetime
4
  from extra_streamlit_components import tab_bar, TabBarItemData
@@ -14,6 +14,8 @@ from translate_app import tr
14
  import getpass
15
  from langchain_mistralai import ChatMistralAI
16
  from langchain_openai import ChatOpenAI
 
 
17
  from langgraph.checkpoint.memory import MemorySaver
18
  from langgraph.graph import START, END, MessagesState, StateGraph
19
  from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
@@ -32,14 +34,16 @@ sidebar_name = "Coaching de vente"
32
  dataPath = st.session_state.DataPath
33
 
34
  os.environ["LANGCHAIN_TRACING_V2"] = "true"
35
- os.environ["LANGCHAIN_ENDPOINT"]="https://api.smith.langchain.com"
36
- os.environ["LANGCHAIN_HUB_API_URL"]="https://api.smith.langchain.com"
37
- os.environ["LANGCHAIN_PROJECT"] = "Sales Coaching Chatbot"
38
  if st.session_state.Cloud != 0:
39
  load_dotenv()
40
  os.getenv("LANGCHAIN_API_KEY")
41
  os.getenv("MISTRAL_API_KEY")
42
  os.getenv("OPENAI_API_KEY")
 
 
43
 
44
 
45
  prompt = ChatPromptTemplate.from_messages(
@@ -52,15 +56,18 @@ prompt = ChatPromptTemplate.from_messages(
52
  ]
53
  )
54
 
 
55
  class State(TypedDict):
56
  messages: Annotated[Sequence[BaseMessage], add_messages]
57
  language: str
58
 
 
59
  def call_model(state: State):
60
  chain = prompt | model
61
  response = chain.invoke(state)
62
  return {"messages": [response]}
63
 
 
64
  # Define a new graph
65
  workflow = StateGraph(state_schema=State)
66
 
@@ -77,17 +84,17 @@ selected_index1 = 0
77
  selected_index2 = 0
78
  selected_index3 = 0
79
  selected_indices4 = []
80
- selected_indices5 = []
81
  selected_indices6 = []
82
- selected_indices7 = []
83
  selected_options4 = []
84
  selected_options5 = []
85
  selected_options6 = []
86
  selected_options7 = []
87
  selected_index8 = 0
88
- context=""
89
- human_message1=""
90
- thread_id =""
91
  virulence = 1
92
  question = []
93
  thread_id = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
@@ -99,11 +106,12 @@ messages = [
99
  HumanMessage(content=""),
100
  AIMessage(content=""),
101
  HumanMessage(content="")
102
- ]
103
  if 'model' in st.session_state:
104
  model = st.session_state.model
105
  used_model = st.session_state.model
106
 
 
107
  def init_run():
108
  global initialized, to_init, thread_id, config, app, context, human_message1, model, used_model, messages
109
 
@@ -112,135 +120,157 @@ def init_run():
112
  thread_id = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
113
  config = {"configurable": {"thread_id": thread_id}}
114
  app.invoke(
115
- {"messages": messages, "language": language},
116
- config,
117
- )
118
  st.session_state.thread_id = thread_id
119
  st.session_state.config = config
120
  st.session_state.messages_init = messages
121
  st.session_state.context = context
122
  st.session_state.human_message1 = human_message1
123
  st.session_state.messages = []
124
- if 'model' in st.session_state and (st.session_state.model[:3]=="gpt") and ("OPENAI_API_KEY" in st.session_state):
125
  model = ChatOpenAI(model=st.session_state.model,
126
- temperature=0.8, # Adjust creativity level
127
- max_tokens=150 # Define max output token limit
128
- )
129
- else:
130
  model = ChatMistralAI(model=st.session_state.model)
131
  if 'model' in st.session_state:
132
- used_model=st.session_state.model
133
- return
 
134
 
135
  def init():
136
- global config,thread_id, context,human_message1,ai_message1,language, app, model_speech,prompt,model,question, to_init, initialized
137
- global selected_index1, selected_index2, selected_index3, selected_indices4,selected_indices5,selected_indices6,selected_indices7
138
- global selected_options4,selected_options5,selected_options6,selected_options7, selected_index8, virulence, used_model, messages
139
-
140
- model_speech = whisper.load_model("base")
141
-
142
  if (st.button(label=tr("Nouvelle conversation"), type="primary")):
143
  selected_index1 = 0
144
  selected_index2 = 0
145
  selected_index3 = 0
146
  selected_indices4 = []
147
- selected_indices5 = []
148
  selected_indices6 = []
149
- selected_indices7 = []
150
  selected_options4 = []
151
  selected_options5 = []
152
  selected_options6 = []
153
  selected_options7 = []
154
  selected_index8 = 0
155
  context = ""
156
- human_message1=""
157
- thread_id =""
158
  virulence = 1
159
- if 'model' in st.session_state and (st.session_state.model[:3]=="gpt") and ("OPENAI_API_KEY" in st.session_state):
160
  model = ChatOpenAI(model=st.session_state.model,
161
- temperature=0.8, # Adjust creativity level
162
- max_tokens=150 # Define max output token limit
163
- )
164
- else:
165
  model = ChatMistralAI(model=st.session_state.model)
166
  if 'model' in st.session_state:
167
- used_model=st.session_state.model
168
-
169
  label, question, options = format_param()
170
  translated_options1 = [tr(o) for o in options[0]]
171
- selected_option1 = st.selectbox(tr(label[0]),translated_options1, index = selected_index1) # index=int(var1_init))
 
172
  selected_index1 = translated_options1.index(selected_option1)
173
-
174
  translated_options2 = [tr(o) for o in options[1]]
175
- selected_option2 = st.selectbox(tr(label[1]),translated_options2, index = selected_index2) # index=int(var2_init))
 
176
  selected_index2 = translated_options2.index(selected_option2)
177
-
178
  translated_options3 = [tr(o) for o in options[2]]
179
- selected_option3 = st.selectbox(tr(label[2]),translated_options3, index=selected_index3) #index=int(var3_init))
 
180
  selected_index3 = translated_options3.index(selected_option3)
181
 
182
  context = tr(f"""Tu es un {options[0][selected_index1]}, d'une {options[1][selected_index2]}.
183
  Cette entreprise propose des {options[2][selected_index3]}.
184
  """)
185
- context = st.text_area(label=tr("Résumé du Contexte (modifiable):"), value=context)
 
186
  st.markdown('''
187
  ------------------------------------------------------------------------------------
188
  ''')
189
-
190
  translated_options4 = [tr(o) for o in options[3]]
191
- selected_options4 = st.multiselect(tr(label[3]),translated_options4, default=[translated_options4[o] for o in selected_indices4])
192
- selected_indices4 = [translated_options4.index(o) for o in selected_options4]
 
 
193
  problematique = selected_options4
194
  if problematique != []:
195
  markdown_text4 = """\n"""+tr(question[3])
196
- markdown_text4 = markdown_text4+"".join(f"\n- {o}" for o in problematique)
 
197
  st.write(markdown_text4)
198
- else: markdown_text4 = ""
199
-
 
200
  translated_options5 = [tr(o) for o in options[4]]
201
- selected_options5 = st.multiselect(tr(label[4]),translated_options5, default=[translated_options5[o] for o in selected_indices5])
202
- selected_indices5 = [translated_options5.index(o) for o in selected_options5]
 
 
203
  processus = selected_options5
204
  if processus != []:
205
  markdown_text5 = """\n\n"""+tr(question[4])
206
  markdown_text5 = markdown_text5+"".join(f"\n- {o}" for o in processus)
207
  st.write(markdown_text5)
208
- else: markdown_text5 = ""
209
-
 
210
  translated_options6 = [tr(o) for o in options[5]]
211
- selected_options6 = st.multiselect(tr(label[5]),translated_options6, default=[translated_options6[o] for o in selected_indices6])
212
- selected_indices6 = [translated_options6.index(o) for o in selected_options6]
 
 
213
  objectifs = selected_options6
214
  if objectifs != []:
215
  markdown_text6 = """\n\n"""+tr(question[5])
216
  markdown_text6 = markdown_text6+"".join(f"\n- {o}" for o in objectifs)
217
  st.write(markdown_text6)
218
- else: markdown_text6 = ""
219
-
 
220
  translated_options7 = [tr(o) for o in options[6]]
221
- selected_options7 = st.multiselect(tr(label[6]),translated_options7, default=[translated_options7[o] for o in selected_indices7])
222
- selected_indices7 = [translated_options7.index(o) for o in selected_options7]
 
 
223
  solutions_utilisees = selected_options7
224
  if solutions_utilisees != []:
225
  markdown_text7 = """\n\n"""+tr(question[6])
226
- markdown_text7 = markdown_text7+"".join(f"\n- {o}" for o in solutions_utilisees)
 
227
  st.write(markdown_text7)
228
  st.write("")
229
- else: markdown_text7 = ""
230
-
 
231
  translated_options8 = [tr(o) for o in options[7]]
232
- selected_option8 = st.selectbox(tr(label[7]),translated_options8, index = selected_index8)
 
233
  selected_index8 = translated_options8.index(selected_option8)
234
- markdown_text8 = """\n\n"""+tr(question[7])+"""\n"""+(f"""{translated_options8[selected_index8]}""")
235
-
236
-
 
237
  col1, col2, col3 = st.columns(3)
238
  with col1:
239
- virulence = st.slider(tr("Virulence (choisissez une valeur entre 1 et 5)"), min_value=1, max_value=5, step=1,value=virulence)
 
240
  markdown_text9 = """\n\n"""+tr(f"""Le prospect est très occupé et n'aime pas être dérangé inutilement.
241
  Tu vas utiliser une échelle de 1 à 5 d'agressivité du prospect à l'égard du vendeur.
242
  Pour cette simulation utilise le niveau {virulence}.""")
243
-
244
  human_message1 = tr("""Je souhaite que nous ayons une conversation verbale entre moi le vendeur, et toi que je prospecte.
245
  Mon entreprise propose une solution logicielle pour gérer la proposition de valeur d’entreprise B2B qui commercialise des solutions technologiques.
246
  """)+markdown_text4+markdown_text5+markdown_text6+markdown_text7+markdown_text8+markdown_text9+tr(f"""
@@ -255,53 +285,56 @@ Attention: Si le vendeur aborde des points qui ne concerne pas cette simulation,
255
  Es tu prêt à commencer ?
256
  """)
257
 
258
- human_message1 = st.text_area(label=tr("Consigne"), value=tr(human_message1),height=300)
 
259
  st.markdown('''
260
  ------------------------------------------------------------------------------------
261
  ''')
262
-
263
- ai_message1 = tr(f"J'ai bien compris, je suis un {options[0][selected_index1]} prospecté et je réponds seulement à tes questions. Je réponds à une seule question à la fois, sans commencer mes réponses par 'En tant que {options[0][selected_index1]}'.")
264
 
 
 
265
 
266
-
267
  # ai_message1 = st.text_area(label=tr("Réponse du prospect"), value=ai_message1)
268
  messages = [
269
  SystemMessage(content=context),
270
  HumanMessage(content=human_message1),
271
  # AIMessage(content=ai_message1),
272
  # HumanMessage(content=tr("Commençons la conversation. Attention, je suis le vendeur et je parle le premier. Tu es le propect."))
273
- ]
274
 
275
  st.write("")
276
  if ("context" in st.session_state) and ("human_message1" in st.session_state):
277
- if (st.session_state.context != context) or (st.session_state.human_message1 != human_message1 ) or (used_model != st.session_state.model) or (thread_id==""):
278
  to_init = True
279
  else:
280
  to_init = False
281
  else:
282
  to_init = True
283
-
284
  if to_init:
285
- if st.button(label=tr("Validez"), on_click=init_run,type="primary"):
286
- initialized=True
287
- else: initialized = False
288
- st.write("**thread_id:** "+thread_id)
 
289
  return config, thread_id, messages
290
 
291
  # Fonction pour générer et jouer le texte en speech
 
 
292
  def play_audio(custom_sentence, Lang_target, speed=1.0):
293
  # Générer le speech avec gTTS
294
  audio_stream_bytesio_src = io.BytesIO()
295
  tts = gTTS(custom_sentence, lang=Lang_target)
296
-
297
  # Revenir au début du flux audio
298
  audio_stream_bytesio_src.seek(0)
299
  audio_stream_bytesio_src.truncate(0)
300
-
301
  tts.write_to_fp(audio_stream_bytesio_src)
302
 
303
  audio_stream_bytesio_src.seek(0)
304
-
305
  # Charger l'audio dans un tableau numpy
306
  data, samplerate = sf.read(audio_stream_bytesio_src)
307
 
@@ -318,52 +351,52 @@ def play_audio(custom_sentence, Lang_target, speed=1.0):
318
  st.audio(new_audio_stream_bytesio, start_time=0, autoplay=True)
319
 
320
 
321
-
322
  def run():
323
- global thread_id, config, model_speech, language,prompt,model, model_name, question, to_init, initialized, messages
324
-
325
  st.write("")
326
  st.write("")
327
  st.title(tr(title))
328
-
329
  if 'language_label' in st.session_state:
330
- language = st.session_state['language_label']
331
- else: language = "French"
332
-
 
333
  chosen_id = tab_bar(data=[
334
- TabBarItemData(id="tab1", title=tr("Initialisation"), description=tr("d'une nouvelle conversation")),
335
- TabBarItemData(id="tab2", title=tr("Conversation"), description=tr("avec le prospect")),
336
- TabBarItemData(id="tab3", title=tr("Evaluation"), description=tr("de l'acte de vente"))],
 
 
337
  default="tab1")
338
-
339
-
340
  if (chosen_id == "tab1"):
341
- if 'model' in st.session_state and (st.session_state.model[:3]=="gpt") and ("OPENAI_API_KEY" in st.session_state):
342
  model = ChatOpenAI(model=st.session_state.model,
343
- temperature=0.8, # Adjust creativity level
344
- max_tokens=150 # Define max output token limit
345
- )
346
- else:
347
  model = ChatMistralAI(model=st.session_state.model)
348
-
349
 
350
- config,thread_id, messages = init()
351
  query = ""
352
  elif (chosen_id == "tab2"):
353
  try:
354
  if to_init and not initialized:
355
  init_run()
356
  except NameError:
357
- config,thread_id, messages = init()
358
  with st.container():
359
  # Diviser l'écran en deux colonnes
360
  col1, col2 = st.columns(2)
361
  with col1:
362
  st.write("**thread_id:** "+thread_id)
363
  query = ""
364
- audio_bytes = audio_recorder (pause_threshold=2.0, sample_rate=16000, auto_start=False, text=tr("Cliquez pour parler, puis attendre 2sec."), \
365
- recording_color="#e8b62c", neutral_color="#1ec3bc", icon_size="6x",)
366
-
367
  if audio_bytes:
368
  # st.write("**"+tr("Vendeur")+" :**\n")
369
  # Fonction pour générer et jouer le texte en speech
@@ -375,58 +408,60 @@ def run():
375
  audio_stream_bytesio = io.BytesIO(audio_bytes)
376
 
377
  # Read the WAV stream using wavio
378
- wav = wavio.read(audio_stream_bytesio)
379
 
380
  # Extract the audio data from the wavio.Wav object
381
  audio_data = wav.data
382
 
383
  # Convert the audio data to a NumPy array
384
- audio_input = np.array(audio_data, dtype=np.float32)
 
385
  audio_input = np.mean(audio_input, axis=1)/32768
386
-
387
  result = model_speech.transcribe(audio_input)
388
  Lang_detected = result["language"]
389
  query = result["text"]
390
-
391
  else:
392
  # Avec l'aide de la bibliothèque speech_recognition de Google
393
- Lang_detected = st.session_state['Language']
394
  # Transcription google
395
- audio_stream = sr.AudioData(audio_bytes, 32000, 2)
396
  r = sr.Recognizer()
397
- query = r.recognize_google(audio_stream, language = Lang_detected)
398
-
399
- # Transcription
 
400
  # st.write("**"+tr("Vendeur :")+"** "+query)
401
  with st.chat_message("user"):
402
  st.markdown(query)
403
  st.write("")
404
-
405
  if query != "":
406
  input_messages = [HumanMessage(query)]
407
  output = app.invoke(
408
  {"messages": input_messages, "language": language},
409
  config,
410
  )
411
- #with st.chat_message("user"):
412
  # Add user message to chat history
413
- st.session_state.messages.append({"role": "user", "content": query})
 
414
 
415
  # Récupération de la réponse
416
  custom_sentence = output["messages"][-1].content
417
-
418
  # Joue l'audio
419
- play_audio(custom_sentence,Lang_detected , 1)
420
-
421
  # st.write("**"+tr("Prospect :")+"** "+custom_sentence)
422
  with st.chat_message("assistant"):
423
  st.markdown(custom_sentence)
424
-
425
  # Add user message to chat history
426
- st.session_state.messages.append({"role": "assistant", "content": custom_sentence})
427
-
428
 
429
-
430
  except KeyboardInterrupt:
431
  st.write(tr("Arrêt de la reconnaissance vocale."))
432
  except:
@@ -435,9 +470,9 @@ def run():
435
  # Ajouter un espace pour séparer les zones
436
  # st.divider()
437
  with col2:
438
- if ("messages" in st.session_state) :
439
  if (st.session_state.messages != []):
440
- # Display chat messages from history on app rerun
441
  for message in st.session_state.messages:
442
  with st.chat_message(message["role"]):
443
  st.markdown(message["content"])
@@ -445,24 +480,25 @@ def run():
445
  if to_init and not initialized:
446
  init_run()
447
  st.write("**thread_id:** "+thread_id)
448
- for i in range(8,len(question)):
449
  st.write("")
450
 
451
- q = st.text_input(label=".", value=tr(question[i]),label_visibility="collapsed")
452
- if (q !=""):
 
453
  input_messages = [HumanMessage(q)]
454
  output = app.invoke(
455
  {"messages": input_messages, "language": language},
456
  config,
457
- )
458
  # output = app.invoke(
459
  # {"messages": q,"language": language},
460
  # config,
461
- # )
462
- custom_sentence = output["messages"][-1].content
463
  st.write(custom_sentence)
464
  st.write("")
465
  if (used_model[:3] == 'mis'):
466
  time.sleep(2)
467
-
468
- st.divider()
 
1
+ import streamlit as st # type: ignore
2
  import os
3
  from datetime import datetime
4
  from extra_streamlit_components import tab_bar, TabBarItemData
 
14
  import getpass
15
  from langchain_mistralai import ChatMistralAI
16
  from langchain_openai import ChatOpenAI
17
+ from langchain_anthropic import ChatAnthropic
18
+ from langchain_google_genai import ChatGoogleGenerativeAI
19
  from langgraph.checkpoint.memory import MemorySaver
20
  from langgraph.graph import START, END, MessagesState, StateGraph
21
  from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
 
34
  dataPath = st.session_state.DataPath
35
 
36
  os.environ["LANGCHAIN_TRACING_V2"] = "true"
37
+ os.environ["LANGCHAIN_ENDPOINT"] = "https://api.smith.langchain.com"
38
+ os.environ["LANGCHAIN_HUB_API_URL"] = "https://api.smith.langchain.com"
39
+ os.environ["LANGCHAIN_PROJECT"] = "Sales Coaching Chatbot"
40
  if st.session_state.Cloud != 0:
41
  load_dotenv()
42
  os.getenv("LANGCHAIN_API_KEY")
43
  os.getenv("MISTRAL_API_KEY")
44
  os.getenv("OPENAI_API_KEY")
45
+ os.getenv("ANTHROPIC_API_KEY")
46
+ os.getenv("GOOGLE_API_KEY")
47
 
48
 
49
  prompt = ChatPromptTemplate.from_messages(
 
56
  ]
57
  )
58
 
59
+
60
  class State(TypedDict):
61
  messages: Annotated[Sequence[BaseMessage], add_messages]
62
  language: str
63
 
64
+
65
  def call_model(state: State):
66
  chain = prompt | model
67
  response = chain.invoke(state)
68
  return {"messages": [response]}
69
 
70
+
71
  # Define a new graph
72
  workflow = StateGraph(state_schema=State)
73
 
 
84
  selected_index2 = 0
85
  selected_index3 = 0
86
  selected_indices4 = []
87
+ selected_indices5 = []
88
  selected_indices6 = []
89
+ selected_indices7 = []
90
  selected_options4 = []
91
  selected_options5 = []
92
  selected_options6 = []
93
  selected_options7 = []
94
  selected_index8 = 0
95
+ context = ""
96
+ human_message1 = ""
97
+ thread_id = ""
98
  virulence = 1
99
  question = []
100
  thread_id = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
 
106
  HumanMessage(content=""),
107
  AIMessage(content=""),
108
  HumanMessage(content="")
109
+ ]
110
  if 'model' in st.session_state:
111
  model = st.session_state.model
112
  used_model = st.session_state.model
113
 
114
+
115
  def init_run():
116
  global initialized, to_init, thread_id, config, app, context, human_message1, model, used_model, messages
117
 
 
120
  thread_id = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
121
  config = {"configurable": {"thread_id": thread_id}}
122
  app.invoke(
123
+ {"messages": messages, "language": language},
124
+ config,
125
+ )
126
  st.session_state.thread_id = thread_id
127
  st.session_state.config = config
128
  st.session_state.messages_init = messages
129
  st.session_state.context = context
130
  st.session_state.human_message1 = human_message1
131
  st.session_state.messages = []
132
+ if 'model' in st.session_state and (st.session_state.model[:3] == "gpt") and ("OPENAI_API_KEY" in st.session_state):
133
  model = ChatOpenAI(model=st.session_state.model,
134
+ temperature=0.8, # Adjust creativity level
135
+ max_tokens=150 # Define max output token limit
136
+ )
137
+ else:
138
  model = ChatMistralAI(model=st.session_state.model)
139
  if 'model' in st.session_state:
140
+ used_model = st.session_state.model
141
+ return
142
+
143
 
144
  def init():
145
+ global config, thread_id, context, human_message1, ai_message1, language, app, model_speech, prompt, model, question, to_init, initialized
146
+ global selected_index1, selected_index2, selected_index3, selected_indices4, selected_indices5, selected_indices6, selected_indices7
147
+ global selected_options4, selected_options5, selected_options6, selected_options7, selected_index8, virulence, used_model, messages
148
+
149
+ model_speech = whisper.load_model("base")
150
+
151
  if (st.button(label=tr("Nouvelle conversation"), type="primary")):
152
  selected_index1 = 0
153
  selected_index2 = 0
154
  selected_index3 = 0
155
  selected_indices4 = []
156
+ selected_indices5 = []
157
  selected_indices6 = []
158
+ selected_indices7 = []
159
  selected_options4 = []
160
  selected_options5 = []
161
  selected_options6 = []
162
  selected_options7 = []
163
  selected_index8 = 0
164
  context = ""
165
+ human_message1 = ""
166
+ thread_id = ""
167
  virulence = 1
168
+ if 'model' in st.session_state and (st.session_state.model[:3] == "gpt") and ("OPENAI_API_KEY" in st.session_state):
169
  model = ChatOpenAI(model=st.session_state.model,
170
+ temperature=0.8, # Adjust creativity level
171
+ max_tokens=150 # Define max output token limit
172
+ )
173
+ else:
174
  model = ChatMistralAI(model=st.session_state.model)
175
  if 'model' in st.session_state:
176
+ used_model = st.session_state.model
177
+
178
  label, question, options = format_param()
179
  translated_options1 = [tr(o) for o in options[0]]
180
+ selected_option1 = st.selectbox(
181
+ tr(label[0]), translated_options1, index=selected_index1) # index=int(var1_init))
182
  selected_index1 = translated_options1.index(selected_option1)
183
+
184
  translated_options2 = [tr(o) for o in options[1]]
185
+ selected_option2 = st.selectbox(
186
+ tr(label[1]), translated_options2, index=selected_index2) # index=int(var2_init))
187
  selected_index2 = translated_options2.index(selected_option2)
188
+
189
  translated_options3 = [tr(o) for o in options[2]]
190
+ selected_option3 = st.selectbox(
191
+ tr(label[2]), translated_options3, index=selected_index3) # index=int(var3_init))
192
  selected_index3 = translated_options3.index(selected_option3)
193
 
194
  context = tr(f"""Tu es un {options[0][selected_index1]}, d'une {options[1][selected_index2]}.
195
  Cette entreprise propose des {options[2][selected_index3]}.
196
  """)
197
+ context = st.text_area(
198
+ label=tr("Résumé du Contexte (modifiable):"), value=context)
199
  st.markdown('''
200
  ------------------------------------------------------------------------------------
201
  ''')
202
+
203
  translated_options4 = [tr(o) for o in options[3]]
204
+ selected_options4 = st.multiselect(tr(label[3]), translated_options4, default=[
205
+ translated_options4[o] for o in selected_indices4])
206
+ selected_indices4 = [translated_options4.index(
207
+ o) for o in selected_options4]
208
  problematique = selected_options4
209
  if problematique != []:
210
  markdown_text4 = """\n"""+tr(question[3])
211
+ markdown_text4 = markdown_text4 + \
212
+ "".join(f"\n- {o}" for o in problematique)
213
  st.write(markdown_text4)
214
+ else:
215
+ markdown_text4 = ""
216
+
217
  translated_options5 = [tr(o) for o in options[4]]
218
+ selected_options5 = st.multiselect(tr(label[4]), translated_options5, default=[
219
+ translated_options5[o] for o in selected_indices5])
220
+ selected_indices5 = [translated_options5.index(
221
+ o) for o in selected_options5]
222
  processus = selected_options5
223
  if processus != []:
224
  markdown_text5 = """\n\n"""+tr(question[4])
225
  markdown_text5 = markdown_text5+"".join(f"\n- {o}" for o in processus)
226
  st.write(markdown_text5)
227
+ else:
228
+ markdown_text5 = ""
229
+
230
  translated_options6 = [tr(o) for o in options[5]]
231
+ selected_options6 = st.multiselect(tr(label[5]), translated_options6, default=[
232
+ translated_options6[o] for o in selected_indices6])
233
+ selected_indices6 = [translated_options6.index(
234
+ o) for o in selected_options6]
235
  objectifs = selected_options6
236
  if objectifs != []:
237
  markdown_text6 = """\n\n"""+tr(question[5])
238
  markdown_text6 = markdown_text6+"".join(f"\n- {o}" for o in objectifs)
239
  st.write(markdown_text6)
240
+ else:
241
+ markdown_text6 = ""
242
+
243
  translated_options7 = [tr(o) for o in options[6]]
244
+ selected_options7 = st.multiselect(tr(label[6]), translated_options7, default=[
245
+ translated_options7[o] for o in selected_indices7])
246
+ selected_indices7 = [translated_options7.index(
247
+ o) for o in selected_options7]
248
  solutions_utilisees = selected_options7
249
  if solutions_utilisees != []:
250
  markdown_text7 = """\n\n"""+tr(question[6])
251
+ markdown_text7 = markdown_text7 + \
252
+ "".join(f"\n- {o}" for o in solutions_utilisees)
253
  st.write(markdown_text7)
254
  st.write("")
255
+ else:
256
+ markdown_text7 = ""
257
+
258
  translated_options8 = [tr(o) for o in options[7]]
259
+ selected_option8 = st.selectbox(
260
+ tr(label[7]), translated_options8, index=selected_index8)
261
  selected_index8 = translated_options8.index(selected_option8)
262
+ markdown_text8 = """\n\n""" + \
263
+ tr(question[7])+"""\n""" + \
264
+ (f"""{translated_options8[selected_index8]}""")
265
+
266
  col1, col2, col3 = st.columns(3)
267
  with col1:
268
+ virulence = st.slider(tr("Virulence (choisissez une valeur entre 1 et 5)"),
269
+ min_value=1, max_value=5, step=1, value=virulence)
270
  markdown_text9 = """\n\n"""+tr(f"""Le prospect est très occupé et n'aime pas être dérangé inutilement.
271
  Tu vas utiliser une échelle de 1 à 5 d'agressivité du prospect à l'égard du vendeur.
272
  Pour cette simulation utilise le niveau {virulence}.""")
273
+
274
  human_message1 = tr("""Je souhaite que nous ayons une conversation verbale entre moi le vendeur, et toi que je prospecte.
275
  Mon entreprise propose une solution logicielle pour gérer la proposition de valeur d’entreprise B2B qui commercialise des solutions technologiques.
276
  """)+markdown_text4+markdown_text5+markdown_text6+markdown_text7+markdown_text8+markdown_text9+tr(f"""
 
285
  Es tu prêt à commencer ?
286
  """)
287
 
288
+ human_message1 = st.text_area(
289
+ label=tr("Consigne"), value=tr(human_message1), height=300)
290
  st.markdown('''
291
  ------------------------------------------------------------------------------------
292
  ''')
 
 
293
 
294
+ ai_message1 = tr(
295
+ f"J'ai bien compris, je suis un {options[0][selected_index1]} prospecté et je réponds seulement à tes questions. Je réponds à une seule question à la fois, sans commencer mes réponses par 'En tant que {options[0][selected_index1]}'.")
296
 
 
297
  # ai_message1 = st.text_area(label=tr("Réponse du prospect"), value=ai_message1)
298
  messages = [
299
  SystemMessage(content=context),
300
  HumanMessage(content=human_message1),
301
  # AIMessage(content=ai_message1),
302
  # HumanMessage(content=tr("Commençons la conversation. Attention, je suis le vendeur et je parle le premier. Tu es le propect."))
303
+ ]
304
 
305
  st.write("")
306
  if ("context" in st.session_state) and ("human_message1" in st.session_state):
307
+ if (st.session_state.context != context) or (st.session_state.human_message1 != human_message1) or (used_model != st.session_state.model) or (thread_id == ""):
308
  to_init = True
309
  else:
310
  to_init = False
311
  else:
312
  to_init = True
313
+
314
  if to_init:
315
+ if st.button(label=tr("Validez"), on_click=init_run, type="primary"):
316
+ initialized = True
317
+ else:
318
+ initialized = False
319
+ st.write("**thread_id:** "+thread_id)
320
  return config, thread_id, messages
321
 
322
  # Fonction pour générer et jouer le texte en speech
323
+
324
+
325
  def play_audio(custom_sentence, Lang_target, speed=1.0):
326
  # Générer le speech avec gTTS
327
  audio_stream_bytesio_src = io.BytesIO()
328
  tts = gTTS(custom_sentence, lang=Lang_target)
329
+
330
  # Revenir au début du flux audio
331
  audio_stream_bytesio_src.seek(0)
332
  audio_stream_bytesio_src.truncate(0)
333
+
334
  tts.write_to_fp(audio_stream_bytesio_src)
335
 
336
  audio_stream_bytesio_src.seek(0)
337
+
338
  # Charger l'audio dans un tableau numpy
339
  data, samplerate = sf.read(audio_stream_bytesio_src)
340
 
 
351
  st.audio(new_audio_stream_bytesio, start_time=0, autoplay=True)
352
 
353
 
 
354
  def run():
355
+ global thread_id, config, model_speech, language, prompt, model, model_name, question, to_init, initialized, messages
356
+
357
  st.write("")
358
  st.write("")
359
  st.title(tr(title))
360
+
361
  if 'language_label' in st.session_state:
362
+ language = st.session_state['language_label']
363
+ else:
364
+ language = "French"
365
+
366
  chosen_id = tab_bar(data=[
367
+ TabBarItemData(id="tab1", title=tr("Initialisation"),
368
+ description=tr("d'une nouvelle conversation")),
369
+ TabBarItemData(id="tab2", title=tr("Conversation"),
370
+ description=tr("avec le prospect")),
371
+ TabBarItemData(id="tab3", title=tr("Evaluation"), description=tr("de l'acte de vente"))],
372
  default="tab1")
373
+
 
374
  if (chosen_id == "tab1"):
375
+ if 'model' in st.session_state and (st.session_state.model[:3] == "gpt") and ("OPENAI_API_KEY" in st.session_state):
376
  model = ChatOpenAI(model=st.session_state.model,
377
+ temperature=0.8, # Adjust creativity level
378
+ max_tokens=150 # Define max output token limit
379
+ )
380
+ else:
381
  model = ChatMistralAI(model=st.session_state.model)
 
382
 
383
+ config, thread_id, messages = init()
384
  query = ""
385
  elif (chosen_id == "tab2"):
386
  try:
387
  if to_init and not initialized:
388
  init_run()
389
  except NameError:
390
+ config, thread_id, messages = init()
391
  with st.container():
392
  # Diviser l'écran en deux colonnes
393
  col1, col2 = st.columns(2)
394
  with col1:
395
  st.write("**thread_id:** "+thread_id)
396
  query = ""
397
+ audio_bytes = audio_recorder(pause_threshold=2.0, sample_rate=16000, auto_start=False, text=tr("Cliquez pour parler, puis attendre 2sec."),
398
+ recording_color="#e8b62c", neutral_color="#1ec3bc", icon_size="6x",)
399
+
400
  if audio_bytes:
401
  # st.write("**"+tr("Vendeur")+" :**\n")
402
  # Fonction pour générer et jouer le texte en speech
 
408
  audio_stream_bytesio = io.BytesIO(audio_bytes)
409
 
410
  # Read the WAV stream using wavio
411
+ wav = wavio.read(audio_stream_bytesio)
412
 
413
  # Extract the audio data from the wavio.Wav object
414
  audio_data = wav.data
415
 
416
  # Convert the audio data to a NumPy array
417
+ audio_input = np.array(
418
+ audio_data, dtype=np.float32)
419
  audio_input = np.mean(audio_input, axis=1)/32768
420
+
421
  result = model_speech.transcribe(audio_input)
422
  Lang_detected = result["language"]
423
  query = result["text"]
424
+
425
  else:
426
  # Avec l'aide de la bibliothèque speech_recognition de Google
427
+ Lang_detected = st.session_state['Language']
428
  # Transcription google
429
+ audio_stream = sr.AudioData(audio_bytes, 32000, 2)
430
  r = sr.Recognizer()
431
+ query = r.recognize_google(
432
+ audio_stream, language=Lang_detected)
433
+
434
+ # Transcription
435
  # st.write("**"+tr("Vendeur :")+"** "+query)
436
  with st.chat_message("user"):
437
  st.markdown(query)
438
  st.write("")
439
+
440
  if query != "":
441
  input_messages = [HumanMessage(query)]
442
  output = app.invoke(
443
  {"messages": input_messages, "language": language},
444
  config,
445
  )
446
+ # with st.chat_message("user"):
447
  # Add user message to chat history
448
+ st.session_state.messages.append(
449
+ {"role": "user", "content": query})
450
 
451
  # Récupération de la réponse
452
  custom_sentence = output["messages"][-1].content
453
+
454
  # Joue l'audio
455
+ play_audio(custom_sentence, Lang_detected, 1)
456
+
457
  # st.write("**"+tr("Prospect :")+"** "+custom_sentence)
458
  with st.chat_message("assistant"):
459
  st.markdown(custom_sentence)
460
+
461
  # Add user message to chat history
462
+ st.session_state.messages.append(
463
+ {"role": "assistant", "content": custom_sentence})
464
 
 
465
  except KeyboardInterrupt:
466
  st.write(tr("Arrêt de la reconnaissance vocale."))
467
  except:
 
470
  # Ajouter un espace pour séparer les zones
471
  # st.divider()
472
  with col2:
473
+ if ("messages" in st.session_state):
474
  if (st.session_state.messages != []):
475
+ # Display chat messages from history on app rerun
476
  for message in st.session_state.messages:
477
  with st.chat_message(message["role"]):
478
  st.markdown(message["content"])
 
480
  if to_init and not initialized:
481
  init_run()
482
  st.write("**thread_id:** "+thread_id)
483
+ for i in range(8, len(question)):
484
  st.write("")
485
 
486
+ q = st.text_input(label=".", value=tr(
487
+ question[i]), label_visibility="collapsed")
488
+ if (q != ""):
489
  input_messages = [HumanMessage(q)]
490
  output = app.invoke(
491
  {"messages": input_messages, "language": language},
492
  config,
493
+ )
494
  # output = app.invoke(
495
  # {"messages": q,"language": language},
496
  # config,
497
+ # )
498
+ custom_sentence = output["messages"][-1].content
499
  st.write(custom_sentence)
500
  st.write("")
501
  if (used_model[:3] == 'mis'):
502
  time.sleep(2)
503
+
504
+ st.divider()