-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
1616 lines (1326 loc) · 59.1 KB
/
Copy pathserver.py
File metadata and controls
1616 lines (1326 loc) · 59.1 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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding: utf-8
from preprocessing_and_stats.PreProcessor import PreProcessor
from preprocessing_and_stats.StopWords import EnglishStopWords, FrenchStopWords
from BackendLogger import BackendLogger
from classification.samplers import *
from classification.learners import *
from classification.vectorizers import *
import argparse
import json
import base64
import os
# std
from datetime import datetime
# web
from flask import Flask, render_template, request
from flask import jsonify
from flask_cors import CORS, cross_origin
from flask_frozen import Freezer
from flask import Response
from flask_htpasswd import HtPasswdAuth
from kneed import KneeLocator
from classification.active_learning import ActiveLearning
from classification.ngram_based_classifier import NgramBasedClasifier
# rest
from flask_restful import Resource, Api, reqparse
# mabed
from mabed.functions import Functions
from tobas.TobasEventDetection import TobasEventDetection
import datetime
app = Flask(__name__, static_folder='browser/static', template_folder='browser/templates')
app.config['FLASK_HTPASSWD_PATH'] = '.htpasswd'
app.config['FLASK_SECRET'] = 'Hey Hey Kids, secure me!'
app.backend_logger = BackendLogger()
# restful api
api = Api(app)
functions = Functions()
SELF = "'self'"
DownSELF = "'self'"
# here we define the content security policy,
# this CSP allows for inline script, and using a nonce will improve security
with open('config.json', 'r') as f:
config = json.load(f)
default_source = config['default']['index']
default_session = config['default']['session']
for source in config['elastic_search_sources']:
if source['index'] == default_source:
default_host = source['host']
default_port = source['port']
default_user = source['user']
default_password = source['password']
default_timeout = source['timeout']
default_index = source['index']
default_doc_type = source['doc_type']
htpasswd = HtPasswdAuth(app)
ngram_classifier = NgramBasedClasifier()
al_classifier = ActiveLearning(download_folder_name="tmp_data")
tobas = TobasEventDetection()
al_path = os.path.join(os.getcwd(), "classification", "logs", "current_al_status.json")
if not os.path.exists(os.path.dirname(al_path)):
os.makedirs(os.path.dirname(al_path))
al_backend_logger = BackendLogger(al_path)
app.loop_index = 0
# ==================================================================
# 1. Tests and Debug
# ==================================================================
# Enable CORS
# cors = CORS(app)
# app.config['CORS_HEADERS'] = 'Content-Type'
# Disable Cache
@app.after_request
def add_header(r):
r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
r.headers["Pragma"] = "no-cache"
r.headers["Expires"] = "0"
r.headers['Cache-Control'] = 'public, max-age=0'
return r
# Settings Form submit
@app.route('/settings', methods=['POST'])
# @cross_origin()
def settings():
data = request.form
return jsonify(data)
@app.route('/event_descriptions')
def event_descriptions():
event_descriptions = functions.event_descriptions("test3")
events = []
for event in event_descriptions:
start_date = datetime.strptime(event[1], "%Y-%m-%d %H:%M:%S")
end_date = datetime.strptime(event[1], "%Y-%m-%d %H:%M:%S")
obj = {
"media": {
"url": "static/images/img.jpg"
},
"start_date": {
"month": start_date.month,
"day": start_date.day,
"year": start_date.year
},
"end_date": {
"month": end_date.month,
"day": end_date.day,
"year": end_date.year
},
"text": {
"headline": event[3],
"text": "<p>" + event[4] + "</p>"
}
}
events.append(obj)
res = {
"events": events
}
return jsonify(res)
# ==================================================================
# 2. MABED
# ==================================================================
# Returns the analysis of the raw dataset
@app.route('/produce_dataset_stats', methods=['POST'])
# @cross_origin()
def produce_dataset_stats():
data = request.form
# pre_processor = PreProcessor()
# raw_tweets = read_raw_tweets_from_elastic()
# pre_processor.pre_process(
# raw_tweets,
# generate_stats=True,
# include_mentions=True,
# include_hashtags=True
# )
# stats = pre_processor.get_stats()
# print(stats)
stats = functions.get_lang_count(index=data['index'])
return jsonify({
"total_tweets": functions.get_total_tweets(index=data['index']),
"total_hashtags": functions.get_total_hashtags(index=data['index']),
"total_urls": functions.get_total_urls(index=data['index']),
"total_images": functions.get_total_images(index=data['index']),
"lang_stats":stats['aggregations']['distinct_lang']['buckets'],
"total_lang": stats['aggregations']['count']['value'],
"total_mentions": functions.get_total_mentions(index=data['index'])
})
# Get Classification stats
@app.route('/produce_classification_stats', methods=['GET','POST'])
def produce_classification_stats():
data = request.form
#get session and index name
stats = functions.get_classification_stats(index=data['index'], session_name=data['session'])
return jsonify({
"classification_stats" : stats
})
@app.route('/get_elastic_logs', methods=['POST', 'GET'])
# @cross_origin()
def get_elastic_logs():
data = request.form
return jsonify(functions.get_elastic_logs(data['index']))
# logs = jsonify(app.backend_logger.get_logs())
# app.backend_logger.clear_logs()
#return logs
@app.route('/get_backend_logs', methods=['POST', 'GET'])
# @cross_origin()
def get_backend_logs():
logs = jsonify(app.backend_logger.get_logs())
app.backend_logger.clear_logs()
return logs
# Run MABED
@app.route('/detect_events_with_tobas', methods=['POST', 'GET'])
# @cross_origin()
def detect_events_with_tobas():
data = request.form
print("Running Tobas")
res = tobas.detect_events(index=data["index"], doc_field=data["doc_field"],
max_perc_words_by_topic=float(data["max_perc_words_by_topic"]),
time_slice_length=int(data["time_slice_length"]),
logger=app.backend_logger) #docs=clean_corpus)
return jsonify(res)
# Run MABED
@app.route('/detect_events', methods=['POST', 'GET'])
# @cross_origin()
def detect_events():
data = request.form
target_index = data['index']
k = int(data['top_events'])
maf = float(data['min_absolute_frequency'])
mrf = float(data['max_relative_frequency'])
tsl = int(data['time_slice_length'])
p = float(data['p_value'])
theta = float(data['t_value'])
sigma = float(data['s_value'])
session = data['session']
filter = data['filter']
cluster = int(data['cluster'])
events=""
res = False
if filter=="all":
events = functions.event_descriptions(target_index, k, maf, mrf, tsl, p, theta, sigma, cluster, logger=app.backend_logger)
elif filter == "proposedconfirmed":
filter = ["proposed","confirmed"]
events = functions.filtered_event_descriptions(target_index, k, maf, mrf, tsl, p, theta, sigma, session, filter, cluster, logger=app.backend_logger)
else:
events = functions.filtered_event_descriptions(target_index, k, maf, mrf, tsl, p, theta, sigma, session, [filter], cluster, logger=app.backend_logger)
if not events:
events = "No Result!"
else:
res = True
return jsonify({"result": res, "events":events})
# ==================================================================
# 3. Images
# ==================================================================
# TODO replace hard coded options
# we are rendering the images of the default index
@app.route('/images')
def images():
# with open('twitter2015.json') as f:
# data = json.load(f)
# TODO make this page compatible with multiple sources
# instead of using default_source
for es_sources in config['elastic_search_sources']:
if es_sources['index'] == default_source:
images_folder = es_sources['images_folder']
with open(es_sources['image_duplicates']) as file:
data = json.load(file)
clusters_num = len(data['duplicates'])
clusters = data['duplicates']
clusters_url = []
for image_url in clusters:
clusters_url.append(images_folder + "/" + image_url[0])
return render_template('images.html',
clusters_num=clusters_num,
clusters=clusters_url
)
# ==================================================================
# 4. Tweets
# ==================================================================
# Get Tweets
@app.route('/search_for_tweets', methods=['POST'])
# @cross_origin()
def search_for_tweets():
data = request.form
last_searched_tweets = functions.get_tweets(index=data['index'], word=data['word'], session=data['session'], label=data['search_by_label'], size=int(data["individual_tweets_limit"]))
clusters = functions.get_clusters(index=data['index'], word=data['word'], session=data['session'], label=data['search_by_label'])
clusters_stats = functions.get_clusters_stats(index=data['index'], word=data['word'], session=data['session'])
return jsonify({"tweets": last_searched_tweets, "clusters": clusters, "clusters_stats": clusters_stats, "total_clusters": 0, "keywords": data['word'] })
# Get Just image clusters
@app.route('/search_for_image_clusters', methods=['POST'])
# @cross_origin()
def search_for_image_clusters():
data = request.form
image_clusters_limit = int(data.get('image_clusters_limit', '20'))
clusters = functions.get_clusters(index=data['index'], session=data['session'], label=data['search_by_label']) #, limit=data['image_clusters_limit'])
if len(clusters)>0:
filtered_clusters = clusters[0:image_clusters_limit]
clusters_stats = functions.get_clusters_stats(index=data['index'], word=data['word'], session=data['session'])
return jsonify({"clusters": clusters, "clusters_stats": clusters_stats, "keywords": data['word'], "total_clusters": len(clusters)})
# Get all tweets with coordinates
@app.route('/get_geo_coordinates', methods=['POST'])
def get_geo_coordinates():
data = request.form
index = data['index']
date_range = [data.get('date_min', None), data.get('date_max', None)]
geo,min_date,max_date,total_matching_docs = functions.get_geo_coordinates(index=index, session=data["session"], search_by_label=data["search_by_label"], word=data["word"], date_range=date_range)
result = {
"geo":geo,
"min_date":min_date,
"max_date": max_date,
"total_hits": total_matching_docs
}
return jsonify(result)
class Maps(Resource):
def get(self, index_name, session_name):
# return the tweets for the index with only the given session and in the geospatial tweets in a geoJson format
args = parser.parse_args()
startDate = args['startDate']
endDate = args['endDate']
geo,_,_ = functions.get_geo_coordinates(index=index_name)
#TODO : add parameters to the query, place, date, label and keyword
return {'geo': geo, "date": startDate, "endDate": endDate}
parser = reqparse.RequestParser()
parser.add_argument('startDate')
parser.add_argument('endDate')
parser.add_argument('endDate')
api.add_resource(Maps, '/maps/<string:index_name>/<string:session_name>', endpoint="/maps")
# Get all tweets with places
@app.route('/get_geo_places', methods=['POST'])
def get_geo_places():
data = request.form
index = data['index']
geo,min_date,max_date = functions.get_geo_places(index=index)
result = {
"geo":geo,
"min_date":min_date,
"max_date": max_date
}
return jsonify(result)
@app.route('/get_geo_polygon', methods=['POST'])
def get_geo_polygon():
data = request.get_json()
index = data['index']
features = data['collection']['features']
date_range = [data.get('date_min', None), data.get('date_max', None)]
#TODO: this checking can be done on the front
if len(features) == 0:
geo,min_date,max_date,total_matching_docs = functions.get_geo_coordinates(index=index, session=data["session"], search_by_label=data["search_by_label"], date_range=date_range)
if len(features) == 1:
if features[0]['geometry']['type'] == "Polygon":
coordinates = features[0]['geometry']['coordinates'][0]
geo,min_date,max_date,total_matching_docs = functions.get_geo_coordinates_polygon(index=index,session=data["session"], search_by_label=data["search_by_label"], word=data["word"], coordinates=coordinates, date_range=date_range)
result = {
"geo":geo,
"min_date":min_date,
"max_date": max_date,
"total_hits": total_matching_docs
}
return jsonify(result)
@app.route('/get_geo_polygon_date', methods=['POST'])
def get_geo_polygon_date():
try:
data = request.get_json()
index = data['index']
features = data['collection']['features']
date_range = [data['date_min'], data['date_max']]
#TODO: this checking can be done on the front
if len(features) == 0:
geo,min_date,max_date,total_hits = functions.get_geo_coordinates_date(index=index, session=data["session"], search_by_label=data["search_by_label"], word=data["word"], date_range=date_range)
if len(features) == 1:
if features[0]['geometry']['type'] == "Polygon":
coordinates = features[0]['geometry']['coordinates'][0]
geo,min_date,max_date,total_hits = functions.get_geo_coordinates_polygon_date_range(index=index, session=data["session"], word=data["word"], search_by_label=data["search_by_label"], coordinates=coordinates, date_range = date_range)
result = {
"geo":geo,
"min_date":min_date,
"max_date": max_date,
"total_hits": total_hits
}
return jsonify(result)
except Exception as e: # This is the correct syntax
print(e)
return {
"geo":[],
"min_date":None,
"max_date": None,
"total_hits": 0
}
# Get Tweets
@app.route('/get_image_folder', methods=['POST'])
# @cross_origin()
def get_image_folder():
data = request.form
folder_name = functions.get_image_folder(data["index"])
return folder_name
# Get Tweets
@app.route('/get_dataset_date_range', methods=['POST'])
# @cross_origin()
def get_dataset_date_range():
data = request.form
range = functions.get_dataset_date_range(index=data["index"])
return jsonify(range)
# Get Tweets
@app.route('/search_bigrams_related_tweets', methods=['POST'])
# @cross_origin()
def search_bigrams_related_tweets():
data = request.form
word = (request.form.get('word', '')).strip()
full_search = len(word) == 0
propName = data["n-grams-to-generate"] + "grams"
matching_tweets = ngram_classifier.search_bigrams_related_tweets(index=data['index'], word=word, session=data['session'],
label=data['search_by_label'], ngram=data['ngram'],
ngramsPropName=propName, full_search=full_search)
return jsonify({"tweets": matching_tweets})
# Get Tweets
@app.route('/ngrams_with_higher_ocurrence', methods=['POST'])
# @cross_origin()
def ngrams_with_higher_ocurrence():
data = request.form
word = (request.form.get('word', '')).strip()
full_search = len(word) == 0
matching_ngrams = ngram_classifier.get_ngrams(index=data['index'], word=data['word'], session=data['session'],
label=data['search_by_label'], results_size=data['top-bubbles-to-display'],
n_size=data['n-grams-to-generate'], full_search=full_search)
return jsonify({
"total_matching_tweets": matching_ngrams['hits']['total'],
"ngrams": matching_ngrams['aggregations']['ngrams_count']['buckets'],
"classiffication": ngram_classifier.get_classification_data(index=data['index'], word=data['word'],
session=data['session'],
label=data['search_by_label'], matching_ngrams=matching_ngrams, full_search=full_search)
})
@app.route('/get_tweets_frequency', methods=['POST', 'GET'])
# @cross_origin()
def get_tweets_frequency():
data = request.form
word = (request.form.get('word', '')).strip()
full_search = len(word) == 0
res = functions.get_tweets_frequency(index=data['index'], word=data['word'], session=data['session'],
label=data['search_by_label'], full_search=full_search)
return jsonify(res)
# Get Tweets
@app.route('/event_ngrams_with_higher_ocurrence', methods=['POST'])
# @cross_origin()
def event_ngrams_with_higher_ocurrence():
data = request.form
source_index = data['index']
event = json.loads(data['event'])
main_term = event['main_term'].replace(",", " ")
related_terms = event['related_terms']
target_terms = functions.get_retated_terms(main_term, related_terms)
results_size = request.form.get('top-bubbles-to-display', 20)
n_size = request.form.get('n-grams-to-generate', '2')
matching_ngrams = ngram_classifier.get_ngrams_for_event(index=data['index'], session=data['session'],
label=data['search_by_label'], results_size=results_size,
n_size=n_size, target_terms=target_terms)
if(matching_ngrams and matching_ngrams['hits']):
total_hits = matching_ngrams['hits']['total']
else: total_hits = 0
if (matching_ngrams and matching_ngrams['aggregations']):
aggs = matching_ngrams['aggregations']['ngrams_count']['buckets']
else:
aggs = []
return jsonify({
"total_matching_tweets": total_hits,
"ngrams": aggs
})
# Get Tweets
@app.route('/search_event_bigrams_related_tweets', methods=['POST'])
# @cross_origin()
def search_event_bigrams_related_tweets():
data = request.form
event = json.loads(data['event'])
main_term = event['main_term'].replace(",", " ")
related_terms = event['related_terms']
target_terms = functions.get_retated_terms(main_term, related_terms)
propName = data["n-grams-to-generate"] + "grams"
matching_tweets = ngram_classifier.search_event_bigrams_related_tweets(index=data['index'], target_terms=target_terms, session=data['session'],
label=data['search_by_label'], ngram=data['ngram'],
ngramsPropName=propName)
return jsonify({"tweets": matching_tweets})
@app.route('/top_retweets', methods=['POST'])
# @cross_origin()
def top_retweets():
data = request.form
word = (request.form.get('word', '')).strip()
full_search = len(word) == 0
retweets = functions.top_retweets(index=data['index'], word=data['word'], session=data['session'],
label=data['search_by_label'], full_search=full_search, retweets_number=data['retweets_number'])
return jsonify(retweets)
# Get Tweets
@app.route('/generate_ngrams_for_index', methods=['POST'])
# @cross_origin()
def generate_ngrams_for_index():
data = request.form
#preproc = PreProcessor()
propName = data['to_property']
from_property = data['from_property']
print("Generating ngrams for index: ", data['index'])
start_time = datetime.datetime.now()
print("Starting at: ", start_time)
#preproc.putDocumentProperty(index=data['index'], prop=propName, prop_type='keyword')
res = ngram_classifier.generate_ngrams_for_index(index=data['index'], length=int(data["ngrams_length"]), prop=propName, from_property=from_property)
print("Starting at: ", start_time, " - Ending at: ", datetime.datetime.now())
return jsonify(res)
# @app.route('/generate_ngrams_for_unlabeled_tweets_on_index', methods=['POST'])
# # @cross_origin()
# def generate_ngrams_for_unlabeled_tweets_on_index():
# data = request.form
# preproc = PreProcessor()
# print(data)
# propName = data['to_property']
#
# start_time = datetime.datetime.now()
# preproc.putDocumentProperty(index=data['index'], prop=propName, prop_type='keyword')
# res = ngram_classifier.generate_ngrams_for_unlabeled_tweets_on_index(index=data['index'], length=int(data["ngrams_length"]), prop=propName)
# print("Starting at: ", start_time, " - Ending at: ", datetime.datetime.now())
# return jsonify(res)
# Get Tweets
@app.route('/get_current_backend_logs', methods=['GET'])
# @cross_origin()
def get_current_backend_logs():
last_logs = ngram_classifier.get_current_backend_logs()
# return a flag indicating when to stop asking for more logs (e.g. when the ending time is not set)
return jsonify(last_logs)
# Get Tweets
@app.route('/tweets_filter', methods=['POST'])
# @cross_origin()
def tweets_filter():
data = request.form
tweets= functions.get_tweets_query_state(index=data['index'], word=data['word'], state=data['state'], session=data['session'])
clusters= functions.get_clusters(index=data['index'], word=data['word'])
clusters_stats = functions.get_clusters_stats(index=data['index'], word=data['word'], session=data['session'])
return jsonify({"tweets": tweets, "clusters": clusters, "clusters_stats": clusters_stats})
@app.route('/tweets_scroll', methods=['POST'])
# @cross_origin()
def tweets_scroll():
data = request.form
tweets= functions.get_tweets_scroll(index=data['index'], sid=data['sid'], scroll_size=int(data['scroll_size']))
return jsonify({"tweets": tweets})
def to_boolean(str_param):
if isinstance(str_param, bool):
return str_param
elif str_param.lower() in ('yes', 'true', 't', 'y', '1'):
return True
else:
return False
@app.route('/download_al_init_data', methods=['POST'])
# @cross_origin()
def download_al_init_data():
data = request.form
download_data = to_boolean(data["download_data"])
debug_limit = to_boolean(data["debug_limit"])
al_classifier.clean_directories()
# download
if(True==download_data): #This just downloads, then add code to copy to tmp_data
al_classifier.download_data(cleaning_dirs=True, index=data["index"], session=data["session"],
gt_session=data["gt_session"], text_field=data["text_field"],
debug_limit=debug_limit, config_relative_path="")
return jsonify(True)
@app.route('/save_classification', methods=['POST'])
def save_classification():
data = request.form
al_classifier.save_classification(index=data["index"], session=data["session"]);
return jsonify(True)
@app.route('/clear_al_logs', methods=['POST'])
def clear_al_logs():
al_backend_logger.clear_logs()
app.loop_index = 0
return jsonify(True)
@app.route('/train_model', methods=['POST'])
# @cross_origin()
def train_model():
data = request.form
num_questions = int(data["num_questions"])
max_samples_to_sort = int(data["max_samples_to_sort"])
index = data["index"]
session = data["session"]
# TODO: move this to the init of the process, not at the beginning of each loop
al_classifier.remove_all_tmp_predictions_field(index=index, field=session + "_tmp")
sampling_strategy = "closer_to_hyperplane"
if (sampling_strategy == "closer_to_hyperplane"):
al_classifier.initialize(learner=LinearSVCBasedModel(), sampler=UncertaintySampler(index=index, session=session))
# Building the model and getting the questions
al_classifier.build_model(remove_stopwords=False)
questions = al_classifier.get_samples(num_questions)
return jsonify({"questions": questions, "scores": []})
@app.route('/save_user_answers', methods=['POST'])
def save_user_answers():
data = request.form
answers = json.loads(data['answers'])
al_classifier.move_answers_to_training_set(answers)
al_classifier.remove_matching_answers_from_test_set(answers)
# Certain sampling strategies have a post_sampling method that also uses the two previous methods
al_classifier.remove_tmp_predictions_field(answers=answers, index=data['index'], session=data['session'])
return jsonify(True)
@app.route('/suggest_classification', methods=['POST'])
def suggest_classification():
data = request.form
target_min_score = float(data.get('target_min_score', '0'))
target_max_score = float(data.get('target_max_score', '1'))
positives, negatives = al_classifier.get_classified_queries_ids(target_min_score=target_min_score, target_max_score=target_max_score)
al_classifier.update_tmp_predictions(positives=positives, negatives=negatives, index=data["index"], session=data["session"])
return jsonify({
"pos": ngram_classifier.get_positive_unlabeled_ngrams(index=data["index"], session=data["session"],
n_size="2", results_size=data["results_size"],
field=data['session'] + "_tmp"),
"neg": ngram_classifier.get_negative_unlabeled_ngrams(index=data["index"], session=data["session"],
n_size="2", results_size=data["results_size"],
field=data['session'] + "_tmp"),
"total_pos": len(positives), # functions.get_total_tweets_by_ids(index=data["index"], session=data["session"], ids=positives), # could this be replaced by len(positives)???
"total_neg": len(negatives) # functions.get_total_tweets_by_ids(index=data["index"], session=data["session"], ids=negatives)
})
@app.route('/get_tweets_by_str_ids', methods=['POST'])
def get_tweets_by_str_ids():
data = request.form
return jsonify(functions.get_tweets_by_str_ids(index=data['index'], id_strs=data["id_strs"]))
@app.route('/get_results_from_al_logs', methods=['POST'])
def get_results_from_al_logs():
data = request.form
hyp_results = []
#session_files = [f for f in os.scandir(os.path.dirname(al_path)) if not f.is_dir()] # and "_OUR_" in f.name]
logs = al_classifier.read_file(al_path) # session_files[0].path)
loops_values, accuracies, precision = al_classifier.process_results(logs)
hyp_results.append({"loops": loops_values, "accuracies": accuracies, "precisions": precision})
return jsonify(hyp_results) # classifier.get_results_from_al_logs())
@app.route('/most_frequent_n_grams', methods=['POST'])
def most_frequent_n_grams():
data = request.form
if data['top_ngrams_to_retrieve'] == '0':
top_ngrams_to_retrieve = None
else:
top_ngrams_to_retrieve = int(data['top_ngrams_to_retrieve'])
stemming = data['stemming'].lower() in ("yes", "true", "t", "1")
remove_stopwords = data['remove_stopwords'].lower() in ("yes", "true", "t", "1")
n_grams = ngram_classifier.most_frequent_n_grams(data['tweet_texts'], int(data['length']), top_ngrams_to_retrieve, remove_stopwords, stemming)
return jsonify(n_grams)
@app.route('/most_frequent_ngrams_in_quadrant', methods=['POST'])
def most_frequent_ngrams_in_quadrant():
data = request.form
quadrant = data["quadrant"] # low-pos high-pos low-neg high-neg
n_grams = []
ids = ["674200892065845249", "673977216393416704", "674163320639913984", "674023070017933312", "674139694154842112", "673996047534841856"]
matching_ngrams = ngram_classifier.get_ngrams(index=data['index'], word=data['word'], session=data['session'],
label=data['search_by_label'],
results_size=data['top-bubbles-to-display'],
n_size=data['n-grams-to-generate'])
return jsonify({
"total_matching_tweets": matching_ngrams['hits']['total'],
"ngrams": matching_ngrams['aggregations']['ngrams_count']['buckets'],
"classiffication": ngram_classifier.get_classification_data(index=data['index'], word=data['word'],
session=data['session'],
label=data['search_by_label'],
matching_ngrams=matching_ngrams)
})
return jsonify(n_grams)
@app.route('/n_grams_classification', methods=['POST'])
def n_grams_classification():
data = request.form
if data['top_ngrams_to_retrieve'] == '0':
top_ngrams_to_retrieve = None
else:
top_ngrams_to_retrieve = int(data['top_ngrams_to_retrieve'])
stemming = data['stemming'].lower() in ("yes", "true", "t", "1")
remove_stopwords = data['remove_stopwords'].lower() in ("yes", "true", "t", "1")
searchClassifier = NgramBasedClasifier()
n_grams = searchClassifier.most_frequent_n_grams(data['tweet_texts'], int(data['length']), top_ngrams_to_retrieve, remove_stopwords, stemming)
return jsonify(n_grams)
# Get Event related tweets
@app.route('/event_tweets', methods=['POST'])
# @cross_origin()
def event_tweets():
data = request.form
source_index = data['index']
session = data['session']
event = json.loads(data['obj'])
main_term = event['main_term'].replace(",", " ")
related_terms = event['related_terms']
tweets = functions.get_event_tweets(source_index, main_term, related_terms)
clusters = functions.get_event_clusters(source_index, main_term, related_terms)
clusters_stats = functions.get_event_image_clusters_stats(source_index, main_term, related_terms, session)
return jsonify({"tweets": tweets, "clusters": clusters, "clusters_stats": clusters_stats})
# Get Event related tweets
@app.route('/event_image_cluster_stats', methods=['POST'])
# @cross_origin()
def event_image_cluster_stats():
data = request.form
source_index = data['index']
session = data['session']
cluster_id = data['cid']
clusters_stats = functions.get_single_event_image_cluster_stats(source_index, session, cluster_id)
return jsonify(clusters_stats)
# Get Event related tweets
@app.route('/massive_tag_event_tweets', methods=['POST'])
# @cross_origin()
def massive_tag_event_tweets():
data = request.form
event = json.loads(data['event'])
main_term = event['main_term'].replace(",", " ")
related_terms = event['related_terms']
res = functions.massive_tag_event_tweets(index=data['index'], session=data['session'], labeling_class=data['labeling_class'], main_term=main_term, related_terms=related_terms)
return jsonify(res)
# Get Event related tweets
@app.route('/event_filter_tweets', methods=['POST'])
def event_filter_tweets():
data = request.form
source_index = data['index']
state = data['state']
session = data['session']
event = json.loads(data['obj'])
main_term = event['main_term'].replace(",", " ")
related_terms = event['related_terms']
tweets = functions.get_event_filter_tweets(source_index, main_term, related_terms, state, session)
clusters = functions.get_event_clusters(source_index, main_term, related_terms)
clusters_stats = functions.get_event_image_clusters_stats(source_index, main_term, related_terms, session)
return jsonify({"tweets": tweets, "clusters": clusters, "clusters_stats": clusters_stats})
@app.route('/tweets_state', methods=['POST'])
# @cross_origin()
def tweets_state():
data = request.form
tweets= functions.get_tweets_state(index=data['index'], session=data['session'], state=data['state'])
return jsonify({"tweets": tweets})
# Get Image Cluster tweets
@app.route('/cluster_tweets', methods=['POST', 'GET'])
# @cross_origin()
def cluster_tweets():
data = request.form
index = data['index']
cid = data['cid']
event = json.loads(data['obj'])
main_term = event['main_term'].replace(",", " ")
related_terms = event['related_terms']
tres = functions.get_event_tweets2(index, main_term, related_terms, cid)
event_tweets = tres
res = functions.get_cluster_tweets(index, cid)
tweets = res['hits']['hits']
tweets = {"results":tweets}
return jsonify({"tweets": tweets, "event_tweets": event_tweets})
# Get Search Image Cluster tweets
@app.route('/cluster_search_tweets', methods=['POST', 'GET'])
# @cross_origin()
def cluster_search_tweets():
data = request.form
index = data['index']
cid = data['cid']
word = data['word']
search_tweets = functions.get_big_tweets(index=index, word=word)
res = functions.get_cluster_tweets(index, cid)
tweets = res['hits']['hits']
tweets = {"results": tweets}
return jsonify({"tweets": tweets, "search_tweets": search_tweets})
# Get Event main image
@app.route('/event_image', methods=['POST'])
# @cross_origin()
def event_image():
data = request.form
index = data['index']
s_name = data['s_name']
event = json.loads(data['obj'])
main_term = event['main_term'].replace(",", " ")
related_terms = event['related_terms']
image = functions.get_event_image(index, main_term, related_terms, s_name)
res = False
if image:
try:
image = image['hits']['hits'][0]['_source']
except IndexError as ie:
print("query:",data)
print("image:",image)
res = True
return jsonify({"result":res, "image": image})
@app.route('/geo_selection_to_state', methods=['POST'])
def geo_selection_to_state():
data = request.form
index = data["index"]
session = data["session"]
state = data["state"]
docs_ids = data["docs_ids"].split(",")
res = functions.geo_selection_to_state(index=index, session=session, state=state, docs_ids=docs_ids)
return jsonify(res)
@app.route('/clear_session_annotations', methods=['POST'])
def clear_session_annotations():
data = request.form
index = data["index"]
session = data["session"]
res = functions.clear_session_annotations(index=index, session=session)
return jsonify(res)
@app.route('/all_events_images', methods=['POST'])
# @cross_origin()
def all_events_images():
data = request.form
index = data['index']
s_name = data['s_name']
events = json.loads(data['events'])
images_by_event = []
for event in events:
main_term = event['main_term'].replace(",", " ")
related_terms = event['related_terms']
image = functions.get_event_image(index, main_term, related_terms, s_name)
# image_src is the url of the original tweet media. Not the one we retrieved.
# image_path is the path to the image we retrieved.
if image and len(image['hits']['hits'])>0:
image_src = image['hits']['hits'][0]['_source']['extended_entities']['media'][0]["media_url"]
image_id = image['hits']['hits'][0]['_source']['id_str'] + "_0"
image_subfolder = data["imagesPath"]+"/"
else:
image_src = "static/images/img.jpg"
image_id = "img"
image_subfolder = ""
images_by_event.append({"cid": event["cid"], "image_id": image_id, "image_src": image_src, "image_subfolder": image_subfolder})
return jsonify(images_by_event)
# TODO replace hard coded options
# Test & Debug
@app.route('/mark_valid', methods=['POST', 'GET'])
# @cross_origin()
def mark_valid():
data = request.form
res = functions.set_all_status(default_source, default_session, "proposed")
return jsonify(res)
@app.route('/mark_event', methods=['POST', 'GET'])
# @cross_origin()
def mark_event():
data = request.form
index = data['index']
session = data['session']
functions.set_status(index, session, data)
return jsonify(data)
@app.route('/mark_cluster', methods=['POST', 'GET'])
# @cross_origin()
def mark_cluster():
data = request.form
index = data['index']
session = data['session']
cid = data['cid']
state = data['state']
res = functions.set_cluster_state(index, session, cid, state)
return jsonify(res)
@app.route('/mark_tweet', methods=['POST', 'GET'])
# @cross_origin()
def mark_tweet():
data = request.form
index = data['index']
session = data['session']
tid = data['tid']
val = data['val']
functions.set_tweet_state(index, session, tid, val)
return jsonify(data)
@app.route('/mark_retweets', methods=['POST', 'GET'])
# @cross_origin()
def mark_retweets():
data = request.form
res = functions.set_retweets_state(index=data['index'], session=data['session'], tag=data['tag'], text=data['text'])
return jsonify(res)
@app.route('/mark_bigram_tweets', methods=['POST', 'GET'])
# @cross_origin()
def mark_bigram_tweets():
data = request.form
propName=data["n-grams-to-generate"] + "grams"
word = (request.form.get('word', '')).strip()
full_search = len(word) == 0
res = ngram_classifier.update_tweets_state_by_ngram(index=data['index'], word=word, session=data['session'],
query_label=data['query_label'], new_label=data['new_label'],
ngram=data['ngram'], ngramsPropName=propName, full_search=full_search)
return jsonify(res)