-
Notifications
You must be signed in to change notification settings - Fork 2
/
entity_custom.py
643 lines (540 loc) · 19.6 KB
/
entity_custom.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
from spacy.tokens import Span
from spacy.util import filter_spans
import re
from functools import partial, reduce
period_rules = [
"segundo",
"segundos",
"minuto",
"minutos",
"hr",
"hs",
"hora",
"horas",
"año",
"años",
"dia",
"día",
"dias",
"días",
"mes",
"meses",
]
law_left_nbors = [
"ley",
"leyes",
]
address_first_left_nbors = [
"calle",
"Calle",
"dirección",
"Dirección",
"avenida",
"av.",
"Avenida",
"Av.",
"pasaje",
"Pasaje",
"Parcela",
"parcela",
]
address_second_left_nbors = [
"instalación",
"contramano",
"sita",
"sitas",
"sito",
"sitos",
"real",
"domiciliado",
"domiciliada",
"constituido",
"constituida",
"contramano",
"intersección",
"domicilio",
"ubicado",
"registrado",
"ubicada",
"real",
]
address_connector = "en"
license_plate_left_nbor = [
"patente",
"dominio",
]
age_right_token = "años"
age_text_in_token = "edad"
number_abreviated_indicator = "nº"
case_first_left_token = "caso"
case_second_left_token = "causa"
cuij_indicator = "cuij"
actuacion_number_indicator = "nro"
actuacion_nbor_token = "actuación"
expediente_indicator = "expediente"
judge_lemma = ["juez", "jueza", "Juez", "Jueza"]
secretarix_lemma = [
"secretario",
"secretaria",
"prosecretario",
"prosecretaria",
"Prosecretario",
"Prosecretaria",
"Secretario",
"Secretaria",
]
prosecutor_lemma = ["fiscal", "fiscalía", "Fiscal", "Fiscalía"]
ombuds_person_lemma = ["defensor", "defensora", "Defensora", "Defensor"]
accused_lemma = [
"acusado",
"acusada",
"imputado",
"imputada",
"infractor",
"infractora",
"Acusado",
"Acusada",
"Imputado",
"Imputada",
"Infractor",
"Infractora",
]
advisor_lemma = ["asesor", "asesora", "Asesor", "Asesora"]
phone_lemma = ["teléfono", "tel", "celular", "número", "numerar", "telefónico"]
phone_text = ["telefono", "tel", "cel"]
def is_age(token):
return token.like_num and token.nbor(1).text == age_right_token and age_text_in_token in token.sent.text
def is_caseNumber(token):
return token.like_num and (
(token.nbor(-1).lower_ == number_abreviated_indicator and token.nbor(-2).lower_ == case_second_left_token)
or token.nbor(-1).lower_ == case_first_left_token
)
def is_cuijNumber(token):
return (token.is_ascii and token.nbor(-3).lower_ == cuij_indicator) or (
token.like_num and token.nbor(-3).lower_ == cuij_indicator
)
def is_actuacionNumber(token):
return (
token.nbor(-1).lower_ == ":"
and token.nbor(-2).lower_ == actuacion_number_indicator
and token.nbor(-3).lower_ == actuacion_nbor_token
)
def is_expedienteNumber(token):
return (
token.nbor(-1).lower_ == number_abreviated_indicator
and (token.nbor(-3).lower_ == expediente_indicator or token.nbor(-2).lower_ == expediente_indicator)
) or (token.like_num and token.nbor(-2).lower_ == expediente_indicator)
def is_place_token(token):
# TODO Este enfoque puede generar falsos positivos
first_left_nbors = [
"asentamiento",
"paraje",
"localidad",
"country",
"distrito",
]
return token.nbor(-1).lower_ in first_left_nbors
def is_law(ent):
first_token = ent[0]
return ent.label_ == "NUM" and (
first_token.nbor(-1).lower_ in law_left_nbors
or first_token.nbor(-2).lower_ in law_left_nbors
or first_token.nbor(-3).lower_ in law_left_nbors
)
def is_last(doc, token_id):
return token_id == len(doc) - 1
def is_between_tokens(token_id, left=0, right=0):
return token_id < right and token_id >= left
is_from_first_tokens = partial(is_between_tokens, left=0, right=3)
def is_judge(ent):
first_token = ent[0]
return ent.label_ in ["PER", "LOC"] and (
first_token.nbor(-1).lemma_ in judge_lemma
or first_token.nbor(-2).lemma_ in judge_lemma
or first_token.nbor(-3).lemma_ in judge_lemma
)
def is_period(ent):
last_token = ent[len(ent) - 1]
return ent.label_ in ["NUM"] and last_token.nbor(1).text in period_rules
def is_secretary(ent):
first_token = ent[0]
return ent.label_ in ["PER", "LOC"] and (
first_token.nbor(-1).lemma_ in secretarix_lemma
or first_token.nbor(-2).lemma_ in secretarix_lemma
or first_token.nbor(-3).lemma_ in secretarix_lemma
)
def is_prosecutor(ent):
first_token = ent[0]
return ent.label_ in ["PER", "LOC"] and (
first_token.nbor(-1).lemma_ in prosecutor_lemma
or first_token.nbor(-2).lemma_ in prosecutor_lemma
or first_token.nbor(-3).lemma_ in prosecutor_lemma
)
def is_ombuds_person(ent):
first_token = ent[0]
return ent.label_ in ["PER", "LOC"] and (
first_token.nbor(-1).lemma_ in ombuds_person_lemma
or first_token.nbor(-2).lemma_ in ombuds_person_lemma
or first_token.nbor(-3).lemma_ in ombuds_person_lemma
)
def is_accused(ent):
first_token = ent[0]
return ent.label_ in ["PER", "LOC"] and (
first_token.nbor(-1).lemma_ in accused_lemma
or first_token.nbor(-2).lemma_ in accused_lemma
or first_token.nbor(-3).lemma_ in accused_lemma
)
def is_advisor(ent):
first_token = ent[0]
return ent.label_ in ["PER", "LOC"] and (
first_token.nbor(-1).lemma_ in advisor_lemma
or first_token.nbor(-2).lemma_ in advisor_lemma
or first_token.nbor(-3).lemma_ in advisor_lemma
)
def is_ip_address(ent):
octet_rx = r"(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
pattern = re.compile(r"^{0}(?:\.{0}){{3}}$".format(octet_rx))
is_ip = pattern.match(str(ent))
return ent.label_ in ["NUM", "NUM_IP"] and is_ip
def is_phone(ent):
first_token = ent[0]
return ent.label_ == "NUM" and (
first_token.nbor(-1).lemma_ in phone_lemma
or first_token.nbor(-2).lemma_ in phone_lemma
or first_token.nbor(-3).lemma_ in phone_lemma
or first_token.nbor(-1).text in phone_text
or first_token.nbor(-2).text in phone_text
or (first_token.nbor(-1).text == "(" and first_token.nbor(1).text == ")")
)
# TODO this function could be used in many methods, check it!
def is_token_in_x_left_pos(token, pos, nbors):
try:
return token.nbor(-pos).lower_ in nbors
except Exception:
return False
def is_address(ent):
first_token = ent[0]
last_token = ent[-1]
address_1_tokens_to_left = is_token_in_x_left_pos(first_token, 1, address_first_left_nbors)
address_2_tokens_to_left_first_nbors = is_token_in_x_left_pos(first_token, 2, address_first_left_nbors)
address_2_tokens_to_left_second_nbors = is_token_in_x_left_pos(first_token, 2, address_second_left_nbors)
address_3_tokens_to_left_first_nbors = is_token_in_x_left_pos(first_token, 3, address_first_left_nbors)
address_3_tokens_to_left_second_nbors = is_token_in_x_left_pos(first_token, 3, address_second_left_nbors)
address_4_tokens_to_left_first_nbors = is_token_in_x_left_pos(first_token, 4, address_first_left_nbors)
address_4_tokens_to_left_second_nbors = is_token_in_x_left_pos(first_token, 4, address_second_left_nbors)
is_address_from_PER = ent.label_ in ["PER"] and (
address_1_tokens_to_left
or address_2_tokens_to_left_second_nbors
or last_token.like_num
or last_token.nbor().like_num
)
is_address_from_NUM = ent.label_ in ["NUM"] and (
address_1_tokens_to_left
or address_2_tokens_to_left_first_nbors
or address_2_tokens_to_left_second_nbors
or address_3_tokens_to_left_first_nbors
or address_3_tokens_to_left_second_nbors
or address_4_tokens_to_left_first_nbors
or address_4_tokens_to_left_second_nbors
)
return is_address_from_PER or is_address_from_NUM
def get_aditional_left_tokens_for_address(ent):
if ent.label_ in ["PER"] and ent[-1].nbor().like_num:
return 1
if ent.label_ in ["NUM"]:
token = ent[0]
if token.nbor(-1).lower_ in address_first_left_nbors:
return 1
if token.nbor(-2).lower_ in address_first_left_nbors or token.nbor(-2).lower_ in address_second_left_nbors:
return 2
if token.nbor(-3).lower_ in address_first_left_nbors:
return 3
if token.nbor(-3).lower_ in address_second_left_nbors:
return 2 - 1 if token.nbor(-2).lower_ == address_connector else 0
if token.nbor(-4).lower_ in address_first_left_nbors:
return 4
if token.nbor(-4).lower_ in address_second_left_nbors:
return 3 - 1 if token.nbor(-3).lower_ == address_connector else 0
return 0
def get_entity_to_remove_if_contained_by(ent_start, ent_end, list_entities):
for i, ent_from_list in enumerate(list_entities):
if (
ent_start >= ent_from_list.start
and ent_start <= ent_from_list.end
or ent_end >= ent_from_list.start
and ent_end <= ent_from_list.end
):
return ent_from_list
return None
def generate_address_span(ent, new_ents, doc):
address_token = get_aditional_left_tokens_for_address(ent)
ent_start = ent.start - address_token
ent_to_remove = get_entity_to_remove_if_contained_by(ent_start, ent.end, new_ents)
if ent_to_remove:
if (ent.end - ent_start) > (ent_to_remove.end - ent_to_remove.start):
new_ents = remove_wrong_labeled_entity_span(new_ents, ent_to_remove)
return Span(doc, ent_start, ent.end, label="DIRECCIÓN")
return Span(doc, ent_start, ent.end, label="DIRECCIÓN")
def could_be_an_article(ent):
token = ent[0]
first_left_token = token.nbor(-1).lower_
second_left_token = token.nbor(-2).lower_
third_left_token = token.nbor(-3).lower_
dont_consider = "bis"
return (
ent.label_ == "PATENTE_DOMINIO"
and token.lower_.find(dont_consider) != -1
and first_left_token not in license_plate_left_nbor
and second_left_token not in license_plate_left_nbor
and third_left_token not in license_plate_left_nbor
)
def is_license_plate(ent):
token = ent[0]
first_left_token = token.nbor(-1).lower_
second_left_token = token.nbor(-2).lower_
third_left_token = token.nbor(-3).lower_
return token.like_num and (
first_left_token in license_plate_left_nbor
or second_left_token in license_plate_left_nbor
or third_left_token in license_plate_left_nbor
)
def is_accused_or_advisor(ent):
return is_accused(ent) or is_advisor(ent)
def get_start_end_license_plate(ent):
token = ent[0]
first_left_token = token.nbor(-1).lower_
first_right_token = token.nbor(1).lower_
if len(ent.text) != 3: # this means it is not an "incomplete" license plate
return ent.start, ent.end
if len(first_left_token) == 3 and isinstance(first_left_token, str):
# 3 letras - 3 núm
return ent.start - 1, ent.end
if (
len(first_left_token) == 2
and len(first_right_token) == 2
and isinstance(first_left_token, str)
and isinstance(first_right_token, str)
):
# 2 letras - 3 núm - 2 letras
return ent.start - 1, ent.end + 1
if len(first_right_token) == 3 and isinstance(first_right_token, str):
# 3 núm - 3 letras
return ent.start, ent.end + 1
def remove_wrong_labeled_entity_span(ent_list, ent_to_remove):
return [ent for ent in ent_list if not (ent_to_remove.start == ent.start and ent_to_remove.end == ent.end)]
def process_fns(acc, data):
# from 3.9 We can use functools.cache on some functions
fn1, fn2, fn3 = data
if not fn1() and fn2():
acc.append(fn3())
return acc
class EntityCustom(object):
name = "entity_custom"
def __init__(self, nlp, tag="todas"):
self.nlp = nlp
self.tag = tag
self.tagged_fns_token = [
self.tag_fn(self.num_causa, ["judicial", "argentina"]),
self.tag_fn(self.edad, ["español"]),
self.tag_fn(self.num_cuij, ["judicial", "argentina"]),
self.tag_fn(self.num_actuacion, ["judicial", "argentina"]),
self.tag_fn(self.num_expediente, ["judicial", "argentina"]),
self.tag_fn(self.loc, ["lugar"]),
]
self.tagged_fns_ent = [
self.tag_fn(self.fecha_resolucion, ["judicial"]),
self.tag_fn(self.ley, ["judicial", "argentina"]),
self.tag_fn(self.periodo, ["español"]),
self.tag_fn(self.juezx, ["judicial", "argentina"]),
self.tag_fn(self.secretarix, ["judicial", "argentina"]),
self.tag_fn(self.fiscal, ["judicial", "argentina"]),
self.tag_fn(self.defensorx, ["judicial", "argentina"]),
self.tag_fn(self.num_ip, ["internet"]),
self.tag_fn(self.num_telefono, ["argentina"]),
self.tag_fn(self.per, ["persona"]),
self.tag_fn(self.direccion, ["español"]),
self.tag_fn(self.patente_dominio, ["argentina"]),
]
@staticmethod
def tag_fn(fn, tags):
return dict(fn=fn, tags=tags)
@staticmethod
def fetch_fn_by_tag(tagged_fns, tag):
fns = []
for tagged_fn in tagged_fns:
if tag == "todas" or tag in tagged_fn["tags"]:
fns.append(tagged_fn["fn"])
return fns
def num_causa(self, token):
return process_fns(
[],
(
partial(is_from_first_tokens, token.i),
partial(is_caseNumber, token),
partial(Span, self.doc, token.i + 0, token.i + 1, label="NUM_CAUSA"),
),
)
def edad(self, token):
return process_fns(
[],
(
partial(is_last, self.doc, token.i),
partial(is_age, token),
partial(Span, self.doc, token.i + 0, token.i + 1, label="EDAD"),
),
)
def num_cuij(self, token):
return process_fns(
[],
(
partial(is_from_first_tokens, token.i),
partial(is_cuijNumber, token),
partial(Span, self.doc, token.i + 0, token.i + 1, label="NUM_CUIJ"),
),
)
def num_actuacion(self, token):
return process_fns(
[],
(
partial(is_from_first_tokens, token.i),
partial(is_actuacionNumber, token),
partial(Span, self.doc, token.i + 0, token.i + 1, label="NUM_ACTUACIÓN"),
),
)
def num_expediente(self, token):
return process_fns(
[],
(
partial(is_from_first_tokens, token.i),
partial(is_expedienteNumber, token),
partial(Span, self.doc, token.i + 0, token.i + 1, label="NUM_EXPEDIENTE"),
),
)
def loc(self, token):
return process_fns(
[],
(
partial(is_from_first_tokens, token.i),
partial(is_place_token, token),
partial(Span, self.doc, token.i - 1, token.i + 1, label="LOC"),
),
)
def ley(self, ent):
return process_fns(
[],
(
partial(is_from_first_tokens, ent.start),
partial(is_law, ent),
partial(Span, self.doc, ent.start + 0, ent.end + 0, label="LEY"),
),
)
def periodo(self, ent):
return process_fns(
[],
(
partial(partial(is_last, self.doc, ent.start)),
partial(is_period, ent),
partial(Span, self.doc, ent.start + 0, ent.end + 1, label="PERIODO"),
),
)
def juezx(self, ent):
return process_fns(
[],
(
partial(is_from_first_tokens, ent.start),
partial(is_judge, ent),
partial(Span, self.doc, ent.start + 0, ent.end + 0, label="JUEZX"),
),
)
def secretarix(self, ent):
return process_fns(
[],
(
partial(is_from_first_tokens, ent.start),
partial(is_secretary, ent),
partial(Span, self.doc, ent.start + 0, ent.end + 0, label="SECRETARIX"),
),
)
def fiscal(self, ent):
return process_fns(
[],
(
partial(is_from_first_tokens, ent.start),
partial(is_prosecutor, ent),
partial(Span, self.doc, ent.start + 0, ent.end + 0, label="FISCAL"),
),
)
def defensorx(self, ent):
return process_fns(
[],
(
partial(is_from_first_tokens, ent.start),
partial(is_ombuds_person, ent),
partial(Span, self.doc, ent.start + 0, ent.end + 0, label="DEFENSORX"),
),
)
def num_ip(self, ent):
return process_fns(
[],
(
partial(is_from_first_tokens, ent.start),
partial(is_ip_address, ent),
partial(Span, self.doc, ent.start + 0, ent.end + 0, label="NUM_IP"),
),
)
def num_telefono(self, ent):
return process_fns(
[],
(
partial(is_from_first_tokens, ent.start),
partial(is_phone, ent),
partial(Span, self.doc, ent.start + 0, ent.end + 0, label="NUM_TELÉFONO"),
),
)
def per(self, ent):
return process_fns(
[],
(
partial(is_from_first_tokens, ent.start),
partial(is_accused_or_advisor, ent),
partial(Span, self.doc, ent.start + 0, ent.end + 0, label="PER"),
),
)
def direccion(self, ent):
if not is_from_first_tokens(ent.start) and is_address(ent):
self.new_ents.append(generate_address_span(ent, self.new_ents, self.doc))
return []
def patente_dominio(self, ent):
new_ents = []
if not is_from_first_tokens(ent.start) and could_be_an_article(ent) and ent.label_ == "PATENTE_DOMINIO":
self.doc.ents = remove_wrong_labeled_entity_span(self.doc.ents, ent)
if not is_from_first_tokens(ent.start) and is_license_plate(ent):
start, end = get_start_end_license_plate(ent)
new_ents.append(Span(self.doc, start, end, label="PATENTE_DOMINIO"))
return new_ents
def fecha_resolucion(self, ent):
new_ents = []
# Modifica FECHA a FECHA_RESOLUCION: solo la primera vez, si esta el token entre 3 y 100
if not self.find_fecha_resolucion and ent.label_ in ["FECHA"] and is_between_tokens(ent.start, 3, 100):
self.find_fecha_resolucion = True
new_ents.append(Span(self.doc, ent.start, ent.end, label="FECHA_RESOLUCION"))
return new_ents
def new_ents_by_ents(self):
self.find_fecha_resolucion = False
for i, ent in enumerate(self.doc.ents):
for fn in self.fetch_fn_by_tag(self.tagged_fns_ent, self.tag):
self.new_ents.extend(fn(ent))
def new_ents_by_token(self):
for token in self.doc:
for fn in self.fetch_fn_by_tag(self.tagged_fns_token, self.tag):
self.new_ents.extend(fn(token))
def __call__(self, doc):
self.new_ents = []
self.doc = doc
self.new_ents_by_token()
self.new_ents_by_ents()
if self.new_ents:
# We'd always want the new entities to be appended first because
# filter_spans prioritizes the first occurrences on overlapping
self.doc.ents = filter_spans(self.new_ents + list(self.doc.ents))
return self.doc