Draco15628 commited on
Commit
cb92cb3
Β·
verified Β·
1 Parent(s): bbe5492
Files changed (1) hide show
  1. app.py +117 -6
app.py CHANGED
@@ -9,7 +9,7 @@ from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
9
  import datetime # Logging
10
  import json # Chat history
11
  from textblob import TextBlob # Sentiment analysis
12
- from deep_translator import GoogleTranslator # Fixed Translator Import
13
  import speech_recognition as sr # Voice recognition
14
  from streamlit_webrtc import webrtc_streamer, WebRtcMode, RTCConfiguration # Video calling
15
  from reportlab.lib.pagesizes import letter
@@ -46,7 +46,7 @@ def generate_question_embeddings():
46
  question_embeddings = generate_question_embeddings()
47
 
48
  # Initialize translator
49
- translator = GoogleTranslator(source="auto", target="en")
50
 
51
  # Suggested Questions
52
  suggested_questions = ["What is AI?", "Tell me a joke!", "How does machine learning work?"]
@@ -78,6 +78,7 @@ def get_best_response(user_input):
78
  if best_match_score > 0.7:
79
  return answers[best_match_idx]
80
 
 
81
  inputs = chatbot_tokenizer(user_input, return_tensors="pt")
82
  outputs = chatbot_model.generate(**inputs)
83
  return chatbot_tokenizer.decode(outputs[0], skip_special_tokens=True)
@@ -124,16 +125,126 @@ def transcribe_audio():
124
  except sr.RequestError:
125
  return "Speech recognition service error."
126
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  # Streamlit UI
128
  st.title("πŸ€– AI Chatbot with File Upload & Video Calling πŸš€")
129
 
