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)