File size: 3,633 Bytes
9f2d6d4
1921bf3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f2d6d4
 
1921bf3
 
 
 
 
 
9f2d6d4
 
1921bf3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f2d6d4
1921bf3
 
 
9f2d6d4
1921bf3
9f2d6d4
 
 
 
 
 
 
 
 
1921bf3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f2d6d4
 
1921bf3
 
9f2d6d4
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import streamlit as st
from transformers import pipeline
import spacy
import random
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.svm import SVC

# Load Spacy model for NLP tasks
nlp = spacy.load("en_core_web_sm")

# Define training data for intent classification
intents = {
    'greeting': ['hello', 'hi', 'hey', 'howdy'],
    'goodbye': ['bye', 'goodbye', 'see you', 'take care'],
    'weather': ['weather', 'rain', 'sunny', 'forecast'],
    'name': ['what is your name', 'who are you'],
    'age': ['how old are you', 'what is your age'],
}

responses = {
    'greeting': ["Hello! How can I help you today?", "Hi there! How can I assist you?", "Hey! What's up?"],
    'goodbye': ["Goodbye! Take care!", "See you soon!", "It was nice talking to you!"],
    'weather': ["I don't have real-time weather updates, but you can check your local weather service."],
    'name': ["I'm Chatbot, your virtual assistant."],
    'age': ["I am ageless! But I was designed recently to assist you."],
    'fallback': ["Sorry, I didn't quite understand that. Could you rephrase your question?"]
}

# Intent classification with machine learning model
class ChatbotModel:
    def __init__(self):
        self.vectorizer = CountVectorizer()
        self.clf = SVC(kernel='linear')
        self._train()

    def _train(self):
        # Prepare the training data (simple intents)
        X = []
        y = []
        for intent, patterns in intents.items():
            for pattern in patterns:
                X.append(pattern)
                y.append(intent)
        X = self.vectorizer.fit_transform(X)
        self.clf.fit(X, y)

    def predict(self, user_input):
        # Preprocess user input and predict intent
        X_test = self.vectorizer.transform([user_input])
        return self.clf.predict(X_test)[0]

# Initialize model
model = ChatbotModel()

# Load Hugging Face pre-trained model for question answering
qa_pipeline = pipeline('question-answering')

# Streamlit UI Setup
st.title("Advanced Chatbot")
st.markdown("I am an advanced chatbot. Ask me about weather, my name, or other topics.")

# Collect user input
if 'history' not in st.session_state:
    st.session_state['history'] = []

# Collect user input
user_input = st.text_input("You: ")

if user_input:
    # Add user message to history
    st.session_state['history'].append(f"You: {user_input}")

    # Predict intent using the model
    intent = model.predict(user_input.lower())

    if intent == 'greeting':
        bot_response = random.choice(responses['greeting'])
    elif intent == 'goodbye':
        bot_response = random.choice(responses['goodbye'])
    elif intent == 'weather':
        bot_response = random.choice(responses['weather'])
    elif intent == 'name':
        bot_response = random.choice(responses['name'])
    elif intent == 'age':
        bot_response = random.choice(responses['age'])
    else:
        bot_response = random.choice(responses['fallback'])

    # Handle additional QA task if needed (e.g., general knowledge questions)
    if "?" in user_input:
        try:
            # Use Hugging Face QA pipeline
            result = qa_pipeline({'context': 'I am a chatbot built with streamlit and transformers.', 'question': user_input})
            bot_response = result['answer']
        except Exception as e:
            bot_response = "Sorry, I couldn't process that question."

    # Add bot's response to history
    st.session_state['history'].append(f"Chatbot: {bot_response}")

# Display the conversation history
for message in st.session_state['history']:
    st.write(message)