-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapplication.py
265 lines (246 loc) · 8.29 KB
/
application.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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
#!flask/bin/python
from flask import Flask, jsonify
from flask import request
from aylienapiclient import textapi
from flask import abort
from time import sleep
from credentials import AWS_ID, AWS_REGION, AWS_SECRET_KEY, QUEUE_NAME,APP_ID,APP_KEY
from requests_aws4auth import AWS4Auth
import json
import requests
from elasticsearch import Elasticsearch, RequestsHttpConnection
from operator import itemgetter
client = textapi.Client(APP_ID,APP_KEY)
application = Flask(__name__)
awsauth = AWS4Auth(AWS_ID, AWS_SECRET_KEY,'us-west-2','es')
host = "search-jask-tweetmap-hhk4izgywmbpwob2zah4fcdiry.us-west-2.es.amazonaws.com"
es = Elasticsearch(
hosts=[{'host': host, 'port': 443}],
use_ssl=True,
http_auth=awsauth,
verify_certs=True,
connection_class=RequestsHttpConnection
)
print(es.info())
@application.route("/")
def hello():
return "Hello World!"
def init_moderator_table():
users = dict()
handles = ['kartikeya','aashima56584982']
for h in handles:
try:
"""
res = es.search(index='moderators', doc_type="twitter", body={
"query": {
"term": {
handle : h
}
}
})
if res['hits']['total'] == 0:
"""
data = {
'handle': h,
'weight': 10
}
es.index(index='moderators', doc_type='twitter', body=data)
except Exception as e:
print('Elasticsearch indexing failed')
print(e)
@application.route('/flaskhw/checkFake',methods=['POST'])
def checkFake():
tweetids = request.form.get('query')
id_list = tweetids.strip().split(',')
tweet_csv = ""
for val in id_list:
#Run elastic search in malicious
res = es.search(index="malicious_tweets", doc_type="twitter", body={
"query": {
"term": {
"tweet_id": val
}
}
})
if res['hits']['total'] > 0:
tweet_csv += str(val) + ","
return tweet_csv
@application.route('/flaskhw/updateWeights',methods=['POST'])
def updateTweetWeights():
content = request.get_json(silent=True)
user_id = content['user_id']
tweet_id= content['tweet_id']
print tweet_id
print user_id
#check if user id exists in moderator table
moderator_res=es.count(index="moderator", doc_type="twitter", body={
"query": {
"term": {
"handle": user_id
}
}
})
if(moderator_res['count']>1):
weight=10
else:
weight=1
#Write Update Query here(update with weight), if query does not exixts then create
#get current count and incr count
tweet_weight=es.search(index="malicious_tweets", doc_type="twitter", body={
"query": {
"term": {
"tweet_id": tweet_id
}
}
})
if(tweet_weight['hits']['total']>1): #if query exists in Elastic Search then update by using index id
index_id= [d['_id'] for d in tweet_weight['hits']['hits']]
print index_id[0]
source = [d['_source'] for d in tweet_weight['hits']['hits']]
old_weight = [d['weight'] for d in source]
new_weight = old_weight[0] + weight
#update weigth
es.update(index='malicious_tweets', doc_type='twitter', id=str(index_id[0]), body={
'doc': {
'weight': new_weight
}
})
else: #tweet does not exist hence create new
data = {
'tweet_id': tweet_id,
'count': 1,
'weight': weight
}
try:
es.index(index="malicious_tweets", doc_type="twitter", body=data)
except Exception as e:
print('Elasticserch indexing failed')
print(e)
return "UPDATION DONE"
@application.route('/flaskhw/visualize', methods=['POST'])
def visualize():
tweet = request.form.get('query')
print tweet
ent = []
#Extract Entities
entities = client.Entities({"text": tweet})
for type,values in entities['entities'].iteritems():
if(type == 'keyword'):
ent = values[1:]
print ent
sent_list = list()
for term in ent:
res_pos = es.count(index="cloud_index", doc_type="twitter", body={
"query": {
"bool": {
"must": [
{ "match": { "content": term }},
{ "match": { "sentiment": "positive"}}
]
}
}
}
)
res_neg = es.count(index="cloud_index", doc_type="twitter", body={
"query": {
"bool": {
"must": [
{ "match": { "content": term }},
{ "match": { "sentiment": "negative"}}
]
}
}
}
)
res_neutral = es.count(index="cloud_index", doc_type="twitter", body={
"query": {
"bool": {
"must": [
{ "match": { "content": term }},
{ "match": { "sentiment": "neutral"}}
]
}
}
}
)
city_counts = es.search(index="cloud_index", doc_type="twitter", body={
"query": {
"bool": {
"should": [
{ "match": { "content": term }},
]
}
},
"size": 0,
"aggs" : {
"city_counts" : {
"terms" : { "field" : "city" }
}
}
}
)
cities=[]
cities = [ d['key'] for d in city_counts['aggregations']['city_counts']['buckets']]
d = dict()
d['entity'] = term
d['pos'] = res_pos['count']
d['neg'] = res_neg['count']
d['neutral'] = res_neutral['count']
city_list = ""
count = 0
for i in range(len(cities)):
if count < 3:
city_list += cities[i] + ", "
count = count + 1
else:
break
city_list = city_list[:-2]
d['cities'] = city_list
sent_list.append(d)
print sent_list
return jsonify(sent_list)
#return render_template(request, "polls/maps.html", {'plot':sent_List})
@application.route('/flaskhw/hashtag', methods=['POST'])
def process_tweet():
#poll for new notifs every second
tweet = request.form.get('query')
print tweet
#do something with the tweet
hashtags = client.Hashtags({"text": tweet})
tags = ','.join(hashtags['hashtags'])
tags += ','
print "The hashtags are" + tags
sentiment = client.Sentiment({"text": tweet})
ent=[]
#Extract Entities
entities = client.Entities({"text": tweet})
for type,values in entities['entities'].iteritems():
if(type == 'keyword'):
ent = values[1:3]
print ent
d = {}
for term in ent:
related = client.Related({"phrase":term})
for phrase in related['related']:
d[phrase['phrase']]=phrase['distance']
d = sorted(d.items(), key=itemgetter(1))
keys = ['#'+x.title().replace(" ","") for x,y in d];
keys=keys[:5]
tags += ','.join(keys)
return jsonify({"tags": tags, "sentiment" : sentiment['polarity']});
if __name__ == '__main__':
#init_moderator_table()
#application.run(debug=True)
"""
data = {
'tweet_id': '811564284706689024',
'count': 1,
'weight': 10
}
try:
es.index(index="malicious_tweets", doc_type="twitter", body=data)
except Exception as e:
print('Elasticserch indexing failed')
print(e)
"""
application.run(debug=True,host="0.0.0.0")