Spaces:
Build error

AI-Chatbot / app.py
Talha1218's picture
Update app.py
81bf74c verified
Raw History Blame Contribute Delete
3.92 kB
import streamlit as st
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
import torch
import emoji
# Load the pre-trained chatbot model and tokenizer
tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-medium")
# Load the sentiment analysis pipeline
sentiment_analyzer = pipeline("sentiment-analysis")
# Function to get the chatbot's response
def get_response(user_input, history):
new_user_input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors='pt')
bot_input_ids = torch.cat([history, new_user_input_ids], dim=-1) if history is not None else new_user_input_ids
chat_history_ids = model.generate(bot_input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id)
bot_output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
return bot_output, chat_history_ids
# Function to process speech input (for local environment only)
def recognize_speech():
try:
import speech_recognition as sr
recognizer = sr.Recognizer()
with sr.Microphone() as source:
st.write("Listening...")
audio = recognizer.listen(source)
text = recognizer.recognize_google(audio)
return text
except Exception as e:
st.write(f"Speech Recognition Error: {e}")
return None
# Streamlit interface
def main():
st.title("Chatbot with Emojis, Voice Input, and Sentiment Analysis")
if 'history' not in st.session_state:
st.session_state.history = None
if st.session_state.history is not None:
conversation = tokenizer.decode(st.session_state.history[0], skip_special_tokens=True)
conversation = conversation.split(tokenizer.eos_token)
for i, message in enumerate(conversation):
if i % 2 == 0: # User's message
st.markdown(f'<div style="background-color: #E0F7FA; border-radius: 10px; padding: 8px; text-align: left;">{message.strip()}</div>', unsafe_allow_html=True)
else: # Bot's message
st.markdown(f'<div style="background-color: #FFEB3B; border-radius: 10px; padding: 8px; text-align: right;">{message.strip()}</div>', unsafe_allow_html=True)
# Option to toggle voice input
voice_input = st.checkbox("Use Voice Input (only available locally)", value=False)
if voice_input:
# Recognize voice input (only available locally)
user_input = recognize_speech()
if user_input:
st.write(f"You said: {user_input}")
else:
# Text input field
user_input = st.text_input("You: ", "", placeholder="Type a message...")
# When the user sends a message
if user_input:
# Sentiment analysis
sentiment = sentiment_analyzer(user_input)[0]
sentiment_label = sentiment['label']
sentiment_score = sentiment['score']
# Display sentiment info
st.write(f"Sentiment: {sentiment_label} ({sentiment_score:.2f})")
# Add emojis based on sentiment
if sentiment_label == 'POSITIVE':
user_input += " ๐Ÿ˜Š"
elif sentiment_label == 'NEGATIVE':
user_input += " ๐Ÿ˜ก"
else:
user_input += " ๐Ÿ˜"
# Get chatbot response
response, history = get_response(user_input, st.session_state.history)
# Update the session state with new chat history
st.session_state.history = history
# Display the chatbot's response with emojis (fixed the emojize function usage)
st.markdown(f'<div style="background-color: #FFEB3B; border-radius: 10px; padding: 8px; text-align: right;">{emoji.emojize(response)}</div>', unsafe_allow_html=True)
# Clear the input box
st.session_state.input_box = ""
# Run the app
if __name__ == '__main__':
main()