-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
163 lines (135 loc) · 6.11 KB
/
app.py
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
from flask import Flask, render_template, url_for, request
import pickle
import numpy as np
import re
from sklearn.feature_extraction.text import TfidfVectorizer
import pandas as pd
import tweepy
from tweepy import OAuthHandler
app = Flask(__name__)
@app.route('/result')
@app.route('/home')
@app.route('/')
def home():
return render_template('index.html')
@app.route('/predict', methods=['POST'])
def predict():
class TwitterClient(object):
def __init__(self):
try:
auth = OAuthHandler('Pf5UlAhL1pncyLfAJPBAYArts', 'jnJf9g5ppiR9dj8yTjrO49MU7DYkgUGiZYBCq3dfXvHBvzAqvI')
auth.set_access_token('1381975250603106307-x8bx6x79VQ9OqV0GriYfNAFMtnWsuQ', 'aLOJ4PgMXXHIK2fj0rvx2RlyifZfUqDcEoTaFvT998T3r')
self.api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
except tweepy.TweepError as e:
print(f"Error: Tweeter Authentication Failed - \n{str(e)}")
def get_tweets(self, query, maxTweets=1000):
tweets = []
sinceId = None
max_id = -1
tweetCount = 0
tweetsPerQry = 100
while tweetCount < maxTweets:
try:
if (max_id <= 0):
if (not sinceId):
new_tweets = self.api.search(q=query, count=tweetsPerQry, tweet_mode='extended', lang="en")
else:
new_tweets = self.api.search(q=query, count=tweetsPerQry,
since_id=sinceId, tweet_mode='extended', lang="en")
else:
if (not sinceId):
new_tweets = self.api.search(q=query, count=tweetsPerQry,
max_id=str(max_id - 1), tweet_mode='extended', lang="en")
else:
new_tweets = self.api.search(q=query, count=tweetsPerQry,
max_id=str(max_id - 1),
since_id=sinceId, tweet_mode='extended', lang="en")
if not new_tweets:
print("No more tweets found")
break
for tweet in new_tweets:
parsed_tweet = {}
parsed_tweet['tweets'] = tweet.full_text
if tweet.retweet_count > 0:
if parsed_tweet not in tweets:
tweets.append(parsed_tweet)
else:
tweets.append(parsed_tweet)
tweetCount += len(new_tweets)
print("Downloaded {0} tweets".format(tweetCount))
max_id = new_tweets[-1].id
except tweepy.TweepError as e:
print("Tweepy error : " + str(e))
break
return pd.DataFrame(tweets)
def remove_pattern(input_txt, pattern):
r = re.findall(pattern, input_txt)
for i in r:
input_txt = re.sub(i, '', input_txt)
return input_txt
def clean_tweets(lst):
lst = np.vectorize(remove_pattern)(lst, "RT @[\w]*:")
lst = np.vectorize(remove_pattern)(lst, "@[\w]*")
lst = np.vectorize(remove_pattern)(lst, "https?://[A-Za-z0-9./]*")
return lst
def con1(sentence):
emotion_list = []
sentence = sentence.split(' ')
with open('emotions.txt', 'r') as file:
for line in file:
clear_line = line.replace("\n", '').replace(",", '').replace("'", '').strip()
word, emotion = clear_line.split(':')
if word in sentence:
emotion_list.append(emotion)
return emotion_list
d = pd.read_csv('App.csv')
x = d.iloc[:, -2].values
tv = TfidfVectorizer(max_df=0.90, min_df=2, stop_words='english', ngram_range=(1, 2), max_features=6000)
x = tv.fit_transform(x.astype('U'))
pickle_in = open("App.pickle", "rb")
classifier = pickle.load(pickle_in)
if request.method == 'POST':
comment = request.form['Tweet']
twitter_client = TwitterClient()
tweets_df = twitter_client.get_tweets(comment, maxTweets=100)
tweets_df['len'] = tweets_df["tweets"].str.len()
df1 = tweets_df[(tweets_df['len'] <= 137)]
df2 = tweets_df[(tweets_df['len'] >= 150)]
data = pd.concat([df1, df2])
data = data.sample(frac=1).reset_index(drop=True)
data['clean'] = clean_tweets(data['tweets'])
data['clean'] = data['clean'].str.replace("[^a-zA-Z ]", " ")
tweets = []
ops = []
for i, tweet in enumerate(data['clean']):
op = classifier.predict(tv.transform([tweet]).toarray())
if op == [0]:
tweets.append(data.tweets[i])
ops.append('Negative')
if op == [1]:
tweets.append(data.tweets[i])
ops.append('Neutral')
if op == [2]:
tweets.append(data.tweets[i])
ops.append('Positive')
output = dict(zip(tweets, ops))
Neucount = ops.count('Neutral')
Negcount = ops.count('Negative')
Poscount = ops.count('Positive')
emo = con1(data['clean'].sum())
h = emo.count(' happy')
s = emo.count(' sad')
a = emo.count(' angry')
l = emo.count(' loved')
pl = emo.count(' powerless')
su = emo.count(' surprise')
fl = emo.count(' fearless')
c = emo.count(' cheated')
at = emo.count(' attracted')
so = emo.count(' singled out')
ax = emo.count(' anxious')
return render_template('visualize.html', outputs=output, NU=Neucount, N=Negcount, P=Poscount, happy=h, sad=s,
angry=a, loved=l, powerless=pl, surprise=su, fearless=fl, cheated=c, attracted=at,
singledout=so, anxious=ax)
if __name__ == '__main__':
app.run(debug=True, use_reloader=False)