Student3331 commited on
Commit
1921bf3
·
verified ·
1 Parent(s): f343ee3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +84 -27
app.py CHANGED
@@ -1,47 +1,104 @@
1
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- # Predefined set of questions and responses
4
  responses = {
5
- 'hello': "Hi there! How can I assist you today?",
6
- 'hi': "Hello! How can I help you today?",
7
- 'how are you': "I'm doing great, thank you for asking! How about you?",
8
- 'what is your name': "I’m Chatbot, your friendly virtual assistant!",
9
- 'tell me the weather today': "I don’t have access to live data, but I suggest checking your local weather service for accurate updates!",
10
- 'what time is it': "Sorry, I can't tell the time, but you can check your device's clock.",
11
- 'bye': "Goodbye! Have a wonderful day!",
12
- 'thanks': "You're welcome! If you need anything else, feel free to ask.",
13
- 'how old are you': "I'm ageless! I was created to assist you whenever you need.",
14
- 'what can you do': "I can help with simple questions like greetings, weather, and more. Try asking me something!",
15
  }
16
 
17
- # Function to handle user input and provide chatbot responses
18
- def get_response(user_input):
19
- user_input = user_input.lower()
20
- return responses.get(user_input, "Sorry, I didn't understand that. Can you ask something else?")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- # Streamlit UI setup
23
- st.title("Chat with Chatbot!")
24
- st.markdown("Ask me anything, and I'll do my best to answer.")
25
 
26
- # Create a chat interface
27
  if 'history' not in st.session_state:
28
  st.session_state['history'] = []
29
 
30
  # Collect user input
31
  user_input = st.text_input("You: ")
32
 
33
- # Process user input and generate response
34
  if user_input:
35
  # Add user message to history
36
  st.session_state['history'].append(f"You: {user_input}")
37
-
38
- # Get the bot's response based on input
39
- bot_response = get_response(user_input)
40
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  # Add bot's response to history
42
  st.session_state['history'].append(f"Chatbot: {bot_response}")
43
-
44
- # Display the chat history
45
  for message in st.session_state['history']:
46
  st.write(message)
47
-
 
1
  import streamlit as st
2
+ from transformers import pipeline
3
+ import spacy
4
+ import random
5
+ import numpy as np
6
+ from sklearn.feature_extraction.text import CountVectorizer
7
+ from sklearn.svm import SVC
8
+
9
+ # Load Spacy model for NLP tasks
10
+ nlp = spacy.load("en_core_web_sm")
11
+
12
+ # Define training data for intent classification
13
+ intents = {
14
+ 'greeting': ['hello', 'hi', 'hey', 'howdy'],
15
+ 'goodbye': ['bye', 'goodbye', 'see you', 'take care'],
16
+ 'weather': ['weather', 'rain', 'sunny', 'forecast'],
17
+ 'name': ['what is your name', 'who are you'],
18
+ 'age': ['how old are you', 'what is your age'],
19
+ }
20
 
 
21
  responses = {
22
+ 'greeting': ["Hello! How can I help you today?", "Hi there! How can I assist you?", "Hey! What's up?"],
23
+ 'goodbye': ["Goodbye! Take care!", "See you soon!", "It was nice talking to you!"],
24
+ 'weather': ["I don't have real-time weather updates, but you can check your local weather service."],
25
+ 'name': ["I'm Chatbot, your virtual assistant."],
26
+ 'age': ["I am ageless! But I was designed recently to assist you."],
27
+ 'fallback': ["Sorry, I didn't quite understand that. Could you rephrase your question?"]
 
 
 
 
28
  }
29
 
30
+ # Intent classification with machine learning model
31
+ class ChatbotModel:
32
+ def __init__(self):
33
+ self.vectorizer = CountVectorizer()
34
+ self.clf = SVC(kernel='linear')
35
+ self._train()
36
+
37
+ def _train(self):
38
+ # Prepare the training data (simple intents)
39
+ X = []
40
+ y = []
41
+ for intent, patterns in intents.items():
42
+ for pattern in patterns:
43
+ X.append(pattern)
44
+ y.append(intent)
45
+ X = self.vectorizer.fit_transform(X)
46
+ self.clf.fit(X, y)
47
+
48
+ def predict(self, user_input):
49
+ # Preprocess user input and predict intent
50
+ X_test = self.vectorizer.transform([user_input])
51
+ return self.clf.predict(X_test)[0]
52
+
53
+ # Initialize model
54
+ model = ChatbotModel()
55
+
56
+ # Load Hugging Face pre-trained model for question answering
57
+ qa_pipeline = pipeline('question-answering')
58
 
59
+ # Streamlit UI Setup
60
+ st.title("Advanced Chatbot")
61
+ st.markdown("I am an advanced chatbot. Ask me about weather, my name, or other topics.")
62
 
63
+ # Collect user input
64
  if 'history' not in st.session_state:
65
  st.session_state['history'] = []
66
 
67
  # Collect user input
68
  user_input = st.text_input("You: ")
69
 
 
70
  if user_input:
71
  # Add user message to history
72
  st.session_state['history'].append(f"You: {user_input}")
73
+
74
+ # Predict intent using the model
75
+ intent = model.predict(user_input.lower())
76
+
77
+ if intent == 'greeting':
78
+ bot_response = random.choice(responses['greeting'])
79
+ elif intent == 'goodbye':
80
+ bot_response = random.choice(responses['goodbye'])
81
+ elif intent == 'weather':
82
+ bot_response = random.choice(responses['weather'])
83
+ elif intent == 'name':
84
+ bot_response = random.choice(responses['name'])
85
+ elif intent == 'age':
86
+ bot_response = random.choice(responses['age'])
87
+ else:
88
+ bot_response = random.choice(responses['fallback'])
89
+
90
+ # Handle additional QA task if needed (e.g., general knowledge questions)
91
+ if "?" in user_input:
92
+ try:
93
+ # Use Hugging Face QA pipeline
94
+ result = qa_pipeline({'context': 'I am a chatbot built with streamlit and transformers.', 'question': user_input})
95
+ bot_response = result['answer']
96
+ except Exception as e:
97
+ bot_response = "Sorry, I couldn't process that question."
98
+
99
  # Add bot's response to history
100
  st.session_state['history'].append(f"Chatbot: {bot_response}")
101
+
102
+ # Display the conversation history
103
  for message in st.session_state['history']:
104
  st.write(message)