130
- # User input handling
131
- user_input = st.text_input("Type your message here...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  if user_input:
 
 
 
 
133
  response = get_best_response(user_input)
134
  log_chat(user_input, response)
 
135
  sentiment_result = analyze_sentiment(user_input)
136
-
 
 
 
 
 
137
  with st.chat_message("assistant"):
138
  st.write(f"{response}\n\n**Sentiment Analysis:** {sentiment_result}")
139
- st.audio(text_to_speech(response), format="audio/mp3")
 
 
 
 
 
9
  import datetime # Logging
10
  import json # Chat history
11
  from textblob import TextBlob # Sentiment analysis
12
+ from googletrans import Translator # Language translation
13
  import speech_recognition as sr # Voice recognition
14
  from streamlit_webrtc import webrtc_streamer, WebRtcMode, RTCConfiguration # Video calling
15
  from reportlab.lib.pagesizes import letter
 
46
  question_embeddings = generate_question_embeddings()
47
 
48
  # Initialize translator
49
+ translator = Translator()
50
 
51
  # Suggested Questions
52
  suggested_questions = ["What is AI?", "Tell me a joke!", "How does machine learning work?"]
 
78
  if best_match_score > 0.7:
79
  return answers[best_match_idx]
80
 
81
+ # Generate response using BlenderBot
82
  inputs = chatbot_tokenizer(user_input, return_tensors="pt")
83
  outputs = chatbot_model.generate(**inputs)
84
  return chatbot_tokenizer.decode(outputs[0], skip_special_tokens=True)
 
125
  except sr.RequestError:
126
  return "Speech recognition service error."
127
 
128
+ def generate_chat_pdf():
129
+ """Creates a PDF of the chat history and returns it as a downloadable file."""
130
+ buffer = BytesIO()
131
+ c = canvas.Canvas(buffer, pagesize=letter)
132
+ width, height = letter
133
+
134
+ y_position = height - 40 # Start at top
135
+
136
+ c.setFont("Helvetica-Bold", 14)
137
+ c.drawString(30, y_position, "Chat History")
138
+ y_position -= 20
139
+ c.setFont("Helvetica", 10)
140
+
141
+ for message in st.session_state.messages:
142
+ role = "User: " if message["role"] == "user" else "Bot: "
143
+ text = role + message["content"]
144
+
145
+ for line in text.split("\n"):
146
+ if y_position < 40: # New page if reaching bottom
147
+ c.showPage()
148
+ c.setFont("Helvetica", 10)
149
+ y_position = height - 40
150
+
151
+ c.drawString(30, y_position, line)
152
+ y_position -= 15
153
+
154
+ c.save()
155
+ buffer.seek(0)
156
+ return buffer
157
+
158
  # Streamlit UI
159
  st.title("πŸ€– AI Chatbot with File Upload & Video Calling πŸš€")
160
 
161
+ # File Upload Feature
162
+ uploaded_file = st.file_uploader("πŸ“„ Upload a document for Q&A", type=["txt", "pdf", "docx"])
163
+
164
+ if uploaded_file:
165
+ extracted_text = extract_text_from_file(uploaded_file)
166
+ if extracted_text:
167
+ st.subheader("πŸ“œ Extracted File Content:")
168
+ st.text_area("File Content", extracted_text, height=200)
169
+ else:
170
+ st.warning("Unsupported file format.")
171
+
172
+ # Suggested Questions
173
+ st.subheader("πŸ’‘ Suggested Questions:")
174
+ cols = st.columns(len(suggested_questions))
175
+
176
+ user_input = None
177
+ for i, q in enumerate(suggested_questions):
178
+ if cols[i].button(q):
179
+ user_input = q
180
+
181
+ # Voice Input
182
+ st.subheader("🎀 Speak instead of typing!")
183
+ if st.button("πŸŽ™οΈ Use Voice Input"):
184
+ user_input = transcribe_audio()
185
+
186
+ # Video Call Feature
187
+ st.subheader("πŸ“Ή Video Call")
188
+
189
+ # Initialize session state for video call
190
+ if "video_call_active" not in st.session_state:
191
+ st.session_state.video_call_active = False
192
+
193
+ # Button to start/stop video call
194
+ if st.button("πŸ“ž Start Video Call"):
195
+ st.session_state.video_call_active = True
196
+
197
+ if st.button("❌ End Video Call"):
198
+ st.session_state.video_call_active = False
199
+
200
+ # Run video call if active
201
+ if st.session_state.video_call_active:
202
+ webrtc_streamer(
203
+ key="video-call",
204
+ mode=WebRtcMode.SENDRECV,
205
+ rtc_configuration=RTCConfiguration(
206
+ {"iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]}
207
+ ),
208
+ media_stream_constraints={"video": True, "audio": True},
209
+ )
210
+
211
+ if user_input is None:
212
+ user_input = st.chat_input("Type your message here...")
213
+
214
+ # Initialize chat history
215
+ if "messages" not in st.session_state:
216
+ st.session_state.messages = []
217
+
218
+ # Clear Chat Button
219
+ if st.button("πŸ—‘οΈ Clear Chat"):
220
+ st.session_state.messages.clear()
221
+ st.rerun()
222
+
223
+
224
+ # Display chat history
225
+ for message in st.session_state.messages:
226
+ with st.chat_message(message["role"]):
227
+ st.write(message["content"])
228
+
229
  if user_input:
230
+ detected_lang = translator.detect(user_input).lang
231
+ if detected_lang != "en":
232
+ user_input = translator.translate(user_input, dest="en").text
233
+
234
  response = get_best_response(user_input)
235
  log_chat(user_input, response)
236
+
237
  sentiment_result = analyze_sentiment(user_input)
238
+
239
+ st.session_state.messages.append({"role": "user", "content": user_input})
240
+ st.session_state.messages.append({"role": "assistant", "content": response})
241
+
242
+ audio_file = text_to_speech(response)
243
+
244
  with st.chat_message("assistant"):
245
  st.write(f"{response}\n\n**Sentiment Analysis:** {sentiment_result}")
246
+ st.audio(audio_file, format="audio/mp3")
247
+
248
+ # Download Chat as PDF
249
+ pdf_file = generate_chat_pdf()
250
+ st.download_button("πŸ“₯ Download Chat as PDF", pdf_file, "chat_history.pdf", "application/pdf")