-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
1453 lines (1233 loc) · 47.8 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
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 -*-
"""
Created on Wed May 30 09:28:36 2018
"""
import json
from flask import Flask, jsonify, request
#from flask_swagger import swagger
from flasgger import Swagger
from flask_cors import CORS
# import requirements_preprocessing as preproc_mod
import src.requirements_segmentation as preproc_seg
import src.requirements_enrichment as preproc_enrich
import src.requirements_triplets as preproc_triplets
from src.requirements_preprocessing import formal_metrics, extract_features
from src.lemmatizer import Lemmatizer
from src.textcleaner import text_cleaner
from src.patternmatcher import pattern_matcher
from src.output_json_schema import generate_json_schema
from src.output_dbpedia import get_output_dbpedia
import tika
from tika import parser
import requests
import time
import os
import os.path
import traceback
import sys
#from IPython import embed
#from werkzeug.utils import secure_filename
app = Flask(__name__)
swagger = Swagger(app)
cors = CORS(app)
Swagger.DEFAULT_CONFIG = {
"headers": [
],
"specs": [
{
"endpoint": 'apispec_1',
"route": '/prs-improving-requirements-quality-features/apispec_1.json',
"rule_filter": lambda rule: True, # all in
"model_filter": lambda tag: True, # all in
}
],
"static_url_path": "/prs-improving-requirements-quality-features/flasgger_static",
# "static_folder": "static", # must be set by user
"swagger_ui": True,
"specs_route": "/prs-improving-requirements-quality-features/apidocs/"
}
@app.before_first_request
def load_data():
global baseAddress
#global baseAdressDBPedia
global wordFileName
global config_parameters
with open("config/config.json") as f:
config_parameters = json.load(f)
baseAddress = config_parameters["baseAddress"]
wordFileName = config_parameters["dummyInput"]["docFile"]
global fileWord
fileWord = open(wordFileName, 'w')
global verb_arguments_parser
verb_arguments_parser = preproc_triplets.EnglishPredicateArguments(config_parameters["spacyModels"]["en"])
global wordlist_list
wordlist_list = []
with open(config_parameters["dictionaries"]["avg_scores"]) as av_scores_text:
average_scores_raw = av_scores_text.read()
average_scores = average_scores_raw.split('\r\n')
wordlist_list.append(average_scores)
with open(config_parameters["dictionaries"]["sections"]) as dict_sect_text:
dict_sect_raw = dict_sect_text.read()
dict_sect = dict_sect_raw.split('\n')
wordlist_list.append(dict_sect)
print("Loading scores...")
with open(config_parameters["dictionaries"]["high_scores"]) as high_scores_text:
high_scores_raw = high_scores_text.read()
high_scores = high_scores_raw.split('\r\n')
wordlist_list.append(high_scores)
with open(config_parameters["dictionaries"]["low_scores"]) as low_scores_text:
low_scores_raw = low_scores_text.read()
low_scores = low_scores_raw.split('\r\n')
wordlist_list.append(low_scores)
global server_errors
server_errors = json.load(open(config_parameters["internals"]["errors"],'r'))
#lemmatizer
print("Loading lemmatizer...")
global lem
lem = Lemmatizer(lang='en',
fast=config_parameters['lemmatizer']['fast'],
proxy_setup=config_parameters['lemmatizer']['proxy_setup'],
chunk_size=config_parameters['lemmatizer']['chunk_size'],
service_address =config_parameters['lemmatizer']['service_address'],
stopwords_list=None,
pos_list=None)
lem.load_morphit_dict(dict_filename=config_parameters['lemmatizer']['morphit_dict'], decoder_POS_file=config_parameters['lemmatizer']['decoder_pos'])
#textcleaner
global tc
tc = text_cleaner(rm_punct = True, rm_tabs = True, rm_newline = True, rm_digits = False,
rm_hashtags = True, rm_tags = True, rm_urls = True, tolower=False,
rm_email=True, rm_html_tags = True)
###########################
##### Orchestrator #######
###########################
@app.route('/prs-improving-requirements-quality-features/uploader/<num_par>', methods = ['GET','POST'])
def upload_file_by_name(num_par):
"""
Upload a file, return enriched dict of blocks.
---
consumes:
- multipart/form-data
produces:
- application/json
parameters:
- in: formData
name: file
type: file
description: The file to upload.
required: true
- in: path
name: num_par
type: number
required: true
description: Number of paragraph
responses:
200:
description: Application run normally
schema:
type: object
properties:
content:
type: array
items:
type: object
error:
type: object
properties:
status:
type: number
code:
type: string
description:
type: string
500:
description: Internal Server Error
schema:
type: object
properties:
content:
type: object
error:
type: object
properties:
status:
type: number
code:
type: string
description:
type: string
"""
#input file
path = os.getcwd()+'/output/'
if request.method == 'POST':
try:
f = request.files['file']
head, tail = os.path.split(f.filename)
complex_name = str(time.time())+tail
f.save(path+complex_name)
except:
return json.dumps({'content': {}, 'error' : server_errors['705'] }), 500, {'Content-Type': 'application/json; charset=utf-8'}
if len(num_par)==0:
num_paragraph = config_parameters['numParsedBlocks']
else:
num_paragraph = num_par
data = {'documentName':path+complex_name, 'numParagraph': int(num_paragraph)}
output = start_process(data)
prettify_enriched_paragraphs = json.loads(output[0]).get('content')
#remove files
try:
os.remove(path+complex_name)
except OSError:
print ("Error: file txt not found")
elif request.method =='GET':
prettify_enriched_paragraphs = {}
return json.dumps({'content': prettify_enriched_paragraphs, 'error': server_errors["600"] }), 200, {'Content-Type': 'application/json; charset=utf-8'}
#return json.dumps({'content': {'enrichedParagraphs':enriched_paragraphs}, 'error': server_errors["600"] }), 200, {'Content-Type': 'application/json; charset=utf-8'}
def start_process(content = None):
"""
Get a document name, return enriched dict of blocks.
---
parameters:
- in: body
name: body
schema:
type: object
properties:
documentName:
type: string
numParagraph:
type: integer
required: true
responses:
200:
description: Application run normally
schema:
type: object
properties:
content:
type: array
items:
type: object
error:
type: object
properties:
status:
type: number
code:
type: string
description:
type: string
500:
description: Internal Server Error
schema:
type: object
properties:
content:
type: object
error:
type: object
properties:
status:
type: number
code:
type: string
description:
type: string
"""
path = os.getcwd()+'/'+ config_parameters['directories']['outputDir'] + '/'
# input json
json_input = None
if content is None:
json_input = request.get_json(force=True)
else:
json_input = content
# check validity of input json
if isinstance(json_input, dict) == False:
return json.dumps({'content': {}, 'error' : server_errors['707'] }), 500, {'Content-Type': 'application/json; charset=utf-8'}
# input documentName
file_word = json_input.get('documentName',None)
# check validity
if isinstance(file_word,basestring) == False or len(file_word)==0 :
return json.dumps({'content': {}, 'error' : server_errors['702'] }), 500, {'Content-Type': 'application/json; charset=utf-8'}
# paragraph number
num_paragraph = json_input.get('numParagraph',config_parameters['numParsedBlocks'])
# check validity
if isinstance(num_paragraph,int) == False:
return json.dumps({'content': {}, 'error' : server_errors['702'] }), 500, {'Content-Type': 'application/json; charset=utf-8'}
#although each service is available as microservices, we internally call them as function
#step 1
out_1 = convert_document(file_word)
#step 2
head, tail = os.path.split(file_word)
file_txt = path + "/"+ tail +'.txt'
data = {'numParagraph' : num_paragraph}
#files = [('file', (file_txt, open(file_txt, 'rb'), 'application/octet')),
# ('data', ('data', json.dumps(data), 'application/json'))]
#out_2 = requests.post(baseAddress + "/parsing/segmentation", files=files)
out_2 = None
#out_2 = requests.post(baseAddress + "/parsing/segmentation", files=files)
out_2 = text_segmentation(json.loads(out_1[0])["content"], data)
list_of_blocks = json.loads(out_2[0]).get('content')
#step 3
# #transform json into structured_dict:
data = {'listOfBlocks':list_of_blocks}
#out_3 = requests.post(baseAddress + '/parsing/to_dict', data=json.dumps(data))
out_3 = json_to_dict(data)
structured_dict = json.loads(out_3[0]).get('content')
# step 4
# #enrich json (technically enrich a dict obtained from json )
data = {'structuredDictList': structured_dict}
#out_4 = requests.post(baseAddress + "/parsing/enrich", data=json.dumps(data))
out_4 = enricher(data)
enriched_paragraphs = json.loads(out_4[0]).get('content')
# step 5
#prettify enched dict
data = {'enrichedDictList': enriched_paragraphs}
#out_5 = requests.post(baseAddress + "/parsing/enrich/prettify", data=json.dumps(data))
out_5 = get_output_json(data)
prettify_enriched_paragraphs = json.loads(out_5[0]).get('content')
return json.dumps({'content': prettify_enriched_paragraphs, 'error': server_errors["600"] }), 200, {'Content-Type': 'application/json; charset=utf-8'}
################################################
######## parsing and convert doc ##############
################################################
### Step 1
@app.route('/prs-improving-requirements-quality-features/parsing/conversion/doc', methods=['POST'])
def convert_document(filename = None):
"""
Parse document with tika
Get a document name, return parsed text.
---
consumes:
- multipart/form-data
produces:
- application/json
parameters:
- in: formData
name: upfile
type: file
description: The file to upload.
required: true
responses:
200:
description: Application run normally
schema:
type: object
properties:
content:
type: string
error:
type: object
properties:
status:
type: number
code:
type: string
description:
type: string
500:
description: Internal Server Error
schema:
type: object
properties:
content:
type: object
error:
type: object
properties:
status:
type: number
code:
type: string
description:
type: string
"""
path = os.getcwd()+'/'+ config_parameters['directories']['outputDir'] + '/'
if filename is None:
f = request.files['file']
f.save(path+f.filename)
#parse with tika
try:
if filename is None:
parsed = parser.from_file(path+f.filename)
else:
parsed = parser.from_file(filename)
except Exception, e:
return json.dumps({'content': 'PARSING ERROR', 'error' : server_errors['705'] }), 500, {'Content-Type': 'application/json; charset=utf-8'}
#parsed text
output = parsed["content"]
print output
#remove uploaded docx file
if filename is None:
try:
os.remove(path+f.filename)
except OSError:
print ("Error while removing temporary docx file")
#output
return json.dumps({'content':output, 'error' : server_errors['600'] }), 200, {'Content-Type': 'application/json; charset=utf-8'}
### Step 2
@app.route('/prs-improving-requirements-quality-features/parsing/segmentation', methods=['POST'])
def text_segmentation(content = None, data = None):
"""
Text Segmentation
Get a document name, return segmented text.
---
consumes:
- multipart/form-data
produces:
- application/json
parameters:
- in: formData
name: file
type: file
description: The file to upload.
required: true
- in: formData
name: numParagraph
type: object
properties:
numParagraph:
type: integer
description: Number of paragraphs
required: true
responses:
200:
description: Application run normally
schema:
type: object
properties:
content:
type: array
items:
type: object
error:
type: object
properties:
status:
type: number
code:
type: string
description:
type: string
500:
description: Internal Server Error
schema:
type: object
properties:
content:
type: object
error:
type: object
properties:
status:
type: number
code:
type: string
description:
type: string
"""
#path = os.getcwd()+'/output/'
path = os.getcwd()+'/'+ config_parameters['directories']['outputDir'] + '/'
input_json = None
num_paragraph = None
if (content == None):
f = request.files['file']
try:
param_json = request.files["data"]
f = request.files['file']
input_json = f.read()
num_paragraph = json.load(param_json)["numParagraph"]
except:
num_paragraph = config_parameters['numParsedBlocks']
else:
input_json = content
try:
num_paragraph = data.get('numParagraph')
except:
num_paragraph = config_parameters['numParsedBlocks']
#apply segmentation
#try:
paragraph_list =preproc_seg.parse([el for el in input_json.replace("\n\n", "\n").split("\n") if el != ""])
#except:
#return json.dumps({'content': {}, 'error' : server_errors['702'] }), 500, {'Content-Type': 'application/json; charset=utf-8'}
#cut list
#num_paragraph = 15
paragraph_out_list = []
if len(paragraph_list) < num_paragraph:
paragraph_out_list = paragraph_list
else:
paragraph_out_list = paragraph_list[0:num_paragraph]
#output
status = 600
error = server_errors[str(status)]
output = json.dumps({'content': paragraph_out_list, 'error' : error })
if status <700:
REST_STATUS = 200
else:
REST_STATUS = 500
return output, REST_STATUS, {'Content-Type': 'application/json; charset=utf-8'}
### Step 3
@app.route('/prs-improving-requirements-quality-features/parsing/to_dict', methods=['POST'])
def json_to_dict(content = None):
"""
From json to a structered dict.
Get a a list of blocks, return list of structered dict.
---
parameters:
- in: body
name: body
schema:
type: object
properties:
listOfBlocks:
type: array
items:
type: object
required: true
responses:
200:
description: Application run normally
schema:
type: object
properties:
content:
type: array
items:
type: object
error:
type: object
properties:
status:
type: number
code:
type: string
description:
type: string
500:
description: Internal Server Error
schema:
type: object
properties:
content:
type: object
error:
type: object
properties:
status:
type: number
code:
type: string
description:
type: string
"""
# per strutturare il file del tipo 'json_out.json' in un dizionario che terremo ed eventualmente arrichirremo
json_input = None
if content is None:
json_input = request.get_json(force=True)
else:
json_input = content
# check validity of input json
if isinstance(json_input, dict) == False:
return json.dumps({'content': {}, 'error' : server_errors['707'] }), 500, {'Content-Type': 'application/json; charset=utf-8'}
# check validity of input document
list_of_blocks = json_input.get('listOfBlocks')
if isinstance(list_of_blocks,list)==False:
return json.dumps({'content': {}, 'error' : server_errors['702'] }), 500, {'Content-Type': 'application/json; charset=utf-8'}
try:
structured_dict = preproc_enrich.json_to_structured_dict(list_of_blocks)
except:
return json.dumps({'content': {}, 'error' : server_errors['705'] }), 500, {'Content-Type': 'application/json; charset=utf-8'}
status = 600
error = server_errors[str(status)]
output = json.dumps({'content': structured_dict, 'error' : error })
if status <700:
REST_STATUS = 200
else:
REST_STATUS = 500
return output, REST_STATUS, {'Content-Type': 'application/json; charset=utf-8'}
### Step 4
@app.route("/prs-improving-requirements-quality-features/parsing/enrich", methods=['POST'])
def enricher(content = None):
"""
Enricher.
Get a text, return an enriched dict.
---
parameters:
- in: body
name: body
schema:
type: object
properties:
structuredDictList:
type: array
items:
type: object
required: true
responses:
200:
description: Application run normally
schema:
type: object
properties:
content:
type: array
items:
type: object
error:
type: object
properties:
status:
type: number
code:
type: string
description:
type: string
500:
description: Internal Server Error
schema:
type: object
properties:
content:
type: object
error:
type: object
properties:
status:
type: number
code:
type: string
description:
type: string
"""
param_dbpedia_dict = {}
param_dbpedia_dict['dbpediaspotlight_url'] = config_parameters['ske']['dbpediaspotlight_url_en']
param_dbpedia_dict['useProxy'] = config_parameters['ske']['use_proxy']
param_dbpedia_dict['confidence'] = 0.4
json_input = None
if content is None:
json_input = request.get_json(force=True)
else:
json_input = content
# check validity of input json
if isinstance(json_input, dict) == False:
return json.dumps({'content': {}, 'error' : server_errors['707'] }), 500, {'Content-Type': 'application/json; charset=utf-8'}
# check validity of input document
structured_dict_list = json_input.get('structuredDictList',None)
if isinstance(structured_dict_list,list)==False:
return json.dumps({'content': {}, 'error' : server_errors['702'] }), 500, {'Content-Type': 'application/json; charset=utf-8'}
enriched_dicts_list = []
try:
for paragraph_dict in structured_dict_list:
paragraph_dict = preproc_enrich.enrich(paragraph_dict, wordlist_list, verb_arguments_parser,lem,tc,param_dbpedia_dict)
enriched_dicts_list.append(paragraph_dict)
except:
return json.dumps({'content': {}, 'error' : server_errors['705'] }), 500, {'Content-Type': 'application/json; charset=utf-8'}
status = 600
error = server_errors[str(status)]
output = json.dumps({'content': enriched_dicts_list, 'error' : error })
if status <700:
REST_STATUS = 200
else:
REST_STATUS = 500
return output, REST_STATUS, {'Content-Type': 'application/json; charset=utf-8'}
### Step 5
@app.route('/prs-improving-requirements-quality-features/parsing/enrich/prettify', methods=['POST'])
def get_output_json(content = None):
"""
Prettify enriched dict
Get a list of enriched dict, return a list of pretty enriched dict.
---
parameters:
- in: body
name: body
schema:
type: object
properties:
enrichedDictList:
type: array
items:
type: object
required: true
responses:
200:
description: Application run normally
schema:
type: object
properties:
content:
type: array
items:
type: object
error:
type: object
properties:
status:
type: number
code:
type: string
description:
type: string
500:
description: Internal Server Error
schema:
type: object
properties:
content:
type: object
error:
type: object
properties:
status:
type: number
code:
type: string
description:
type: string
"""
json_schema = []
json_input = None
if content is None:
json_input = request.get_json(force=True)
else:
json_input = content
# check validity of input json
if isinstance(json_input, dict) == False:
return json.dumps({'content': {}, 'error' : server_errors['707'] }), 500, {'Content-Type': 'application/json; charset=utf-8'}
input_dictionary_list = json_input.get('enrichedDictList',None)
if isinstance(input_dictionary_list,list)==False:
return json.dumps({'content': {}, 'error' : server_errors['702'] }), 500, {'Content-Type': 'application/json; charset=utf-8'}
#json_object = get_json(force=True)
#input_dictionary_list = json_object['content']
try:
for inner_dict in input_dictionary_list:
json_enriched = generate_json_schema(inner_dict)
json_schema.append(json_enriched)
except:
return json.dumps({'content': {}, 'error' : server_errors['705'] }), 500, {'Content-Type': 'application/json; charset=utf-8'}
content = json_schema
status = 600
error = server_errors[str(status)]
output = json.dumps({'content' : content, 'error' : error })
if status <700:
REST_STATUS = 200
else:
REST_STATUS = 500
return output, REST_STATUS, {'Content-Type': 'application/json; charset=utf-8'}
################################################
######## enrichment flow apps ################
################################################
#1
# lemmatizer app
@app.route('/prs-improving-requirements-quality-features/parsing/lemmatizer/<string:extr_type>', methods=['POST'])
def parsing_lemmatizer(extr_type=None):
"""
Text lemmatization.
Get a list of text, return a list of lemmatized text.
---
parameters:
- name: extr_type
in: path
description: Language en for english or it for italian.
required: true
schema:
type: string
- in: body
name: body
schema:
type: object
properties:
documents:
type: array
items:
type: string
selectedPOS:
type: array
items:
type: string
removeStopwords:
type: array
items:
type: string
required: true
responses:
200:
description: Application run normally
schema:
type: object
properties:
content:
type: object
properties:
lemmatizedDocuments:
type: array
items:
type: array
items:
type: string
error:
type: object
properties:
status:
type: number
code:
type: string
description:
type: string
500:
description: Internal Server Error
schema:
type: object
properties:
content:
type: object
error:
type: object
properties:
status:
type: number
code:
type: string
description:
type: string
"""
language = None
if (extr_type is None):
language = "en"
elif (extr_type == "it"):
language = "it"
elif (extr_type == "en"):
language = "en"
lem.lang=language
json_input = request.get_json(force=True)
# check validity of input json
if isinstance(json_input, dict) == False:
return json.dumps({'content': {}, 'error' : server_errors['707'] }), 500, {'Content-Type': 'application/json; charset=utf-8'}
# check validity of input document
documents = json_input.get('documents',[])
if isinstance(documents,list) == False or len(documents)==0:
return json.dumps({'content': {}, 'error' : server_errors['702'] }), 500, {'Content-Type': 'application/json; charset=utf-8'}
# check validity of pos list
pos_list = json_input.get('selectedPOS',None)
if isinstance(pos_list,list):
lem.pos_list = pos_list
# check validity of stopwords list
stopwords_list = json_input.get('removeStopwords',None)
if isinstance(stopwords_list,list):
lem.stopwords_list = stopwords_list
# apply lemmatizer
try:
lemmatized_docs = lem.lemmatize(sentences_list=documents)
except:
return json.dumps({'content': {}, 'error' : server_errors['702'] }), 500, {'Content-Type': 'application/json; charset=utf-8'}
return json.dumps({'content': {'lemmatizedDocuments':lemmatized_docs}, 'error': server_errors["600"] }), 200, {'Content-Type': 'application/json; charset=utf-8'}
#2
# supervised keyords extraction app
@app.route('/prs-improving-requirements-quality-features/parsing/keywords/supervised/<string:extr_type>', methods=['POST'])
def parsing_db_entities_extraction(extr_type = None):
"""
DbPedia entities extraction.
Get a text, return dbpedia entities.
---
parameters:
- name: extr_type
in: path
description: Language en for english or it for italian.
required: true
schema:
type: string
- in: body
name: body
schema:
type: object
properties:
document:
type: string
description: Parsed Text
confidence:
type: number
customEntities:
type: array
items: