-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPI_SENTIMENT.py
More file actions
547 lines (436 loc) · 20.5 KB
/
Copy pathAPI_SENTIMENT.py
File metadata and controls
547 lines (436 loc) · 20.5 KB
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
import tornado.ioloop
import tornado.web
from json import dumps
from pymongo import MongoClient
from bson.json_util import dumps
from wordcloud import WordCloud
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from bson.code import Code
import re
import json
from os import path
import sys
reload(sys)
sys.setdefaultencoding('utf8')
# Configuracion de las caracteristicas de los servicios
class BaseHandler( tornado.web.RequestHandler ):
def set_default_headers( self ):
self.set_header( 'Access-Control-Allow-Origin', '*' )
self.set_header( 'Access-Control-Allow-Headers', 'origin, x-requested-with, content-type' )
self.set_header( 'Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS' )
# Deficion de la aplicacion REST
class Application( tornado.web.Application ):
def __init__( self ):
handlers = [
(r'/', BaseHandler ),
(r"/followers/(.*)", getFollowers),
(r"/followersAll", getFollowersAll),
(r"/general", getInfoGeneral),
(r"/generalDos", getInfoGeneralDos),
(r"/getInfoGeneralTres", getInfoGeneralTres),
(r"/getInfoGeneralCuatro", getInfoGeneralCuatro),
(r"/geo", getGeoSentiment),
(r"/getLastTweetsByAccount/(.*)", getLastTweetsByAccount),
(r"/getLastReplayByTweetID/(.*)", getLastReplayByTweetID),
(r"/getLastSentimentReplayByTweetID/(.*)", getLastSentimentReplayByTweetID),
(r"/topics", getTopics),
(r"/images/(.*)", tornado.web.StaticFileHandler, {'path': "./images"}),
(r"/cloudUser/(.*)", doCloudUser),
(r"/cloudTopic/(.*)", doCloudTopic),
(r"/getMostFrequentWordsByUser", getMostFrequentWordsByUser),
(r"/getFrequencyByTopic", getFrequencyByTopic),
(r"/getFrequencyByTopicByUsername/(.*)", getFrequencyByTopicByUsername),
(r"/getFrequencyByTopicUsedByUser/(.*)", getFrequencyByTopicUsedByUser),
(r"/getTweetsByHastag/(.*)", getTweetsByHastag),
(r"/getUsersByCityandByTopic/(.*)/(.*)", getUsersByCityandByTopic),
(r"/getUserNature/(.*)", getUserNature),
]
tornado.web.Application.__init__( self, handlers )
class getInfoGeneral(BaseHandler):
def get(self):
client = MongoClient('bigdata-mongodb-01', 27017)
db = client['Grupo10']
mine = db['tweets']
self.write(dumps(mine.aggregate([{"$group": {"_id": "$sentiment", "value": {"$sum": 1}}},
{"$project": {
"name": "$_id",
"value": 1,
"_id":0
}}])))
class getInfoGeneralDos(BaseHandler):
def get(self):
client = MongoClient('bigdata-mongodb-01', 27017)
db = client['Grupo10']
mine = db['tweets']
json = []
response_json = {}
response_json["name"] = "Tweets"
series = mine.aggregate([{'$group':{'_id':{'year':{'$year':'$tweet_date'},'month':{'$month':'$tweet_date'},'day':{'$dayOfMonth':'$tweet_date'}},'value':{'$sum':1},'name':{'$first':"$tweet_date"}}},{'$project':{'name':{'$dateToString':{'format':"%Y-%m-%d",'date':"$name"}},'value':1,'_id': 0}},
{ '$sort':
{
'name': 1
}
}])
response_json["series"] = series
json.append(response_json)
self.write(dumps(json))
class getInfoGeneralTres(BaseHandler):
def get(self):
client = MongoClient('bigdata-mongodb-01', 27017)
db = client['Grupo10']
mine = db['tweets']
personajes = ['CGurisattiNTN24', 'DanielSamperO', 'ELTIEMPO', 'elespectador', 'NoticiasCaracol', 'NoticiasRCN',
'CaracolRadio', 'BluRadioCo', 'JuanManSantos', 'ClaudiaLopez', 'German_Vargas', 'AlvaroUribeVel',
'AndresPastrana_', 'TimoFARC', 'OIZuluaga', 'A_OrdonezM', 'JSantrich_FARC', 'IvanDuque',
'mluciaramirez', 'petrogustavo', 'DeLaCalleHum', 'FARC_EPaz'];
json = []
for persona in personajes:
response_json = {}
response_json["name"] = persona
series = mine.aggregate([
{"$match": {"screen_name":persona}},
{"$group": {"_id": "$sentiment", "value": {"$sum": 1}}},
{"$project": {
"name": "$_id",
"value": 1,
"_id":0
}}])
response_json["series"] = series
json.append(response_json)
self.write(dumps(json))
class getInfoGeneralCuatro(BaseHandler):
def get(self):
client = MongoClient('bigdata-mongodb-01', 27017)
db = client['Grupo10']
mine = db['tweets']
personajes = ['CGurisattiNTN24', 'DanielSamperO', 'ELTIEMPO', 'elespectador', 'NoticiasCaracol', 'NoticiasRCN',
'CaracolRadio', 'BluRadioCo', 'JuanManSantos', 'ClaudiaLopez', 'German_Vargas', 'AlvaroUribeVel',
'AndresPastrana_', 'TimoFARC', 'OIZuluaga', 'A_OrdonezM', 'JSantrich_FARC', 'IvanDuque',
'mluciaramirez', 'petrogustavo', 'DeLaCalleHum', 'FARC_EPaz'];
json = []
for persona in personajes:
response_json = {}
response_json["name"] = persona
series = mine.aggregate([
{"$match": {"entities_mentions":persona}},
{"$group": {"_id": "$sentiment", "value": {"$sum": 1}}},
{"$project": {
"name": "$_id",
"value": 1,
"_id":0
}}])
response_json["series"] = series
json.append(response_json)
self.write(dumps(json))
class getGeoSentiment(BaseHandler):
def get(self):
client = MongoClient('bigdata-mongodb-01', 27017)
db = client['Grupo10']
mine = db['tweets']
self.write(dumps(mine.find({"tweet_location_lati" : {'$ne' : None}, }, {'screen_name':1, 'entities_mentions':1, 'entities_hashtags':1, 'text':1,'sentiment':1,'tweet_location_lati': 1,'tweet_location_long': 1, '_id':0})))
class getFollowers(BaseHandler):
def get(self, name):
client = MongoClient('bigdata-mongodb-01', 27017)
db = client['Grupo10']
mine = db['users']
json = []
response_json = {}
response_json["name"] = "Followers"
series = mine.aggregate(
[
{'$match': {'screen_name': name}},
{'$project':
{
'_id': 0, 'name': "$downloaded_date", 'value': "$followers_number"}
}
])
response_json["series"] = series
json.append(response_json)
self.write(dumps(json))
class getFollowersAll(BaseHandler):
def get(self):
personajes =['CGurisattiNTN24','DanielSamperO','ELTIEMPO','elespectador','NoticiasCaracol','NoticiasRCN','CaracolRadio','BluRadioCo','JuanManSantos','ClaudiaLopez','German_Vargas','AlvaroUribeVel','AndresPastrana_','TimoFARC','OIZuluaga','A_OrdonezM','JSantrich_FARC','IvanDuque','mluciaramirez','petrogustavo','DeLaCalleHum','FARC_EPaz'];
client = MongoClient('bigdata-mongodb-01', 27017)
db = client['Grupo10']
mine = db['users']
json = []
for person in personajes:
response_json = {}
response_json["name"] = "Seguidores de " + person
series = mine.aggregate(
[
{'$match': {'screen_name': person}},
{'$project':
{
'_id': 0, 'name': "$downloaded_date", 'value': "$followers_number"}
}
])
response_json["series"] = series
json.append(response_json)
self.write(dumps(json))
class getLastTweetsByAccount(BaseHandler):
def get(self, account):
client = MongoClient('bigdata-mongodb-01', 27017)
db = client['Grupo10']
mine = db['tweets']
self.write(dumps(mine.aggregate([{ '$match': {'screen_name': account } }, {'$lookup': { 'from': 'tweets', 'localField': '_id', 'foreignField': 'in_reply_to_status_id', 'as': 'grp' }},{'$sort': { 'tweet_date': -1 }},{ '$project': { '_id': 1, 'text': 1 }},{ '$limit': 20 }])))
class getLastReplayByTweetID(BaseHandler):
def get(self, id):
client = MongoClient('bigdata-mongodb-01', 27017)
db = client['Grupo10']
mine = db['tweets']
self.write(dumps(mine.find({ 'in_reply_to_status_id': long(float(str(id))) }, { '_id': 0, 'screen_name': 1, 'text': 1, 'sentiment': 1 })))
class getLastSentimentReplayByTweetID(BaseHandler):
def get(self, id):
client = MongoClient('bigdata-mongodb-01', 27017)
db = client['Grupo10']
mine = db['tweets']
self.write(dumps(mine.aggregate([{'$match': { 'in_reply_to_status_id': long(float(str(id))) } }, { '$group': { '_id': '$sentiment', 'count': { '$sum': 1 }}},{ '$project' : { '_id': 0, 'name': '$_id', 'value': '$count' } }])))
#EN DESARROLLO
class getTopics(BaseHandler):
def get(self):
client = MongoClient('bigdata-mongodb-01', 27017)
db = client['Grupo10']
mine = db['trends']
self.write(dumps(mine.find().limit(2)))
class doCloudUser(BaseHandler):
def get(self, name):
client = MongoClient('bigdata-mongodb-01', 27017)
db = client['Grupo10']
mine = db['tweets']
map = Code( """function()
{
var
text = this.text;
text = text.replace('.',' '); text = text.replace(',',' '); text = text.replace('(',' '); text = text.replace(')',' '); text = text.replace(':',' ');
var
wordArr = text.toLowerCase().split(' ');
var
stoppedwords = 'el, la, de, es, a, un, una, que, de, por, para, como, al, ?, !, +, y, no, los, las, en, se, lo, con, o, del, q, su, //t, https, si, mas, le, cuando, ellos, este, son, tan, esa, eso, ha, sus, e, pero, porque, tienen, d';
var
stoppedwordsobj = [];
var
uncommonArr = [];
stoppedwords = stoppedwords.split(',');
for (i = 0; i < stoppedwords.length; i++ ) {stoppedwordsobj[stoppedwords[i].trim()] = true;}
for ( i = 0; i < wordArr.length; i++ ) {word = wordArr[i].trim().toLowerCase(); if ( !stoppedwordsobj[word] ) {uncommonArr.push(word);}}
for (var i = uncommonArr.length - 1; i >= 0; i--) {if (uncommonArr[i]) {if (uncommonArr[i].startsWith("#")) {emit(uncommonArr[i], 1);}}}}""")
reduce = Code("""function( key, values ) {
var count = 0;
values.forEach(function(v) {
count +=v;
});
return count;
}""")
result = mine.map_reduce(map, reduce, "myresults", query={'entities_mentions': name})
json_result = []
for doc in result.find():
json_result.append(doc)
d = path.dirname(__file__)
col_mask = np.array(Image.open(path.join(d, "images/col.png")))
#text = "y es es es es es es es es es es es es forcing the closing of the figure window in my giant loop, so I do"
#text = open(path.join(d, 'images/red.txt')).read()
jsonCloud = json.loads(dumps(json_result))
text = ""
for item in jsonCloud:
for x in xrange(1, int(item['value']*2)):
text += " "+item['_id']
wordcloud = WordCloud(width=1000, height=800, max_font_size=1000).generate(text)
#wordcloud = WordCloud(mask=col_mask, max_font_size=1000).generate(text)
#fig = plt.figure(figsize=(4.2,6.2))
fig = plt.figure(figsize=(20,10))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
fig.savefig('images/foo.png', facecolor='k', bbox_inches='tight')
self.write(dumps(json_result))
class doCloudTopic(BaseHandler):
def get(self, topic):
client = MongoClient('bigdata-mongodb-01', 27017)
db = client['Grupo10']
mine = db['tweets']
map = Code( """function()
{var
text = this.text;
text = text.replace('.',' '); text = text.replace(',',' '); text = text.replace('(',' '); text = text.replace(')',' '); text = text.replace(':',' ');
var
wordArr = text.toLowerCase().split(' ');
var
stoppedwords = 'el, la, de, es, a, un, una, que, de, por, para, como, al, ?, !, +, y, no, los, las, en, se, lo, con, o, del, q, su, //t, https, si, mas, le, cuando, ellos, este, son, tan, esa, eso, ha, sus, e, pero, porque, tienen, d';
var
stoppedwordsobj = [];
var
uncommonArr = [];
stoppedwords = stoppedwords.split(',');
for (i = 0; i < stoppedwords.length; i++ ) {stoppedwordsobj[stoppedwords[i].trim()] = true;}
for ( i = 0; i < wordArr.length; i++ ) {word = wordArr[i].trim().toLowerCase(); if ( !stoppedwordsobj[word] ) {uncommonArr.push(word);}}
for (var i = uncommonArr.length - 1; i >= 0; i--) {if (uncommonArr[i]) {if (uncommonArr[i].startsWith("#")) {emit(uncommonArr[i], 1);}}}}""")
reduce = Code("""function( key, values ) {
var count = 0;
values.forEach(function(v) {
count +=v;
});
return count;
}""")
regx = re.compile(topic, re.IGNORECASE)
result = mine.map_reduce(map, reduce, "myresults", query={"text": regx})
json_result = []
for doc in result.find():
json_result.append(doc)
d = path.dirname(__file__)
col_mask = np.array(Image.open(path.join(d, "images/col.png")))
#text = "y es es es es es es es es es es es es forcing the closing of the figure window in my giant loop, so I do"
#text = open(path.join(d, 'images/red.txt')).read()
jsonCloud = json.loads(dumps(json_result))
text = ""
for item in jsonCloud:
for x in xrange(1, int(item['value']*2)):
text += " "+item['_id']
wordcloud = WordCloud(width=1000, height=800, max_font_size=1000).generate(text)
#wordcloud = WordCloud(mask=col_mask, max_font_size=1000).generate(text)
#fig = plt.figure(figsize=(4.2,6.2))
fig = plt.figure(figsize=(20,10))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
fig.savefig('images/foo.png', facecolor='k', bbox_inches='tight')
self.write(dumps(json_result))
class getTweetsByHastag(BaseHandler):
def get(self, hash):
client = MongoClient('bigdata-mongodb-01', 27017)
db = client['Grupo10']
mine = db['tweets']
regx = re.compile(hash, re.IGNORECASE)
val = mine.find({"entities_hashtags": regx})
self.write(dumps(val))
class getMostFrequentWordsByUser(BaseHandler):
def get(self):
client = MongoClient('bigdata-mongodb-01', 27017)
db = client['Grupo10']
mine = db['tweets']
map = Code( "function() {"
"var text = this.text;"
"if (text) { "
"text = text.toLowerCase().split(' ');"
"for (var i = text.length - 1; i >= 0; i--) {"
"if (text[i]) {"
"emit(text[i], 1);"
"}}}}")
reduce = Code("function( key, values ) {"
"var count = 0; "
"values.forEach(function(v) {"
"count +=v;"
"});"
"return count;}")
result = mine.map_reduce(map, reduce, "myresults", query={ 'screen_name': "elespectador" })
json_result = []
for doc in result.find():
doc['name'] = doc['_id']
json_result.append(doc)
self.write(dumps(json_result))
class getFrequencyByTopic(BaseHandler):
def get(self):
temas = ['Corrup', 'jep', 'farc', 'presidencial', 'paz', 'candida', 'coca', 'eln', 'narco', 'mermelada', 'justicia'];
client = MongoClient('bigdata-mongodb-01', 27017)
db = client['Grupo10']
mine = db['tweets']
json = []
for tema in temas:
regx = re.compile(tema, re.IGNORECASE)
val = mine.find({"text" : regx}).count()
response_json = {}
response_json["name"] = tema
response_json["value"] = val
json.append(response_json)
self.write(dumps(json))
class getFrequencyByTopicByUsername(BaseHandler):
def get(self, name):
temas = ['Corrup', 'jep', 'farc', 'presidencial', 'paz', 'candida', 'coca', 'eln', 'narco', 'mermelada',
'justicia'];
client = MongoClient('bigdata-mongodb-01', 27017)
db = client['Grupo10']
mine = db['tweets']
json = []
for tema in temas:
regx = re.compile(tema, re.IGNORECASE)
val = mine.find({"$and":[ {"text" :regx}, {"entities_mentions":name} ]}).count()
response_json = {}
response_json["name"] = tema
response_json["value"] = val
json.append(response_json)
self.write(dumps(json))
class getFrequencyByTopicUsedByUser(BaseHandler):
def get(self, name):
temas = ['Corrup', 'jep', 'farc', 'presidencial', 'paz', 'candida', 'coca', 'eln', 'narco', 'mermelada',
'justicia'];
client = MongoClient('bigdata-mongodb-01', 27017)
db = client['Grupo10']
mine = db['tweets']
json = []
otrosJ = {};
contador = 0;
for tema in temas:
response_json = {}
regx = re.compile(tema, re.IGNORECASE)
val = mine.find({"$and": [{"text": regx}, {"screen_name": name}]}).count()
contador += val
if val > 0:
response_json["name"] = tema
response_json["value"] = val
json.append(response_json)
total = mine.find({"screen_name": name}).count()
otros = total - contador
otrosJ["name"] = 'Otros temas'
otrosJ["value"] = otros
json.append(otrosJ)
self.write(dumps(json))
#EN DESARROLLO
class getFrequencyByTopicByUsernameGetHashtags(BaseHandler):
def get(self, name):
temas = ['Corrup', 'jep', 'farc', 'presidencial', 'paz', 'candida', 'coca', 'eln', 'narco', 'mermelada',
'justicia'];
client = MongoClient('bigdata-mongodb-01', 27017)
db = client['Grupo10']
mine = db['tweets']
for tema in temas:
regx = re.compile(tema, re.IGNORECASE)
val = mine.find({"$and": [{"text": regx}, {"entities_mentions": name}]}).count()
response_json = {}
response_json["name"] = tema
response_json["value"] = val
#json.append(response_json)
self.write(dumps(mine.find({"$and": [{"text": regx}, {"entities_mentions": name}]})))
class getUsersByCityandByTopic(BaseHandler):
def get(self, city, topic):
client = MongoClient('bigdata-mongodb-01', 27017)
db = client['Grupo10']
mine = db['tweets']
regxCiudad = re.compile(city, re.IGNORECASE)
regxTopic = re.compile(topic, re.IGNORECASE)
a = mine.aggregate([
{'$match': { 'text' : regxTopic }},
{'$lookup': { 'from': 'users', 'localField': 'user_id', 'foreignField': 'user_id', 'as': "users"}},
{'$unwind' : "$users"},
{'$match' : {"users.location": regxCiudad}},
{'$sort': {"tweet_date": -1}},
{'$project' : {
'screen_name' : 1,
'text': 1,
'entities_mentions': 1,
'sentiment': 1
}},
{'$limit': 50}
])
self.write(dumps(a))
class getUserNature(BaseHandler):
def get(self, user):
client = MongoClient('bigdata-mongodb-01', 27017)
db = client['Grupo10']
mine = db['users']
a = mine.find({'screen_name':'AlvaroUribeVel'},{'user_category':1}).limit(1)
self.write(dumps(a))
#Metodo main
if __name__ == "__main__":
app = Application()
app.listen(8082)
tornado.ioloop.IOLoop.current().start()