File size: 5,185 Bytes
0230643
c4bec8e
0230643
 
 
 
 
 
 
4e13ed2
0230643
8ec5620
 
c4e4261
 
0230643
c4e4261
 
 
4e13ed2
 
 
 
cb991a1
d3e4b8e
c4e4261
 
 
 
 
 
 
0230643
 
 
c4e4261
0230643
 
c4e4261
0230643
 
c4e4261
0230643
 
c4e4261
9e4e74d
0230643
 
 
 
 
c4e4261
0230643
 
 
c4e4261
0230643
 
 
d3e4b8e
0230643
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e4261
a5a946f
c4e4261
 
 
0230643
 
 
 
 
 
 
 
 
 
 
 
c4e4261
 
0230643
 
 
c4e4261
0230643
 
 
 
 
 
 
 
 
 
cb991a1
0230643
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29d3eff
7c103cf
096acbf
aa835ed
b5add12
096acbf
205b3c1
7c103cf
d3e4b8e
29d3eff
9084855
0230643
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
from PIL import Image, ImageDraw, ImageFont
from textwrap import wrap
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 os



import configparser
import tweepy

config = configparser.ConfigParser()
config.read('./config.ini')

api_key = os.environ.get('api_key')
api_key_secret = os.environ.get('api_key_secret')
access_token = os.environ.get('access_token')
access_token_secret = os.environ.get('access_token_secret')
huggingFaceAuth = os.environ.get('Huggingface_Authorization')


# Authenticate with Twitter
auth = tweepy.OAuthHandler(api_key, api_key_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

tweets = []


def drawTweet(tweet,i):
    
    width, height = 1000, 200
    
    
    image = Image.new('RGBA', (width, height), 'white')

    
    draw = ImageDraw.Draw(image)

    
    font = ImageFont.truetype('SofiaSansCondensed-VariableFont_wght.ttf',  size=36, encoding='utf-16')

    user = tweet.user


    user_tag = user.screen_name
    tweet_text = tweet.full_text


    words = tweet_text.split()
    
    formatted_string = ''
    for i, word in enumerate(words):
        formatted_string += word+' '
        if (i + 1) % 10 == 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):
    

    limit=200
    tweets = tweepy.Cursor(api.search_tweets,q=f"{topic} -filter:retweets", lang="en", tweet_mode='extended', result_type = 'recent').items(limit)

    tweets = [tweet for tweet in tweets]

    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.full_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": huggingFaceAuth}

        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


with gr.Blocks() as app:
    with gr.Column():
        gr.Markdown("""
                    # Due to Twitter's restriction on free tier API access, the app will not work properly.
                    ## If you are a recuriter who would like to view a functioning version of this app, please send me a direct message.
                    """)
        topic = gr.Textbox(label="Enter a topic for tweets")
        output2 = gr.Image(label="Sentiment Analysis Result")
        output1 = gr.Gallery(label="Screenshot of Tweets", show_label=True, elem_id="gallery").style(grid=[3], height="50", width="80")
    greet_btn = gr.Button("Initiate Sentiment Analysis")
    greet_btn.click(collect_tweets, inputs=topic, outputs=[output1, output2])

app.launch()