Muthuraja commited on
Commit
685c012
·
verified ·
1 Parent(s): 79ff97d

Update app.py (#4)

Browse files

- Update app.py (e836caaad6df9b25afabd777cfb75667141b0fe0)

Files changed (1) hide show
  1. app.py +308 -308
app.py CHANGED
@@ -1,308 +1,308 @@
1
- import PyPDF2
2
- import streamlit as st
3
- from transformers import pipeline
4
- import io
5
- from datetime import datetime, timedelta
6
- import gspread
7
- from google.oauth2.service_account import Credentials
8
- import pandas as pd
9
- import matplotlib.pyplot as plt
10
- from io import BytesIO
11
- from reportlab.lib.pagesizes import letter
12
- from reportlab.pdfgen import canvas
13
- import speech_recognition as sr # Speech recognition package
14
-
15
- # Google Sheets setup
16
- SCOPE = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
17
- CREDS_PATH = r"C:\Users\Muthuraja\Downloads\modern-cycling-444916-g6-82c207d3eb47.json" # Provide your Google credentials path
18
-
19
- # Initialize the Hugging Face QA pipeline
20
- qa_pipeline = pipeline("question-answering")
21
-
22
- # Initialize Sentiment Analysis Pipeline using Hugging Face
23
- sentiment_model = pipeline('sentiment-analysis')
24
-
25
- # Initialize Google Sheets connection
26
- def initialize_google_sheets():
27
- credentials = Credentials.from_service_account_file(CREDS_PATH, scopes=SCOPE)
28
- try:
29
- client = gspread.authorize(credentials)
30
- sheet = client.open("SalesStores").sheet1 # Change Google Sheet name to "SalesStores"
31
- return sheet
32
- except gspread.exceptions.APIError as e:
33
- st.error(f"Google Sheets API error: {e}")
34
- return None
35
-
36
- sheet = initialize_google_sheets()
37
-
38
- # Function to extract text from PDF using PyPDF2
39
- def extract_pdf_text_with_pypdf(pdf_file):
40
- pdf_text = ""
41
- with io.BytesIO(pdf_file.read()) as pdf_data:
42
- pdf_reader = PyPDF2.PdfReader(pdf_data)
43
- for page_num in range(len(pdf_reader.pages)):
44
- page = pdf_reader.pages[page_num]
45
- pdf_text += page.extract_text()
46
- return pdf_text.strip()
47
-
48
- # Function to answer a query using Hugging Face's QA pipeline
49
- def answer_query(question, context):
50
- result = qa_pipeline(question=question, context=context)
51
- return result['answer']
52
-
53
- # Function to analyze sentiment using Hugging Face's pre-trained model
54
- def analyze_sentiment(text):
55
- sentiment = sentiment_model(text)[0] # Output is a list of dictionaries
56
- label = sentiment['label']
57
- score = sentiment['score']
58
-
59
- # Define sentiment labels
60
- if label == "POSITIVE" and score > 0.6:
61
- sentiment_description = "Positive"
62
- elif label == "NEGATIVE" and score < 0.4: # Adjust threshold for negative sentiment
63
- sentiment_description = "Negative"
64
- else:
65
- sentiment_description = "Neutral"
66
-
67
- return score, sentiment_description
68
-
69
- # Function to update Google Sheets without product name
70
- def update_sheet_without_product(sentiment_score, sentiment_description, relevant_answer):
71
- if sheet:
72
- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
73
- sheet.append_row([timestamp, sentiment_description, sentiment_score, relevant_answer, "No Product Name"])
74
- else:
75
- st.error("Google Sheets connection not initialized.")
76
-
77
- # Function to suggest product recommendations based on sentiment or query
78
- def suggest_product_recommendations(sentiment_description, query):
79
- # Based on the sentiment, recommend a product type
80
- if "laptop" in query.lower():
81
- if sentiment_description == "Positive":
82
- recommendations = [
83
- "Check out this powerful gaming laptop!",
84
- "How about this lightweight ultrabook?",
85
- "This laptop has amazing reviews, you should consider it!"
86
- ]
87
- elif sentiment_description == "Negative":
88
- recommendations = [
89
- "Maybe you'd prefer a different laptop brand?",
90
- "Check out these budget-friendly laptops instead."
91
- ]
92
- else:
93
- recommendations = [
94
- "Looking for a laptop? Here's a variety of options for you!"
95
- ]
96
- elif "smartphone" in query.lower():
97
- if sentiment_description == "Positive":
98
- recommendations = [
99
- "Check out our best-selling smartphone!",
100
- "This smartphone has incredible features and great reviews."
101
- ]
102
- elif sentiment_description == "Negative":
103
- recommendations = [
104
- "Looking for an alternative smartphone? Here's something else you might like.",
105
- "You might like these highly-rated budget smartphones instead."
106
- ]
107
- else:
108
- recommendations = [
109
- "Looking for the latest smartphone? Here's a range of options."
110
- ]
111
- elif "headphones" in query.lower():
112
- if sentiment_description == "Positive":
113
- recommendations = [
114
- "These headphones are highly rated and perfect for music lovers!",
115
- "Check out this noise-cancelling model."
116
- ]
117
- elif sentiment_description == "Negative":
118
- recommendations = [
119
- "Here are some alternatives that might suit your needs better.",
120
- "Consider these wireless headphones for more comfort."
121
- ]
122
- else:
123
- recommendations = [
124
- "Here's a list of headphones with great sound quality!"
125
- ]
126
- else:
127
- recommendations = [
128
- "Based on your query, here are some great options across different categories!"
129
- ]
130
-
131
- return recommendations
132
-
133
- # Function to filter data by date
134
- def filter_data_by_date(data, date_filter):
135
- if date_filter == "Today":
136
- start_date = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
137
- data = data[data['Timestamp'] >= start_date]
138
- elif date_filter == "One Week":
139
- start_date = datetime.now() - timedelta(weeks=1)
140
- data = data[data['Timestamp'] >= start_date]
141
- return data
142
-
143
- # Function to generate PDF for the call history
144
- def generate_pdf(data):
145
- buffer = BytesIO()
146
- c = canvas.Canvas(buffer, pagesize=letter)
147
- c.setFont("Helvetica", 10)
148
- y_position = 750
149
- c.drawString(30, y_position, "Call History Report")
150
- y_position -= 20
151
- for index, row in data.iterrows():
152
- c.drawString(30, y_position, f"Sentiment: {row['Sentiment']}, Answer: {row['Answer']}, Product: {row['Product Name']}")
153
- y_position -= 15
154
- if y_position <= 40:
155
- c.showPage()
156
- c.setFont("Helvetica", 10)
157
- y_position = 750
158
- c.save()
159
- buffer.seek(0)
160
- return buffer
161
-
162
- # Function to listen to speech and convert it to text
163
- def listen_to_speech():
164
- recognizer = sr.Recognizer()
165
- with sr.Microphone() as source:
166
- recognizer.adjust_for_ambient_noise(source) # Adjust for background noise
167
- st.write("Listening...") # Optional: Add a message to indicate listening state
168
- try:
169
- audio = recognizer.listen(source, timeout=5, phrase_time_limit=10) # Listen for the audio input
170
- st.write("Recognizing...") # Optional: Add a message for recognition process
171
- text = recognizer.recognize_google(audio) # Use Google's speech recognition to convert audio to text
172
- st.write(f"Recognized: {text}")
173
- return text # Return the text detected from the audio
174
- except sr.UnknownValueError:
175
- st.error("Sorry, I could not understand the audio.") # Handle case when the audio is unclear
176
- return None
177
- except sr.RequestError:
178
- st.error("Could not request results from Google Speech Recognition service.") # Handle network issues
179
- return None
180
- except Exception as e:
181
- st.error(f"An error occurred: {e}")
182
- return None
183
-
184
- # Function to suggest related follow-up questions based on the answer
185
- def suggest_related_questions():
186
- related_questions = [
187
- "Can you explain more about the product?",
188
- "What are the features of this product?",
189
- "How does it compare to other products?",
190
- "Can I get more details about the specifications?",
191
- "What is the price of the product?"
192
- ]
193
- return related_questions
194
-
195
- # Dashboard functions
196
- def display_dashboard():
197
- # Fetch data from Google Sheets
198
- if sheet:
199
- data = pd.DataFrame(sheet.get_all_records()) # Load all rows into a DataFrame
200
-
201
- # Ensure the Timestamp column exists and is in datetime format
202
- if 'Timestamp' in data.columns:
203
- data['Timestamp'] = pd.to_datetime(data['Timestamp'])
204
-
205
- # Add a date filter to the dashboard
206
- date_filter = st.selectbox("Filter by Date", ["All Time", "Today", "One Week"])
207
-
208
- # Filter data based on the selected date range
209
- if date_filter != "All Time":
210
- data = filter_data_by_date(data, date_filter)
211
-
212
- # Ensure we have required columns
213
- if 'Sentiment' in data.columns and 'Answer' in data.columns:
214
- # Product Relevance Chart: Show sentiment distribution for each product
215
- st.subheader("Product Relevance Chart")
216
- product_sentiment = data.groupby(['Product Name', 'Sentiment']).size().unstack().fillna(0)
217
-
218
- fig, ax = plt.subplots(figsize=(8, 6))
219
- product_sentiment.plot(kind='bar', stacked=True, ax=ax, colormap='viridis')
220
- ax.set_ylabel("Number of Queries")
221
- ax.set_xlabel("Product Name")
222
- ax.set_title("Sentiment Distribution for Each Product")
223
- st.pyplot(fig)
224
-
225
- # Plot sentiment distribution overall
226
- sentiment_counts = data['Sentiment'].value_counts()
227
- st.subheader("Overall Sentiment Distribution")
228
- fig, ax = plt.subplots()
229
- sentiment_counts.plot(kind='bar', ax=ax, color='lightcoral')
230
- ax.set_ylabel("Frequency")
231
- ax.set_xlabel("Sentiment")
232
- st.pyplot(fig)
233
-
234
- # Call Statistics
235
- total_calls = len(data)
236
- avg_sentiment = data['Sentiment'].apply(lambda x: 1 if x == 'Positive' else -1 if x == 'Negative' else 0).mean()
237
- avg_sentiment = round(avg_sentiment, 2)
238
-
239
- st.subheader("Call Activity Statistics")
240
- st.write(f"Total Calls: {total_calls}")
241
- st.write(f"Average Sentiment: {avg_sentiment}")
242
-
243
- # Call History Table
244
- st.subheader("Call History")
245
- st.write(data[['Timestamp', 'Sentiment', 'Answer', 'Product Name']])
246
-
247
- # Download option for the entire history (PDF)
248
- pdf = generate_pdf(data)
249
- st.download_button(
250
- label="Download Call History as PDF",
251
- data=pdf,
252
- file_name="call_history.pdf",
253
- mime="application/pdf"
254
- )
255
-
256
- # Main Streamlit UI and workflow
257
- def main():
258
- st.title('Real-Time Customer Query Analysis & Call History')
259
-
260
- # Sidebar Navigation
261
- sidebar_option = st.sidebar.selectbox("Select an Option", ["Dashboard", "Call Analysis"])
262
-
263
- if sidebar_option == "Dashboard":
264
- display_dashboard()
265
-
266
- elif sidebar_option == "Call Analysis":
267
- # Upload PDF file
268
- uploaded_pdf = st.file_uploader("Upload a PDF file", type="pdf")
269
- if uploaded_pdf:
270
- pdf_text = extract_pdf_text_with_pypdf(uploaded_pdf)
271
-
272
- if not pdf_text:
273
- st.error("No text could be extracted from the PDF.")
274
- return
275
-
276
- # Speech recognition button
277
- if st.button("Start Speech Recognition"):
278
- user_input = listen_to_speech()
279
- if user_input:
280
- # Sentiment Analysis
281
- sentiment_score, sentiment_description = analyze_sentiment(user_input)
282
-
283
- # Answer the query using the Hugging Face QA pipeline
284
- answer = answer_query(user_input, pdf_text)
285
- st.write(f"Answer: {answer}")
286
-
287
- # Display Sentiment Result
288
- st.write(f"Sentiment: {sentiment_description} (Score: {sentiment_score:.2f})")
289
-
290
- # Recommend products based on sentiment and query
291
- st.subheader("Recommended Products")
292
- recommendations = suggest_product_recommendations(sentiment_description, user_input)
293
- for rec in recommendations:
294
- st.write(f"- {rec}")
295
-
296
- # Store the query and the response in Google Sheets without the product name
297
- update_sheet_without_product(sentiment_score, sentiment_description, answer)
298
-
299
-
300
-
301
- # Suggest related follow-up questions
302
- st.subheader("Related Follow-up Questions")
303
- related_questions = suggest_related_questions()
304
- for question in related_questions:
305
- st.write(f"- {question}")
306
-
307
- if __name__ == "__main__":
308
- main()
 
1
+ import PyPDF2
2
+ import streamlit as st
3
+ from transformers import pipeline
4
+ import io
5
+ from datetime import datetime, timedelta
6
+ import gspread
7
+ from google.oauth2.service_account import Credentials
8
+ import pandas as pd
9
+ import matplotlib.pyplot as plt
10
+ from io import BytesIO
11
+ from reportlab.lib.pagesizes import letter
12
+ from reportlab.pdfgen import canvas
13
+ import speech_recognition as sr # Speech recognition package
14
+
15
+ # Google Sheets setup
16
+ SCOPE = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
17
+ CREDS_PATH = r"C:\Users\Muthuraja\OneDrive\Attachments\Desktop\second\modern-cycling-444916-g6-82c207d3eb47.json" # Provide your Google credentials path
18
+
19
+ # Initialize the Hugging Face QA pipeline
20
+ qa_pipeline = pipeline("question-answering")
21
+
22
+ # Initialize Sentiment Analysis Pipeline using Hugging Face
23
+ sentiment_model = pipeline('sentiment-analysis')
24
+
25
+ # Initialize Google Sheets connection
26
+ def initialize_google_sheets():
27
+ credentials = Credentials.from_service_account_file(CREDS_PATH, scopes=SCOPE)
28
+ try:
29
+ client = gspread.authorize(credentials)
30
+ sheet = client.open("SalesStores").sheet1 # Change Google Sheet name to "SalesStores"
31
+ return sheet
32
+ except gspread.exceptions.APIError as e:
33
+ st.error(f"Google Sheets API error: {e}")
34
+ return None
35
+
36
+ sheet = initialize_google_sheets()
37
+
38
+ # Function to extract text from PDF using PyPDF2
39
+ def extract_pdf_text_with_pypdf(pdf_file):
40
+ pdf_text = ""
41
+ with io.BytesIO(pdf_file.read()) as pdf_data:
42
+ pdf_reader = PyPDF2.PdfReader(pdf_data)
43
+ for page_num in range(len(pdf_reader.pages)):
44
+ page = pdf_reader.pages[page_num]
45
+ pdf_text += page.extract_text()
46
+ return pdf_text.strip()
47
+
48
+ # Function to answer a query using Hugging Face's QA pipeline
49
+ def answer_query(question, context):
50
+ result = qa_pipeline(question=question, context=context)
51
+ return result['answer']
52
+
53
+ # Function to analyze sentiment using Hugging Face's pre-trained model
54
+ def analyze_sentiment(text):
55
+ sentiment = sentiment_model(text)[0] # Output is a list of dictionaries
56
+ label = sentiment['label']
57
+ score = sentiment['score']
58
+
59
+ # Define sentiment labels
60
+ if label == "POSITIVE" and score > 0.6:
61
+ sentiment_description = "Positive"
62
+ elif label == "NEGATIVE" and score < 0.4: # Adjust threshold for negative sentiment
63
+ sentiment_description = "Negative"
64
+ else:
65
+ sentiment_description = "Neutral"
66
+
67
+ return score, sentiment_description
68
+
69
+ # Function to update Google Sheets without product name
70
+ def update_sheet_without_product(sentiment_score, sentiment_description, relevant_answer):
71
+ if sheet:
72
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
73
+ sheet.append_row([timestamp, sentiment_description, sentiment_score, relevant_answer, "No Product Name"])
74
+ else:
75
+ st.error("Google Sheets connection not initialized.")
76
+
77
+ # Function to suggest product recommendations based on sentiment or query
78
+ def suggest_product_recommendations(sentiment_description, query):
79
+ # Based on the sentiment, recommend a product type
80
+ if "laptop" in query.lower():
81
+ if sentiment_description == "Positive":
82
+ recommendations = [
83
+ "Check out this powerful gaming laptop!",
84
+ "How about this lightweight ultrabook?",
85
+ "This laptop has amazing reviews, you should consider it!"
86
+ ]
87
+ elif sentiment_description == "Negative":
88
+ recommendations = [
89
+ "Maybe you'd prefer a different laptop brand?",
90
+ "Check out these budget-friendly laptops instead."
91
+ ]
92
+ else:
93
+ recommendations = [
94
+ "Looking for a laptop? Here's a variety of options for you!"
95
+ ]
96
+ elif "smartphone" in query.lower():
97
+ if sentiment_description == "Positive":
98
+ recommendations = [
99
+ "Check out our best-selling smartphone!",
100
+ "This smartphone has incredible features and great reviews."
101
+ ]
102
+ elif sentiment_description == "Negative":
103
+ recommendations = [
104
+ "Looking for an alternative smartphone? Here's something else you might like.",
105
+ "You might like these highly-rated budget smartphones instead."
106
+ ]
107
+ else:
108
+ recommendations = [
109
+ "Looking for the latest smartphone? Here's a range of options."
110
+ ]
111
+ elif "headphones" in query.lower():
112
+ if sentiment_description == "Positive":
113
+ recommendations = [
114
+ "These headphones are highly rated and perfect for music lovers!",
115
+ "Check out this noise-cancelling model."
116
+ ]
117
+ elif sentiment_description == "Negative":
118
+ recommendations = [
119
+ "Here are some alternatives that might suit your needs better.",
120
+ "Consider these wireless headphones for more comfort."
121
+ ]
122
+ else:
123
+ recommendations = [
124
+ "Here's a list of headphones with great sound quality!"
125
+ ]
126
+ else:
127
+ recommendations = [
128
+ "Based on your query, here are some great options across different categories!"
129
+ ]
130
+
131
+ return recommendations
132
+
133
+ # Function to filter data by date
134
+ def filter_data_by_date(data, date_filter):
135
+ if date_filter == "Today":
136
+ start_date = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
137
+ data = data[data['Timestamp'] >= start_date]
138
+ elif date_filter == "One Week":
139
+ start_date = datetime.now() - timedelta(weeks=1)
140
+ data = data[data['Timestamp'] >= start_date]
141
+ return data
142
+
143
+ # Function to generate PDF for the call history
144
+ def generate_pdf(data):
145
+ buffer = BytesIO()
146
+ c = canvas.Canvas(buffer, pagesize=letter)
147
+ c.setFont("Helvetica", 10)
148
+ y_position = 750
149
+ c.drawString(30, y_position, "Call History Report")
150
+ y_position -= 20
151
+ for index, row in data.iterrows():
152
+ c.drawString(30, y_position, f"Sentiment: {row['Sentiment']}, Answer: {row['Answer']}, Product: {row['Product Name']}")
153
+ y_position -= 15
154
+ if y_position <= 40:
155
+ c.showPage()
156
+ c.setFont("Helvetica", 10)
157
+ y_position = 750
158
+ c.save()
159
+ buffer.seek(0)
160
+ return buffer
161
+
162
+ # Function to listen to speech and convert it to text
163
+ def listen_to_speech():
164
+ recognizer = sr.Recognizer()
165
+ with sr.Microphone() as source:
166
+ recognizer.adjust_for_ambient_noise(source) # Adjust for background noise
167
+ st.write("Listening...") # Optional: Add a message to indicate listening state
168
+ try:
169
+ audio = recognizer.listen(source, timeout=5, phrase_time_limit=10) # Listen for the audio input
170
+ st.write("Recognizing...") # Optional: Add a message for recognition process
171
+ text = recognizer.recognize_google(audio) # Use Google's speech recognition to convert audio to text
172
+ st.write(f"Recognized: {text}")
173
+ return text # Return the text detected from the audio
174
+ except sr.UnknownValueError:
175
+ st.error("Sorry, I could not understand the audio.") # Handle case when the audio is unclear
176
+ return None
177
+ except sr.RequestError:
178
+ st.error("Could not request results from Google Speech Recognition service.") # Handle network issues
179
+ return None
180
+ except Exception as e:
181
+ st.error(f"An error occurred: {e}")
182
+ return None
183
+
184
+ # Function to suggest related follow-up questions based on the answer
185
+ def suggest_related_questions():
186
+ related_questions = [
187
+ "Can you explain more about the product?",
188
+ "What are the features of this product?",
189
+ "How does it compare to other products?",
190
+ "Can I get more details about the specifications?",
191
+ "What is the price of the product?"
192
+ ]
193
+ return related_questions
194
+
195
+ # Dashboard functions
196
+ def display_dashboard():
197
+ # Fetch data from Google Sheets
198
+ if sheet:
199
+ data = pd.DataFrame(sheet.get_all_records()) # Load all rows into a DataFrame
200
+
201
+ # Ensure the Timestamp column exists and is in datetime format
202
+ if 'Timestamp' in data.columns:
203
+ data['Timestamp'] = pd.to_datetime(data['Timestamp'])
204
+
205
+ # Add a date filter to the dashboard
206
+ date_filter = st.selectbox("Filter by Date", ["All Time", "Today", "One Week"])
207
+
208
+ # Filter data based on the selected date range
209
+ if date_filter != "All Time":
210
+ data = filter_data_by_date(data, date_filter)
211
+
212
+ # Ensure we have required columns
213
+ if 'Sentiment' in data.columns and 'Answer' in data.columns:
214
+ # Product Relevance Chart: Show sentiment distribution for each product
215
+ st.subheader("Product Relevance Chart")
216
+ product_sentiment = data.groupby(['Product Name', 'Sentiment']).size().unstack().fillna(0)
217
+
218
+ fig, ax = plt.subplots(figsize=(8, 6))
219
+ product_sentiment.plot(kind='bar', stacked=True, ax=ax, colormap='viridis')
220
+ ax.set_ylabel("Number of Queries")
221
+ ax.set_xlabel("Product Name")
222
+ ax.set_title("Sentiment Distribution for Each Product")
223
+ st.pyplot(fig)
224
+
225
+ # Plot sentiment distribution overall
226
+ sentiment_counts = data['Sentiment'].value_counts()
227
+ st.subheader("Overall Sentiment Distribution")
228
+ fig, ax = plt.subplots()
229
+ sentiment_counts.plot(kind='bar', ax=ax, color='lightcoral')
230
+ ax.set_ylabel("Frequency")
231
+ ax.set_xlabel("Sentiment")
232
+ st.pyplot(fig)
233
+
234
+ # Call Statistics
235
+ total_calls = len(data)
236
+ avg_sentiment = data['Sentiment'].apply(lambda x: 1 if x == 'Positive' else -1 if x == 'Negative' else 0).mean()
237
+ avg_sentiment = round(avg_sentiment, 2)
238
+
239
+ st.subheader("Call Activity Statistics")
240
+ st.write(f"Total Calls: {total_calls}")
241
+ st.write(f"Average Sentiment: {avg_sentiment}")
242
+
243
+ # Call History Table
244
+ st.subheader("Call History")
245
+ st.write(data[['Timestamp', 'Sentiment', 'Answer', 'Product Name']])
246
+
247
+ # Download option for the entire history (PDF)
248
+ pdf = generate_pdf(data)
249
+ st.download_button(
250
+ label="Download Call History as PDF",
251
+ data=pdf,
252
+ file_name="call_history.pdf",
253
+ mime="application/pdf"
254
+ )
255
+
256
+ # Main Streamlit UI and workflow
257
+ def main():
258
+ st.title('Real-Time Customer Query Analysis & Call History')
259
+
260
+ # Sidebar Navigation
261
+ sidebar_option = st.sidebar.selectbox("Select an Option", ["Dashboard", "Call Analysis"])
262
+
263
+ if sidebar_option == "Dashboard":
264
+ display_dashboard()
265
+
266
+ elif sidebar_option == "Call Analysis":
267
+ # Upload PDF file
268
+ uploaded_pdf = st.file_uploader("Upload a PDF file", type="pdf")
269
+ if uploaded_pdf:
270
+ pdf_text = extract_pdf_text_with_pypdf(uploaded_pdf)
271
+
272
+ if not pdf_text:
273
+ st.error("No text could be extracted from the PDF.")
274
+ return
275
+
276
+ # Speech recognition button
277
+ if st.button("Start Speech Recognition"):
278
+ user_input = listen_to_speech()
279
+ if user_input:
280
+ # Sentiment Analysis
281
+ sentiment_score, sentiment_description = analyze_sentiment(user_input)
282
+
283
+ # Answer the query using the Hugging Face QA pipeline
284
+ answer = answer_query(user_input, pdf_text)
285
+ st.write(f"Answer: {answer}")
286
+
287
+ # Display Sentiment Result
288
+ st.write(f"Sentiment: {sentiment_description} (Score: {sentiment_score:.2f})")
289
+
290
+ # Recommend products based on sentiment and query
291
+ st.subheader("Recommended Products")
292
+ recommendations = suggest_product_recommendations(sentiment_description, user_input)
293
+ for rec in recommendations:
294
+ st.write(f"- {rec}")
295
+
296
+ # Store the query and the response in Google Sheets without the product name
297
+ update_sheet_without_product(sentiment_score, sentiment_description, answer)
298
+
299
+
300
+
301
+ # Suggest related follow-up questions
302
+ st.subheader("Related Follow-up Questions")
303
+ related_questions = suggest_related_questions()
304
+ for question in related_questions:
305
+ st.write(f"- {question}")
306
+
307
+ if __name__ == "__main__":
308
+ main()