-
Notifications
You must be signed in to change notification settings - Fork 1
/
dj_mapper.py
executable file
·990 lines (861 loc) · 40.2 KB
/
dj_mapper.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
#! /usr/bin/env python3
import os
import sys
import argparse
import signal
import time
from datetime import datetime, timedelta
import xml.etree.ElementTree as etree
import xml.dom.minidom as minidom
import json
import random
import re
#--import the base mapper library and variants
try:
import base_mapper
except:
print('')
print('Please export PYTHONPATH=$PYTHONPATH:<path to mapper-base project>')
print('')
sys.exit(1)
baseLibrary = base_mapper.base_library(os.path.abspath(base_mapper.__file__).replace('base_mapper.py','base_variants.json'))
if not baseLibrary.initialized:
sys.exit(1)
#----------------------------------------
def pause(question='PRESS ENTER TO CONTINUE ...'):
""" pause for debug purposes """
try: response = input(question)
except KeyboardInterrupt:
response = None
global shutDown
shutDown = True
return response
#----------------------------------------
def signal_handler(signal, frame):
print('USER INTERUPT! Shutting down ... (please wait)')
global shutDown
shutDown = True
return
#----------------------------------------
def updateStat(cat1, cat2, example = None):
if cat1 not in statPack:
statPack[cat1] = {}
if cat2 not in statPack[cat1]:
statPack[cat1][cat2] = {}
statPack[cat1][cat2]['count'] = 0
statPack[cat1][cat2]['count'] += 1
if example:
if 'examples' not in statPack[cat1][cat2]:
statPack[cat1][cat2]['examples'] = []
if example not in statPack[cat1][cat2]['examples']:
if len(statPack[cat1][cat2]['examples']) < 5:
statPack[cat1][cat2]['examples'].append(example)
else:
randomSampleI = random.randint(2,4)
statPack[cat1][cat2]['examples'][randomSampleI] = example
return
#----------------------------------------
def getAttr (segment, tagName):
""" get an xml element text value """
try: value = segment.attrib[tagName]
except: value = None
else:
if len(value) == 0:
value = None
return value
#----------------------------------------
def getValue (segment, tagName = None):
""" get an xml element text value """
try:
if tagName:
value = segment.find(tagName).text.strip()
else:
value = segment.text.strip()
except: value = None
else:
if len(value) == 0:
value = None
return value
#----------------------------------------
def idNoteParse(notes, codeType):
#--check if enclosed in parens
notes = notes.lower().replace('.','')
groupedStrings = re.findall('\(.*?\)',notes)
for maybeCountry in groupedStrings:
maybeCountry = maybeCountry[1:len(maybeCountry)-1]
isoCountry = baseLibrary.isoCountryCode(maybeCountry) if codeType == 'country' else baseLibrary.isoStateCode(maybeCountry)
if isoCountry:
return isoCountry
elif ',' in maybeCountry:
countryName = maybeCountry[maybeCountry.find(',')+1:].strip()
isoCountry = baseLibrary.isoCountryCode(maybeCountry) if codeType == 'country' else baseLibrary.isoStateCode(maybeCountry)
if isoCountry:
return isoCountry
#--look for various labels
tokenList = []
if 'country of issue:' in notes:
tokenList = notes[notes.find('country of issue:')+17:].strip().split()
else: #or try the whole string
tokenList = notes.strip().split()
#--if single token (just confirm or deny)
if len(tokenList) == 1:
if tokenList[0][-1] in (',', ';', ':'):
tokenList[0] = tokenList[0][0:-1]
maybeCountry = tokenList[0]
isoCountry = baseLibrary.isoCountryCode(maybeCountry) if codeType == 'country' else baseLibrary.isoStateCode(maybeCountry)
if isoCountry:
return isoCountry
else:
return None
priorToken1 = ''
priorToken2 = ''
priorToken3 = ''
maybeCountry = ''
for currentToken in tokenList:
if currentToken[-1] in (',', ';', ':'):
currentToken = currentToken[0:-1]
maybeCountry = currentToken
isoCountry0 = baseLibrary.isoCountryCode(maybeCountry) if codeType == 'country' else baseLibrary.isoStateCode(maybeCountry)
isoCountry1 = None
isoCountry2 = None
isoCountry3 = None
if priorToken1:
maybeCountry = priorToken1 + ' ' + currentToken
isoCountry1 = baseLibrary.isoCountryCode(maybeCountry) if codeType == 'country' else baseLibrary.isoStateCode(maybeCountry)
if priorToken2:
maybeCountry = priorToken2 + ' ' + priorToken1 + ' ' + currentToken
isoCountry2 = baseLibrary.isoCountryCode(maybeCountry) if codeType == 'country' else baseLibrary.isoStateCode(maybeCountry)
if priorToken3:
maybeCountry = priorToken3 + ' ' + priorToken2 + ' ' + priorToken1 + ' ' + currentToken
isoCountry3 = baseLibrary.isoCountryCode(maybeCountry) if codeType == 'country' else baseLibrary.isoStateCode(maybeCountry)
if isoCountry0 and currentToken not in ('id', 'in','is','on','no','and'): #--careful of connecting words here!
return isoCountry0
elif isoCountry1:
return isoCountry1
elif isoCountry2:
return isoCountry2
elif isoCountry3:
return isoCountry3
priorToken3 = priorToken2
priorToken2 = priorToken1
priorToken1 = currentToken
return None
#----------------------------------------
def concatDateParts(day, month, year):
#--15-mar-2010 is format
fullDate = ''
if day:
fullDate += day + '-'
if month:
fullDate += month + '-'
if year:
fullDate += year
return fullDate
#----------------------------------------
def g2Mapping(masterRecord, recordType):
truncation_list = []
#--header
jsonData = {}
jsonData['DATA_SOURCE'] = dataSource
jsonData['RECORD_ID'] = masterRecord.attrib['id']
jsonData['LAST_UPDATE'] = masterRecord.attrib['date']
jsonData['STATUS'] = getValue(masterRecord, 'ActiveStatus')
jsonData['DJ_PROFILE_ID'] = masterRecord.attrib['id']
gender = getValue(masterRecord, 'Gender')
if gender:
jsonData['GENDER'] = gender
updateStat('ATTRIBUTE', 'GENDER')
deceased = getValue(masterRecord, 'Deceased')
if deceased == 'Yes':
jsonData['DECEASED'] = deceased
updateStat('OTHER', 'DECEASED', deceased)
if extendedFormat:
profileNotes = getValue(masterRecord, 'ProfileNotes')
if profileNotes:
jsonData['PROFILE_NOTES'] = profileNotes
updateStat('ATTRIBUTE', 'PROFILE_NOTES')
#--names
# <NameType NameTypeID="1" RecordType="Person">Primary Name</NameType>
# <NameType NameTypeID="2" RecordType="Person">Also Known As</NameType>
# <NameType NameTypeID="3" RecordType="Person">Low Quality AKA</NameType>
# <NameType NameTypeID="4" RecordType="Person">Maiden Name</NameType>
# <NameType NameTypeID="5" RecordType="Person">Formerly Known As</NameType>
# <NameType NameTypeID="6" RecordType="Person">Spelling Variation</NameType>
# <NameType NameTypeID="7" RecordType="Entity">Primary Name</NameType>
# <NameType NameTypeID="8" RecordType="Entity">Also Known As</NameType>
# <NameType NameTypeID="9" RecordType="Entity">Formerly Known As</NameType>
# <NameType NameTypeID="10" RecordType="Entity">Spelling Variation</NameType>
# <NameType NameTypeID="11" RecordType="Entity">Low Quality AKA</NameType>
orgPersonNameConflict = False
thisList = []
for nameRecord in masterRecord.findall('NameDetails/Name'):
nameType = nameRecord.attrib['NameType'][0:25]
if 'PRIMARY' in nameType.upper():
nameType = 'PRIMARY'
for nameValue in nameRecord.findall('NameValue'):
nameStr = ''
name = {}
name['NAME_TYPE'] = nameType
updateStat('NAME_TYPE', nameType)
nameOrg = getValue(nameValue, 'EntityName')
if nameOrg:
if len(nameOrg.split()) > 16:
truncation_list.append({"EntityName": nameOrg})
updateStat('TRUNCATIONS', 'longNameOrgCnt', jsonData['RECORD_ID'] + ' | ' + nameOrg)
nameOrg = ' '.join(nameOrg.split()[:16])
name['NAME_ORG'] = nameOrg
nameStr = nameOrg
nameLast = getValue(nameValue, 'Surname')
if nameLast:
if len(nameLast.split()) > 10:
truncation_list.append({"Surname": nameLast})
updateStat('TRUNCATIONS', 'longNameLastCnt', jsonData['RECORD_ID'] + ' | ' + nameLast)
nameLast = ' '.join(nameLast.split()[:10])
name['NAME_LAST'] = nameLast
nameStr = nameLast
nameMaiden = getValue(nameValue, 'MaidenName')
if nameMaiden and not nameLast: #--either Surname or MaidenName will be populated
if len(nameMaiden.split()) > 10:
truncation_list.append({"MaidenName": nameMaiden})
updateStat('TRUNCATIONS', 'longNameMaidenCnt', jsonData['RECORD_ID'] + ' | ' + nameMaiden)
nameMaiden = ' '.join(nameMaiden.split()[:10])
name['NAME_LAST'] = nameMaiden
nameStr = nameLast
nameFirst = getValue(nameValue, 'FirstName')
if nameFirst:
if len(nameFirst.split()) > 10:
truncation_list.append({"FirstName": nameFirst})
updateStat('TRUNCATIONS', 'longNameFirstCnt', jsonData['RECORD_ID'] + ' | ' + nameFirst)
nameFirst = ' '.join(nameFirst.split()[:10])
name['NAME_FIRST'] = nameFirst
nameStr += (' '+nameFirst)
nameMiddle = getValue(nameValue, 'MiddleName')
if nameMiddle:
if len(nameMiddle.split()) > 10:
truncation_list.append({"MiddleName": nameMiddle})
updateStat('TRUNCATIONS', 'longNameMiddleCnt', jsonData['RECORD_ID'] + ' | ' + nameMiddle)
nameMiddle = ' '.join(nameMiddle.split()[:10])
name['NAME_MIDDLE'] = nameMiddle
nameStr += (' '+nameMiddle)
namePrefix = getValue(nameValue, 'TitleHonorific')
if namePrefix:
name['NAME_PREFIX'] = namePrefix
nameSuffix = getValue(nameValue, 'Suffix')
if nameSuffix:
name['NAME_SUFFIX'] = nameSuffix
thisList.append(name)
#--check for a name conflict
if (recordType == 'PERSON' and 'NAME_ORG' in name) or (recordType != 'PERSON' and 'NAME_LAST' in name):
orgPersonNameConflict = True
#--duplicate this name segment for original script version if supplied
originalScriptName = getValue(nameValue, 'OriginalScriptName')
if originalScriptName:
name = {}
updateStat('NAME_TYPE', 'OriginalScriptName')
name['NAME_TYPE'] = 'OriginalScriptName'
name['NAME_FULL'] = originalScriptName
thisList.append(name)
#--duplicate this name segment for SingleStringName if supplied
singleStringName = getValue(nameValue, 'SingleStringName')
if singleStringName:
name = {}
updateStat('NAME_TYPE', 'singleStringName')
name['NAME_TYPE'] = 'singleStringName'
name['NAME_FULL'] = singleStringName
thisList.append(name)
if thisList:
jsonData['NAMES'] = thisList
if orgPersonNameConflict:
print('warning: person and org names on record %s' % jsonData['RECORD_ID'])
#--dates
# <DateType Id="1" RecordType="Person" name="Date of Birth"/>
# <DateType Id="2" RecordType="Person" name="Deceased Date"/>
# <DateType Id="3" RecordType="Entity" name="Date of Registration"/>
thisList = []
for dateRecord in masterRecord.findall('DateDetails/Date'):
try: dateType = dateRecord.attrib['DateType']
except: #--all but the anti-corruption (SOC) feed use DateType
try: dateType = dateRecord.attrib['DateTypeId']
except:
print('bad date record!')
print(minidom.parseString(etree.tostring(dateRecord, 'utf-8')).toprettyxml(indent="\t"))
continue
if dateType == 'Date of Birth':
dateType = 'DATE_OF_BIRTH'
elif dateType == 'Deceased Date':
dateType = 'DATE_OF_DEATH'
elif dateType == 'Date of Registration':
dateType = 'REGISTRATION_DATE'
for dateValue in dateRecord.findall('DateValue'):
day = getAttr(dateValue, 'Day')
month = getAttr(dateValue, 'Month')
year = getAttr(dateValue, 'Year')
thisDate = concatDateParts(day, month, year)
if dateType == 'DATE_OF_BIRTH':
outputFormat = '%Y-%m-%d'
if not day and not month:
updateStat('DOB_DATA', 'year only', thisDate)
elif year and month and not day:
updateStat('DOB_DATA', 'year/month only', thisDate)
elif month and day and not year:
updateStat('DOB_DATA', 'month/day only', thisDate)
else:
updateStat('DOB_DATA', 'full', thisDate)
formattedDate = baseLibrary.formatDate(thisDate)
if formattedDate:
thisList.append({dateType: formattedDate})
else:
jsonData[dateType] = thisDate
updateStat('ATTRIBUTE', dateType, thisDate)
if thisList:
jsonData['DATES'] = thisList
#--addresses
thisList = []
for addrRecord in masterRecord.findall('Address'):
address = {}
addrLine = getValue(addrRecord, 'AddressLine')
if addrLine:
if len(addrLine.split()) > 16:
truncation_list.append({"AddressLine": addrLine})
updateStat('TRUNCATIONS', 'longAddrLineCnt', jsonData['RECORD_ID'] + ' | ' + addrLine)
addrLine = ' '.join(addrLine.split()[:16])
address['ADDR_LINE1'] = addrLine
addrCity = getValue(addrRecord, 'AddressCity')
if addrCity:
address['ADDR_CITY'] = addrCity
addrCountry = getValue(addrRecord, 'AddressCountry')
if addrCountry:
address['ADDR_COUNTRY'] = countryCodes[addrCountry] if addrCountry in countryCodes else addrCountry
isoCountry = baseLibrary.isoCountryCode(address['ADDR_COUNTRY'])
if isoCountry:
address['ADDR_COUNTRY'] = isoCountry
thisList.append(address)
updateStat('ADDRESS', 'UNTYPED')
if thisList:
jsonData['ADDRESSES'] = thisList
#--company details (address/website)
thisList1 = []
thisList2 = []
for addrRecord in masterRecord.findall('CompanyDetails'):
address = {}
address['ADDR_TYPE'] = 'BUSINESS'
addrLine = getValue(addrRecord, 'AddressLine')
if addrLine:
if len(addrLine.split()) > 16:
updateStat('TRUNCATIONS', 'longAddrLineCnt', addrLine)
addrLine = ' '.join(addrLine.split()[:16])
address['ADDR_LINE1'] = addrLine
addrCity = getValue(addrRecord, 'AddressCity')
if addrCity:
address['ADDR_CITY'] = addrCity
addrCountry = getValue(addrRecord, 'AddressCountry')
if addrCountry:
address['ADDR_COUNTRY'] = countryCodes[addrCountry] if addrCountry in countryCodes else addrCountry
isoCountry = baseLibrary.isoCountryCode(address['ADDR_COUNTRY'])
if isoCountry:
address['ADDR_COUNTRY'] = isoCountry
thisList1.append(address)
updateStat('ADDRESS', 'BUSINESS')
url = getValue(addrRecord, 'URL')
if url:
thisList2.append({'WEBSITE_ADDRESS': url})
updateStat('ATTRIBUTE', 'WEBSITE_ADDRESS')
if thisList1:
jsonData['COMPANY_ADDRESSES'] = thisList1
if thisList2:
jsonData['COMPANY_WEBSITES'] = thisList2
#--countries
thisList1 = []
for birthPlaceRecord in masterRecord.findall('BirthPlace/Place'):
birthPlace = birthPlaceRecord.attrib['name']
thisList1.append({'PLACE_OF_BIRTH': birthPlace})
updateStat('ATTRIBUTE', 'PLACE_OF_BIRTH')
for countryRecord in masterRecord.findall('CountryDetails/Country'):
countryType = countryRecord.attrib['CountryType']
if countryType == 'Citizenship':
attributeType = 'CITIZENSHIP'
else:
if countryType == 'REGISTRATION':
usageType = 'REGISTRATION'
elif countryType == 'Resident of':
usageType = 'RESIDENT'
elif countryType == 'Jurisdiction':
usageType = 'JURISDICTION'
elif countryType == 'Country of Affiliation':
usageType = 'AFFILIATED'
elif countryType == 'Enhanced Risk Country':
usageType = 'RISK'
else:
usageType = 'OTHER'
attributeType = usageType + '_COUNTRY_OF_ASSOCIATION'
itemNum = 0
for countryValue in countryRecord.findall('CountryValue'):
countryCode = countryValue.attrib['Code']
countryName = countryCodes[countryCode] if countryCode in countryCodes else countryCode
isoCountry = baseLibrary.isoCountryCode(countryName)
if isoCountry:
countryName = isoCountry
thisList1.append({attributeType: countryName})
updateStat('COUNTRIES', attributeType, countryName)
if thisList1:
jsonData['COUNTRIES'] = thisList1
#--identifiers
itemNum = 0
thisList = []
for idRecord in masterRecord.findall('IDNumberTypes/ID'):
idType = idRecord.attrib['IDType']
for idValue in idRecord.findall('IDValue'):
idNumber = getValue(idValue)
idNotes = getAttr(idValue, 'IDnotes')
if not idNotes:
idNotes = ''
attrType1 = None
attrType2 = None
countryCheck = 0
if idType.upper() == 'SOCIAL SECURITY NO.':
attrType1 = 'SSN_NUMBER'
elif idType.upper() == 'PASSPORT NO.':
attrType1 = 'PASSPORT_NUMBER'
attrType2 = 'PASSPORT_COUNTRY'
countryCheck = 1
elif idType.upper() == 'DRIVING LICENCE NO.':
attrType1 = 'DRIVERS_LICENSE_NUMBER'
attrType2 = 'DRIVERS_LICENSE_STATE'
countryCheck = 2
elif idType.upper() == 'NATIONAL ID':
attrType1 = 'NATIONAL_ID_NUMBER'
attrType2 = 'NATIONAL_ID_COUNTRY'
countryCheck = 1
elif idType.upper() == 'NATIONAL TAX NO.':
attrType1 = 'TAX_ID_NUMBER'
attrType2 = 'TAX_ID_COUNTRY'
countryCheck = 1
elif idType.upper() == 'COMPANY IDENTIFICATION NO.':
attrType1 = 'COMPANY_ID_NUMBER'
attrType2 = 'COMPANY_ID_COUNTRY'
countryCheck = 1
elif idType.upper() == 'DUNS NUMBER':
attrType1 = 'DUNS_NUMBER'
elif idType.upper() == 'OFAC UNIQUE ID':
attrType1 = 'OFAC_ID'
elif idType.upper() == 'NATIONAL PROVIDER IDENTIFIER (NPI)' or idNotes.startswith('NPI') or '(NPI)' in idNotes.upper():
attrType1 = 'NPI_NUMBER'
elif idType.upper() == 'LEGAL ENTITY IDENTIFIER (LEI)':
attrType1 = 'LEI_NUMBER'
elif idType.upper() == 'NATIONAL CRIMINAL IDENTIFICATION CODE (USA)' or '(NCIC)' in idNotes.upper():
attrType1 = 'NCIC_NUMBER'
elif idType.upper() == 'CENTRAL REGISTRATION DEPOSITORY (CRD)':
attrType1 = 'CRD_NUMBER'
elif idType.upper() == 'INTERNATIONAL MARITIME ORGANIZATION (IMO) SHIP NO.':
attrType1 = 'IMO_NUMBER'
elif idType.upper() == 'INTERNATIONAL SECURITIES IDENTIFICATION NUMBER (ISIN)':
attrType1 = 'ISIN_NUMBER'
elif idType.upper() == 'MSB LICENCE NUMBER':
attrType1 = 'MSB_LICENSE_NUMBER'
elif idType.upper() == 'MARIJUANA LICENCE NUMBER':
attrType1 = 'MARIJUANA_LICENSE_NUMBER'
elif idType.upper() == 'OTHERS' and idNotes.upper() == 'MMSI':
attrType1 = 'MMSI_NUMBER'
elif '(MSN)' in idType.upper():
attrType1 = 'AIRCRAFT_MFG_SERIAL_NUM'
elif idType.upper() == 'OTHERS' and 'AIRCRAFT TAIL NUMBER' in idNotes.upper():
attrType1 = 'AIRCRAFT_TAIL_NUMBER'
else:
attrType1 = None
#--if mapped
if attrType1:
#--parse notes for a country or state code
isoCode = None
if idNotes:
#--try for country code
if countryCheck:
isoCode = idNoteParse(idNotes, 'country')
#--try for US state code
if countryCheck == 2 and (isoCode in ('USA', 'US') or not isoCode):
isoCode = idNoteParse(idNotes, 'state')
#--create the identity structure
idDict = {}
idDict[attrType1] = idNumber
if attrType2 and isoCode: #--the notes should contain a country or a state
idDict[attrType2] = isoCode
thisList.append(idDict)
updateStat('ID_TYPE', '%s | %s' % (attrType1, isoCode), idNumber)
#--un-mapped
else:
updateStat('UNKNOWN', '%s | %s' % (idType, idNotes), idNumber)
itemNum += 1
jsonData['ID%s' % itemNum] = idType + ' = ' + idNumber + ((' ' + idNotes) if idNotes else '')
if thisList:
jsonData['IDENTIFIERS'] = thisList
#--descriptions
itemNum = 0
for descriptionRecord in masterRecord.findall('Descriptions/Description'):
description1Code = None
description2Code = None
description3Code = None
try:
description1 = '%s=%s' % (descriptionRecord.attrib['Description1'], description1Codes[descriptionRecord.attrib['Description1']])
description1Code = descriptionRecord.attrib['Description1']
except: description1 = ''
try:
description2 = '%s=%s' % (descriptionRecord.attrib['Description2'], description2Codes[descriptionRecord.attrib['Description2']])
description2Code = descriptionRecord.attrib['Description2']
except: description2 = ''
try:
description3 = '%s=%s' % (descriptionRecord.attrib['Description3'], description3Codes[descriptionRecord.attrib['Description3']])
description3Code = description3Codes[descriptionRecord.attrib['Description3']].upper()
except: description3 = ''
if description1 or description2 or description3:
itemNum += 1
description = description1
description += (' | ' if description2 else '') + description2
description += (' | ' if description3 else '') + description3
jsonData["Description%s" % itemNum] = description
updateStat('DESCRIPTIONS', description, jsonData['RECORD_ID'])
#--record type reclassifications
if description3Code == 'SHIP':
recordType = 'VESSEL'
if description3Code == 'AIRCRAFT':
recordType = 'AIRCRAFT'
#--roles
for roleRecord in masterRecord.findall('RoleDetail/Roles'):
itemNum = 0
roleType = roleRecord.attrib['RoleType']
for occTitle in roleRecord.findall('OccTitle'):
itemNum += 1
fromDate = concatDateParts(getAttr(occTitle, 'SinceDay'), getAttr(occTitle, 'SinceMonth'), getAttr(occTitle, 'SinceYear'))
thruDate = concatDateParts(getAttr(occTitle, 'ToDay'), getAttr(occTitle, 'ToMonth'), getAttr(occTitle, 'ToYear'))
thisRole = getValue(occTitle)
if fromDate:
thisRole += ' From ' + fromDate
if thruDate:
thisRole += ' To ' + thruDate
jsonData[roleType + str(itemNum)] = thisRole
updateStat('OTHER', 'ROLES', thisRole)
#--references
itemNum = 0
for referenceRecord in masterRecord.findall('SanctionsReferences/Reference'):
itemNum += 1
referenceName = '%s=%s' % (getValue(referenceRecord), referenceCodes[getValue(referenceRecord)])
fromDate = concatDateParts(getAttr(referenceRecord, 'SinceDay'), getAttr(referenceRecord, 'SinceMonth'), getAttr(referenceRecord, 'SinceYear'))
thruDate = concatDateParts(getAttr(referenceRecord, 'ToDay'), getAttr(referenceRecord, 'ToMonth'), getAttr(referenceRecord, 'ToYear'))
if fromDate:
referenceName += ' From ' + fromDate
if thruDate:
referenceName += ' To ' + thruDate
jsonData["Reference%s" % itemNum] = referenceName
updateStat('OTHER', 'REFERENCES', referenceName)
#--sources
if extendedFormat: #--disabled to keep reports smaller
itemNum = 0
for sourceRecord in masterRecord.findall('SourceDescription/Source'):
itemNum += 1
sourceName = sourceRecord.attrib['name']
updateStat('OTHER', 'SOURCES')
jsonData["Source%s" % itemNum] = sourceName
#--images
if extendedFormat: #--disabled to keep reports smaller
itemNum = 0
for imageRecord in masterRecord.findall('Images/Image'):
itemNum += 1
imageURL = imageRecord.attrib['URL']
#--updateStat('source-' + sourceName) <--too many of these to log
jsonData["Image%s" % itemNum] = imageURL
#--disclosed relationships
thisList = []
thisId = jsonData['DJ_PROFILE_ID']
if thisId in relationships:
if relationshipStyle == 2:
thisRecord = {}
thisRecord['REL_ANCHOR_DOMAIN'] = 'DJ_ID'
thisRecord['REL_ANCHOR_KEY'] = thisId
thisList.append(thisRecord)
for relationship in relationships[thisId]:
otherId = relationship['id']
relType = relationCodes[relationship['code']].replace(' ', '_').replace('-','_')
if relationship['ex'] == 'Yes':
relType = 'EX_' + relType
thisRecord = {}
if noRelationships:
thisRecord['Related to'] = '%s | %s | %s' % (dataSource, otherId, relType)
#--new relationship strategy
elif relationshipStyle == 2:
thisRecord['REL_POINTER_DOMAIN'] = 'DJ_ID'
thisRecord['REL_POINTER_KEY'] = otherId
thisRecord['REL_POINTER_ROLE'] = relType
else:
#--get other side
relType1 = None
if otherId in relationships:
for relationship1 in relationships[otherId]:
if relationship1['id'] == thisId:
relType1 = relationCodes[relationship1['code']].replace(' ', '_').replace('-','_')
break
relKey = '-'.join(sorted([thisId, otherId]))
if relType1 and relType1 != relType:
relType = '/'.join(sorted([relType, relType1]))
#--create the relationship
thisRecord['RELATIONSHIP_TYPE'] = relType
thisRecord['RELATIONSHIP_KEY'] = relKey
updateStat('RELATIONSHIPS', relType)
thisList.append(thisRecord)
#--group association name
if recordType == 'PERSON' and relationship['id'] in entityNames:
thisRecord = {}
#thisRecord[relType + '_GROUP_ASSOCIATION_TYPE'] = 'ORG'
thisRecord[relType + '_GROUP_ASSOCIATION_ORG_NAME'] = entityNames[relationship['id']]
thisList.append(thisRecord)
updateStat('GROUP_ASSOCIATION', 'NAME', relType)
#--group association IDs
if recordType == 'PERSON' and relationship['id'] in entityDuns:
thisRecord = {}
thisRecord[relType + '_GROUP_ASSN_ID_TYPE'] = 'DUNS'
thisRecord[relType + '_GROUP_ASSN_ID_NUMBER'] = entityDuns[relationship['id']]
thisList.append(thisRecord)
updateStat('GROUP_ASSOCIATION', 'DUNS', relType)
if thisList:
jsonData['RELATIONSHIPS'] = thisList
#--assign the entity and record type
jsonData['RECORD_TYPE'] = recordType.upper()
updateStat('RECORD_TYPE', jsonData['RECORD_TYPE'])
if truncation_list:
jsonData['truncations'] = truncation_list
#--add composite keys
if addCompositeKeys:
jsonData = baseLibrary.jsonUpdater(jsonData)
return jsonData
#----------------------------------------
if __name__ == "__main__":
appPath = os.path.dirname(os.path.abspath(sys.argv[0]))
global shutDown
shutDown = False
signal.signal(signal.SIGINT, signal_handler)
procStartTime = time.time()
progressInterval = 10000
argparser = argparse.ArgumentParser()
argparser.add_argument('-i', '--input_file', default=os.getenv('input_file', None), type=str, help='A Dow Jones xml file for PFA or HRF.')
argparser.add_argument('-o', '--output_file', default=os.getenv('output_file', None), type=str, help='output filename, defaults to input file name with a .json extension.')
argparser.add_argument('-l', '--log_file', default=os.getenv('log_file', None), type=str, help='optional statistics filename (json format).')
argparser.add_argument('-d', '--data_source', default=os.getenv('data_source'.upper(), None), type=str, help='please use DJ-PFA, DJ-HRF or DJ-AME based on the type of file.')
argparser.add_argument('-r', '--relationship_style', dest='relationship_style', type=int, default=2, help='styles: 0=None, 1=Legacy linking, 2=Pointers (new for Senzing v1.15)')
argparser.add_argument('-e', '--extended_format', dest='extended_format', action='store_true', default=False, help='include profile notes, sources, and images')
argparser.add_argument('-D', '--debug_level', dest='debug_level', type=int, default=0, help='debug options: 1=Show XML only, 2=Show XML and JSON')
argparser.add_argument('-L', '--lookup_profile', dest='dj_profile_id', type=str, help='enter a DJ profile ID to lookup for debugging purposes')
args = argparser.parse_args()
inputFileName = args.input_file
outputFileName = args.output_file
logFile = args.log_file
dataSource = args.data_source
relationshipStyle = args.relationship_style
extendedFormat = args.extended_format
debugLevel = args.debug_level
dj_profile_id = args.dj_profile_id
if dj_profile_id and not debugLevel: #--looking up a profile is a form of debugging
debugLevel = 1
#--deprecated arguments
noRelationships = False
addCompositeKeys = False
if not inputFileName:
print('')
print('Please select a dow jones xml input file')
print('')
sys.exit(1)
if not os.path.exists(inputFileName):
print('')
print('Input file %s not found!' % inputFileName)
print('')
sys.exit(1)
#--default and validate the data source
if not dataSource:
dataSource = 'DJ-PFA'
else:
dataSource = dataSource.upper()
if not (outputFileName) and not debugLevel:
print('')
print('Please supply an output file name.')
print('')
sys.exit(1)
#--open output file
if outputFileName:
try: outputFileHandle = open(outputFileName, "w", encoding='utf-8')
except IOError as err:
print('')
print('Could not open output file %s for writing' % outputFileName)
print(' %s' % err)
print('')
sys.exit(1)
#--initialize some stats
recordCnt = 0
personCnt = 0
entityCnt = 0
statPack = {}
#--initialize code dictionaries
countryCodes = {}
description1Codes = {}
description2Codes = {}
description3Codes = {}
referenceCodes = {}
relationCodes = {}
relationships = {}
entityNames = {}
entityDuns = {}
#--iterate through the xml file serially as it is huge!
print('')
print('Data source set to %s' % dataSource)
print('')
print('Reading from: %s ...' % inputFileName)
if debugLevel != 1:
xmlReader = etree.iterparse(inputFileName, events=("start", "end"))
for event, node in xmlReader:
if event == 'end':
if node.tag == 'CountryList':
print('loading %s ...' % node.tag)
for record in node.findall('CountryName'):
countryCodes[getAttr(record, 'code')] = getAttr(record, 'name')
node.clear()
elif node.tag == 'Description1List':
print('loading %s ...' % node.tag)
for record in node.findall('Description1Name'):
description1Codes[getAttr(record, 'Description1Id')] = getValue(record)
node.clear()
elif node.tag == 'Description2List':
print('loading %s ...' % node.tag)
for record in node.findall('Description2Name'):
description2Codes[getAttr(record, 'Description2Id')] = getValue(record)
node.clear()
elif node.tag == 'Description3List':
print('loading %s ...' % node.tag)
for record in node.findall('Description3Name'):
description3Codes[getAttr(record, 'Description3Id')] = getValue(record)
node.clear()
elif node.tag == 'SanctionsReferencesList':
print('loading %s ...' % node.tag)
for record in node.findall('ReferenceName'):
referenceCodes[getAttr(record, 'code')] = getAttr(record, 'name')
node.clear()
elif node.tag == 'RelationshipList':
print('loading %s ...' % node.tag)
for record in node.findall('Relationship'):
try: relationCodes[getAttr(record, 'code')] = getAttr(record, 'name').replace('_', '-')
except: #--all but the anti-corruption (soc) feed use the name attribute
try: relationCodes[getAttr(record, 'code')] = getValue(record).replace('_', '-')
except:
print(minidom.parseString(etree.tostring(record, 'utf-8')).toprettyxml(indent="\t"))
node.clear()
elif node.tag == 'Associations':
print('loading %s ...' % node.tag)
for record in node.findall('PublicFigure'):
id = getAttr(record, 'id')
relationships[id] = []
for record1 in record.findall('Associate'):
relationships[id].append({'id': getAttr(record1, 'id'), 'code': getAttr(record1, 'code'), 'ex': getAttr(record1, 'ex')})
for record in node.findall('SpecialEntity'):
id = getAttr(record, 'id')
relationships[id] = []
for record1 in record.findall('Associate'):
relationships[id].append({'id': getAttr(record1, 'id'), 'code': getAttr(record1, 'code'), 'ex': getAttr(record1, 'ex')})
node.clear()
elif node.tag == 'Entity':
id = getAttr(node, 'id')
for nameRecord in node.findall('NameDetails/Name'):
if nameRecord.attrib['NameType'] == 'Primary Name':
for nameValue in nameRecord.findall('NameValue'):
nameOrg = getValue(nameValue, 'EntityName')
if nameOrg:
entityNames[id] = nameOrg
break
break
for idRecord in node.findall('IDNumberTypes/ID'):
if idRecord.attrib['IDType'] == 'DUNS Number':
for idValue in idRecord.findall('IDValue'):
idNumber = getValue(idValue)
if idNumber:
entityDuns[id] = idNumber
break
break
node.clear()
elif node.tag in ('Person'):
node.clear()
#print('countryCodes', len(countryCodes))
#print('description1Codes', len(description1Codes))
#print('description2Codes', len(description2Codes))
#print('description3Codes', len(description3Codes))
#print('referenceCodes', len(referenceCodes))
#print('relationCodes', len(relationCodes))
#print('relationships', len(relationships))
#print('entityNames', len(entityNames))
#sys.exit(1)
#--go through a second time to process the records
print('')
if dj_profile_id:
print('searching for %s ...' % dj_profile_id)
else:
print('processing records ...')
xmlReader = etree.iterparse(inputFileName, events=("start", "end"))
for event, node in xmlReader:
if event == 'end' and node.tag in ('Person','Entity'):
if shutDown:
break
if dj_profile_id and node.attrib['id'] != dj_profile_id:
node.clear()
continue
if debugLevel in (1,2):
print('='*50)
print(minidom.parseString(etree.tostring(node, 'utf-8')).toprettyxml(indent="\t"))
if debugLevel == 1:
pause()
continue
if node.tag == 'Person':
jsonData = g2Mapping(node, 'PERSON')
personCnt += 1
else:
jsonData = g2Mapping(node, 'ORGANIZATION')
entityCnt += 1
msg = json.dumps(jsonData, ensure_ascii=False)
if debugLevel == 2:
print('-'*50)
print(json.dumps(jsonData, ensure_ascii=False, indent=4))
pause()
if outputFileName:
try: outputFileHandle.write(msg + '\n')
except IOError as err:
print('')
print('Could not write to %s' % outputFileName)
print(' %s' % err)
print('')
shutDown = True
if dj_profile_id and node.attrib['id'] == dj_profile_id:
break
node.clear()
if shutDown:
break
recordCnt += 1
if recordCnt % progressInterval == 0:
print('%s rows processed' % recordCnt)
if outputFileName:
outputFileHandle.close()
print('%s rows processed, completed!' % recordCnt)
print('%s persons' % personCnt)
print('%s entities' % entityCnt)
#print('%s longNameOrgCnt' % longNameOrgCnt)
#print('%s longNameLastCnt' % longNameLastCnt)
#print('%s longNameMaidenCnt' % longNameMaidenCnt)
#print('%s longNameFirstCnt' % longNameFirstCnt)
#print('%s longNameMiddleCnt' % longNameMiddleCnt)
#print('%s longAddrLineCnt' % longAddrLineCnt)
#print('')
#--write statistics file
if logFile:
print('')
statPack['BASE_LIBRARY'] = baseLibrary.statPack
with open(logFile, 'w') as outfile:
json.dump(statPack, outfile, indent=4, sort_keys = True)
print('Mapping stats written to %s' % logFile)
print('')
elapsedMins = round((time.time() - procStartTime) / 60, 1)
if shutDown == 0:
print('Process completed successfully in %s minutes!' % elapsedMins)
else:
print('Process aborted after %s minutes!' % elapsedMins)
print('')
sys.exit(0)