furquan commited on
Commit
0230643
·
1 Parent(s): 0969dc2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +161 -0
app.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image, ImageDraw, ImageFont
2
+ from textwrap import wrap
3
+ import requests
4
+ import numpy as np
5
+ import gradio as gr
6
+ import matplotlib.pyplot as plt
7
+ import seaborn as sns
8
+ from matplotlib.backends.backend_agg import FigureCanvasAgg
9
+ from io import BytesIO
10
+
11
+ import twitter
12
+
13
+ api = twitter.Api(consumer_key='IXpQTCB9vo9IGfOVAPBePE2Wi',
14
+ consumer_secret='qD1m4zaAiM6h2T7swBuWboORTXY4cA9eNcgDHlfFAuqKfNTiT3',
15
+ access_token_key='1529787212417605634-Io7LlY8AEdZEzOgiAYMb3hZyu9gsLL',
16
+ access_token_secret='QGo3eOn7xgPWHusmuP2JDZxkTMPJ51wtgO9wV3PY1b8wm')
17
+
18
+
19
+ def drawTweet(tweet,i):
20
+ # Set the dimensions of the image
21
+ width, height = 1000, 200
22
+
23
+ # Create a blank image with a white background
24
+ image = Image.new('RGBA', (width, height), 'white')
25
+
26
+ # Get a drawing context
27
+ draw = ImageDraw.Draw(image)
28
+
29
+ # Set the font for the tweet text
30
+ font = ImageFont.truetype('arial.ttf', size=36, encoding='utf-16')
31
+
32
+ user = tweet.user
33
+
34
+
35
+ user_tag = user.screen_name
36
+ text = tweet.text
37
+
38
+
39
+ tweet_text = text
40
+
41
+ words = tweet_text.split()
42
+ # Insert a newline character after every 10 words
43
+ formatted_string = ''
44
+ for i, word in enumerate(words):
45
+ formatted_string += word+' '
46
+ if (i + 1) % 7 == 0:
47
+ formatted_string += '\n'
48
+
49
+
50
+
51
+ draw.multiline_text( (135,50), formatted_string , fill='black' , font=font, embedded_color=True)
52
+ draw.text((135,10), f"@{user_tag}", fill='black',font=font)
53
+
54
+
55
+
56
+ response = requests.get(user.profile_image_url_https)
57
+ content = response.content
58
+
59
+ f = BytesIO(content)
60
+
61
+ avatar_size = (100, 100)
62
+ avatar_image = Image.open(f)
63
+ avatar_image = avatar_image.resize(avatar_size)
64
+ image.paste(avatar_image, (10, 10))
65
+
66
+
67
+ return image
68
+
69
+
70
+ def collect_tweets(topic):
71
+
72
+ # Search for tweets matching the query
73
+ tweets = api.GetSearch(term=f"{topic} -filter:retweets", lang='en', result_type="recent", count=100)
74
+
75
+ # Filter out retweets
76
+
77
+ tweets.sort(key=lambda tweet: tweet.favorite_count + tweet.retweet_count, reverse=True)
78
+
79
+ images = []
80
+ i = 1
81
+ for tweet in tweets:
82
+ img = drawTweet(tweet,i)
83
+ images.append(img)
84
+
85
+ sentiment_plot = sentiment_analysis(tweets,topic)
86
+
87
+ return images,sentiment_plot
88
+
89
+ def sentiment_analysis(tweets,topic):
90
+
91
+ tweet_procs = []
92
+ for tweet in tweets:
93
+ tweet_words = []
94
+ for word in tweet.text.split(' '):
95
+ if word.startswith('@') and len(word) > 1:
96
+ word = '@user'
97
+ elif word.startswith('https'):
98
+ word = "http"
99
+ tweet_words.append(word)
100
+ tweet_proc = " ".join(tweet_words)
101
+ tweet_procs.append(tweet_proc)
102
+
103
+
104
+ API_URL = "https://api-inference.huggingface.co/models/cardiffnlp/twitter-roberta-base-sentiment"
105
+ headers = {"Authorization": "Bearer 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"}
106
+
107
+ def query(payload):
108
+ response = requests.post(API_URL, headers=headers, json=payload)
109
+ return response.json()
110
+
111
+ model_input = {
112
+ "inputs": [tweet_procs[0]]
113
+ }
114
+
115
+ for i in range(1,len(tweets)):
116
+ model_input["inputs"].append(tweet_procs[i])
117
+
118
+ output = query({
119
+ "inputs": model_input["inputs"]})
120
+
121
+ negative = 0
122
+ neutral = 0
123
+ positive = 0
124
+
125
+ for score in output:
126
+ neg = 0
127
+ neu = 0
128
+ pos = 0
129
+ for labels in score:
130
+ if labels['label'] == 'LABEL_0':
131
+ neg += labels['score']
132
+ elif labels['label'] == 'LABEL_1':
133
+ neu += labels['score']
134
+ elif labels['label'] == 'LABEL_2':
135
+ pos += labels['score']
136
+ sentiment = max(neg,neu,pos)
137
+ if neg == sentiment:
138
+ negative += 1
139
+ elif neu == sentiment:
140
+ neutral += 1
141
+ elif pos == sentiment:
142
+ positive += 1
143
+
144
+
145
+ sns.barplot(x=["Negative Sentiment", "Neutral Sentiment", "Positive Sentiment"], y = [negative,neutral,positive])
146
+ plt.title(f"Sentiment Analysis on Twitter regarding {topic}")
147
+ canvas = FigureCanvasAgg(plt.gcf())
148
+ canvas.draw()
149
+ plot = np.array(canvas.buffer_rgba())
150
+ return plot
151
+
152
+
153
+
154
+
155
+ # Create the Gradio app
156
+ 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")])
157
+
158
+ # Run the app
159
+ app.launch()
160
+
161
+