-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
1522 lines (1328 loc) · 86.5 KB
/
server.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# load tempfile for temporary dir creation
import sys, os, tempfile, subprocess
# load libraries for NLP pipeline
import spacy
# load Visualizers
from spacy import displacy
# load Matcher
from spacy.matcher import Matcher
# load textacy
import textacy
import textacy.ke
# load misc utils
import json
# import uuid
from werkzeug.utils import secure_filename
import logging
# logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.DEBUG)
# logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.ERROR)
# load libraries for string proccessing
import re, string
# load libraries for pdf processing pdfminer
from io import StringIO, BytesIO
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfparser import PDFParser
# load libraries for docx processing
import zipfile
WORD_NAMESPACE = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
PARA = WORD_NAMESPACE + 'p'
TEXT = WORD_NAMESPACE + 't'
# load libraries for XML proccessing
import xml.etree.ElementTree as ET
# load libraries for API proccessing
from flask import Flask, jsonify, flash, request, Response, redirect, url_for, abort, render_template
# A Flask extension for handling Cross Origin Resource Sharing (CORS), making cross-origin AJAX possible.
from flask_cors import CORS
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'docx'])
# Load globally spaCy model via package name
NLP_NB = spacy.load('nb_core_news_sm')
# Load lemmas only
NLP_NB_LEMMA = spacy.load('nb_core_news_sm', disable=["parser", "tagger"])
# NLP_NB_VECTORES = spacy.load('./tmp/nb_nowac_vectores')
# NLP_EN_VECTORES = spacy.load('en_core_web_lg')
# Load globally textacy spaCy model
nb = textacy.load_spacy_lang("nb_core_news_sm", disable=("parser",))
# Stanza – A Python NLP Package for Many Human Languages
import stanza
nlp_stanza = stanza.Pipeline(lang='nb', processors='tokenize,mwt,pos,lemma', dir='./deploy/stanza_resources')
# try:
# nlp_stanza = stanza.Pipeline(lang='nb', processors='tokenize,mwt,pos,lemma', dir='./deploy/stanza_resources')
# except:
# logging.debug('Installing Stance pretrained NLP model for Norwegian Bokmaal.')
# stanza.download('nb', dir='./deploy/stanza_resources')
# nlp_stanza = stanza.Pipeline(lang='nb', processors='tokenize,mwt,pos,lemma', dir='./deploy/stanza_resources')
# logging.debug('Stance pretrained NLP model for Norwegian Bokmaal is ready to use.')
# load SnowballStemmer stemmer from nltk
from nltk.stem.snowball import SnowballStemmer
# Load globally english SnowballStemmer
NORWEGIAN_STEMMER = SnowballStemmer("norwegian")
# for hunspell https://github.com/blatinier/pyhunspell
import hunspell
nb_spell = hunspell.HunSpell('./deploy/dictionary/nb.dic', './deploy/dictionary/nb.aff')
__author__ = "Kyrylo Malakhov <malakhovks@nas.gov.ua> and Vitalii Velychko <aduisukr@gmail.com>"
__copyright__ = "Copyright (C) 2020 Kyrylo Malakhov <malakhovks@nas.gov.ua> and Vitalii Velychko <aduisukr@gmail.com>"
app = Flask(__name__)
CORS(app)
"""
Limited the maximum allowed payload to 16 megabytes.
If a larger file is transmitted, Flask will raise an RequestEntityTooLarge exception.
"""
# app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
"""
Set the secret key to some random bytes. Keep this really secret!
How to generate good secret keys.
A secret key should be as random as possible. Your operating system has ways to generate pretty random data based on a cryptographic random generator. Use the following command to quickly generate a value for Flask.secret_key (or SECRET_KEY):
$ python -c 'import os; print(os.urandom(16))'
b'_5#y2L"F4Q8z\n\xec]/'
"""
# app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
app.secret_key = os.urandom(42)
"""
# ------------------------------------------------------------------------------------------------------
# Functions
# ------------------------------------------------------------------------------------------------------
# """
# function that check if an extension is valid
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
# default sentence normalization
def sentence_normalization_default(raw_sentence):
# remove tabs and insert spaces
raw_sentence = re.sub('[\t]', ' ', raw_sentence)
# remove multiple spaces
raw_sentence = re.sub('\s\s+', ' ', raw_sentence)
# remove all numbers
# line = re.sub(r'\d+','',line)
# remove leading and ending spaces
raw_sentence = raw_sentence.strip()
normalized_sentence = raw_sentence
return normalized_sentence
# default text normalization
def text_normalization_default(raw_text):
raw_text_list = []
for line in raw_text.splitlines(True):
# if line contains letters
if re.search(r'[a-z]+', line):
"""
remove \n \r \r\n new lines and insert spaces
\r = CR (Carriage Return) → Used as a new line character in Mac OS before X
\n = LF (Line Feed) → Used as a new line character in Unix/Mac OS X
\r\n = CR + LF → Used as a new line character in Windows
"""
"""
\W pattern: When the LOCALE and UNICODE flags are not specified, matches any non-alphanumeric character;
this is equivalent to the set [^a-zA-Z0-9_]. With LOCALE, it will match any character not in the set [0-9_], and not defined as alphanumeric for the current locale.
If UNICODE is set, this will match anything other than [0-9_] plus characters classified as not alphanumeric in the Unicode character properties database.
To remove all the non-word characters, the \W pattern can be used as follows:
"""
# line = re.sub(r'\W', ' ', line, flags=re.I)
# remove all non-words except punctuation
# line = re.sub('[^\w.,;!?-]', ' ', line)
# remove all words which contains number
line = re.sub(r'\w*\d\w*', ' ', line)
# remove % symbol
line = re.sub('%', ' ', line)
# remove ° symbol
line = re.sub('[°]', ' ', line)
line = re.sub('[\n]', ' ', line)
line = re.sub('[\r\n]', ' ', line)
line = re.sub('[\r]', ' ', line)
# remove tabs and insert spaces
line = re.sub('[\t]', ' ', line)
# Replace multiple dots with space
line = re.sub('\.\.+', ' ', line)
# remove multiple spaces
line = re.sub('\s\s+', ' ', line)
# remove all numbers
# line = re.sub(r'\d+','',line)
# remove leading and ending spaces
line = line.strip()
raw_text_list.append(line)
yet_raw_text = ' '.join(raw_text_list)
return yet_raw_text
# Extracting all the text from DOCX
def get_unicode_from_docx(docx_path):
"""
Take the path of a docx file as argument, return the text in unicode.
"""
document = zipfile.ZipFile(docx_path)
xml_content = document.read('word/document.xml')
document.close()
tree = ET.XML(xml_content)
paragraphs = []
for paragraph in tree.iter(PARA):
texts = [node.text
for node in paragraph.iter(TEXT)
if node.text]
if texts:
paragraphs.append(''.join(texts))
return '\n\n'.join(paragraphs)
# Extracting all the text from PDF with PDFMiner.six
def get_unicode_from_pdf(pdf_path):
rsrcmgr = PDFResourceManager()
codec = 'utf-8'
laparams = LAParams()
# save document layout including spaces that are only visual not a character
"""
Some pdfs mark the entire text as figure and by default PDFMiner doesn't try to perform layout analysis for figure text. To override this behavior the all_texts parameter needs to be set to True
"""
laparams = LAParams()
setattr(laparams, 'all_texts', True)
# save document layout including spaces that are only visual not a character
with StringIO() as retstr:
with TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams) as device:
with open(pdf_path, 'rb') as fp:
interpreter = PDFPageInterpreter(rsrcmgr, device)
password = ""
maxpages = 0
caching = True
pagenos = set()
for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password, caching=caching, check_extractable=True):
interpreter.process_page(page)
return retstr.getvalue()
"""
# ------------------------------------------------------------------------------------------------------
# """
""" @app.route('/')
def index():
return Response(render_template('index.html'), mimetype='text/html')
"""
@app.route('/help')
def index():
return Response(render_template('help.html'), mimetype='text/html')
"""
# API ---------------------------------------------------------------------------------------------------
# """
# --------------------------------------------------------------------------------------------------------
# Text messages
@app.route('/api/bot/nb/alltermsxml', methods=['POST'])
def get_allterms():
req_data = request.get_json()
try:
# spaCy doc init + default sentence normalization
doc = NLP_NB(req_data['message'])
# create the <allterms.xml> file structure
# create root element <termsintext>
root_termsintext_element = ET.Element("termsintext")
# create element <sentences>
sentences_element = ET.Element("sentences")
# create element <filepath>
# filepath_element = ET.Element("filepath")
# filepath_element.text = file.filename
# create element <exporterms>
exporterms_element = ET.Element("exporterms")
# Helper list for one-word terms
one_word_terms_help_list = []
# Helper list for two-word terms
two_word_terms_help_list = []
# Helper list for multiple-word terms (from 4-word terms)
multiple_word_terms_help_list = []
noun_chunks = []
# Main text parsing cycle for sentences
for sentence_index, sentence in enumerate(doc.sents):
# default sentence normalization
sentence_clean = sentence.text
# create and append <sent>
new_sent_element = ET.Element('sent')
new_sent_element.text = sentence_clean #.encode('ascii', 'ignore') errors='replace'
sentences_element.append(new_sent_element)
# for processing specific sentence
doc_for_chunks = NLP_NB(sentence_clean)
# sentence NP shallow parsing cycle
for chunk in doc_for_chunks.noun_chunks:
doc_for_tokens = NLP_NB(chunk.text)
'''
# EXTRACT ONE-WORD TERMS ----------------------------------------------------------------------
'''
if len(doc_for_tokens) == 1:
if doc_for_tokens[0].pos_ in ['NOUN', 'PROPN']:
if doc_for_tokens[0].lemma_ in one_word_terms_help_list:
for term in exporterms_element.findall('term'):
if term.find('tname').text == doc_for_tokens[0].lemma_:
new_sentpos_element = ET.Element('sentpos')
new_sentpos_element.text = str(sentence_index) + '/' + str(chunk.start+1)
term.append(new_sentpos_element)
if doc_for_tokens[0].lemma_ not in one_word_terms_help_list:
one_word_terms_help_list.append(doc_for_tokens[0].lemma_)
# create and append <wcount>
new_wcount_element = ET.Element('wcount')
new_wcount_element.text = '1'
# create and append <ttype>
new_ttype_element = ET.Element('ttype')
new_ttype_element.text = doc_for_tokens[0].pos_
# create <term>
new_term_element = ET.Element('term')
# create and append <tname>
new_tname_element = ET.Element('tname')
new_tname_element.text = doc_for_tokens[0].lemma_
# create and append <osn>
new_osn_element = ET.Element('osn')
new_osn_element.text = NORWEGIAN_STEMMER.stem(doc_for_tokens[0].text)
# create and append <sentpos>
new_sentpos_element = ET.Element('sentpos')
new_sentpos_element.text = str(sentence_index) + '/' + str(chunk.start+1)
new_term_element.append(new_sentpos_element)
# append to <term>
new_term_element.append(new_ttype_element)
new_term_element.append(new_tname_element)
new_term_element.append(new_osn_element)
new_term_element.append(new_wcount_element)
# append to <exporterms>
exporterms_element.append(new_term_element)
if len(doc_for_tokens) == 2:
'''
# Extract one-word terms from 2-words statements (excluding articles DET)
'''
# if doc_for_tokens[0].pos_ in ['DET', 'PUNCT']:
if doc_for_tokens[0].pos_ in ['DET', 'PUNCT', 'PART', 'ADP']:
if doc_for_tokens[1].lemma_ in one_word_terms_help_list:
for term in exporterms_element.findall('term'):
if term.find('tname').text == doc_for_tokens[1].lemma_:
new_sentpos_element = ET.Element('sentpos')
new_sentpos_element.text = str(sentence_index) + '/' + str(chunk.start+2)
term.append(new_sentpos_element)
if doc_for_tokens[1].lemma_ not in one_word_terms_help_list:
one_word_terms_help_list.append(doc_for_tokens[1].lemma_)
# create and append <wcount>
new_wcount_element = ET.Element('wcount')
new_wcount_element.text = '1'
# create and append <ttype>
new_ttype_element = ET.Element('ttype')
new_ttype_element.text = doc_for_tokens[1].pos_
# create <term>
new_term_element = ET.Element('term')
# create and append <tname>
new_tname_element = ET.Element('tname')
new_tname_element.text = doc_for_tokens[1].lemma_
# create and append <osn>
new_osn_element = ET.Element('osn')
new_osn_element.text = NORWEGIAN_STEMMER.stem(doc_for_tokens[1].text)
# create and append <sentpos>
new_sentpos_element = ET.Element('sentpos')
new_sentpos_element.text = str(sentence_index) + '/' + str(chunk.start+2)
new_term_element.append(new_sentpos_element)
# append to <term>
new_term_element.append(new_ttype_element)
new_term_element.append(new_tname_element)
new_term_element.append(new_osn_element)
new_term_element.append(new_wcount_element)
# append to <exporterms>
exporterms_element.append(new_term_element)
'''
# EXTRACT TWO-WORD TERMS ---------------------------------------------------------------
'''
# if doc_for_tokens[0].pos_ not in ['DET', 'PUNCT']:
if doc_for_tokens[0].pos_ not in ['DET', 'PUNCT', 'PART', 'ADP']:
# print('two-word term lemma ---> ' + chunk.lemma_ +' POS[0]:'+ doc_for_tokens[0].pos_ + ' POS[0]:'+ doc_for_tokens[0].tag_ + ' HEAD[0]:' + doc_for_tokens[0].head.lower_ +' POS[1]:' + doc_for_tokens[1].pos_ + ' POS[1]:'+ doc_for_tokens[1].tag_ + ' HEAD[1]:' + doc_for_tokens[1].head.lower_)
# print('--------------------')
# If two-word term already exists in two_word_terms_help_list
# if chunk.lower_ in two_word_terms_help_list:
if chunk.lemma_ in two_word_terms_help_list:
# add new <sentpos> for existing two-word term
for term in exporterms_element.findall('term'):
# if term.find('tname').text == chunk.lower_:
if term.find('tname').text == chunk.lemma_:
new_sentpos_element = ET.Element('sentpos')
new_sentpos_element.text = str(sentence_index) + '/' + str(chunk.start+1)
term.append(new_sentpos_element)
# Check If root (root of Noun chunks always is a NOUN) of the two-word term
# already exists in one_word_terms_help_list
if chunk.root.lemma_ in one_word_terms_help_list:
sent_pos_helper = []
for relup_index, one_term in enumerate(exporterms_element.findall('term')):
if one_term.find('tname').text == chunk.root.lemma_:
for sent_pos in one_term.findall('sentpos'):
sent_pos_helper.append(sent_pos.text)
# create and append new <sentpos>
# check if new <sentpos> already exist, if no then add new <sentpos>
if chunk.root.lower_ == doc_for_tokens[0].lower_:
if (str(sentence_index) + '/' + str(chunk.start+1)) not in sent_pos_helper:
new_sentpos_element = ET.Element('sentpos')
new_sentpos_element.text = str(sentence_index) + '/' + str(chunk.start+1)
one_term.append(new_sentpos_element)
else:
if (str(sentence_index) + '/' + str(chunk.start+2)) not in sent_pos_helper:
new_sentpos_element = ET.Element('sentpos')
new_sentpos_element.text = str(sentence_index) + '/' + str(chunk.start+2)
one_term.append(new_sentpos_element)
# Check If child of the root (Child not always be a NOUN, so not always be a term) of the two-word term
# already exists in one_word_terms_help_list
for t in doc_for_tokens:
if t.lemma_ != chunk.root.lemma_:
# if child of the root is NOUN, so it is a term
if t.pos_ in ['NOUN']:
if t.lemma_ in one_word_terms_help_list:
sent_pos_helper = []
if t.i == 0:
index_helper = chunk.start+1
else:
index_helper = chunk.start+2
for relup_index, one_term in enumerate(exporterms_element.findall('term')):
if one_term.find('tname').text == t.lemma_:
for sent_pos in one_term.findall('sentpos'):
sent_pos_helper.append(sent_pos.text)
if (str(sentence_index) + '/' + str(index_helper)) not in sent_pos_helper:
new_sentpos_element = ET.Element('sentpos')
new_sentpos_element.text = str(sentence_index) + '/' + str(index_helper)
one_term.append(new_sentpos_element)
# If two-word term not exists in two_word_terms_help_list
if chunk.lemma_ not in two_word_terms_help_list:
# update two_word_terms_help_list with the new two-word term
# two_word_terms_help_list.append(chunk.lower_)
two_word_terms_help_list.append(chunk.lemma_)
# create and append <wcount>
new_wcount_element = ET.Element('wcount')
new_wcount_element.text = '2'
# create and append <ttype>
new_ttype_element = ET.Element('ttype')
new_ttype_element.text = doc_for_tokens[0].pos_ + '_' + doc_for_tokens[1].pos_
# create <term>
new_term_element = ET.Element('term')
# create and append <tname>
new_tname_element = ET.Element('tname')
# new_tname_element.text = chunk.lower_
new_tname_element.text = chunk.lemma_
# create and append <osn>
new_osn_element = ET.Element('osn')
new_osn_element.text = NORWEGIAN_STEMMER.stem(doc_for_tokens[0].text)
new_term_element.append(new_osn_element)
new_osn_element = ET.Element('osn')
new_osn_element.text = NORWEGIAN_STEMMER.stem(doc_for_tokens[1].text)
new_term_element.append(new_osn_element)
# create and append <sentpos>
new_sentpos_element = ET.Element('sentpos')
new_sentpos_element.text = str(sentence_index) + '/' + str(chunk.start+1)
new_term_element.append(new_sentpos_element)
# append to <term>
new_term_element.append(new_ttype_element)
new_term_element.append(new_tname_element)
new_term_element.append(new_wcount_element)
# append to <exporterms>
exporterms_element.append(new_term_element)
# Check If root (root of Noun chunks always is a NOUN) of the two-word term
# already exists in one_word_terms_help_list
# add relup/reldown
if chunk.root.lemma_ in one_word_terms_help_list:
sent_pos_helper = []
for relup_index, one_term in enumerate(exporterms_element.findall('term')):
if one_term.find('tname').text == chunk.root.lemma_:
for sent_pos in one_term.findall('sentpos'):
sent_pos_helper.append(sent_pos.text)
if chunk.root.lower_ == doc_for_tokens[0].lower_:
if (str(sentence_index) + '/' + str(chunk.start+1)) not in sent_pos_helper:
new_sentpos_element = ET.Element('sentpos')
new_sentpos_element.text = str(sentence_index) + '/' + str(chunk.start+1)
one_term.append(new_sentpos_element)
else:
if (str(sentence_index) + '/' + str(chunk.start+2)) not in sent_pos_helper:
new_sentpos_element = ET.Element('sentpos')
new_sentpos_element.text = str(sentence_index) + '/' + str(chunk.start+2)
one_term.append(new_sentpos_element)
for reldown_index, two_term in enumerate(exporterms_element.findall('term')):
# if two_term.find('tname').text == chunk.lower_:
if two_term.find('tname').text == chunk.lemma_:
new_relup_element = ET.Element('relup')
new_relup_element.text = str(relup_index)
two_term.append(new_relup_element)
new_reldown_element = ET.Element('reldown')
new_reldown_element.text = str(reldown_index)
one_term.append(new_reldown_element)
# Check If root NOUN not exists in one_word_terms_help_list
# add root NOUN to one_word_terms_help_list
# add relup/reldown
if chunk.root.lemma_ not in one_word_terms_help_list:
# print('root NOUN not exists in one_word_terms_help_list --->> ' + chunk.root.lemma_)
# print('--------------------')
one_word_terms_help_list.append(chunk.root.lemma_)
# create and append <wcount>
new_wcount_element = ET.Element('wcount')
new_wcount_element.text = '1'
# create and append <ttype>
new_ttype_element = ET.Element('ttype')
new_ttype_element.text = 'NOUN'
# create <term>
new_term_element = ET.Element('term')
# create and append <tname>
new_tname_element = ET.Element('tname')
new_tname_element.text = chunk.root.lemma_
# create and append <osn>
new_osn_element = ET.Element('osn')
new_osn_element.text = NORWEGIAN_STEMMER.stem(chunk.root.lower_)
# create and append <sentpos>
new_sentpos_element = ET.Element('sentpos')
if chunk.root.lower_ == doc_for_tokens[0].lower_:
new_sentpos_element.text = str(sentence_index) + '/' + str(chunk.start+1)
else:
new_sentpos_element.text = str(sentence_index) + '/' + str(chunk.start+2)
new_term_element.append(new_sentpos_element)
# append to <term>
new_term_element.append(new_ttype_element)
new_term_element.append(new_tname_element)
new_term_element.append(new_wcount_element)
# append to <exporterms>
exporterms_element.append(new_term_element)
for relup_index, one_term in enumerate(exporterms_element.findall('term')):
if one_term.find('tname').text == chunk.root.lemma_:
for reldown_index, two_term in enumerate(exporterms_element.findall('term')):
# if two_term.find('tname').text == chunk.lower_:
if two_term.find('tname').text == chunk.lemma_:
new_relup_element = ET.Element('relup')
new_relup_element.text = str(relup_index)
two_term.append(new_relup_element)
new_reldown_element = ET.Element('reldown')
new_reldown_element.text = str(reldown_index)
one_term.append(new_reldown_element)
for t in doc_for_tokens:
if t.lemma_ != chunk.root.lemma_:
if t.pos_ in ['NOUN']:
# print('-------->>>>>>' + t.lemma_)
if t.lemma_ in one_word_terms_help_list:
sent_pos_helper = []
if t.i == 0:
index_helper = chunk.start+1
else:
index_helper = chunk.start+2
for relup_index, one_term in enumerate(exporterms_element.findall('term')):
if one_term.find('tname').text == t.lemma_:
for reldown_index, two_term in enumerate(exporterms_element.findall('term')):
# if two_term.find('tname').text == chunk.lower_:
if two_term.find('tname').text == chunk.lemma_:
for sent_pos in one_term.findall('sentpos'):
sent_pos_helper.append(sent_pos.text)
if (str(sentence_index) + '/' + str(index_helper)) not in sent_pos_helper:
new_sentpos_element = ET.Element('sentpos')
new_sentpos_element.text = str(sentence_index) + '/' + str(index_helper)
one_term.append(new_sentpos_element)
new_relup_element = ET.Element('relup')
new_relup_element.text = str(relup_index)
two_term.append(new_relup_element)
new_reldown_element = ET.Element('reldown')
new_reldown_element.text = str(reldown_index)
one_term.append(new_reldown_element)
if t.lemma_ not in one_word_terms_help_list:
# print('if t.lemma_ not in one_word_terms_help_list ----->>>>>>' + t.lemma_)
sent_pos_helper = []
if t.i == 0:
index_helper = chunk.start+1
else:
index_helper = chunk.start+2
one_word_terms_help_list.append(t.lemma_)
# create and append <wcount>
new_wcount_element = ET.Element('wcount')
new_wcount_element.text = '1'
# create and append <ttype>
new_ttype_element = ET.Element('ttype')
new_ttype_element.text = 'NOUN'
# create <term>
new_term_element = ET.Element('term')
# create and append <tname>
new_tname_element = ET.Element('tname')
new_tname_element.text = t.lemma_
# create and append <osn>
new_osn_element = ET.Element('osn')
new_osn_element.text = NORWEGIAN_STEMMER.stem(t.lower_)
# create and append <sentpos>
new_sentpos_element = ET.Element('sentpos')
new_sentpos_element.text = str(sentence_index) + '/' + str(index_helper)
# append to <term>
new_term_element.append(new_sentpos_element)
new_term_element.append(new_ttype_element)
new_term_element.append(new_tname_element)
new_term_element.append(new_wcount_element)
# append to <exporterms>
exporterms_element.append(new_term_element)
for relup_index, one_term in enumerate(exporterms_element.findall('term')):
if one_term.find('tname').text == t.lemma_:
for reldown_index, two_term in enumerate(exporterms_element.findall('term')):
# if two_term.find('tname').text == chunk.lower_:
if two_term.find('tname').text == chunk.lemma_:
for sent_pos in one_term.findall('sentpos'):
sent_pos_helper.append(sent_pos.text)
if (str(sentence_index) + '/' + str(index_helper)) not in sent_pos_helper:
new_sentpos_element = ET.Element('sentpos')
new_sentpos_element.text = str(sentence_index) + '/' + str(index_helper)
one_term.append(new_sentpos_element)
new_relup_element = ET.Element('relup')
new_relup_element.text = str(relup_index)
two_term.append(new_relup_element)
new_reldown_element = ET.Element('reldown')
new_reldown_element.text = str(reldown_index)
one_term.append(new_reldown_element)
'''
# EXTRACT THREE-WORD TERMS
'''
if len(doc_for_tokens) == 3:
logging.debug('three-word term lemma ---> ' + chunk.lemma_ +' POS[0]:'+ doc_for_tokens[0].pos_ + ' POS[1]:' + doc_for_tokens[1].pos_ + ' POS[2]:' + doc_for_tokens[2].pos_)
logging.debug('--------------------')
if len(doc_for_tokens) > 3:
logging.debug('multi-word term lemma ---> ' + chunk.lemma_)
logging.debug('--------------------')
# if doc_for_tokens[0].pos_ not in ['DET', 'PUNCT']:
if doc_for_tokens[0].pos_ not in ['DET', 'PUNCT', 'PART', 'ADP']:
# If multiple-word term already exists in multiple_word_terms_help_list
if chunk.lemma_ in multiple_word_terms_help_list:
# add new <sentpos> for existing two-word term
for term in exporterms_element.findall('term'):
if term.find('tname').text == chunk.lemma_:
new_sentpos_element = ET.Element('sentpos')
new_sentpos_element.text = str(sentence_index) + '/' + str(chunk.start+1)
term.append(new_sentpos_element)
# If multiple-word term not exists in multiple_word_terms_help_list
if chunk.lemma_ not in multiple_word_terms_help_list:
# update multiple_word_terms_help_list with the new multiple-word term
multiple_word_terms_help_list.append(chunk.lemma_)
# create and append <wcount>
new_wcount_element = ET.Element('wcount')
new_wcount_element.text = str(len(chunk))
# create and append <ttype>
multiple_pos_helper = []
for multiple_pos in doc_for_tokens:
multiple_pos_helper.append(multiple_pos.pos_)
new_ttype_element = ET.Element('ttype')
new_ttype_element.text = '_'.join(multiple_pos_helper)
# create <term>
new_term_element = ET.Element('term')
# create and append <tname>
new_tname_element = ET.Element('tname')
# new_tname_element.text = chunk.lower_
new_tname_element.text = chunk.lemma_
# create and append <osn>
multiple_osn_helper = []
for multiple_osn in doc_for_tokens:
new_osn_element = ET.Element('osn')
new_osn_element.text = NORWEGIAN_STEMMER.stem(multiple_osn.text)
new_term_element.append(new_osn_element)
# create and append <sentpos>
new_sentpos_element = ET.Element('sentpos')
new_sentpos_element.text = str(sentence_index) + '/' + str(chunk.start+1)
new_term_element.append(new_sentpos_element)
# append to <term>
new_term_element.append(new_ttype_element)
new_term_element.append(new_tname_element)
new_term_element.append(new_wcount_element)
# append to <exporterms>
exporterms_element.append(new_term_element)
# create full <allterms.xml> file structure
# root_termsintext_element.append(filepath_element)
root_termsintext_element.append(exporterms_element)
root_termsintext_element.append(sentences_element)
return Response(ET.tostring(root_termsintext_element, encoding='utf8', method='xml'), mimetype='text/xml')
except Exception as e:
logging.error(e, exc_info=True)
return abort(500)
# Text messages
@app.route('/api/bot/nb/message/json/allterms', methods=['POST'])
def get_allterms_json():
req_data = request.get_json()
# for allterms JSON structure
allterms = {
"termsintext": {
"exporterms": {
"term": {}
},
"keyterms": {
"algorithm": {
"textrank": {
"terms": []
}
}
},
"sentences": {
"sent": []
}
}
}
terms_element = allterms['termsintext']['exporterms']['term']
terms_textrank_array = allterms['termsintext']['keyterms']['algorithm']['textrank']['terms']
sent_array = allterms['termsintext']['sentences']['sent']
# for allterms JSON structure
# patterns for spaCy Matcher https://spacy.io/usage/rule-based-matching
patterns = [
# 1 term
[{'POS': {'IN':['NOUN', 'PROPN']}}],
# [{'POS': 'PROPN'}],
# [{'POS': 'NOUN'}],
# 2 terms
[{'POS': {'IN':['NOUN', 'ADJ','PROPN']}}, {'POS': {'IN':['NOUN', 'ADJ','PROPN']}}],
# 3 terms
[{'POS': {'IN':['NOUN', 'ADJ','PROPN']}}, {'POS': {'IN':['NOUN', 'ADJ','PROPN']}}, {'POS': {'IN':['NOUN', 'ADJ','PROPN']}}],
# 4 terms
[{'POS': {'IN':['NOUN', 'ADJ','PROPN']}}, {'POS': {'IN':['NOUN', 'ADJ','PROPN']}},{'POS': {'IN':['NOUN', 'ADJ','PROPN']}}, {'POS': {'IN':['NOUN', 'ADJ','PROPN']}}],
# 3 terms with APD in the middle
[{'POS': {'IN':['NOUN', 'ADJ','PROPN']}}, {'POS': {'IN':['NOUN', 'ADJ','PROPN', 'ADP']}}, {'POS': {'IN':['NOUN', 'ADJ','PROPN']}}]
]
matcher = Matcher(NLP_NB.vocab)
matcher.add("NOUN/PROPN", None, patterns[0])
matcher.add("NOUN/ADJ/PROPN+NOUN/ADJ/PROPN", None, patterns[1])
matcher.add("NOUN/ADJ/PROPN+NOUN/ADJ/PROPN+NOUN/ADJ/PROPN", None, patterns[2])
matcher.add("NOUN/ADJ/PROPN+NOUN/ADJ/PROPN+NOUN/ADJ/PROPN+NOUN/ADJ/PROPN", None, patterns[3])
matcher.add("NOUN/ADJ/PROPN+NOUN/ADJ/PROPN/ADP+NOUN/ADJ/PROPN", None, patterns[4])
try:
# spaCy doc init + default sentence normalization
doc = NLP_NB(req_data['message'])
# Helper list for 1-word terms
# one_word_terms_help_list_json = []
# Helper list for 2-word terms
# two_word_terms_help_list_json = []
# Helper list for 3-word terms
# three_word_terms_help_list_json = []
# Helper list for multiple-word terms (from 4-word terms)
multiple_word_terms_help_list = []
# Main text parsing cycle for sentences
for sentence_index, sentence in enumerate(doc.sents):
# default sentence normalization
# sentence_clean = sentence_normalization_default(sentence.text)
sentence_clean = sentence.text
# for processing specific sentence
doc_for_chunks = NLP_NB(sentence_clean)
# for processing specific sentence with textacy
doc_textacy = textacy.make_spacy_doc(sentence_clean, lang=nb)
logging.debug('Sentence: ' + doc_for_chunks.text)
# TEXTACY TextRank for KEY TERMS ---------------------
key_terms_list = textacy.ke.textrank(doc_textacy, normalize="lemma", topn=10)
if key_terms_list:
logging.debug('TextRank Key terms list: ' + str(key_terms_list))
for trm in key_terms_list:
if not terms_textrank_array:
terms_textrank_array.append({'tname': trm[0], 'rank': trm[1], 'sentidx': [sentence_index]})
if terms_textrank_array:
indx_if_exist = next((i for i, item in enumerate(terms_textrank_array) if item["tname"] == trm[0]), None)
if indx_if_exist:
logging.debug('Index of a sentence in which the term is: ' + str(indx_if_exist))
terms_textrank_array[indx_if_exist]['sentidx'].append(sentence_index)
if indx_if_exist is None:
logging.debug('Index of a sentence in which the term is: ' + str(indx_if_exist))
terms_textrank_array.append({'tname': trm[0], 'rank': trm[1], 'sentidx': [sentence_index]})
if not key_terms_list:
logging.debug('TextRank Key terms list: EMPTY')
# MATCHING NOUN --------------------------------------
matches = matcher(doc_for_chunks)
# add sentence to sent array
sent_array.append(doc_for_chunks.text)
for match_id, start, end in matches:
string_id = NLP_NB.vocab.strings[match_id]
span = doc_for_chunks[start:end]
if len(span) == 1:
logging.debug('Matched span: ' + span.text + ' | Span lenght: ' + str(len(span)) + ' | Span POS: ' + span.root.pos_)
if span.lemma_ not in terms_element:
# if span.lemma_ not in one_word_terms_help_list_json:
# one_word_terms_help_list_json.append(span.lemma_)
term_properties = {}
sentpos_array = []
term_properties['wcount'] = '1'
term_properties['ttype'] = span.root.pos_
term_properties['tname'] = span.lemma_
term_properties['osn'] = NORWEGIAN_STEMMER.stem(span.text)
sentpos_array.append(str(sentence_index) + '/' + str(span.start+1))
term_properties['sentpos'] = sentpos_array
terms_element[span.lemma_] = term_properties
else:
if span.lemma_ in terms_element:
if str(sentence_index) + '/' + str(span.start+1) not in terms_element[span.lemma_]['sentpos']:
terms_element[span.lemma_]['sentpos'].append(str(sentence_index) + '/' + str(span.start+1))
if len(span) == 2:
logging.debug('Matched span: ' + span.text + ' | Span lenght: ' + str(len(span)) + ' | Span POS: ' + str([tkn.pos_ for tkn in span]) + ' | Span\'s root: ' + span.root.lemma_ + ' | Span subtree: ' + str([sub.head for sub in span.subtree]))
if span.lemma_ not in terms_element:
# if span.lemma_ not in two_word_terms_help_list_json:
# two_word_terms_help_list_json.append(span.lemma_)
term_properties = {}
sentpos_array = []
term_properties['wcount'] = '2'
term_properties['ttype'] = '_'.join(tkn.pos_ for tkn in span)
term_properties['tname'] = span.lemma_
term_properties['osn'] = [NORWEGIAN_STEMMER.stem(tkn.text) for tkn in span]
sentpos_array.append(str(sentence_index) + '/' + str(span.start+1))
term_properties['sentpos'] = sentpos_array
terms_element[span.lemma_] = term_properties
if span.root.pos_ in ['NOUN', 'PROPN']:
if span.root.lemma_ in terms_element:
if 'reldown' in terms_element[span.root.lemma_]:
terms_element[span.root.lemma_]['reldown'].append(list(terms_element).index(span.lemma_) + 1)
else:
reldown_array = []
reldown_array.append(list(terms_element).index(span.lemma_) + 1)
terms_element[span.root.lemma_]['reldown'] = reldown_array
else:
# one_word_terms_help_list_json.append(span.root.lemma_)
term_properties = {}
sentpos_array = []
term_properties['wcount'] = '1'
term_properties['ttype'] = span.root.pos_
term_properties['tname'] = span.root.lemma_
term_properties['osn'] = NORWEGIAN_STEMMER.stem(span.root.text)
sentpos_array.append(str(sentence_index) + '/' + str(span.root.i+1))
term_properties['sentpos'] = sentpos_array
reldown_array = []
reldown_array.append(list(terms_element).index(span.lemma_) + 1)
term_properties['reldown'] = reldown_array
terms_element[span.root.lemma_] = term_properties
# if ROOT in 0 position
if [tkn.text for tkn in span].index(span.root.text) == 0:
if span[1].pos_ in ['NOUN', 'PROPN']:
if span[1].lemma_ in terms_element:
if 'reldown' in terms_element[span[1].lemma_]:
terms_element[span[1].lemma_]['reldown'].append(list(terms_element).index(span.lemma_) + 1)
else:
reldown_array = []
reldown_array.append(list(terms_element).index(span.lemma_) + 1)
terms_element[span[1].lemma_]['reldown'] = reldown_array
else:
# one_word_terms_help_list_json.append(span[1].lemma_)
term_properties = {}
sentpos_array = []
term_properties['wcount'] = '1'
term_properties['ttype'] = span[1].pos_
term_properties['tname'] = span[1].lemma_
term_properties['osn'] = NORWEGIAN_STEMMER.stem(span[1].text)
sentpos_array.append(str(sentence_index) + '/' + str(span[1].i+1))
term_properties['sentpos'] = sentpos_array
reldown_array = []
reldown_array.append(list(terms_element).index(span.lemma_) + 1)
term_properties['reldown'] = reldown_array
terms_element[span[1].lemma_] = term_properties
# if ROOT in 1 position
else:
if span[0].pos_ in ['NOUN', 'PROPN']:
if span[0].lemma_ in terms_element:
if 'reldown' in terms_element[span[0].lemma_]:
terms_element[span[0].lemma_]['reldown'].append(list(terms_element).index(span.lemma_) + 1)
else:
reldown_array = []
reldown_array.append(list(terms_element).index(span.lemma_) + 1)
terms_element[span[0].lemma_]['reldown'] = reldown_array
else:
# one_word_terms_help_list_json.append(span[1].lemma_)
term_properties = {}
sentpos_array = []
term_properties['wcount'] = '1'
term_properties['ttype'] = span[0].pos_
term_properties['tname'] = span[0].lemma_
term_properties['osn'] = NORWEGIAN_STEMMER.stem(span[0].text)
sentpos_array.append(str(sentence_index) + '/' + str(span[0].i+1))
term_properties['sentpos'] = sentpos_array
reldown_array = []
reldown_array.append(list(terms_element).index(span.lemma_) + 1)
term_properties['reldown'] = reldown_array
terms_element[span[0].lemma_] = term_properties
if 'relup' in terms_element[span.lemma_]:
terms_element[span.lemma_]['relup'].append(list(terms_element).index(span.lemma_) + 1)
else:
relup_array = []
relup_array.append(list(terms_element).index(span.root.lemma_) + 1)
terms_element[span.lemma_]['relup'] = relup_array
# if span.root.pos_ == 'ADJ':
# if span.root.lemma_ in terms_element:
# if 'reldown' in terms_element[span.root.lemma_]:
# terms_element[span.root.lemma_]['reldown'].append(list(terms_element).index(span.root.lemma_) + 1)
# else:
# reldown_array = []
# reldown_array.append(list(terms_element).index(span.root.lemma_) + 1)
# terms_element[span.root.lemma_]['reldown'] = reldown_array
# else:
# one_word_terms_help_list_json.append(span.root.lemma_)
# term_properties = {}
# sentpos_array = []
# term_properties['wcount'] = '1'
# term_properties['ttype'] = span.root.pos_
# term_properties['tname'] = span.root.lemma_
# term_properties['osn'] = NORWEGIAN_STEMMER.stem(span.root.text)
# sentpos_array.append(str(sentence_index) + '/' + str(span.root.i+1))
# term_properties['sentpos'] = sentpos_array
# reldown_array = []
# reldown_array.append(list(terms_element).index(span.lemma_) + 1)
# term_properties['reldown'] = reldown_array
# terms_element[span.root.lemma_] = term_properties
# if 'relup' in terms_element[span.lemma_]:
# terms_element[span.lemma_]['relup'].append(list(terms_element).index(span.lemma_) + 1)
# else:
# relup_array = []
# relup_array.append(list(terms_element).index(span.root.lemma_) + 1)
# terms_element[span.lemma_]['relup'] = relup_array
else:
if span.lemma_ in terms_element:
if str(sentence_index) + '/' + str(span.start+1) not in terms_element[span.lemma_]['sentpos']: