-
Notifications
You must be signed in to change notification settings - Fork 4
/
preprocess_fields_v3.py
2205 lines (1997 loc) · 84.6 KB
/
preprocess_fields_v3.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
# Standard modules
import csv, itertools, re, logging, optparse, time, sys, math, os, unidecode
from functools import partial, reduce, lru_cache
from collections import defaultdict, Counter, Iterable
from operator import itemgetter, add
from fuzzywuzzy import fuzz
import stdnum.fr.nir, stdnum.fr.nif, stdnum.fr.siren, stdnum.fr.siret, stdnum.fr.tva
import pandas as pd
import numpy as np
# Parsing/normalization packages
import custom_name_parsing
import urllib.request, urllib.parse, json # For BAN address API on data.gouv.fr
from dateparser import DateDataParser
import phonenumbers
from CONFIG import RESOURCE_PATH
lastTime = 0
timingInfo = Counter()
countInfo = Counter()
MICROS_PER_SEC = 1000000
# Ratio of unhandled, non-fatal errors after which a given TypeMatcher will be dropped
MAX_ERROR_RATE = 20
# Number of unhandled, fatal errors after which a given TypeMatcher will be dropped
MAX_FATAL_COUNT = 5
# If set to True, all errors will be treated as fatal
FAIL_FAST_MODE = True
def snapshot_timing(end):
global lastTime
if lastTime > 0 and lastTime + MICROS_PER_SEC > end: return
if lastTime > 0:
logging.debug('Timing info')
for k, v in timingInfo.most_common(50): logging.debug(k.rjust(50), str(v))
logging.debug('')
lastTime = end
TIMING_BY_INSTANCE = False
def timed(original_func):
def wrapper(*args, **kwargs):
start = time.clock()
result = original_func(*args, **kwargs)
end = time.clock()
key = original_func.__name__ if len(args) < 1 else (args[0] if TIMING_BY_INSTANCE else args[0].__class__.__name__) + '.' + original_func.__name__
t = int((end - start) * MICROS_PER_SEC)
timingInfo[key] += t
countInfo[key] += 1
snapshot_timing(end)
return result
return wrapper
def chngrams(string="", n=3, top=None, threshold=0, exclude=[], **kwargs):
""" Returns a dictionary of (character n-gram, count)-`s.
N-grams in the exclude list are not counted.
N-grams whose count falls below (or equals) the given threshold are excluded.
N-grams that are not in the given top most counted are excluded.
"""
# An optional dict-parameter can be used to specify a subclass of dict,
# e.g., count(words, dict=readonlydict) as used in Document.
count = defaultdict(int)
if n > 0:
for i in xrange(len(string)-n+1):
w = string[i:i+n]
if w not in exclude:
count[w] += 1
if threshold > 0:
count = dict((k, v) for k, v in count.items() if v > threshold)
if top is not None:
count = dict(heapq.nsmallest(top, count.items(), key=lambda kv: (-kv[1], kv[0])))
return kwargs.get("dict", dict)(count)
class ApproximateLookup:
def __init__(self, maxHits = 10):
self.words = set()
self.index = {}
self.maxHits = maxHits
def add(self, item):
self.words.add(item)
def remove(self, item):
self.words.discard(item)
def indexkeys(self, w):
L = len(w)
res = set([w])
for i in range(L):
for j in range(i,L):
res.add(w[:i]+w[i+1:j]+w[j+1:])
return res
def makeindex(self):
self.index.clear()
for w in self.words:
for key in self.indexkeys(w):
if key in self.index: self.index[key].add(w)
else: self.index[key] = set([w])
def search(self, query):
res = {0:[], 1:[], 2:[]}
candidate = set()
for key in self.indexkeys(query):
if key in self.index: candidate.update(self.index[key])
for word in candidate:
dist = edit_dist(word, query)
if dist < 3 and len(res) < self.maxHits: res[dist].append(word)
return res
# Fast Levenshtein distance implementation
def edit_dist(s,t):
matrix = {}
for i in range(len(s)+1):
matrix[(i, 0)] = i
for j in range(len(t)+1):
matrix[(0, j)] = j
for j in range(1,len(t)+1):
for i in range(1,len(s)+1):
if s[i-1] == t[j-1]:
matrix[(i, j)] = matrix[(i-1, j-1)]
else:
matrix[(i, j)] = min([matrix[(i-1, j)] +1, matrix[(i, j-1)]+1, matrix[(i-1, j-1)] +1])
return matrix[(i,j)]
# Misc utilities
def flatten_list(l): return '' if l is None else l if isinstance(l, str) else '; '.join([flatten_list(v) for v in uniq(l)])
def uniq(sequence):
''' Maintains the original sequence order. '''
unique = []
[unique.append(item) for item in sequence if item not in unique]
return unique
# Natural language toolbox and lexical stuff: FRENCH ONLY!!!
STOP_WORDS = [
# Prepositions (excepted "avec" and "sans" which are semantically meaningful)
"a", "au", "aux", "de", "des", "du", "par", "pour", "sur", "chez", "dans", "sous", "vers",
# Articles
"le", "la", "les", "l", "c", "ce", "ca",
# Conjonctions of coordination
"mais", "et", "ou", "donc", "or", "ni", "car"
]
def is_stop_word(word): return word in STOP_WORDS
def is_valid_phrase(tokens): return len(tokens) > 0 and not all(len(t) < 2 and t.isdigit() for t in tokens)
def stripped(s): return s.strip(" -_.,'?!").strip('"').strip()
def is_valid_token(token):
token = stripped(token)
if token.isspace() or not token: return False
if token.isdigit(): return False # Be careful this does not get called when doing regex or template matching!
if len(token) <= 2 and not (token.isalpha() and token.isupper()): return False
return not is_stop_word(token)
def is_valid_value(v):
''' Validates a single value (sufficient non-empty data and such things) '''
stripped = stripped(v)
return len(stripped) > 0 and stripped not in ['null', 'NA', 'N/A']
def is_acronym_token(token):
return re.match("[A-Z][0-9]*$", token) or re.match("[A-Z0-9]+$", token)
MIN_ACRO_SIZE = 3
MAX_ACRO_SIZE = 6
def lower_or_not(token, keepAcronyms, keepInitialized = False):
''' Set keepAcronyms to true in order to improve precision (e.g. a CAT scan will not be matched by a kitty). '''
if keepAcronyms and len(token) >= MIN_ACRO_SIZE and len(token) <= MAX_ACRO_SIZE and is_acronym_token(token):
return token
if keepInitialized:
m = re.search("([A-Z][0-9]+)[^'a-zA-Z].*", token)
if m:
toKeep = m.group(0)
return toKeep + lower_or_not(token[len(toKeep):], keepAcronyms, keepInitialized)
return token.lower()
def to_ASCII(phrase): return unidecode.unidecode(phrase)
def rejoin(v): return to_ASCII(v)
def case_phrase(p, keepAcronyms = False):
ps = pre_split(p) if p is not None else ''
return to_ASCII(lower_or_not(ps.strip(), keepAcronyms))
def replace_by_space(str, *patterns): return reduce(lambda s, p: re.sub(p, ' ', s), patterns, str)
def dehyphenate_token(token):
result = token[:]
i = result.find('-')
while i >= 0 and i < len(result) - 1:
left = result[0:i]
right = result[i+1:]
if left.isdigit() or right.isdigit(): break
result = left + right
i = result.find('-')
return result.strip()
def pre_split(v):
s = ' ' + v.strip() + ' '
s = replace_by_space(s, '[\{\}\[\](),\.\"\';:!?&\^\/\*-]')
return re.sub('([^\d\'])-([^\d])', '\1 \2', s)
# def fold_for_changes(s, normalizeCase = False):
# ''' Override this if we want to skip minor changes (case, hyphenation, etc.) '''
# return split_and_case(s) if normalizeCase else s
def normalize_and_validate_tokens(phrase,
keepAcronyms = False, tokenValidator = is_valid_token, phraseValidator = is_valid_phrase, stopWords = None):
''' Returns a list of normalized, valid tokens for the input phrase (an empty list
if no valid tokens were found) '''
if phrase:
tokens = str.split(case_phrase(phrase, keepAcronyms))
validTokens = []
for token in tokens:
if tokenValidator(token) and (stopWords is None or token not in stopWords): validTokens.append(token)
if phraseValidator(validTokens): return validTokens
return []
def normalize_and_validate_phrase(value,
keepAcronyms = False, tokenValidator = is_valid_token, phraseValidator = is_valid_phrase, stopWords = None):
''' Returns a string that joins normalized, valid tokens for the input phrase
(None if no valid tokens were found) '''
tokens = normalize_and_validate_tokens(value, keepAcronyms = keepAcronyms, tokenValidator = tokenValidator,
phraseValidator = phraseValidator, stopWords = stopWords)
return ' '.join(tokens) if len(tokens) > 0 else None
def validated_lexicon(lexicon, tokenize = False):
return set(filter(lambda v: v is not None, [normalize_or_not(s, tokenize) for s in lexicon]))
def add_to_lexicon_map(lexical_map, s, tokenize, stopWords):
k = normalize_and_validate_phrase(s, stopWords = stopWords) if tokenize else case_phrase(s)
if k is None: return
lexical_map[k].append(s)
def cased_multi_map(mm):
return dict([(case_phrase(k), set([case_phrase(v) for v in vs])) for k, vs in mm.items()])
def validated_lexical_map(lexicon, tokenize = False, stopWords = None, synMap = None):
''' Returns a dictionary from normalized string to list of original strings. '''
syn_map0 = None if synMap is None else cased_multi_map(synMap)
lexical_map = defaultdict(list)
for s in lexicon:
if syn_map0 is not None:
for (main_var, alt_vars) in synMap.items():
s = re.sub(r"\b(%s)\b" % '|'.join(alt_vars), main_var, s, re.I)
add_to_lexicon_map(lexical_map, s, tokenize, stopWords)
return lexical_map
# Loading CSV and raw (one entry per line) text files
def file_row_iter(fileName, sep, path = RESOURCE_PATH):
filePath = fileName if path is None else os.path.join(path, fileName)
with open(filePath, mode = 'r') as csvfile:
reader = csv.reader(csvfile, delimiter = sep, quotechar='"')
for row in reader:
try:
yield list(map(stripped, row))
except UnicodeDecodeError as ude:
logging.error('Unicode error while parsing "%s"', row)
def file_column_to_list(fileName, c, sep = '\t', includeInvalid = True):
return [r[c] for r in file_row_iter(fileName, sep) if len(r) > c and (includeInvalid or is_valid_value(r[c]))]
FRENCH_LEXICON = file_column_to_list('most_common_tokens_fr', 0, '|')
def file_to_list(fileName, path = RESOURCE_PATH):
filePath = fileName if path is None else os.path.join(path, fileName)
with open(filePath, mode = 'r') as f:
return [stripped(line) for line in f]
# TODO improve following function :
# - to accept a varargs with several filenames
# - to automatically handle multiple languages by checking suffixes ("_en", "_fr") without having to enumerate them by hand
def file_to_set(fileName): return set(file_to_list(fileName))
def file_to_variant_map(fileName, sep = '|', includeSelf = False, tokenize = False):
''' The input format is pipe-separated, column 1 is the main variant, column 2 an alternative variant.
Returns a reverse index, namely a map from original alternative variant to original main variant
Parameters:
includeSelf if True, then the main variant will be included in the list of alternative variants
(so as to enable partial matching simultaneously).
'''
otherToMain = dict()
mainToOther = defaultdict(list)
for row in file_row_iter(fileName, sep):
if len(row) < 2: continue
r = list([normalize_or_not(e, tokenize = tokenize) for e in row])
main, alts = r[0], set(r[1:])
alts.discard(main)
for alt in alts:
if alt not in otherToMain:
otherToMain[alt] = main
elif main not in otherToMain and otherToMain[alt] != main:
otherToMain[main] = otherToMain[alt]
mainToOther[main].extend(list(alts))
l = list(otherToMain.items())
if includeSelf: l = list([(main, main) for main in mainToOther.keys()]) + l
return dict(l)
# Template extraction and matching
def char_templates(c): return 'L' if c.isalpha() else 'D' if c.isdigit() else 'A'
def char_template(c): return 'D' if c.isdigit() else ('L' if c.isalpha() else '?')
MPL = (5, 16) # Min and max pattern length
def token_templates(token, simple = True):
''' Parameters:
simple if True, then this method only builds full patterns (i.e. no strict prefixes) and also just considers
L and D (not A) '''
if simple:
if len(token) >= MPL[0] and len(token) <= MPL[1]:
candidate = list([char_template(token[n]) for n in range(len(token))])
if 'D' in candidate: yield '{}$'.format(''.join(candidate))
else:
l = list()
for n in range(len(token)):
l.append(''.join(char_templates(token[n])))
if n < MPL[0] or 'D' not in l: continue
for p in itertools.product(l):
yield p
if n == len(token) - 1: yield '{}$'.format(p)
# Ngram extraction and matching
def ngram_iter(v, n, bounds = False):
if len(v) < n: return iter(())
return chngrams(' {} '.format(v) if bounds else v, n).items()
# Special datatype categories
C_OTHERS = 'Autres types'
# Special fields and field prefixes
# F_COMPOSITE_REMAINDER = u'+++'
F_ORIGINAL_PATTERN = u'Original %s'
F_ACRONYMS = u'Acronyme' # For on-the-fly acronym detection (i.e. when acronym and expanded form occur in the same context)
F_VARIANTS = u'Variante' # For other forms of synonyms, including acronyms from pre-collected acro/expansion pair files
# Generic, MESR-domain and other field names
F_PERSON = u'Nom de personne'
F_FIRST = u'Prénom'
F_LAST = u'Nom'
F_TITLE = u'Titre'
F_JOURNAL = u'Titre de revue'
F_EMAIL = u'Email'
F_URL = u'URL'
F_INSEE = u'Code INSEE'
F_YEAR = u'Année'
F_MONTH = u'Mois'
F_DATE = u'Date'
F_PHONE = u'Téléphone'
F_GEO = u'Entité Géo'
F_ADDRESS = u'Adresse'
F_ZIP = u'Code Postal'
F_COUNTRY = u'Pays'
F_CITY = u'Commune'
F_STREET = u'Voie'
F_HOUSENUMBER = u'Numéro de voie'
F_DPT = u'Département'
F_REGION = u'Région'
F_STRUCTURED_TYPE = u'Type structuré'
F_TEXT = u'Texte'
F_ENGLISH = u'Anglais'
F_FRENCH = u'Français'
F_ID = u'ID'
F_ORG_ID = u'ID organisation'
F_PERSON_ID = u'ID personne'
F_ENTREPRISE = u'Entreprise' # Nom ou raison sociale de l'entreprise
F_SIREN = u'SIREN'
F_SIRET = u'SIRET'
F_NIF = u'NIF' # Numéro d'Immatriculation Fiscale
F_NIR = u'NIR' # French personal identification number
F_TVA = u'TVA'
F_GRID_LABEL = u'Intitulé GRID'
F_PUBLI = u'Publication'
F_ARTICLE = u'Article'
F_ABSTRACT = u'Résumé'
F_ISSN = u'ISSN'
F_ARTICLE_CONTENT = u'Contenu d\'article'
F_PUBLI_ID = u'ID publication'
F_DOI = u'DOI'
F_CORPS_GRADE = u'Corps et Grades'
F_MESR = u'Entité MESR'
F_NNS = u'Numéro National de Structure'
F_UAI = u'UAI'
F_UMR = u'Numéro UMR'
F_RD_STRUCT = u'Structure de recherche'
F_RD_PARTNER = u'Partenaire de recherche'
F_CLINICALTRIAL_COLLAB = u'Collaborateur d\'essai clinique'
F_RD = u'Institution de recherche'
F_ETAB = u'Etablissement'
F_EDUC_NAT = u'Education Nationale'
F_ACADEMIE = u'Académie'
F_ETAB_NOTSUP = u'Etablissement des premier et second degrés'
F_ETAB_ENSSUP = u'Etablissement d\'Enseignement Supérieur'
F_APB_MENTION = u'Mention APB'
F_RD_DOMAIN = u'Domaine de Recherche'
# A very high-level institution, comprising
# 1. (higher) education entities
# 2. R&D organizations
# 3. entreprises/corporations
F_INSTITUTION = u'Institution'
F_CLINICALTRIAL_NAME = u'Nom d\'essai clinique'
F_MEDICAL_SPEC = u'Spécialité médicale'
F_BIOMEDICAL = u'Entité biomédicale'
F_PHYTO = u'Phyto'
F_AGRO = u'Entité agro'
F_RAISON_SOCIALE = u'Raison sociale'
# This mapping only covers supertype-subtype relationships
SUBTYPING_RELS = defaultdict(set)
# This mapping only covers composition relationships
COMPOSITION_RELS = defaultdict(set)
# This mapping covers both subtyping and composition relationships
PARENT_CHILD_RELS = defaultdict(set)
TYPE_TAGS = {
F_PERSON: [F_LAST, F_PERSON],
F_FIRST: [F_PERSON],
F_LAST: [u'Patronyme', F_PERSON],
F_EMAIL: [F_ADDRESS, u'Courriel'],
F_URL: [F_ADDRESS],
F_INSEE: [F_ID, u'Code', u'Numéro'],
F_NIF: [F_ID],
F_NIR: [F_ID],
F_NNS : [F_NNS, u'NumNatStruct', 'RNSR'],
F_TVA: [F_ID],
F_GRID_LABEL: [F_ID, 'GRID', 'Recherche', 'Index'],
F_YEAR: [F_DATE],
F_MONTH: [F_DATE],
F_PHONE: [u'Numéro'],
F_ADDRESS: [F_GEO],
F_ZIP: [u'CP', u'Code', F_ADDRESS, F_GEO],
F_COUNTRY: [F_ADDRESS, F_GEO],
F_CITY: [u'Ville', F_ADDRESS, F_GEO],
F_STREET: [u'Rue', F_ADDRESS, F_GEO],
F_DPT: [F_ADDRESS, F_GEO],
F_REGION: [F_ADDRESS, F_GEO],
F_ID: [u'Identifiant', u'Code', u'Numéro'],
F_ORG_ID: [u'Organisation', u'Structure', u'Identifiant', u'Code', u'Numéro'],
F_PERSON_ID: [u'Personne', u'Individu', u'Identifiant', u'Code', u'Numéro'],
F_ENTREPRISE: [u'Société', u'Organisation'],
F_SIREN: [u'Identifiant', u'Numéro'],
F_SIRET: [u'Identifiant', u'Numéro'],
F_PUBLI_ID: [F_PUBLI, u'Identifiant', u'Numéro'],
F_DOI: [u'Identifiant', u'Numéro'],
F_UAI: [u'Identifiant', u'Numéro'],
F_UMR: [u'Identifiant', u'Numéro', u'Recherche'],
F_RD_STRUCT: [u'Organisation', u'Structure', u'Recherche'],
F_RD_PARTNER: [u'Organisation', u'Structure', u'Recherche'],
F_RD: [u'Recherche'],
F_EDUC_NAT: [u'Education', u'Enseignement'],
F_ACADEMIE: [u'Enseignement'],
F_ETAB: [u'Enseignement'],
F_ETAB_NOTSUP: [u'Primaire', u'Secondaire', u'Lycée', u'Collège'],
F_ETAB_ENSSUP: [u'Enseignement supérieur'],
F_CORPS_GRADE: [u'Corps', u'Grade', u'Fonction publique'],
F_PHYTO: [u'Agro'],
F_AGRO: [u'Agro'],
F_MEDICAL_SPEC: [u'Médecine'],
F_BIOMEDICAL: [u'Médecine']
}
# Stop words specific to certain data types
STOP_WORDS_CITY = ['commune', 'cedex', 'cdx']
# Base class for all type matchers
class TypeMatcher(object):
def __init__(self, t):
self.t = t
self.diversion = set()
def diversity(self):
''' Specifies the min number of distinct reference values to qualify a column-wide match
(it is essential to carefully override this constraint when the labels in question represent
singleton instances, i.e. specific entities, as opposed to a qualified and/or controlled
vocabulary). '''
return 1
def __str__(self):
return '{}<{}>'.format(self.__class__.__name__, self.t)
def register_full_match(self, c, t, s, hit = None):
ms = cover_score(c.value, hit) if s is None else s
outputFieldPrefix = None if self.t == t else self.t
c.register_full_match(t, outputFieldPrefix, ms, hit)
self.update_diversity(hit)
def register_partial_match(self, c, t, ms, hit, span):
outputFieldPrefix = None if self.t == t else self.t
c.register_partial_match(t, outputFieldPrefix, ms, hit, span)
self.update_diversity(hit)
@timed
def match_all_field_values(self, f):
error_values = Counter()
fatal_values = Counter()
values_seen = 0
for vc in f.cells:
error_count = sum(error_values.values())
fatal_count = sum(fatal_values.values())
if values_seen >= 100 and (error_count + fatal_count) * 100 > values_seen * MAX_ERROR_RATE:
logging.warning('{}: bailing out after {} total matching errors'.format(self, error_count + fatal_count))
break
elif fatal_count > MAX_FATAL_COUNT:
logging.warning('{}: bailing out after {} fatal matching errors'.format(self, fatal_count))
break
values_seen += 1
v = vc.value
if v in fatal_values:
fatal_values[v] += 1
continue
elif v in error_values:
error_values[v] += 1
continue
try :
self.match(vc)
# Handling non-fatal errors
except ValueError as ve:
logging.warning('{}: value error for "{}": {}'.format(self, vc.value, ve))
if FAIL_FAST_MODE:
fatal_values[v] += 1
else:
error_values[v] += 1
except OverflowError as oe:
logging.error('{} : overflow error (e.g. while parsing date) for "{}": {}'.format(self, vc.value, oe))
if FAIL_FAST_MODE:
fatal_values[v] += 1
else:
error_values[v] += 1
# Handling fatal errors
except RuntimeError as rte:
logging.warning('{}: runtime error for "{}": {}'.format(self, vc.value, rte))
fatal_values[v] += 1
except TypeError as te:
logging.warning('{}: type or parsing error for "{}": {}'.format(self, vc.value, te))
fatal_values[v] += 1
except UnicodeDecodeError as ude:
logging.error('{} : unicode error while parsing input value "{}": {}'.format(self, vc.value, ude))
fatal_values[v] += 1
except urllib.error.URLError as ue:
logging.warning('{}: request rejected for "{}": {}'.format(self, vc.value, ue))
fatal_values[v] += 1
except ConnectionError as cne:
logging.warning('{}: connection error: {}'.format(self, cne))
fatal_values[v] += 1
except Exception as une:
logging.warning('{}: unknown exception: {}'.format(self, une))
fatal_values[v] += 1
def update_diversity(self, hit):
self.diversion |= set(hit if isinstance(hit, list) else [hit])
def check_diversity(self, cells):
div = len(self.diversion)
if div <= 0: return
self.diversion.clear()
if div < self.diversity():
logging.info('Not enough diversity matches of type {} produced by {} ({})'.format(self.t, self, div))
else:
logging.info('Positing value type {} by {}'.format(self.t, self))
for c in cells: c.posit_type(self.t)
class GridMatcher(TypeMatcher):
@timed
def __init__(self):
super(GridMatcher, self).__init__(F_GRID_LABEL)
gridding.init_gridding()
def match_all_field_values(self, f):
src_items_by_label = gridding.grid_label_set([vc.value for vc in f.cells])
for vc in f.cells:
item = src_items_by_label[vc.value]
if 'grid' in item:
self.register_full_match(vc, self.t, 100, item['label'])
MATCH_MODE_EXACT = 0
MATCH_MODE_CLOSE = 1
# stdnum-based matcher-normalizer class
class StdnumMatcher(TypeMatcher):
@timed
def __init__(self, t, validator, normalizer):
super(StdnumMatcher, self).__init__(t)
self.t = t
self.validator = validator
self.normalizer = normalizer
@timed
def match(self, c):
nv = c.value
if self.validator(nv):
nv0 = self.normalizer(nv)
self.register_full_match(c, self.t, 100, nv0)
else:
raise TypeError('{} stdnum matcher did not validate "{}"'.format(self, c))
# Regex-based matcher-normalizer class
class RegexMatcher(TypeMatcher):
@timed
def __init__(self, t, p, g = 0, ignoreCase = False, partial = False, validator = None, neg = False, wordBoundary = True):
super(RegexMatcher, self).__init__(t)
self.p = pattern_with_word_boundary(p)
self.g = g
self.flags = re.I if ignoreCase else 0
self.partial = partial
self.validator = validator
self.neg = neg
self.wordBoundary = wordBoundary
logging.info('SET UP regex matcher for <%s> (length %d)', self.t, len(self.p))
@timed
def match(self, c):
if self.partial:
ms = re.findall(self.p, c.value, self.flags)
if ms:
if self.neg:
c.negate_type(self.t)
return
else:
for m in ms:
if not isinstance(m, str):
if len(m) > self.g:
m = m[self.g]
else:
continue
i1 = c.value.find(m)
if i1 >= 0:
if self.validator is None or self.validator(m):
self.register_partial_match(c, self.t, 100, m, (i1, i1 + len(m)))
return
else:
raise RuntimeError('{} could not find regex multi-match "{}" in original "{}"'.format(self, m, c.value))
else:
m = re.match(self.p, c.value, self.flags)
if m:
if self.neg:
c.negate_type(self.t)
return
else:
try:
grp = m.group(self.g)
if self.validator is None or self.validator(grp):
if len(grp) == len(c.value):
self.register_full_match(c, self.t, 100, grp)
else:
self.register_partial_match(c, self.t, 100, grp, (0, len(grp)))
return
except IndexError:
raise RuntimeError('No group {} matched in regex {} for input "{}"'.format(self.g, self.p, c))
raise ValueError('{} unmatched "{}"'.format(self, c.value))
def build_vocab_regex(vocab, partial):
j = '|'.join(vocab)
return '({}).*$'.format(j if partial else j)
class VocabMatcher(RegexMatcher):
''' When matcher is not None, the matching will be dispatched to it, which is useful when normalization is far costlier
than type detection. '''
@timed
def __init__(self, t, vocab, ignoreCase = False, partial = False, validator = None, neg = False, matcher = None):
super(VocabMatcher, self).__init__(t, build_vocab_regex(vocab, partial),
g = 0, ignoreCase = ignoreCase, partial = partial, validator = validator, neg = neg)
self.matcher = matcher
@timed
def match(self, c):
if self.matcher is not None:
logging.debug('%s normalizing "%s" from %s', self, c, self.matcher)
self.matcher.match(c)
elif self.matcher is None or self.t not in c.non_excluded_types():
logging.debug('%s normalizing "%s" from vocab only', self, c)
super(VocabMatcher, self).match(c)
else:
raise TypeError('{} matcher only found excluded type in "{}"'.format(self, c))
# Tokenization-based matcher-normalizer class
def tokenization_based_score(matchedSrcTokens, srcTokens, matchedRefPhrase, refPhrase,
minSrcTokenRatio = 80, minSrcCharRatio = 70, minRefCharRatio = 60):
srcTokenRatio = 100 * len(matchedSrcTokens) / len(srcTokens)
if srcTokenRatio < minSrcTokenRatio: return 0
srcCharRatio = 100 * sum([len(t) for t in matchedSrcTokens]) / sum([len(t) for t in srcTokens])
if srcCharRatio < minSrcCharRatio: return 0
matchedRefPhrase = ' '.join(matchedSrcTokens)
refCharRatio = 100 * len(matchedRefPhrase) / len(refPhrase)
return 0 if refCharRatio < minRefCharRatio else refCharRatio
def stop_words_as_normalized_list(stopWords):
return [] if stopWords is None else list([case_phrase(s, False) for s in stopWords])
DTC = 6 # Dangerous Token Count (becomes prohibitive to tokenize many source strings above this!)
class TokenizedMatcher(TypeMatcher):
@timed
def __init__(self, t, lexicon, maxTokens = 0, scorer = tokenization_based_score, distinctCount = 0, stopWords = None):
super(TokenizedMatcher, self).__init__(t)
currentMax = maxTokens
self.scorer = scorer
self.phrasesMap = validated_lexical_map(lexicon)
self.tokenIdx = dict()
self.distinctCount = distinctCount
self.stopWords = stop_words_as_normalized_list(stopWords)
for np in self.phrasesMap.keys():
tokens = list([t for t in np.split(' ') if t not in self.stopWords])
if len(tokens) < 1: continue
if maxTokens < 1 and len(tokens) > currentMax:
currentMax = len(tokens)
if currentMax > DTC:
logging.warning('Full tokenization of lexicon: encountered token of length {}, above DTC!'.format(currentMax))
matchedRefPhrase = ' '.join(tokens[:currentMax])
if matchedRefPhrase not in self.tokenIdx or len(self.tokenIdx[matchedRefPhrase]) < len(np):
self.tokenIdx[matchedRefPhrase] = np
self.maxTokens = currentMax
logging.info('SET UP %d-token matcher (%s-defined length) for <%s> with lexicon of size %d, total variants %d',
self.maxTokens, 'user' if maxTokens > 0 else 'data', self.t, len(self.phrasesMap), len(self.tokenIdx))
def diversity(self):
return self.distinctCount if self.distinctCount > 0 else math.log(len(self.phrasesMap), 1.5)
@timed
def match(self, c):
tokens = normalize_and_validate_tokens(c.value, tokenValidator = lambda t: is_valid_token(t) and t not in self.stopWords)
if tokens is not None:
for k2 in range(self.maxTokens, 0, -1):
for k1 in range(0, len(tokens) + 1 - k2):
matchSrcTokens = tokens[k1:k1 + k2]
matchRefPhrase = ' '.join(matchSrcTokens)
if matchRefPhrase in self.tokenIdx:
nm = self.tokenIdx[matchRefPhrase]
score = self.scorer(matchSrcTokens, tokens, matchRefPhrase, nm)
if nm not in self.phrasesMap:
raise RuntimeError('Normalized phrase {} not found in phrases map'.format(nm))
hit = self.phrasesMap[nm]
v = case_phrase(c.value)
# The next line joins on '' and not on ' ' because non-pure space chars might have been transformed
# during tokenization (hyphens, punctuation, etc.)
subStr = ''.join(matchSrcTokens)
span = check_non_consecutive_subsequence(v, subStr)
if span is None:
logging.warning('%s could not find tokens "%s" in original "%s"', self, matchRefPhrase, v)
span = (0, len(c.value))
self.register_partial_match(c, self.t, score, hit, span)
return
raise ValueError('{} found no matching token sequence in "{}"'.format(self, c))
# Label-based matcher-normalizer class and its underlying FSS structure
def build_fast_sim_struct(terms):
fss = ApproximateLookup()
for term in terms: fss.add(term)
fss.makeindex()
return fss
def fast_sim_score(r, l = 1024):
''' Return a pair (list of matched substrings, score) '''
if len(r[0]) > 0: return (r[0], 100)
elif len(r[1]) < 1 and len(r[2]) < 1: return ([], 0)
elif l > 8: return (r[1], 50) if len(r[1]) > 0 else (r[2], 20)
elif l > 4: return (r[1], 20) if len(r[1]) > 0 else (r[2], 10)
else: return (r[1], 5) if len(r[1]) > 0 else ([], 0)
def normalize_or_not(v, tokenize = False, stopWords = None):
return normalize_and_validate_phrase(v, stopWords = stopWords) if tokenize else case_phrase(v)
class LabelMatcher(TypeMatcher):
@timed
def __init__(self, t, lexicon, mm, stopWords = None, synMap = None):
''' Parameters:
diversity specifies the min number of distinct reference values to qualify a column-wide match
(it is essential to have this constraint when the labels in question represent singleton instances,
i.e. specific entities, as opposed to a qualified and/or controlled vocabulary. '''
super(LabelMatcher, self).__init__(t)
self.mm = mm
self.stopWords = stop_words_as_normalized_list(stopWords)
self.synMap = synMap
self.tokenize = synMap is not None
# dictionary from normalized string to list of original strings
labelsMap = validated_lexical_map(lexicon, tokenize = self.tokenize, stopWords = self.stopWords, synMap = synMap)
self.labelsMap = labelsMap
if mm == MATCH_MODE_EXACT:
logging.info('SET UP exact label matcher for <%s>: lexicon of size %d', self.t, len(labelsMap))
elif mm == MATCH_MODE_CLOSE:
self.fss = build_fast_sim_struct(labelsMap.keys())
logging.info('SET UP close label matcher for <%s>: lexicon of size %d', self.t, len(labelsMap))
def diversity(self):
return math.log(len(self.labelsMap), 1.8)
@timed
def match(self, c):
v = normalize_or_not(c.value, stopWords = self.stopWords, tokenize = self.tokenize)
if not v:
raise TypeError('{} found no non-trivial label value from "{}"'.format(self, c))
if self.synMap is not None and v in self.synMap: # Check for synonyms
v = self.synMap[v]
if self.mm == MATCH_MODE_EXACT:
if v in self.labelsMap:
self.register_full_match(c, self.t, 100, self.labelsMap[v])
return
elif self.mm == MATCH_MODE_CLOSE:
(matchedRefPhrases, score) = fast_sim_score(self.fss.search(v), len(v))
if score > 0:
for matchedRefPhrase in matchedRefPhrases:
self.register_full_match(c, self.t, score, matchedRefPhrase)
return
raise ValueError('{} found no matching label in "{}"'.format(self, c))
class HeaderMatcher(LabelMatcher):
def __init__(self, t, lexicon):
super(HeaderMatcher, self).__init__(t, lexicon, MATCH_MODE_CLOSE)
# Subtype matcher-normalizer class
class SubtypeMatcher(TypeMatcher):
def __init__(self, t, subtypes):
super(SubtypeMatcher, self).__init__(t)
self.subtypes = set(subtypes)
if len(subtypes) < 1: raise Error('Invalid subtype matcher setup')
logging.info('SET UP subtype matcher for <%s> with subtypes: %s', self.t, ', '.join(subtypes))
PARENT_CHILD_RELS[t] |= set(subtypes)
SUBTYPING_RELS[t] |= set(subtypes)
def match(self, c):
sts = list(self.subtypes & c.non_excluded_types())
if len(sts) < 1: return None
ps = 0
ms = None
fs = 0
tis = list()
for st in sts:
pss = c.matches(st, PARTIAL_MATCH)
if len(pss) > 0:
ps = max([ps] + [ti.ms for ti in pss])
tis.extend(pss)
fss = c.matches(st, FULL_MATCH)
if len(fss) > 0:
fs = max([fs] + [ti.ms for ti in fss])
tis.extend(fss)
if ps > 0 or fs > 0: c.register_cover_match(self.t, max(ps, fs), tis)
# Composite type matcher-normalizer class
class CompositeMatcher(TypeMatcher):
def __init__(self, t, compTypes):
super(CompositeMatcher, self).__init__(t)
self.compTypes = compTypes
if len(compTypes) < 1: raise RuntimeError('Invalid composite matcher setup')
logging.info('SET UP composite matcher for <%s> with %d types', self.t, len(compTypes))
PARENT_CHILD_RELS[t] |= set(compTypes)
COMPOSITION_RELS[t] |= set(compTypes)
@timed
def match(self, c):
sts = list(set(self.compTypes) & c.non_excluded_types())
if len(sts) < 1: return None
ps = 0
ms = None
fs = 0
tis = list()
for st in sts:
pss = c.matches(st, PARTIAL_MATCH)
if len(pss) > 0:
ps += sum([ti.ms for ti in pss])
tis.extend(pss)
fss = c.matches(st, FULL_MATCH)
if len(fss) > 0:
fs += sum([ti.ms for ti in pss])
tis.extend(fss)
if ps > 0 or fs > 0: c.register_cover_match(self.t, max(ps, fs) / len(sts), tis)
class CompositeRegexMatcher(TypeMatcher):
''' This class is useful when several children fields of a parent composite field
can be captured as groups within the same regex.
It assumes that all children types have been matched against, hence it
only registers matches on the composite type itself. '''
def __init__(self, t, p, tgs, ignoreCase = False, partial = False, validators = { }):
''' Parameters:
tgs a dictionary { type: group } to capture multiple types '''
super(CompositeRegexMatcher, self).__init__(t)
self.tgs = tgs
self.p = pattern_with_word_boundary(p)
self.flags = re.I if ignoreCase else 0
self.partial = partial
self.validators = validators
def match(self, c):
if self.partial:
ms = re.findall(self.p, v, flags = self.flags)
if not ms: return
for m in ms:
for (t, g) in self.tgs.items():
try:
grp = m.group(g)
if t not in self.validators or self.validators[t](grp):
self.register_partial_match(c, t, 100, grp, m.span(g))
except IndexError:
logging.error('No group %d matched in %s for input %s', g, self.p, c)
else:
m = re.match(self.p, c.value, flags = self.flags)
if not m: return
for (t, g) in self.tgs.items():
try:
grp = m.group(g)
if t not in self.validators or self.validators[t](grp):
if len(grp) == len(c.value):
self.register_full_match(c, t, 100, grp)
else:
self.register_partial_match(c, t, 100, grp, (0, len(grp)))
except IndexError:
logging.error('No group %d matched in regex "%s" for input "%s"', g, self.p, c)
# Object model representing our inference process
# Drop inferred types falling below this column-wide threshold (in percent):
COLUMN_SCORE_THRESHOLD = 10
# For supertype relationships only (not composite-type!), switch from parent to child type when:
# parent's score < this ratio * child's score
SUBTYPING_RATIO = 2
# SUPERTYPE_RATIO = 2 # Switch from parent to child type when: parent's score < this ratio * child's score
# COMPTYPE_RATIO = 2 # Switch from composite to component type when: composite's score < this ratio * child's score
def parse_fields_from_CSV(fileName, delimiter):
''' Takes a CSV filepath and a delimiter as input, returns an instance of the Fields class. '''
a = list(file_row_iter(fileName, delimiter, path = None))
return Fields({ Cell(h, h): Field([Cell(a[i][k] if len(a[i]) > k else '', h) for i in range(1, len(a))]) for (k, h) in enumerate(a[0]) },
len(a) - 1)
def parse_fields_from_Panda(df):
''' Takes a DataFrame as input, returns an instance of the Fields class. '''
return Fields({ Cell(h, h): Field([Cell(v, h) for v in c]) for (h, c) in df.items() },
df.shape[0])
class Fields(object):
def __init__(self, fields, entries):
self.fields = fields # Mapping from header Cell object to value Field object
self.entries = entries
self.modifiedByColumn = { }
self.outputFieldsByColumn = { }
@timed
def match_headers_and_values(self):
logging.info('RUNNING all header matchers')
for hm in header_matchers():
for hc in self.fields.keys():
logging.debug('RUNNING %s on %s header', hm, hc.value)
try:
hm.match(hc)
except:
pass # Ignore errors on header matching since no need to bail out (few values to check)
logging.info('RUNNING all value matchers')
for vm in value_matchers():
if isinstance(vm, SubtypeMatcher): continue
if isinstance(vm, CompositeMatcher): continue
for (hc, f) in self.fields.items():
logging.debug('RUNNING %s on %s values', vm, hc.value)
vm.match_all_field_values(f)
vm.check_diversity(f.cells)
def match_by_types(self, trusted_types):
for vm in value_matchers():
if isinstance(vm, SubtypeMatcher): continue
if isinstance(vm, CompositeMatcher): continue
for (hc, f) in self.fields.items():
if hc.value not in trusted_types:
continue
if vm.t != trusted_types[hc.value]:
continue
logging.debug('TRUSTING %s on %s values', vm, hc.value)
vm.match_all_field_values(f)
def likeliest_types(self, h, f, singleType = False):
''' Returns None rather than an empty list to signify that not a single type has been inferred.
Parameters:
h the field header
f the field itself
singleType if True, then a unique choice per column will be made '''
lht = h.likeliest_type()
logging.info('Likeliest type for %s header: %s', h.value, lht)
lvts = [lht] if lht is not None else None
if singleType:
lvt = f.likeliest_type()
if lvt is not None:
logging.info('Likeliest type for %s values: %s', h.value, lvt)
lvts = [lvt]
else:
lvt = f.likeliest_types()
if len(lvt) > 0:
logging.info('Likeliest types for %s values: %s', h.value, ', '.join(lvt))
lvts = lvt
if lvts is None:
logging.info('Could not infer type for %s values: %s', h.value, ', '.join(lvt))
return lvts
def process_values(self, outputFormat, singleType = False):
''' Parameters:
outputFormat either "md" for markdown output, or a separator string for CSV output '''
self.match_headers_and_values()