-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathpparser.py
executable file
·1625 lines (1355 loc) · 56.8 KB
/
pparser.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
import tokenizer
import copy
import re
import multiprocessing
import numpy as np
from datetime import date, datetime, time
import collections
import helpers
import entities
import string
import os
import gensim
import mimetypes
import logging
import pprint
from gensim.models import KeyedVectors
import logging
import itertools
import glob
import sys
import phrase_fun
import syntax
import json
# configuration and parameters
logging.basicConfig(
format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
params = {'size': 200, 'iter': 20, 'window': 2, 'min_count': 15,
'workers': max(1, multiprocessing.cpu_count() - 1), 'sample': 1E-3, }
class IssueParser:
"""
This is a class for holding information about an issue in
computer-friendly form. It is responsible for:
1. Detecting Dates
2. Split document to articles
3. Split articles to extracts and non-extracts for assisting
in construction of the parse tree for each ROI.
4. Detect Signatories of Given Documents
5. Train a word2vec model with gensim for further usage."""
def __init__(self, filename, stdin=False, toTxt=False):
self.filename = filename
self.lines = []
tmp_lines = []
if not stdin:
filetype = mimetypes.guess_type(filename)[0]
# if it is in PDF format convert it to txt
if filetype == 'application/pdf':
outfile = filename.replace('.pdf', '.txt')
if not os.path.isfile(outfile):
os.system('pdf2txt.py {} > {}'.format(filename, outfile))
filename = outfile
elif filetype != 'text/plain':
raise UnrecognizedFileException(filename)
if not stdin:
infile = open(filename, 'r')
# remove ugly hyphenthation
while True:
if not stdin:
l = infile.readline()
else:
l = sys.stdin.readline()
if not l:
break
l = l.replace('−\n', '')
l = l.replace('\n', ' ')
l = re.sub(r' +', ' ', l)
l = helpers.fix_par_abbrev(l)
tmp_lines.append(l)
if not stdin:
infile.close()
for line in tmp_lines:
if line == '':
continue
elif line.startswith('Τεύχος') or line.startswith('ΕΦΗΜΕΡΙ∆Α TΗΣ ΚΥΒΕΡΝΗΣΕΩΣ') or line.startswith('ΕΦΗΜΕΡΙΣ ΤΗΣ ΚΥΒΕΡΝΗΣΕΩΣ'):
continue
else:
try:
n = int(line)
continue
except ValueError:
self.lines.append(line)
if line.startswith('Αρ. Φύλλου'):
for x in line.split(' '):
if x.isdigit():
self.issue_number = x
break
self.dates = []
self.find_dates()
self.articles = {}
self.articles_as_paragraphs = {}
if not stdin:
self.name = filename.replace('.pdf', '')
else:
self.name = 'stdin'
self.sentences = {}
self.find_articles()
self.detect_statutes()
def __str__(self):
return self.name
def split_article(self, article):
paragraphs = collections.defaultdict(list)
paragraph_ids = [
par_id.group().strip('.') for par_id in re.finditer(
r'\d+.', self.articles[article])]
paragraph_corpus = list(
filter(
lambda x: x.rstrip() != '',
re.split(
r'\d+.',
self.articles[article])))
paragraph_corpus = [p.rstrip().lstrip() for p in paragraph_corpus]
return paragraph_corpus
def detect_statutes(self):
"""Detect all statutes within the issue
such as Laws, Decrees and Acts"""
self.statutes = {}
for article in self.articles.keys():
for extract in self.get_non_extracts(article):
legislative_acts = list(re.finditer(
entities.legislative_act_regex, extract))
laws = list(re.finditer(entities.law_regex, extract))
presidential_decrees = list(re.finditer(
entities.presidential_decree_regex, extract))
legislative_decrees = list(re.finditer(
entities.legislative_decree_regex, extract))
self.statutes[article] = []
self.statutes[article].extend(laws)
self.statutes[article].extend(legislative_acts)
self.statutes[article].extend(presidential_decrees)
self.statutes[article].extend(legislative_decrees)
self.statutes[article] = [statute.group()
for statute in self.statutes[article]]
return self.statutes
def __contains__(self, key):
for article in self.articles.keys():
if key in self.statutes[article]:
return True
return False
def find_statute(self, key):
for article in sorted(self.articles.keys()):
if key in self.statutes[article]:
yield article
def serialize(self):
serializable = {
'_id': self.__str__(),
'date': str(self.issue_date),
'articles': self.articles,
'articles_as_paragraphs': self.articles_as_paragraphs,
'dates': self.dates,
'statutes': self.statutes,
'extracts': self.extracts
}
return serializable
def __dict__(self):
return self.serialize()
def find_dates(self):
"""Detect all dates withing the given document"""
year_regex = r'([1-2][0-9][0-9][0-9])'
now = datetime.now()
for i, line in enumerate(self.lines):
result = entities.date_regex.findall(line)
if result != []:
self.dates.append((i, result))
for line in self.lines:
res = re.search(year_regex, line)
if res:
result = int(res.group())
if 1976 <= result <= now.year:
self.year = result
break
if self.dates == []:
logging.warning('Could not find dates!')
return []
try:
self.issue_date = string_to_date(self.dates[0][1][0])
self.signed_date = self.dates[-1]
except IndexError:
logging.warning('Could not find dates!')
finally:
return self.dates
def parse_name(self):
# parse 20150100022.txt
r = helpers.split_index(s, [4, 6, 8])
return 'ΦΕΚ Α {}/{}'.format(r[-1], r[1])
def find_articles(self, min_extract_chars=100):
"""Split the document into articles,
Detect Extracts that are more than min_extract_chars.
Extracts start with quotation marks («, »).
Strip punctuation and split document into sentences.
"""
article_indices = []
for i, line in enumerate(self.lines):
if line.startswith('Άρθρο') or line.startswith(
'Ο Πρόεδρος της Δημοκρατίας'):
article_indices.append((i, line))
self.articles[line] = ''
for j in range(len(article_indices) - 1):
content = self.lines[article_indices[j]
[0] + 1: article_indices[j + 1][0]]
paragraphs = collections.defaultdict(list)
current = '0'
for t in content:
x = re.search(r'\d+.', t)
if x and x.span() in [(0, 2), (0, 3)]:
current = x.group().strip('.')
paragraphs[current].append(t)
sentences = {}
for par in paragraphs.keys():
val = ''.join(paragraphs[par])[1:]
paragraphs[par] = val
sentences[par] = list(
filter(
lambda x: x.rstrip() != '',
tokenizer.tokenizer.split(val, False, '. ')))
self.articles[article_indices[j][1]] = ''.join(content)
self.articles_as_paragraphs[article_indices[j][1]] = paragraphs
try:
del self.articles['Ο Πρόεδρος της Δημοκρατίας']
except BaseException:
pass
self.extracts = {}
self.non_extracts = {}
for article in self.articles.keys():
# find extracts
left_quot = [m.start()
for m in re.finditer('«', self.articles[article])]
right_quot = [m.start()
for m in re.finditer('»', self.articles[article])]
left_quot.extend(right_quot)
temp_extr = sorted(left_quot)
res_extr = []
c = '«'
for idx in temp_extr:
if c == '«' and self.articles[article][idx] == c:
res_extr.append(idx)
c = '»'
elif c == '»' and self.articles[article][idx] == c:
res_extr.append(idx)
c = '«'
self.extracts[article] = list(zip(res_extr[::2], res_extr[1::2]))
# drop extracts with small chars
self.extracts[article] = sorted(
list(
filter(
lambda x: x[1] -
x[0] +
1 >= min_extract_chars,
self.extracts[article])),
key=lambda x: x[0])
tmp = self.articles[article].strip('-').split('.')
# remove punctuation
tmp = [re.sub(r'[^\w\s]', '', s) for s in tmp]
tmp = [line.split(' ') for line in tmp]
self.sentences[article] = tmp
def get_extracts(self, article):
"""Get direct parts that should be added, modified or deleted"""
for i, j in self.extracts[article]:
yield self.articles[article][i + 1: j]
def get_non_extracts(self, article):
"""Get non-extracts i.e. where the commands for ammendments
can be found"""
if len(self.extracts[article]) == 0:
yield self.articles[article]
return
x0, y0 = self.extracts[article][0]
yield self.articles[article][0: max(0, x0)]
for i in range(1, len(self.extracts[article]) - 1):
x1, y1 = self.extracts[article][i]
x2, y2 = self.extracts[article][i + 1]
yield self.articles[article][y1 + 1: x2]
xl, yl = self.extracts[article][-1]
yield self.articles[article][yl + 1:]
def get_alternating(self, article):
"""Get extracts and non-extracts alternating as a generator"""
# start with an extract
if self.extracts[article][0] == 0:
flag = False
else:
flag = True
extracts_ = list(self.get_extracts(article))
non_extracts_ = list(self.get_non_extracts(article))
for e, n in itertools.zip_longest(extracts_, non_extracts_):
if flag:
if n is not None:
yield n
if e is not None:
yield e
else:
if e is not None:
yield e
if n is not None:
yield n
def all_sentences(self):
for article in self.sentences.keys():
for sentence in self.sentences[article]:
yield sentence
def detect_signatories(self):
self.signatories = set([])
for i, line in enumerate(self.lines):
if line.startswith('Ο Πρόεδρος της Δημοκρατίας'):
minister_section = self.lines[i:]
break
for i, line in enumerate(minister_section):
for minister in ministers:
x = minister.is_mentioned(line)
if x is not None:
self.signatories |= set([minister])
for signatory in self.signatories:
logging.info(signatory)
self.signatories = list(self.signatories)
return self.signatories
def detect_new_laws(self):
"""Detect new laws being added to Greek
Legislation. Proceedure includes
1. Detection of regular expressions that undermine new addition
2. Detection of the new law identifier
3. Construction of LawParser Objects and parse the law corpus
4. Keep the new laws in a dictionary"""
new_law_regex = entities.LegalEntities.ratification
self.new_laws = {}
regions_of_interest = []
for i, line in enumerate(self.lines):
if re.search(new_law_regex, line):
regions_of_interest.append(i)
if regions_of_interest == []:
return self.new_laws
else:
regions_of_interest.append(len(self.lines) - 1)
for start, end in zip(regions_of_interest, regions_of_interest[1:]):
for j, line in enumerate(self.lines[start:end]):
i = j + start
result = re.search(new_law_regex, line + self.lines[i + 1])
if result:
result = result.group().rstrip().split(' ')
abbreviation = 'ν.'
if result[0] == 'ΠΡΟΕΔΡΙΚΟ':
abbreviation = 'π.δ.'
elif result[0] == 'ΚΟΙΝΗ':
abbreviation = 'ΚΥΑ'
elif result[0] == 'ΝΟΜΟΘΕΤΙΚΟ':
abbreviation = 'ν.δ.'
identifier = '{} {}/{}'.format(abbreviation,
result[-1], self.year)
logging.info(
'Issue: ' +
self.name +
'Identifier: ' +
identifier)
ignore = True
self.new_laws[identifier] = LawParser(identifier)
self.new_laws[identifier].lines = self.lines
self.new_laws[identifier].find_corpus(
government_gazette_issue=True)
return self.new_laws
class UnrecognizedFileException(Exception):
def __init__(self, filename):
super().__init__('Unrecognized filetype ' + str(filename))
def get_issues_from_dataset(directory='../data', text_format=False):
cwd = os.getcwd()
os.chdir(directory)
issues = []
if text_format:
filelist = glob.glob('*.txt')
for filename in filelist:
issue = IssueParser(filename)
issues.append(issue)
else:
filelist = glob.glob('*.pdf')
for filename in filelist:
outfile = filename.strip('.pdf') + '.txt'
logging.info(outfile)
if not os.path.isfile(outfile):
os.system('pdf2txt.py {} > {}'.format(filename, outfile))
issue = IssueParser(outfile)
issues.append(issue)
os.chdir(cwd)
return issues
class LawParser:
"""
This class hosts the law parser. The law is provided
in a file (if it exists) and is parsed in order to be
split in articles and sentences, ready to be stored in
the database. This class supports insertions, replacements
and deletions of articles, paragraphs, phrases and periods.
It can also provide a serializable object for updating the
database with its contents.
"""
def __init__(self, identifier, filename=None, autoincrement_version=False):
"""The constructor of LawParser is responsible for
reading and parsing the file as well as detecting
titles, lemmas and articles which are split into sentences
by find_corpus()
:param identifier This is the law identifier (for example ν. 1920/1991)
:param filename (optional) the text file
"""
self.lines = []
self.identifier = identifier
self.autoincrement_version = autoincrement_version
self.version_index = 0
if filename and isinstance(filename, str):
self.filename = filename
tmp_lines = []
with open(filename, 'r') as infile:
# remove ugly hyphenthation
while 1 == 1:
l = infile.readline()
if not l:
break
l = l.replace('-\n', '')
l = l.replace('\n', ' ')
tmp_lines.append(l)
for line in tmp_lines:
if line == '':
continue
else:
self.lines.append(line)
self.thesaurus = {}
self.lemmas = {}
self.articles = collections.defaultdict(dict)
self.titles = {}
self.corpus = {}
self.sentences = collections.defaultdict(dict)
self.amendee = None
self.find_corpus(fix_paragraphs=False)
self.detect_entities()
def __repr__(self):
return self.identifier
def __str__(self):
return self.identifier
def fix_paragraphs(self, lines, get_title=True):
"""Fix paragraphs in a text. That means that
a corpus of lines enumerated with natural numbers
1., 2., etc. would be groupped into respective
paragraps
"""
result = []
if lines[0].startswith('Άρθρο'):
lines.pop()
indices = []
start = 0
for i, t in enumerate(lines):
x = re.search(r'\d+.', t)
if x and x.span() in [(0, 2), (0, 3)]:
try:
number = int(x.group().split('.')[0])
except BaseException:
continue
if number == start + 1:
indices.append(i)
start += 1
for j in range(len(indices) - 1):
content = lines[indices[j]: indices[j + 1]]
result.append(content)
if result != []:
result.append(lines[indices[-1]:])
result = [''.join(r) for r in result]
if get_title:
title = ''.join(lines[:indices[0]])
else:
title = None
return result, title
else:
splitter = -1
for i, line in enumerate(lines):
if line.rstrip() == '':
splitter = i
break
# Split in first ' ' character
# The article title is before the space character(s)
# The rest is after the space character(s)
if splitter != -1:
title = ''.join(lines[:splitter])
result = '1. ' + ''.join(lines[splitter:])
else:
result = ''.join(lines)
title = ''
return result, title
def fix_name(self, name):
if name.isdigit():
return name
else:
try:
return str(entities.Numerals.full_number_to_integer(name))
except BaseException:
return name
def find_corpus(self, government_gazette_issue=False, fix_paragraphs=True):
"""Analyzes the corpus to articles, paragraphs and
then sentences"""
idx = []
for i, line in enumerate(self.lines):
if line.startswith('Αρθρο:') or line.startswith('Άρθρο '):
idx.append(i)
for j in range(len(idx) - 1):
x, y = idx[j], idx[j + 1]
self.lines[x] = self.lines[x].strip(':').replace(':\t', ' ')
name = self.lines[x].rstrip().replace(
'Αρθρο: ', '').replace('Άρθρο ', '')
name = self.fix_name(name)
self.corpus[name] = self.lines[x: y]
if fix_paragraphs:
for article in self.corpus.keys():
fixed_lines, title = self.fix_paragraphs(self.corpus[article])
self.titles[article] = title
self.corpus[article] = fixed_lines
self.prune_title(article)
for article in self.corpus.keys():
for i, line in enumerate(self.corpus[article]):
if line.startswith(
'Κείμενο Αρθρου') or government_gazette_issue:
if government_gazette_issue:
self.articles[article] = self.corpus[article]
elif line.startswith('Κείμενο Άρθρου'):
self.articles[article] = self.corpus[article][i + 1:]
paragraphs = collections.defaultdict(list)
current = '0'
for t in self.articles[article]:
x = re.search(r'\d+.', t)
if x and x.span() in [(0, 2), (0, 3)]:
current = x.group().strip('.')
paragraphs[current].append(t)
sentences = {}
for par in paragraphs.keys():
val = ''.join(paragraphs[par])[1:]
val = helpers.fix_whitespaces(val)
val = helpers.fix_par_abbrev(val)
val = helpers.fix_hyphenthation(val)
paragraphs[par] = val
sentences[par] = list(
filter(
lambda x: x.rstrip() != '',
tokenizer.tokenizer.split(
val, False, '. ')
)
)
self.articles[article] = paragraphs
self.sentences[article] = sentences
if government_gazette_issue:
break
def detect_entities(self):
"""Detect all entities within the issue and stores them in a dictionary"""
# Creating entity dictionary and setting keys
self.entities = {}
self.entities["Urls"] = []
self.entities["CPC Codes"] = []
self.entities["CPV Codes"] = []
self.entities["IBANs"] = []
self.entities["E-mails"] = []
self.entities["Id Numbers"] = []
self.entities["Military Personel"] = []
self.entities["Natura 2000 Regions"] = []
self.entities["Scales"] = []
self.entities["EU Directives"] = []
self.entities["EU Regulations"] = []
self.entities["EU Decisions"] = []
self.entities["Phone Numbers"] = []
self.entities["Protocols"] = []
self.entities["AFM numbers"] = []
self.entities["NUTS Region Codes"] = []
self.entities["Exact times"] = []
self.entities["Ship Tonnage"] = []
self.entities["KAEK Codes"] = []
self.entities["Hull"] = []
self.entities["Flags"] = []
self.entities["Monetary Amounts"] = []
self.entities["Metrics"] = []
self.entities["Conditions"] = []
self.entities["Contraints"] = []
self.entities["Durations"] = []
# Iterating through lines
for i , line in enumerate(self.lines):
urls = re.findall(entities.urls,line)
cpc = re.findall(entities.cpc, line)
cpv = re.findall(entities.cpv,line)
ibans = re.findall(entities.ibans,line)
e_mails = re.findall(entities.e_mails,line)
id_numbers = re.findall(entities.id_numbers, line)
military_personel = re.findall(entities.military_personel_id, line)
natura_regions = re.findall(entities.natura_regions,line)
scales = re.findall(entities.scales, line)
directives_eu = re.findall(entities.directives_eu, line)
regulations_eu = re.findall(entities.regulations_eu, line)
decisions_eu = re.findall(entities.decisions_eu, line)
phone_numbers = re.findall(entities.phone_numbers, line)
protocols = re.findall(entities.protocols, line)
afm = re.findall(entities.afm, line)
nuts_reg = re.findall(entities.nuts_reg, line)
exact_times = re.findall(entities.exact_times, line)
tonnage = re.findall(entities.tonnage, line)
kaek = re.findall(entities.kaek, line)
hull = re.findall(entities.hull, line)
flag = re.findall(entities.flag, line)
money = entities.get_monetary_amounts(line)
metrics = entities.get_metrics(line)
conditions = entities.get_conditions(line)
constraints = entities.get_constraints(line)
durations = entities.get_durations(line)
if urls != []:
self.entities["Urls"].append((i,urls))
if cpc != []:
self.entities["CPC Codes"].append((i,cpc))
if cpv != []:
self.entities["CPV Codes"].append((i,cpv))
if ibans != []:
self.entities["IBANs"].append((i,ibans))
if e_mails != []:
self.entities["E-mails"].append((i,e_mails))
if id_numbers != []:
self.entities["Id Numbers"].append((i,id_numbers))
if military_personel != []:
self.entities["Military Personel"].append((i,military_personel))
if natura_regions != []:
self.entities["Natura 2000 Regions"].append((i,natura_regions))
if scales != []:
self.entities["Scales"].append((i,scales))
if directives_eu != []:
self.entities["EU Directives"].append((i,directives_eu))
if regulations_eu != []:
self.entities["EU Regulations"].append((i,regulations_eu))
if decisions_eu != []:
self.entities["EU Decisions"].append((i,decisions_eu))
if phone_numbers != []:
self.entities["Phone Numbers"].append((i,phone_numbers))
if protocols != []:
self.entities["Protocols"].append((i,protocols))
if afm != []:
self.entities["AFM numbers"].append((i,afm))
if nuts_reg != []:
self.entities["NUTS Region Codes"].append((i,nuts_reg))
if exact_times != []:
self.entities["Exact times"].append((i,exact_times))
if tonnage != []:
self.entities["Ship Tonnage"].append((i,tonnage))
if kaek != []:
self.entities["KAEK Codes"].append((i,kaek))
if hull != []:
self.entities["Hull"].append((i,hull))
if flag != []:
self.entities["Flags"].append((i,flag))
if money != []:
self.entities["Monetary Amounts"].append((i,money))
if metrics != []:
self.entities["Metrics"].append((i,metrics))
if conditions != []:
self.entities["Conditions"].append((i,conditions))
if constraints != []:
self.entities["Contraints"].append((i,constraints))
if durations != []:
self.entities["Durations"].append((i,durations))
return self.entities
def __dict__(self):
return self.serialize()
def serialize(self, full=True):
"""Returns the object in database-friendly format
in a dictionary.
:params full: Return the full law if true else avoid articles
This flag can be used to avoid the 16MB limit of BSON
"""
if self.autoincrement_version:
self.version_index += 1
data = {
'_id': self.identifier,
'thesaurus': self.thesaurus,
'lemmas': self.lemmas,
'titles': self.titles,
'amendee': self.amendee,
'entities':self.entities
}
if full:
data['articles'] = self.sentences
return data
@staticmethod
def from_serialized(x):
identifier = x['_id']
law = LawParser(identifier)
law.thesaurus = x['thesaurus']
law.lemmas = x['lemmas']
law.titles = x['titles']
law.sentences = x['articles']
law.amendee = x['amendee']
law.entities = x['entities']
try:
law.issue = x['issue']
except BaseException:
law.issue = ''
return law, identifier
def add_article(self, article, content, title=None, lemmas=None):
"""Add article from content
:param article the article id
:param content the content in raw text
:title (optional) title of article
:lemmas (optional) lemmas for article
"""
# prepare context
article = str(article)
paragraphs = collections.defaultdict(list)
paragraph_ids = [par_id.group().strip('.')
for par_id in re.finditer(r'\d+.', content)]
# filter ids
filtered_ids = []
current = 1
for i, x in enumerate(paragraph_ids):
if int(x) == current:
filtered_ids.append(x + '.')
current += 1
if len(paragraph_ids) == 0:
filtered_ids = ['1']
filtered_ids_regex = '|'.join(map(re.escape, filtered_ids))
paragraph_corpus = list(
filter(
lambda x: x.rstrip() != '',
re.split(
filtered_ids_regex,
content)))
paragraph_corpus = [p.rstrip().lstrip() for p in paragraph_corpus]
sentences = {}
paragraphs = {}
for kkey, val in itertools.zip_longest(filtered_ids, paragraph_corpus):
if kkey is None or val is None:
break
key = kkey.strip('. ')
sentences[key] = tokenizer.tokenizer.split(val, False, '. ')
paragraphs[key] = val
self.sentences[article] = sentences
if title:
self.titles[article] = title
if lemmas:
self.lemmas[article] = lemmas
return self.serialize()
def remove_article(self, article):
"""Removal of article based on its id
:param artitcle id
"""
article = str(article)
try:
del self.sentences[article]
except BaseException:
logging.warning('Could not find sentences')
try:
del self.corpus[article]
except BaseException:
logging.warning('Could not find corpus')
try:
del self.lemmas[article]
except BaseException:
logging.warning('Could not find lemmas')
try:
del self.titles[article]
except BaseException:
logging.warning('Could not find titles')
return self.serialize()
def add_paragraph(self, article, paragraph, content):
"""Addition of paragraph on article
:article article id
:paragraph paragraph id
:content content in raw text to be split into periods
"""
article = str(article)
paragraph = str(paragraph)
# prepare content for modification
try:
content = helpers.remove_front_num(content).rstrip('.')
except BaseException:
content = content.rstrip('.')
# add in its full form or split into periods
self.articles[article][paragraph] = content
self.sentences[article][paragraph] = tokenizer.tokenizer.split(
content, False, '. ')
return self.serialize()
def remove_paragraph(self, article, paragraph):
"""Removal of paragraph"""
article = str(article)
paragraph = str(paragraph)
try:
del self.sentences[article][paragraph]
except BaseException:
pass
return self.serialize()
def replace_phrase(
self,
old_phrase,
new_phrase,
article=None,
paragraph=None):
"""Replacement of phrase inside document
:old_phrase phrase to be replaced
:new_phrase new phrase
:article optional detect phrase in certain article
:paragraph optional detect phrase in certain paragraph
"""
self.sentences[article][paragraph] = phrase_fun.replace_phrase(
self.sentences[article][paragraph],
new_phrase=new_phrase,
old_phrase=old_phrase
)
return self.serialize()
def remove_phrase(self, old_phrase, article=None, paragraph=None):
"""Removal of certain phrase i.e. replacement with empty string"""
return self.replace_phrase(old_phrase, '', article, paragraph)
def insert_phrase(
self,
new_phrase,
position='append',
old_phrase='',
article=None,
paragraph=None):
"""Phrase insertion with respect to another phrase"""
self.sentences[article][paragraph] = phrase_fun.insert_phrase(
self.sentences[article][paragraph],
new_phrase=new_phrase,
position=position,
old_phrase=old_phrase
)
return self.serialize()
def renumber_case(
self,