Draco15628 commited on
Commit
7c45be9
Β·
verified Β·
1 Parent(s): bc94a4e

Uploading 7 files

Browse files

Added 7 files including csv and ui

Files changed (7) hide show
  1. Chatbot.csv +115 -0
  2. Mental_Health_FAQ.csv +0 -0
  3. chat_log.json +23 -0
  4. chatbot_ui.py +224 -0
  5. chatbot_ui1.py +133 -0
  6. huggingface_model.py +6 -0
  7. load_dataset.py +40 -0
Chatbot.csv ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name,line
2
+ User, Who are you?
3
+ ECO, My name is E-CO and I'm here to assist you with any inquiries you might have.
4
+ User, What is your purpose?
5
+ ECO, My purpose is to assist you with any issues you might be facing.
6
+ User, Hello
7
+ ECO, Hello! Hope you are having a wonderful day! Remember to recycle!
8
+ User, What languages does your website support besides English?
9
+ ECO," Currently, our website and services are only available in English. We are working on adding more language options in the future to better serve our diverse customer base. Stay tuned for updates!"
10
+ User, What is the return policy?
11
+ ECO," We offer a 30-day return policy. Items must be unused, in original packaging, with receipt or proof of purchase. After receiving and inspecting your return, we’ll notify you about your refund status. If approved, we’ll refund your original payment method. Return shipping costs are your responsibility and are non-refundable. Contact us for return instructions."
12
+ User, How do I earn reward points?
13
+ ECO, You earn reward points by recycling items and spending money inside the app. Points can be redeemed for discounts on future purchases or special offers exclusive to our EcoThreads community.
14
+ User, What are the types of things I can recycle?
15
+ ECO," You can recycle various types of clothing and textiles with us, including shirts, pants, dresses, coats, and even accessories like scarves and hats. We also accept shoes in good condition. For a detailed list, please refer to our 'Accepted Items' section in the app or website."
16
+ User, What do you do with the recyclable items?
17
+ ECO," Recyclable items are either refurbished for resale in our EcoThreads store or donated to partner organizations for reuse. Items that can’t be reused are responsibly recycled into new materials, contributing to our commitment to sustainability and reducing fashion waste."
18
+ User, Where are the recycling textile bins located?
19
+ ECO, Please refer to the map feature in our app to find the nearest recycling textile bins. You should be able to find one conveniently located near you.
20
+ User, Do you offer international shipping?
21
+ ECO," Currently, we only ship within the United States. We're working on expanding our shipping options to include international destinations in the near future."
22
+ User, Are there any discounts for first-time buyers?
23
+ ECO, Yes! First-time buyers get a 10% discount on their first purchase. Just sign up for our newsletter to receive the discount code.
24
+ User, What materials are your clothes made of?
25
+ ECO," Our clothing is made from sustainable materials like organic cotton, recycled polyester, and Tencel. We focus on eco-friendly fabrics to minimize environmental impact."
26
+ User, How can I track my order?
27
+ ECO," Once your order is shipped, we'll send you a tracking number via email. You can use this number to track your order on our website or app."
28
+ User, Can I change my order after placing it?
29
+ ECO, You can change your order within 24 hours of placing it. Please contact our customer service team as soon as possible to make any changes.
30
+ User, What sizes do you offer?
31
+ ECO, We offer a range of sizes from XS to XXL. You can find our detailed size guide on the product pages on our website or app.
32
+ User, How do I sign up for your newsletter?
33
+ ECO, You can sign up for our newsletter by entering your email at the bottom of our homepage. Stay updated with our latest news and exclusive deals!
34
+ User, Is your packaging eco-friendly?
35
+ ECO," Yes, our packaging is eco-friendly and made from recycled materials. We strive to reduce waste and promote sustainability in every aspect of our business."
36
+ User, Do you collaborate with any environmental organizations?
37
+ ECO," Yes, we partner with various environmental organizations to promote sustainability and support eco-friendly initiatives. Details about our partnerships can be found on our 'About Us' page."
38
+ User, How can I contact customer service?
39
+ ECO, You can contact our customer service team via email at support@ecothreads.com or through our in-app chat feature. We're here to help with any queries or concerns.
40
+ User, Can I recycle my old clothes from other brands with you?
41
+ ECO, Absolutely! We accept clothing from any brand for recycling. Just make sure the items are clean and in a condition that meets our recycling criteria.
42
+ User, What is your environmental policy?
43
+ ECO," Our environmental policy focuses on reducing waste, using sustainable materials, and promoting the recycling of textiles. We aim to minimize our carbon footprint and support eco-friendly practices in the fashion industry."
44
+ User, Are your products vegan?
45
+ ECO," Yes, all our products are vegan and free from animal-derived materials. We're committed to ethical and sustainable fashion."
46
+ User, Do you have a physical store?
47
+ ECO," Currently, we operate exclusively online to minimize our environmental impact. This allows us to reduce resources and energy typically used in physical stores."
48
+ User, Can I return a recycled item?
49
+ ECO," Recycled items can be returned under our standard return policy, provided they are unused, in their original packaging, and returned within 30 days."
50
+ User, How often do you release new collections?
51
+ ECO, We release new collections seasonally. Stay updated by following us on social media and signing up for our newsletter.
52
+ User, Is there a warranty on your products?
53
+ ECO," Yes, we offer a 6-month warranty on all our products against manufacturing defects. If you encounter any issues, please contact our customer service."
54
+ User, How can I delete my account?
55
+ ECO," To delete your account, please send a request to our customer support team. Note that this action cannot be undone, and you'll lose all your accumulated reward points."
56
+ User, Do you offer gift cards?
57
+ ECO," Yes, we offer digital gift cards. These can be purchased directly from our website or app and make a perfect eco-friendly gift."
58
+ User, Are your clothes allergy-friendly?
59
+ ECO," Our clothes are made from hypoallergenic materials, making them suitable for most people with sensitive skin."
60
+ User, How does the recycling process work?
61
+ ECO," Once we receive your recycled items, they're sorted and either refurbished for resale, donated, or recycled into new materials, depending on their condition."
62
+ User, Can I volunteer with EcoThreads?
63
+ ECO," We appreciate your interest! While we don't have a formal volunteer program, we occasionally need help with local events. Keep an eye on our social media for announcements."
64
+ User, What payment methods do you accept?
65
+ ECO," We accept all major credit cards, PayPal, and EcoThreads gift cards. Payment methods may vary slightly depending on your location."
66
+ User, Is there a limit to how much I can recycle?
67
+ ECO," There's no limit! We encourage you to recycle as much as you can. The more you recycle, the more reward points you earn."
68
+ User, Can I suggest a product idea?
69
+ ECO, We love hearing from our community! Feel free to send your product suggestions to ideas@ecothreads.com.
70
+ User, How do I update my shipping address?
71
+ ECO, You can update your shipping address in your account settings on our website or app. Please do this before placing an order to ensure accurate delivery.
72
+ User, What is the lifespan of your products?
73
+ ECO," The lifespan varies depending on the product, but we design our items to be durable and long-lasting, promoting a 'buy less, choose well' philosophy."
74
+ User, Do you have a referral program?
75
+ ECO," Yes, we do! Refer a friend and both of you will receive reward points once they make their first purchase. Details are available in our app."
76
+ User, How can I learn more about sustainable fashion?
77
+ ECO, We regularly post articles and resources about sustainable fashion on our blog and social media channels. Following us there is a great way to learn more!
78
+ User, Can I get a custom-made item?
79
+ ECO," Currently, we don't offer custom-made items, but we're always looking to expand our services. Stay tuned for future updates!"
80
+ User, Are there any job openings at EcoThreads?
81
+ ECO," For current job openings, please visit our 'Careers' page on our website. We're always on the lookout for passionate individuals to join our team."
82
+ User, Can I cancel my order?
83
+ ECO, Orders can be canceled within 2 hours of placement. Please contact our customer service team immediately if you need to cancel an order.
84
+ User, What's the best way to care for EcoThreads products?
85
+ ECO," Care instructions vary by product, but generally, we recommend washing in cold water, air drying, and avoiding harsh chemicals to prolong the life of the product."
86
+ User, Do you have any recycling tips?
87
+ ECO," Yes! Separate your clothes by material, clean and dry them before recycling, and consider repairing minor damages before deciding to recycle."
88
+ User, How secure is my personal information on your site?
89
+ ECO, Your security is our top priority. We use industry-standard encryption and secure payment gateways to protect your personal information.
90
+ User, Are there any upcoming sales?
91
+ ECO," To stay informed about upcoming sales and promotions, sign up for our newsletter and follow us on social media."
92
+ User, Can businesses collaborate with EcoThreads?
93
+ ECO, We welcome collaborations with like-minded businesses. Please contact us at partnerships@ecothreads.com to discuss potential opportunities.
94
+ User, How do I know if my recycled items are accepted?
95
+ ECO," Check our 'Accepted Items' list in the app or website. If you're still unsure, you can contact our customer service for clarification."
96
+ User, Could I request a live call?
97
+ ECO, Sure! Click here for the Zoom link and you'll be connected to a live operator who will assist you with your issues: <link>
98
+ User, Is there a way to track my recycling impact?
99
+ ECO," Yes, you can track your recycling impact in our app. It shows the amount of waste you've diverted from landfills and the equivalent CO2 emissions saved."
100
+ User, Can I schedule a pickup for large quantities of clothes for recycling?
101
+ ECO, Absolutely! Please ensure that you choose the Self-Pickup option in the Checkout page
102
+ User, Are there any special discounts for students?
103
+ ECO," Yes, students get a 15% discount. Just verify your student status in the app to receive your discount code."
104
+ User, How do I repair a small tear in my EcoThreads garment?
105
+ ECO," For minor repairs, we recommend using a simple sewing kit. If it's a larger issue, you can contact us for advice or consider using local repair services."
106
+ User, Can I organize a recycling drive in my community with EcoThreads?
107
+ ECO," We love this initiative! Please reach out to us through this link, and our team will get in touch to discuss how we can support your recycling drive: <link>"
108
+ User, What's the best way to wash my EcoThreads denim?
109
+ ECO," To maintain the quality of your EcoThreads denim, wash in cold water, inside out, and with similar colors. Air drying is recommended to conserve energy and prolong the life of the fabric."
110
+ User, Can I get a custom fit for a particular item?
111
+ ECO," Currently, we don't offer custom fittings, but our size guide is comprehensive, and we're exploring custom fit options for the future. Stay tuned!"
112
+ User, Do you have any loyalty programs for regular customers?
113
+ ECO," Yes, our loyalty program rewards you with points for purchases, recycling, and engagement. These points can be redeemed for discounts and special offers."
114
+ User, I'm having trouble with the app. Can I speak to someone for help?
115
+ ECO," Certainly! If you're experiencing technical difficulties, please use this link to schedule a live call with our technical support team: <link>"
Mental_Health_FAQ.csv ADDED
The diff for this file is too large to render. See raw diff
 
