awacke1's picture
Update app.py
1971026
raw
history blame
2.51 kB
import streamlit as st
import tweepy as tw
import pandas as pd
import matplotlib.pyplot as plt
from transformers import pipeline
import os
consumer_key = 'OCgWzDW6PaBvBeVimmGBqdAg1'
consumer_secret = 'tBKnmyg5Jfsewkpmw74gxHZbbZkGIH6Ee4rsM0lD1vFL7SrEIM'
access_token = '1449663645412065281-LNjZoEO9lxdtxPcmLtM35BRdIKYHpk'
access_token_secret = 'FL3SGsUWSzPVFnG7bNMnyh4vYK8W1SlABBNtdF7Xcbh7a'
auth = tw.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tw.API(auth, wait_on_rate_limit=True)
classifier = pipeline('sentiment-analysis')
FILE_NAME = 'query_history.csv'
HEADERS = ['Search Query', 'Number of Tweets', 'Results', 'Date']
if not os.path.isfile(FILE_NAME):
df = pd.DataFrame(columns=HEADERS)
df.to_csv(FILE_NAME, index=False)
st.set_page_config(page_title='πŸ˜ƒ Twitter Sentiment Analysis', layout='wide')
def display_history():
df = pd.read_csv(FILE_NAME)
st.dataframe(df.style.highlight_max(axis=0))
def run():
with st.form(key='Enter name'):
search_words = st.text_input('Enter a word or phrase you want to know about')
number_of_tweets = st.number_input('How many tweets do you want to see? (maximum 50)', 1, 50, 50)
submit_button = st.form_submit_button(label='Submit')
if submit_button:
unique_tweets, tweet_list, sentiment_list = set(), [], []
tweets = tw.Cursor(api.search_tweets, q=search_words, lang="en").items(number_of_tweets)
for tweet in tweets:
if tweet.text not in unique_tweets:
unique_tweets.add(tweet.text)
tweet_list.append(tweet.text)
p = classifier(tweet.text)
sentiment_list.append(p[0]['label'])
df = pd.DataFrame(list(zip(tweet_list, sentiment_list)), columns=['Tweets', 'Sentiment'])
st.write(df)
summary = df.groupby('Sentiment').size().reset_index(name='Counts')
fig, ax = plt.subplots()
ax.pie(summary['Counts'], labels=summary['Sentiment'], autopct='%1.1f%%', startangle=90)
ax.axis('equal')
st.pyplot(fig)
with open(FILE_NAME, mode='a', newline='') as file:
df.to_csv(file, header=False, index=False)
if st.button('Clear History'):
os.remove(FILE_NAME)
st.write('History has been cleared.')
if st.button('Display History'):
display_history()
if __name__=='__main__':
run()