mery22 commited on
Commit
c6bf6d7
1 Parent(s): bc6d497

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +138 -63
app.py CHANGED
@@ -1,44 +1,56 @@
1
  import os
2
  import streamlit as st
3
- import pandas as pd
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
9
- from huggingface_hub import login
10
- from langchain_community.document_loaders import TextLoader
11
- from langchain_text_splitters import CharacterTextSplitter
12
- from langchain_community.document_loaders import PyPDFLoader
13
- from langchain.chains import RetrievalQA
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
- # Authenticate with Hugging Face
 
16
  login(token=st.secrets["HF_TOKEN"])
17
 
18
- # Load FAISS index
19
  db = FAISS.load_local("faiss_index", HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L12-v2'), allow_dangerous_deserialization=True)
20
-
21
- # Set up retriever
22
  retriever = db.as_retriever(search_type="mmr", search_kwargs={'k': 1})
23
 
24
- # Prompt template for the LLM
25
  prompt_template = """
26
  ### [INST]
27
  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.
28
- 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?
29
- Answer in French only.
30
-
31
  {context}
32
  Vous devez répondre aux questions en français.
33
 
34
  ### QUESTION:
35
  {question}
36
  [/INST]
37
- Answer in French only.
38
- Vous devez répondre aux questions en français.
39
  """
40
 
41
- # Set up the LLM from Hugging Face
42
  repo_id = "mistralai/Mistral-7B-Instruct-v0.3"
43
 
44
  mistral_llm = HuggingFaceEndpoint(
@@ -51,11 +63,10 @@ prompt = PromptTemplate(
51
  template=prompt_template,
52
  )
53
 
54
- # Create LLM chain
55
  llm_chain = LLMChain(llm=mistral_llm, prompt=prompt)
56
 
57
- # Set up RetrievalQA chain
58
- retriever.search_kwargs = {'k': 1}
59
  qa = RetrievalQA.from_chain_type(
60
  llm=mistral_llm,
61
  chain_type="stuff",
@@ -63,52 +74,116 @@ qa = RetrievalQA.from_chain_type(
63
  chain_type_kwargs={"prompt": prompt},
64
  )
65
 
66
- # Streamlit interface setup
67
  st.set_page_config(page_title="Alter-IA Chat", page_icon="🤖")
68
 
69
- # Function to handle user input and display chatbot response
70
  def chatbot_response(user_input):
71
  response = qa.run(user_input)
72
  return response
73
 
74
- import gspread
75
- from oauth2client.service_account import ServiceAccountCredentials
76
- import json
77
-
78
- # Load Google service account credentials from Hugging Face secrets
79
- GOOGLE_SERVICE_ACCOUNT_JSON = st.secrets["GOOGLE_SERVICE_ACCOUNT_JSON"]
80
-
81
- # Google Sheets setup
82
- scope = ["https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive"]
83
- service_account_info = json.loads(GOOGLE_SERVICE_ACCOUNT_JSON)
84
- creds = ServiceAccountCredentials.from_json_keyfile_dict(service_account_info, scope)
85
- client = gspread.authorize(creds)
86
- sheet = client.open("users feedback").sheet1 # Replace with your Google Sheet name
87
-
88
- # Function to save user feedback to Google Sheets
89
- def save_feedback(user_input, bot_response, rating, comment):
90
- feedback = [user_input, bot_response, rating, comment]
91
- sheet.append_row(feedback)
92
-
93
- # Streamlit app layout
94
-
95
- st.markdown("<h3 style='text-align: center;'>🤖 Chatbot Feedback 🤖</h3>", unsafe_allow_html=True)
96
-
97
- user_input = st.text_input("You:")
98
- bot_response = "This is a bot response." # Replace this with your chatbot's response logic
99
-
100
- st.markdown("### Rate the response:")
101
- rating = st.selectbox("", [1, 2, 3, 4, 5])
102
-
103
- st.markdown("### Leave a comment:")
104
- comment = st.text_area("")
105
-
106
- if st.button("Submit"):
107
- if user_input.strip() and comment.strip():
108
- save_feedback(user_input, bot_response, rating, comment)
109
- st.success("Thank you for your feedback!")
110
- else:
111
- st.warning("Please provide both input and comment.")
112
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  st.markdown("---")
114
- st.markdown("Collaboration is the key to success. Each question finds its answer, each challenge becomes an opportunity.")
 
1
  import os
2
  import streamlit as st
 
3
  from langchain_community.vectorstores import FAISS
4
  from langchain_community.embeddings import HuggingFaceEmbeddings
5
  from langchain_huggingface import HuggingFaceEndpoint
6
  from langchain.prompts import PromptTemplate
7
+ from langchain.chains import LLMChain, RetrievalQA
8
+ import gspread
9
+ from oauth2client.service_account import ServiceAccountCredentials
10
+ import json
11
+
12
+ import gspread
13
+ from oauth2client.service_account import ServiceAccountCredentials
14
+ import json
15
+
16
+ # Load Google service account credentials from Hugging Face secrets
17
+ GOOGLE_SERVICE_ACCOUNT_JSON = st.secrets["GOOGLE_SERVICE_ACCOUNT_JSON"]
18
+
19
+ # Google Sheets setup
20
+ scope = ["https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive"]
21
+ service_account_info = json.loads(GOOGLE_SERVICE_ACCOUNT_JSON)
22
+ creds = ServiceAccountCredentials.from_json_keyfile_dict(service_account_info, scope)
23
+ client = gspread.authorize(creds)
24
+ sheet = client.open("users feedback").sheet1 # Replace with your Google Sheet name
25
+ # Function to save user feedback to Google Sheets
26
+ def save_feedback(user_input, bot_response, rating, comment):
27
+ feedback = [user_input, bot_response, rating, comment]
28
+ sheet.append_row(feedback)
29
 
30
+ # Hugging Face API login
31
+ from huggingface_hub import login
32
  login(token=st.secrets["HF_TOKEN"])
33
 
34
+ # Initialize LangChain components
35
  db = FAISS.load_local("faiss_index", HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L12-v2'), allow_dangerous_deserialization=True)
 
 
36
  retriever = db.as_retriever(search_type="mmr", search_kwargs={'k': 1})
37
 
 
38
  prompt_template = """
39
  ### [INST]
40
  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.
41
+ Analyse carefully the context and provide a direct answer based on the context. If the user says Bonjour or Hello, your only answer will be: Hi! comment puis-je vous aider?
42
+ Answer in french only
43
+
44
  {context}
45
  Vous devez répondre aux questions en français.
46
 
47
  ### QUESTION:
48
  {question}
49
  [/INST]
50
+ Answer in french only
51
+ Vous devez répondre aux questions en français.
52
  """
53
 
 
54
  repo_id = "mistralai/Mistral-7B-Instruct-v0.3"
55
 
56
  mistral_llm = HuggingFaceEndpoint(
 
63
  template=prompt_template,
64
  )
65
 
66
+ # Create llm chain
67
  llm_chain = LLMChain(llm=mistral_llm, prompt=prompt)
68
 
69
+ # Create RetrievalQA chain
 
70
  qa = RetrievalQA.from_chain_type(
71
  llm=mistral_llm,
72
  chain_type="stuff",
 
74
  chain_type_kwargs={"prompt": prompt},
75
  )
76
 
77
+ # Streamlit interface with improved aesthetics
78
  st.set_page_config(page_title="Alter-IA Chat", page_icon="🤖")
79
 
80
+ # Define function to handle user input and display chatbot response
81
  def chatbot_response(user_input):
82
  response = qa.run(user_input)
83
  return response
84
 
85
+ # Create columns for logos
86
+ col1, col2, col3 = st.columns([2, 3, 2])
87
+
88
+ with col1:
89
+ st.image("Design 3_22.png", width=150, use_column_width=True) # Adjust image path and size as needed
90
+
91
+ with col3:
92
+ st.image("Altereo logo 2023 original - eau et territoires durables.png", width=150, use_column_width=True) # Adjust image path and size as needed
93
+
94
+ # Streamlit components
95
+ st.markdown("""
96
+ <style>
97
+ .centered-text {
98
+ text-align: center;
99
+ }
100
+ .stars {
101
+ font-size: 24px;
102
+ color: lightgray;
103
+ cursor: pointer;
104
+ }
105
+ .stars:hover,
106
+ .stars.selected {
107
+ color: gold;
108
+ }
109
+ .stars.filled {
110
+ color: gold;
111
+ }
112
+ </style>
113
+ """, unsafe_allow_html=True)
114
+
115
+ # Star rating system with JavaScript
116
+ st.markdown("""
117
+ <script>
118
+ function setRating(starId) {
119
+ const stars = document.querySelectorAll('.stars');
120
+ stars.forEach(star => star.classList.remove('filled'));
121
+ document.querySelectorAll('.stars').forEach(star => {
122
+ if (star.dataset.rating <= starId) {
123
+ star.classList.add('filled');
124
+ }
125
+ });
126
+ document.getElementById('rating').value = starId;
127
+ }
128
+ document.addEventListener('DOMContentLoaded', (event) => {
129
+ document.querySelectorAll('.stars').forEach(star => {
130
+ star.addEventListener('click', () => {
131
+ setRating(star.dataset.rating);
132
+ });
133
+ });
134
+ });
135
+ </script>
136
+ """, unsafe_allow_html=True)
137
+
138
+ # Display star rating
139
+ st.markdown('<div class="stars" data-rating="1">&#9733;</div>', unsafe_allow_html=True)
140
+ st.markdown('<div class="stars" data-rating="2">&#9733;</div>', unsafe_allow_html=True)
141
+ st.markdown('<div class="stars" data-rating="3">&#9733;</div>', unsafe_allow_html=True)
142
+ st.markdown('<div class="stars" data-rating="4">&#9733;</div>', unsafe_allow_html=True)
143
+ st.markdown('<div class="stars" data-rating="5">&#9733;</div>', unsafe_allow_html=True)
144
+
145
+ # Hidden input field to store the rating value
146
+ st.markdown('<input type="hidden" id="rating" value="0">', unsafe_allow_html=True)
147
+
148
+ # Input and button for user interaction
149
+ user_input = st.text_input("You:", "")
150
+ submit_button = st.button("Ask 📨")
151
+
152
+ # Handle user input
153
+ if submit_button:
154
+ if user_input.strip() != "":
155
+ bot_response = chatbot_response(user_input)
156
+ st.markdown("### Bot:")
157
+ st.text_area("", value=bot_response, height=600)
158
+
159
+ # Feedback form
160
+ st.markdown("### Rate the response:")
161
+ st.markdown('<p>Please click on the stars to rate the response.</p>', unsafe_allow_html=True)
162
+ st.markdown('<p id="rating-value">Rating: 0</p>', unsafe_allow_html=True)
163
+
164
+ st.markdown("### Leave a comment:")
165
+ comment = st.text_area("")
166
+
167
+ # Update rating value on star click
168
+ st.markdown("""
169
+ <script>
170
+ document.querySelectorAll('.stars').forEach(star => {
171
+ star.addEventListener('click', function() {
172
+ document.getElementById('rating-value').innerText = 'Rating: ' + this.dataset.rating;
173
+ });
174
+ });
175
+ </script>
176
+ """, unsafe_allow_html=True)
177
+
178
+ # Feedback submission
179
+ if st.button("Submit Feedback"):
180
+ rating = st.text_input("Rating", value="0")
181
+ if comment.strip() and rating != "0":
182
+ save_feedback(user_input, bot_response, rating, comment)
183
+ st.success("Thank you for your feedback!")
184
+ else:
185
+ st.warning("⚠️ Please provide a comment and a rating.")
186
+
187
+ # Motivational quote at the bottom
188
  st.markdown("---")
189
+ st.markdown("La collaboration est la clé du succès. Chaque question trouve sa réponse, chaque défi devient une opportunité.")