mery22 commited on
Commit
1fe0c9e
·
verified ·
1 Parent(s): d5caf79

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -45
app.py CHANGED
@@ -1,68 +1,59 @@
1
  import os
 
2
  import streamlit as st
3
  from langchain_community.vectorstores import FAISS
4
  from langchain_community.embeddings import HuggingFaceEmbeddings
5
-
6
  from langchain_huggingface import HuggingFaceEndpoint
7
-
8
  from langchain.prompts import PromptTemplate
9
- from langchain.schema.runnable import RunnablePassthrough
10
- from langchain.chains import LLMChain
11
-
12
  from huggingface_hub import login
13
- login(token=st.secrets["HF_TOKEN"])
14
-
15
- from langchain_community.document_loaders import TextLoader
16
- from langchain_text_splitters import CharacterTextSplitter
17
- from langchain_community.document_loaders import PyPDFLoader
18
- from langchain.chains import RetrievalQA
19
- from langchain.prompts import PromptTemplate
20
- from langchain.embeddings.huggingface import HuggingFaceEmbeddings
21
-
22
- db = FAISS.load_local("faiss_index", HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L12-v2'),allow_dangerous_deserialization=True)
23
 
 
 
24
 
 
 
 
 
 
25
 
 
26
  retriever = db.as_retriever(
27
  search_type="mmr",
28
  search_kwargs={'k': 1}
29
  )
30
 
31
-
32
  prompt_template = """
33
  ### [INST]
34
  Instruction: You are a Q&A assistant. Your goal is to answer questions as accurately as possible based on the instructions and context provided without using prior knowledge.You answer in FRENCH
35
- Analyse carefully the context and provide a direct answer based on the context. If the user said Bonjour or Hello your only answer will be Hi! comment puis-je vous aider?
36
  Answer in french only
37
-
38
  {context}
39
  Vous devez répondre aux questions en français.
40
-
41
  ### QUESTION:
42
  {question}
43
  [/INST]
44
  Answer in french only
45
  Vous devez répondre aux questions en français.
46
-
47
- """
48
 
49
  repo_id = "mistralai/Mistral-7B-Instruct-v0.3"
50
 
 
51
  mistral_llm = HuggingFaceEndpoint(
52
  repo_id=repo_id, max_length=2048, temperature=0.05, huggingfacehub_api_token=st.secrets["HF_TOKEN"]
53
  )
54
 
55
- # Create prompt from prompt template
56
  prompt = PromptTemplate(
57
  input_variables=["question"],
58
  template=prompt_template,
59
  )
60
-
61
- # Create llm chain
62
  llm_chain = LLMChain(llm=mistral_llm, prompt=prompt)
63
 
64
-
65
- retriever.search_kwargs = {'k':1}
66
  qa = RetrievalQA.from_chain_type(
67
  llm=mistral_llm,
68
  chain_type="stuff",
@@ -70,9 +61,7 @@ qa = RetrievalQA.from_chain_type(
70
  chain_type_kwargs={"prompt": prompt},
71
  )
72
 
73
- import streamlit as st
74
-
75
- # Streamlit interface with improved aesthetics
76
  st.set_page_config(page_title="Alter-IA Chat", page_icon="🤖")
77
 
78
  # Define function to handle user input and display chatbot response
@@ -80,30 +69,32 @@ def chatbot_response(user_input):
80
  response = qa.run(user_input)
81
  return response
82
 
 
 
 
 
 
 
 
 
 
 
83
 
84
  # Create columns for logos
85
  col1, col2, col3 = st.columns([2, 3, 2])
86
 
87
  with col1:
88
- st.image("Design 3_22.png", width=150, use_column_width=True) # Adjust image path and size as needed
89
 
90
  with col3:
91
- st.image("Altereo logo 2023 original - eau et territoires durables.png", width=150, use_column_width=True) # Adjust image path and size as needed
92
- # Streamlit components
93
- # Ajouter un peu de CSS pour centrer le texte
94
- # Ajouter un peu de CSS pour centrer le texte et le colorer en orange foncé
95
  st.markdown("""
96
  <style>
97
  .centered-text {
98
  text-align: center;
99
  }
100
- </style>
101
- """, unsafe_allow_html=True)
102
-
103
- # Utiliser la classe CSS pour centrer et colorer le texte
104
- st.markdown('<h3 class="centered-text">🤖 AlteriaChat 🤖 </h3>', unsafe_allow_html=True)
105
- st.markdown("""
106
- <style>
107
  .centered-orange-text {
108
  text-align: center;
109
  color: darkorange;
@@ -111,23 +102,35 @@ st.markdown("""
111
  </style>
112
  """, unsafe_allow_html=True)
113
 
114
- # Centrer le texte principal
115
- # Centrer et colorer en orange foncé le texte spécifique
116
  st.markdown('<p class="centered-orange-text">"Votre Réponse à Chaque Défi Méthodologique "</p>', unsafe_allow_html=True)
 
117
  # Input and button for user interaction
118
  user_input = st.text_input("You:", "")
119
  submit_button = st.button("Ask 📨")
120
 
121
- # Handle user input
122
  if submit_button:
123
  if user_input.strip() != "":
124
  bot_response = chatbot_response(user_input)
125
  st.markdown("### Bot:")
126
  st.text_area("", value=bot_response, height=600)
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  else:
128
  st.warning("⚠️ Please enter a message.")
129
 
130
  # Motivational quote at the bottom
131
  st.markdown("---")
132
  st.markdown("La collaboration est la clé du succès. Chaque question trouve sa réponse, chaque défi devient une opportunité.")
133
-
 
1
  import os
2
+ import csv
3
  import streamlit as st
4
  from langchain_community.vectorstores import FAISS
5
  from langchain_community.embeddings import HuggingFaceEmbeddings
 
6
  from langchain_huggingface import HuggingFaceEndpoint
 
7
  from langchain.prompts import PromptTemplate
8
+ from langchain.chains import LLMChain, RetrievalQA
 
 
9
  from huggingface_hub import login
 
 
 
 
 
 
 
 
 
 
10
 
11
+ # Login to Hugging Face
12
+ login(token=st.secrets["HF_TOKEN"])
13
 
14
+ # Load FAISS index
15
+ db = FAISS.load_local(
16
+ "faiss_index", HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L12-v2'),
17
+ allow_dangerous_deserialization=True
18
+ )
19
 
20
+ # Create retriever
21
  retriever = db.as_retriever(
22
  search_type="mmr",
23
  search_kwargs={'k': 1}
24
  )
25
 
26
+ # Define prompt template
27
  prompt_template = """
28
  ### [INST]
29
  Instruction: You are a Q&A assistant. Your goal is to answer questions as accurately as possible based on the instructions and context provided without using prior knowledge.You answer in FRENCH
30
+ Analyse carefully the context and provide a direct answer based on the context. If the user said Bonjour or Hello your only answer will be Hi! comment puis-je vous aider?
31
  Answer in french only
32
+
33
  {context}
34
  Vous devez répondre aux questions en français.
 
35
  ### QUESTION:
36
  {question}
37
  [/INST]
38
  Answer in french only
39
  Vous devez répondre aux questions en français.
40
+ """
 
41
 
42
  repo_id = "mistralai/Mistral-7B-Instruct-v0.3"
43
 
44
+ # Create LLM model
45
  mistral_llm = HuggingFaceEndpoint(
46
  repo_id=repo_id, max_length=2048, temperature=0.05, huggingfacehub_api_token=st.secrets["HF_TOKEN"]
47
  )
48
 
49
+ # Create prompt and LLM chain
50
  prompt = PromptTemplate(
51
  input_variables=["question"],
52
  template=prompt_template,
53
  )
 
 
54
  llm_chain = LLMChain(llm=mistral_llm, prompt=prompt)
55
 
56
+ # Create QA chain
 
57
  qa = RetrievalQA.from_chain_type(
58
  llm=mistral_llm,
59
  chain_type="stuff",
 
61
  chain_type_kwargs={"prompt": prompt},
62
  )
63
 
64
+ # Streamlit UI setup
 
 
65
  st.set_page_config(page_title="Alter-IA Chat", page_icon="🤖")
66
 
67
  # Define function to handle user input and display chatbot response
 
69
  response = qa.run(user_input)
70
  return response
71
 
72
+ # Define function to save feedback to CSV
73
+ def save_feedback(question, response, rating, comment):
74
+ filename = 'feedback.csv'
75
+ file_exists = os.path.isfile(filename)
76
+ with open(filename, 'a', newline='', encoding='utf-8') as csvfile:
77
+ fieldnames = ['question', 'response', 'rating', 'comment']
78
+ writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
79
+ if not file_exists:
80
+ writer.writeheader()
81
+ writer.writerow({'question': question, 'response': response, 'rating': rating, 'comment': comment})
82
 
83
  # Create columns for logos
84
  col1, col2, col3 = st.columns([2, 3, 2])
85
 
86
  with col1:
87
+ st.image("Design 3_22.png", width=150, use_column_width=True)
88
 
89
  with col3:
90
+ st.image("Altereo logo 2023 original - eau et territoires durables.png", width=150, use_column_width=True)
91
+
92
+ # Add CSS for styling
 
93
  st.markdown("""
94
  <style>
95
  .centered-text {
96
  text-align: center;
97
  }
 
 
 
 
 
 
 
98
  .centered-orange-text {
99
  text-align: center;
100
  color: darkorange;
 
102
  </style>
103
  """, unsafe_allow_html=True)
104
 
105
+ # Center and color text
106
+ st.markdown('<h3 class="centered-text">🤖 AlteriaChat 🤖 </h3>', unsafe_allow_html=True)
107
  st.markdown('<p class="centered-orange-text">"Votre Réponse à Chaque Défi Méthodologique "</p>', unsafe_allow_html=True)
108
+
109
  # Input and button for user interaction
110
  user_input = st.text_input("You:", "")
111
  submit_button = st.button("Ask 📨")
112
 
 
113
  if submit_button:
114
  if user_input.strip() != "":
115
  bot_response = chatbot_response(user_input)
116
  st.markdown("### Bot:")
117
  st.text_area("", value=bot_response, height=600)
118
+
119
+ # Feedback Section
120
+ st.markdown("### Évaluation de la réponse")
121
+ rating = st.slider("Rating (1 to 5)", 1, 5, 3)
122
+ comment = st.text_area("Your comment:", "")
123
+
124
+ if st.button("Submit Feedback"):
125
+ if comment.strip() != "":
126
+ save_feedback(user_input, bot_response, rating, comment)
127
+ st.success("Thank you for your feedback!")
128
+ else:
129
+ st.warning("⚠️ Please enter a comment.")
130
+
131
  else:
132
  st.warning("⚠️ Please enter a message.")
133
 
134
  # Motivational quote at the bottom
135
  st.markdown("---")
136
  st.markdown("La collaboration est la clé du succès. Chaque question trouve sa réponse, chaque défi devient une opportunité.")