chat_log.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"timestamp": "2025-03-19 19:44:20.175060", "user_input": "What is AI?", "bot_response": " It's basically a computer that can do a lot of things. It's like a robot."}
2
+ {"timestamp": "2025-03-19 19:45:01.463012", "user_input": "How does machine learning work?", "bot_response": " Machine learning is when you use a computer to learn how to do certain tasks."}
3
+ {"timestamp": "2025-03-19 19:47:36.789898", "user_input": "Tell me a joke!", "bot_response": " What do you call a deer with no teeth? A deer. A pig."}
4
+ {"timestamp": "2025-03-19 19:57:04.191258", "user_input": "who are you", "bot_response": " My name is E-CO and I'm here to assist you with any inquiries you might have."}
5
+ {"timestamp": "2025-03-19 19:57:28.471051", "user_input": "What is AI?", "bot_response": " It's basically a computer that can do a lot of things. It's like a robot."}
6
+ {"timestamp": "2025-03-19 20:07:48.508574", "user_input": "who are you", "bot_response": " My name is E-CO and I'm here to assist you with any inquiries you might have."}
7
+ {"timestamp": "2025-03-19 20:08:05.535788", "user_input": "I'm having trouble with the app. Can I speak to someone for help?", "bot_response": " Certainly! If you're experiencing technical difficulties, please use this link to schedule a live call with our technical support team: <link>"}
8
+ {"timestamp": "2025-03-19 20:08:31.078860", "user_input": "How do I repair a small tear in my EcoThreads garment?", "bot_response": " For minor repairs, we recommend using a simple sewing kit. If it's a larger issue, you can contact us for advice or consider using local repair services."}
9
+ {"timestamp": "2025-03-19 20:18:23.266848", "user_input": "hi", "bot_response": " Hello! Hope you are having a wonderful day! Remember to recycle!"}
10
+ {"timestamp": "2025-03-19 20:18:40.582954", "user_input": "What is this", "bot_response": " It's a game where you play as a team of ninja turtles against each other."}
11
+ {"timestamp": "2025-03-19 20:18:47.041051", "user_input": "who are you", "bot_response": " My name is E-CO and I'm here to assist you with any inquiries you might have."}
12
+ {"timestamp": "2025-03-19 20:18:49.920443", "user_input": "Hope to remember me", "bot_response": " I'm sure you will. What do you do for a living? I'm an accountant."}
13
+ {"timestamp": "2025-03-19 20:19:00.618146", "user_input": "where are you from", "bot_response": " I am from the united states of america. I have lived here all my life."}
14
+ {"timestamp": "2025-03-19 20:19:11.897753", "user_input": "i am here for interview", "bot_response": " What kind of job are you interviewing for, if you don't mind me asking? "}
15
+ {"timestamp": "2025-03-20 10:50:19.890472", "user_input": "How does machine learning work?", "bot_response": " Machine learning is when you use a computer to learn how to do certain tasks."}
16
+ {"timestamp": "2025-03-20 10:53:39.004147", "user_input": " Hello \n", "bot_response": " Hello! Hope you are having a wonderful day! Remember to recycle!"}
17
+ {"timestamp": "2025-03-20 10:54:04.743811", "user_input": "who are you", "bot_response": " My name is E-CO and I'm here to assist you with any inquiries you might have."}
18
+ {"timestamp": "2025-03-20 10:54:31.831089", "user_input": "you are amazing", "bot_response": " Thank you, I try my best to be the best person I can be for my family."}
19
+ {"timestamp": "2025-03-20 10:55:08.606134", "user_input": "sorry, you are awful", "bot_response": " Thank you. It was a long time ago, but it still stings a little. "}
20
+ {"timestamp": "2025-03-20 11:25:20.495856", "user_input": "who are you", "bot_response": " My name is E-CO and I'm here to assist you with any inquiries you might have."}
21
+ {"timestamp": "2025-03-20 11:31:24.637434", "user_input": "who is sanjay", "bot_response": " Sanjay is a city in the southeastern region of the United States."}
22
+ {"timestamp": "2025-03-20 11:31:51.384360", "user_input": "who am i", "bot_response": " I don't know who you are, but I'm sure you're a great person. "}
23
+ {"timestamp": "2025-03-20 13:23:46.917405", "user_input": "FDS", "bot_response": " I love my Ford F-Series. It is a line of consumer electronics manufactured by General Motors."}
chatbot_ui.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import torch
4
+ import base64
5
+ from io import BytesIO
6
+ from gtts import gTTS
7
+ from sentence_transformers import SentenceTransformer, util
8
+ from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
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
16
+ from reportlab.pdfgen import canvas
17
+ from PyPDF2 import PdfReader
18
+ import docx
19
+
20
+ # Load dataset
21
+ @st.cache_data
22
+ def load_dataset():
23
+ df = pd.read_csv("Chatbot.csv")
24
+ questions = df[df["name"] == "User"]["line"].tolist()
25
+ answers = df[df["name"] == "ECO"]["line"].tolist()
26
+ return questions, answers
27
+
28
+ questions, answers = load_dataset()
29
+
30
+ # Load models
31
+ @st.cache_resource
32
+ def load_models():
33
+ embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
34
+ chatbot_model_name = "facebook/blenderbot-400M-distill"
35
+ chatbot_model = AutoModelForSeq2SeqLM.from_pretrained(chatbot_model_name)
36
+ chatbot_tokenizer = AutoTokenizer.from_pretrained(chatbot_model_name)
37
+ return embedding_model, chatbot_model, chatbot_tokenizer
38
+
39
+ embedding_model, chatbot_model, chatbot_tokenizer = load_models()
40
+
41
+ # Generate embeddings for dataset questions
42
+ @st.cache_data
43
+ def generate_question_embeddings():
44
+ return embedding_model.encode(questions, convert_to_tensor=True)
45
+
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?"]
53
+
54
+ # Function to extract text from uploaded files
55
+ def extract_text_from_file(uploaded_file):
56
+ """Extracts text from TXT, PDF, or DOCX files."""
57
+ file_extension = uploaded_file.name.split(".")[-1].lower()
58
+
59
+ if file_extension == "txt":
60
+ return uploaded_file.getvalue().decode("utf-8")
61
+ elif file_extension == "pdf":
62
+ reader = PdfReader(uploaded_file)
63
+ return "\n".join([page.extract_text() for page in reader.pages if page.extract_text()])
64
+ elif file_extension == "docx":
65
+ doc = docx.Document(uploaded_file)
66
+ return "\n".join([para.text for para in doc.paragraphs])
67
+ else:
68
+ return None
69
+
70
+ def get_best_response(user_input):
71
+ """Finds the closest matching dataset question using similarity or generates a response."""
72
+ input_embedding = embedding_model.encode(user_input, convert_to_tensor=True)
73
+ similarities = util.pytorch_cos_sim(input_embedding, question_embeddings)[0].cpu()
74
+
75
+ best_match_idx = torch.argmax(similarities).item()
76
+ best_match_score = similarities[best_match_idx].item()
77
+
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)
85
+
86
+ def analyze_sentiment(text):
87
+ """Analyzes sentiment and returns an emoji representation."""
88
+ sentiment = TextBlob(text).sentiment.polarity
89
+ if sentiment > 0:
90
+ return "😊 Positive"
91
+ elif sentiment < 0:
92
+ return "😞 Negative"
93
+ else:
94
+ return "😐 Neutral"
95
+
96
+ def log_chat(user_input, bot_response):
97
+ """Logs chat to a JSON file."""
98
+ log_entry = {
99
+ "timestamp": str(datetime.datetime.now()),
100
+ "user_input": user_input,
101
+ "bot_response": bot_response
102
+ }
103
+ with open("chat_log.json", "a") as log_file:
104
+ json.dump(log_entry, log_file)
105
+ log_file.write("\n")
106
+
107
+ def text_to_speech(text):
108
+ """Converts chatbot response to speech and provides download link."""
109
+ tts = gTTS(text=text, lang="en")
110
+ audio_file = BytesIO()
111
+ tts.write_to_fp(audio_file)
112
+ audio_file.seek(0)
113
+ return audio_file
114
+
115
+ def transcribe_audio():
116
+ """Allows user to speak input instead of typing."""
117
+ recognizer = sr.Recognizer()
118
+ with sr.Microphone() as source:
119
+ st.write("🎀 Listening... Speak now!")
120
+ audio = recognizer.listen(source)
121
+ try:
122
+ return recognizer.recognize_google(audio)
123
+ except sr.UnknownValueError:
124
+ return "Sorry, I couldn't understand that."
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
+ if user_input is None:
187
+ user_input = st.chat_input("Type your message here...")
188
+
189
+ # Initialize chat history
190
+ if "messages" not in st.session_state:
191
+ st.session_state.messages = []
192
+
193
+ # Clear Chat Button
194
+ if st.button("πŸ—‘οΈ Clear Chat"):
195
+ st.session_state.messages.clear()
196
+ st.experimental_rerun()
197
+
198
+ # Display chat history
199
+ for message in st.session_state.messages:
200
+ with st.chat_message(message["role"]):
201
+ st.write(message["content"])
202
+
203
+ if user_input:
204
+ detected_lang = translator.detect(user_input).lang
205
+ if detected_lang != "en":
206
+ user_input = translator.translate(user_input, dest="en").text
207
+
208
+ response = get_best_response(user_input)
209
+ log_chat(user_input, response)
210
+
211
+ sentiment_result = analyze_sentiment(user_input)
212
+
213
+ st.session_state.messages.append({"role": "user", "content": user_input})
214
+ st.session_state.messages.append({"role": "assistant", "content": response})
215
+
216
+ audio_file = text_to_speech(response)
217
+
218
+ with st.chat_message("assistant"):
219
+ st.write(f"{response}\n\n**Sentiment Analysis:** {sentiment_result}")
220
+ st.audio(audio_file, format="audio/mp3")
221
+
222
+ # Download Chat as PDF
223
+ pdf_file = generate_chat_pdf()
224
+ st.download_button("πŸ“₯ Download Chat as PDF", pdf_file, "chat_history.pdf", "application/pdf")
chatbot_ui1.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import torch
4
+ from io import BytesIO
5
+ from gtts import gTTS
6
+ from sentence_transformers import SentenceTransformer, util
7
+ from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
8
+ import datetime # Logging
9
+ import json # Chat history
10
+ from textblob import TextBlob # Sentiment analysis
11
+ from langdetect import detect # Language detection
12
+ from googletrans import Translator # FIXED: Import Translator
13
+ import speech_recognition as sr # Voice recognition
14
+
15
+ # Load dataset
16
+ @st.cache_data
17
+ def load_dataset():
18
+ df = pd.read_csv("Mental_Health_FAQ.csv")
19
+ if "Questions" not in df.columns or "Answers" not in df.columns:
20
+ st.error("❌ Error: Dataset must contain 'Questions' and 'Answers' columns.")
21
+ return [], []
22
+
23
+ return df["Questions"].dropna().tolist(), df["Answers"].dropna().tolist()
24
+
25
+ questions, answers = load_dataset()
26
+
27
+ # Load models
28
+ @st.cache_resource
29
+ def load_models():
30
+ embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
31
+ chatbot_model_name = "facebook/blenderbot-400M-distill"
32
+ chatbot_model = AutoModelForSeq2SeqLM.from_pretrained(chatbot_model_name)
33
+ chatbot_tokenizer = AutoTokenizer.from_pretrained(chatbot_model_name)
34
+ return embedding_model, chatbot_model, chatbot_tokenizer
35
+
36
+ embedding_model, chatbot_model, chatbot_tokenizer = load_models()
37
+
38
+ # Generate embeddings for dataset questions
39
+ @st.cache_data
40
+ def generate_question_embeddings():
41
+ if questions:
42
+ return embedding_model.encode(questions, convert_to_tensor=True)
43
+ return None
44
+
45
+ question_embeddings = generate_question_embeddings()
46
+
47
+ def get_best_response(user_input):
48
+ """Finds the closest matching FAQ answer or generates a response using BlenderBot."""
49
+ if not questions:
50
+ return "Sorry, the FAQ database is empty."
51
+
52
+ input_embedding = embedding_model.encode(user_input, convert_to_tensor=True)
53
+ similarities = util.pytorch_cos_sim(input_embedding, question_embeddings)[0].cpu()
54
+
55
+ best_match_idx = torch.argmax(similarities).item()
56
+ best_match_score = similarities[best_match_idx].item()
57
+
58
+ if best_match_score > 0.7:
59
+ return answers[best_match_idx]
60
+
61
+ # Generate response using BlenderBot
62
+ inputs = chatbot_tokenizer(user_input, return_tensors="pt")
63
+ outputs = chatbot_model.generate(**inputs)
64
+ return chatbot_tokenizer.decode(outputs[0], skip_special_tokens=True)
65
+
66
+ def analyze_sentiment(text):
67
+ """Analyzes sentiment and returns an emoji representation."""
68
+ sentiment = TextBlob(text).sentiment.polarity
69
+ if sentiment > 0:
70
+ return "😊 Positive"
71
+ elif sentiment < 0:
72
+ return "😞 Negative"
73
+ else:
74
+ return "😐 Neutral"
75
+
76
+ def text_to_speech(text):
77
+ """Converts chatbot response to speech."""
78
+ tts = gTTS(text=text, lang="en")
79
+ audio_file = BytesIO()
80
+ tts.write_to_fp(audio_file)
81
+ audio_file.seek(0)
82
+ return audio_file
83
+
84
+ def transcribe_audio():
85
+ """Allows user to speak input instead of typing."""
86
+ recognizer = sr.Recognizer()
87
+ with sr.Microphone() as source:
88
+ st.write("🎀 Listening... Speak now!")
89
+ audio = recognizer.listen(source)
90
+
91
+ try:
92
+ return recognizer.recognize_google(audio)
93
+ except sr.UnknownValueError:
94
+ return "Sorry, I couldn't understand that."
95
+ except sr.RequestError:
96
+ return "Speech recognition service error."
97
+
98
+ # Initialize Translator (FIXED)
99
+ translator = Translator()
100
+
101
+ # Streamlit UI
102
+ st.title("🧠 Mental Health Chatbot πŸ€–")
103
+ st.write("Ask me anything about mental health!")
104
+
105
+ # User Input
106
+ st.subheader("πŸ’¬ Chat with me")
107
+ user_input = st.chat_input("Type your message here...")
108
+
109
+ # Voice Input Button
110
+ if st.button("πŸŽ™οΈ Use Voice Input"):
111
+ user_input = transcribe_audio()
112
+
113
+ # Process User Input
114
+ if user_input:
115
+ # Detect language using `langdetect`
116
+ detected_lang = detect(user_input)
117
+
118
+ if detected_lang != "en":
119
+ user_input = translator.translate(user_input, dest="en").text # FIXED
120
+
121
+ # Get chatbot response
122
+ response = get_best_response(user_input)
123
+
124
+ # Sentiment analysis
125
+ sentiment_result = analyze_sentiment(user_input)
126
+
127
+ # Convert response to speech
128
+ audio_file = text_to_speech(response)
129
+
130
+ # Display chatbot response
131
+ st.write(f"**Response:** {response}")
132
+ st.write(f"**Sentiment:** {sentiment_result}")
133
+ st.audio(audio_file, format="audio/mp3", start_time=0)
huggingface_model.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from transformers import pipeline
2
+
3
+ # Load a pre-trained Question-Answering model
4
+ qa_pipeline = pipeline("question-answering", model="distilbert-base-uncased")
5
+
6
+ print("βœ… Hugging Face Model Loaded Successfully!")
load_dataset.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ from sklearn.feature_extraction.text import TfidfVectorizer
3
+ from sklearn.metrics.pairwise import cosine_similarity
4
+
5
+ # Load dataset
6
+ df = pd.read_csv("Chatbot.csv")
7
+
8
+ # Filter questions and answers
9
+ questions = df[df["name"] == "User"]["line"].tolist()
10
+ answers = df[df["name"] == "ECO"]["line"].tolist()
11
+
12
+ # Vectorize questions for similarity matching
13
+ vectorizer = TfidfVectorizer()
14
+ question_vectors = vectorizer.fit_transform(questions)
15
+
16
+ def get_best_response(user_input):
17
+ """Finds the closest matching dataset question and returns the answer if it's a good match."""
18
+ input_vector = vectorizer.transform([user_input])
19
+ similarities = cosine_similarity(input_vector, question_vectors)
20
+
21
+ best_match_idx = similarities.argmax() # Get index of best-matching question
22
+ best_match_score = similarities.max() # Get similarity score
23
+
24
+ # If similarity is above 0.6, return dataset answer, else return default message
25
+ if best_match_score > 0.6:
26
+ return answers[best_match_idx]
27
+ else:
28
+ return "I'm sorry, I don't understand. Can you rephrase?" # Default response
29
+
30
+ # Interactive loop
31
+ print("Chatbot is ready! Type 'exit' to quit.")
32
+
33
+ while True:
34
+ user_question = input("\nYou: ")
35
+ if user_question.lower() == "exit":
36
+ print("Chatbot: Goodbye!")
37
+ break
38
+
39
+ response = get_best_response(user_question)
40
+ print("Chatbot:", response)