mood-meter / app.py
Ayesha003's picture
Update app.py
fcf517f verified
import streamlit as st
from transformers import pipeline
import matplotlib.pyplot as plt
from wordcloud import WordCloud
import tweepy
import numpy as np
# Load pre-trained sentiment analysis model from Hugging Face
sentiment_model = pipeline('sentiment-analysis')
# Function to analyze sentiment
def analyze_sentiment(text):
result = sentiment_model(text)
sentiment = result[0]['label']
return sentiment
# Function to visualize sentiment-bearing words in a word cloud
def sentiment_wordcloud(text):
sentiment = analyze_sentiment(text)
# Creating a word cloud only for the input text
wordcloud = WordCloud(width=800, height=400, background_color='white').generate(text)
plt.figure(figsize=(8, 4))
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
return plt
# Function to classify sentiment and visualize sentiment distribution
def classify_and_visualize(text):
sentiment = analyze_sentiment(text)
sentiment_counts = {"Positive": 0, "Negative": 0, "Neutral": 0}
sentiment_counts[sentiment] += 1
# Pie chart visualization
fig, ax = plt.subplots(figsize=(6, 6))
ax.pie(sentiment_counts.values(), labels=sentiment_counts.keys(), autopct='%1.1f%%', startangle=90, colors=["#4CAF50", "#F44336", "#9E9E9E"])
ax.axis('equal') # Equal aspect ratio ensures pie is drawn as a circle.
return fig, sentiment
# Twitter API credentials (replace with your own credentials)
consumer_key = "YOUR_CONSUMER_KEY"
consumer_secret = "YOUR_CONSUMER_SECRET"
access_token = "YOUR_ACCESS_TOKEN"
access_token_secret = "YOUR_ACCESS_TOKEN_SECRET"
# Function to fetch live data from Twitter
def fetch_twitter_data(query):
auth = tweepy.OAuth1UserHandler(consumer_key, consumer_secret, access_token, access_token_secret)
api = tweepy.API(auth)
tweets = api.search(q=query, count=5, lang='en', tweet_mode='extended')
tweet_texts = [tweet.full_text for tweet in tweets]
return tweet_texts
# Streamlit UI
st.title("Real-Time Sentiment Analysis")
st.write("Analyze customer reviews, social media posts, or feedback in real-time. Sentiment classification (Positive/Negative/Neutral) with visualizations.")
text_input = st.text_area("Enter text or tweet for analysis")
if text_input:
sentiment_fig, sentiment = classify_and_visualize(text_input)
st.subheader(f"Sentiment: {sentiment}")
st.pyplot(sentiment_fig)
# Word Cloud
st.subheader("Sentiment-Bearing Words")
sentiment_wordcloud(text_input)
st.pyplot(plt)
# Option to fetch live data from Twitter
fetch_tweets = st.checkbox("Fetch tweets for analysis from Twitter")
if fetch_tweets:
query = st.text_input("Enter search query for Twitter")
if query:
tweets = fetch_twitter_data(query)
st.write("Live tweets fetched:")
for tweet in tweets:
st.write(tweet)