from PIL import Image, ImageDraw, ImageFont import requests import numpy as np import gradio as gr import matplotlib.pyplot as plt import seaborn as sns from matplotlib.backends.backend_agg import FigureCanvasAgg from io import BytesIO import twitter api = twitter.Api(consumer_key='IXpQTCB9vo9IGfOVAPBePE2Wi', consumer_secret='qD1m4zaAiM6h2T7swBuWboORTXY4cA9eNcgDHlfFAuqKfNTiT3', access_token_key='1529787212417605634-Io7LlY8AEdZEzOgiAYMb3hZyu9gsLL', access_token_secret='QGo3eOn7xgPWHusmuP2JDZxkTMPJ51wtgO9wV3PY1b8wm') def drawTweet(tweet,i): # Set the dimensions of the image width, height = 1000, 200 # Create a blank image with a white background image = Image.new('RGBA', (width, height), 'white') # Get a drawing context draw = ImageDraw.Draw(image) # Set the font for the tweet text font = ImageFont.truetype('arial.ttf', size=36, encoding='utf-16') user = tweet.user user_tag = user.screen_name text = tweet.text tweet_text = text words = tweet_text.split() # Insert a newline character after every 10 words formatted_string = '' for i, word in enumerate(words): formatted_string += word+' ' if (i + 1) % 7 == 0: formatted_string += '\n' draw.multiline_text( (135,50), formatted_string , fill='black' , font=font, embedded_color=True) draw.text((135,10), f"@{user_tag}", fill='black',font=font) response = requests.get(user.profile_image_url_https) content = response.content f = BytesIO(content) avatar_size = (100, 100) avatar_image = Image.open(f) avatar_image = avatar_image.resize(avatar_size) image.paste(avatar_image, (10, 10)) return image def collect_tweets(topic): # Search for tweets matching the query tweets = api.GetSearch(term=f"{topic} -filter:retweets", lang='en', result_type="recent", count=100) # Filter out retweets tweets.sort(key=lambda tweet: tweet.favorite_count + tweet.retweet_count, reverse=True) images = [] i = 1 for tweet in tweets: img = drawTweet(tweet,i) images.append(img) sentiment_plot = sentiment_analysis(tweets,topic) return images,sentiment_plot def sentiment_analysis(tweets,topic): tweet_procs = [] for tweet in tweets: tweet_words = [] for word in tweet.text.split(' '): if word.startswith('@') and len(word) > 1: word = '@user' elif word.startswith('https'): word = "http" tweet_words.append(word) tweet_proc = " ".join(tweet_words) tweet_procs.append(tweet_proc) API_URL = "https://api-inference.huggingface.co/models/cardiffnlp/twitter-roberta-base-sentiment" headers = {"Authorization": "Bearer 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"} def query(payload): response = requests.post(API_URL, headers=headers, json=payload) return response.json() model_input = { "inputs": [tweet_procs[0]] } for i in range(1,len(tweets)): model_input["inputs"].append(tweet_procs[i]) output = query({ "inputs": model_input["inputs"]}) negative = 0 neutral = 0 positive = 0 for score in output: neg = 0 neu = 0 pos = 0 for labels in score: if labels['label'] == 'LABEL_0': neg += labels['score'] elif labels['label'] == 'LABEL_1': neu += labels['score'] elif labels['label'] == 'LABEL_2': pos += labels['score'] sentiment = max(neg,neu,pos) if neg == sentiment: negative += 1 elif neu == sentiment: neutral += 1 elif pos == sentiment: positive += 1 sns.barplot(x=["Negative Sentiment", "Neutral Sentiment", "Positive Sentiment"], y = [negative,neutral,positive]) plt.title(f"Sentiment Analysis on Twitter regarding {topic}") canvas = FigureCanvasAgg(plt.gcf()) canvas.draw() plot = np.array(canvas.buffer_rgba()) return plot # Create the Gradio app app = gr.Interface(fn=collect_tweets, inputs=gr.Textbox(label="Enter a topic for tweets"), outputs=[gr.Gallery(label="Generated images", show_label=False, elem_id="gallery").style(grid=[2], height="50"), gr.Image(label="Sentiment Analysis Result")]) # Run the app app.launch()