-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathG2Explorer.py
5645 lines (4886 loc) · 275 KB
/
G2Explorer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python3
import argparse
import cmd
import csv
import glob
import json
import os
import pathlib
import re
import sys
import textwrap
import logging
import traceback
from collections import OrderedDict
import subprocess
import readline
import atexit
from io import StringIO
from contextlib import suppress
from datetime import datetime
try:
from prettytable import PrettyTable
from prettytable import ALL as PRETTY_TABLE_ALL
try: # Supports both ptable and prettytable builds of prettytable (only prettytable has these styles)
from prettytable import SINGLE_BORDER, DOUBLE_BORDER, MARKDOWN, ORGMODE
pretty_table_style_available = True
except:
pretty_table_style_available = False
except:
print('\nPlease install python pretty table (pip3 install prettytable)\n')
sys.exit(1)
try:
from senzing import G2ConfigMgr, G2Diagnostic, G2Engine, G2EngineFlags, G2Exception, G2Product
except Exception as err:
print(f"\n{err}\n")
sys.exit(1)
with suppress(Exception):
import G2Paths
from G2IniParams import G2IniParams
# ---------------------------
def execute_api_call(api_name, flag_list, parm_list):
parm_list = parm_list if type(parm_list) == list else [parm_list]
called_by = sys._getframe().f_back.f_code.co_name
if not hasattr(g2Engine, api_name):
raise Exception(f"{called_by}: {api_name} not valid in {api_version['BUILD_VERSION']}")
try: flags = int(G2EngineFlags.combine_flags(flag_list))
except Exception as err:
raise Exception(f"{called_by}: {api_name} - {err}")
response = bytearray()
parm_list += [response, flags]
api_called = f"{api_name}({', '.join(str(x) for x in parm_list)})"
try:
api_call = getattr(g2Engine, api_name)
api_call(*parm_list)
response_data = json.loads(response)
if debugOutput:
showDebug(called_by, api_name + '\n\t' + '\n\t'.join(flag_list) + '\n' + json.dumps(response_data, indent=4))
return response_data
except G2Exception as err:
raise Exception(f"{called_by}: {api_name} - {err}")
#except Exception as err:
# raise Exception(f"{called_by}: {api_name} - {err}")
# ==============================
class Colors:
@classmethod
def apply(cls, in_string, color_list=None):
''' apply list of colors to a string '''
if color_list:
prefix = ''.join([getattr(cls, i.strip().upper()) for i in color_list.split(',')])
suffix = cls.RESET
return f'{prefix}{in_string}{suffix}'
return in_string
@classmethod
def set_theme(cls, theme):
# best for dark backgrounds
if theme.upper() == 'DEFAULT':
cls.TABLE_TITLE = cls.FG_GREY42
cls.ROW_TITLE = cls.FG_GREY42
cls.COLUMN_HEADER = cls.FG_GREY42
cls.ENTITY_COLOR = cls.SZ_PURPLE #cls.FG_MEDIUMORCHID1
cls.DSRC_COLOR = cls.SZ_ORANGE #cls.FG_ORANGERED1
cls.ATTR_COLOR = cls.SZ_BLUE #cls.FG_CORNFLOWERBLUE
cls.GOOD = cls.SZ_GREEN #cls.FG_CHARTREUSE3
cls.BAD = cls.SZ_RED #cls.FG_RED3
cls.CAUTION = cls.SZ_YELLOW #cls.FG_GOLD3
cls.HIGHLIGHT1 = cls.SZ_PINK #cls.FG_DEEPPINK4
cls.HIGHLIGHT2 = cls.SZ_CYAN #cls.FG_DEEPSKYBLUE1
cls.MATCH = cls.SZ_BLUE
cls.AMBIGUOUS = cls.SZ_LIGHTORANGE
cls.POSSIBLE = cls.SZ_ORANGE
cls.RELATED = cls.SZ_GREEN
cls.DISCLOSED = cls.SZ_PURPLE
elif theme.upper() == 'LIGHT':
cls.TABLE_TITLE = cls.FG_LIGHTBLACK
cls.ROW_TITLE = cls.FG_LIGHTBLACK
cls.COLUMN_HEADER = cls.FG_LIGHTBLACK # + cls.ITALICS
cls.ENTITY_COLOR = cls.FG_LIGHTMAGENTA + cls.BOLD
cls.DSRC_COLOR = cls.FG_LIGHTYELLOW + cls.BOLD
cls.ATTR_COLOR = cls.FG_LIGHTCYAN + cls.BOLD
cls.GOOD = cls.FG_LIGHTGREEN
cls.BAD = cls.FG_LIGHTRED
cls.CAUTION = cls.FG_LIGHTYELLOW
cls.HIGHLIGHT1 = cls.FG_LIGHTMAGENTA
cls.HIGHLIGHT2 = cls.FG_LIGHTCYAN
cls.MATCH = cls.FG_LIGHTBLUE
cls.AMBIGUOUS = cls.FG_LIGHTYELLOW
cls.RELATED = cls.FG_LIGHTGREEN
cls.DISCLOSED = cls.FG_LIGHTMAGENTA
elif theme.upper() == 'DARK':
cls.TABLE_TITLE = cls.FG_BLACK
cls.ROW_TITLE = cls.FG_BLACK
cls.COLUMN_HEADER = cls.FG_BLACK # + cls.ITALICS
cls.ENTITY_COLOR = cls.FG_MAGENTA
cls.DSRC_COLOR = cls.FG_YELLOW
cls.ATTR_COLOR = cls.FG_CYAN
cls.GOOD = cls.FG_GREEN
cls.BAD = cls.FG_RED
cls.CAUTION = cls.FG_YELLOW
cls.HIGHLIGHT1 = cls.FG_MAGENTA
cls.HIGHLIGHT2 = cls.FG_CYAN
cls.MATCH = cls.FG_BLUE
cls.AMBIGUOUS = cls.FG_YELLOW
cls.POSSIBLE = cls.FG_RED
cls.RELATED = cls.FG_GREEN
cls.DISCLOSED = cls.FG_MAGENTA
# styles
RESET = '\033[0m'
BOLD = '\033[01m'
DIM = '\033[02m'
ITALICS = '\033[03m'
UNDERLINE = '\033[04m'
BLINK = '\033[05m'
REVERSE = '\033[07m'
STRIKETHROUGH = '\033[09m'
INVISIBLE = '\033[08m'
# foregrounds
FG_BLACK = '\033[30m'
FG_WHITE = '\033[37m'
FG_BLUE = '\033[34m'
FG_MAGENTA = '\033[35m'
FG_CYAN = '\033[36m'
FG_YELLOW = '\033[33m'
FG_GREEN = '\033[32m'
FG_RED = '\033[31m'
FG_LIGHTBLACK = '\033[90m'
FG_LIGHTWHITE = '\033[97m'
FG_LIGHTBLUE = '\033[94m'
FG_LIGHTMAGENTA = '\033[95m'
FG_LIGHTCYAN = '\033[96m'
FG_LIGHTYELLOW = '\033[93m'
FG_LIGHTGREEN = '\033[92m'
FG_LIGHTRED = '\033[91m'
# backgrounds
BG_BLACK = '\033[40m'
BG_WHITE = '\033[107m'
BG_BLUE = '\033[44m'
BG_MAGENTA = '\033[45m'
BG_CYAN = '\033[46m'
BG_YELLOW = '\033[43m'
BG_GREEN = '\033[42m'
BG_RED = '\033[41m'
BG_LIGHTBLACK = '\033[100m'
BG_LIGHTWHITE = '\033[47m'
BG_LIGHTBLUE = '\033[104m'
BG_LIGHTMAGENTA = '\033[105m'
BG_LIGHTCYAN = '\033[106m'
BG_LIGHTYELLOW = '\033[103m'
BG_LIGHTGREEN = '\033[102m'
BG_LIGHTRED = '\033[101m'
# extended
FG_DARKORANGE = '\033[38;5;208m'
FG_SYSTEMBLUE = '\033[38;5;12m' # darker
FG_DODGERBLUE2 = '\033[38;5;27m' # lighter
FG_PURPLE = '\033[38;5;93m'
FG_DARKVIOLET = '\033[38;5;128m'
FG_MAGENTA3 = '\033[38;5;164m'
FG_GOLD3 = '\033[38;5;178m'
FG_YELLOW1 = '\033[38;5;226m'
FG_SKYBLUE1 = '\033[38;5;117m'
FG_SKYBLUE2 = '\033[38;5;111m'
FG_ROYALBLUE1 = '\033[38;5;63m'
FG_CORNFLOWERBLUE = '\033[38;5;69m'
FG_HOTPINK = '\033[38;5;206m'
FG_DEEPPINK4 = '\033[38;5;89m'
FG_SALMON = '\033[38;5;209m'
FG_MEDIUMORCHID1 = '\033[38;5;207m'
FG_NAVAJOWHITE3 = '\033[38;5;144m'
FG_DARKGOLDENROD = '\033[38;5;136m'
FG_STEELBLUE1 = '\033[38;5;81m'
FG_GREY42 = '\033[38;5;242m'
FG_INDIANRED = '\033[38;5;131m'
FG_DEEPSKYBLUE1 = '\033[38;5;39m'
FG_ORANGE3 = '\033[38;5;172m'
FG_RED3 = '\033[38;5;124m'
FG_SEAGREEN2 = '\033[38;5;83m'
FG_SZRELATED = '\033[38;5;64m'
FG_YELLOW3 = '\033[38;5;184m'
FG_CYAN3 = '\033[38;5;43m'
FG_CHARTREUSE3 = '\033[38;5;70m'
FG_ORANGERED1 = '\033[38;5;202m'
# senzing
SZ_BLUE = '\033[38;5;25m'
SZ_LIGHTORANGE = '\033[38;5;172m'
SZ_ORANGE = '\033[38;5;166m'
SZ_GREEN = '\033[38;5;64m'
SZ_PURPLE = '\033[38;5;93m'
SZ_CYAN = '\033[38;5;68m'
SZ_PINK = '\033[38;5;170m'
SZ_RED = '\033[38;5;160m'
SZ_YELLOW = '\033[38;5;178m'
# ----------------------------
def colorize(in_string, color_list='None'):
return Colors.apply(in_string, color_list)
# ----------------------------
def colorize_prompt(prompt_str, auto_scroll='off'):
# this is effectively off until the autoscroll parameter gets passed
# otherwise colorized tags causes word wrapping
# example prompt: (P)revious, (N)ext, (G)oto, (D)etail, (H)ow, (W)hy, (E)xport, (Q)uit
if auto_scroll == 'on':
for str1 in 'PNGDHWEQCFSO':
prompt_str = prompt_str.replace(f"({str1})", f"({Colors.apply(str1, 'bold')})")
return prompt_str
# ---------------------------
def colorize_attr(attr_str, attr_color='attr_color'):
if ':' in attr_str:
attr_name = attr_str[0:attr_str.find(':') + 1]
attr_value = attr_str[attr_str.find(':') + 1:].strip()
return colorize(attr_name, attr_color) + ' ' + attr_value
return colorize(attr_str, attr_color)
# ---------------------------
def colorize_dsrc(dsrc_str):
if ':' in dsrc_str:
return colorize_attr(dsrc_str, 'dsrc_color')
return colorize(dsrc_str, 'dsrc_color')
# ---------------------------
def colorize_dsrc1(dsrc_str):
return colorize(dsrc_str, 'dsrc_color')
# ---------------------------
def colorize_entity(entity_str, added_color=None):
entity_color = 'entity_color' + (',' + added_color if added_color else '')
if ':' in str(entity_str):
return colorize_attr(entity_str, entity_color)
return colorize(entity_str, entity_color)
# ---------------------------
def colorize_match_data(matchDict):
if not matchDict['matchKey']:
if matchDict.get('anyCandidates', False):
matchStr = colorize('scored too low!', 'bad')
else:
matchStr = colorize('no matching keys', 'bad')
else:
goodSegments = []
badSegments = []
priorKey = ''
keyColor = 'fg_green'
for key in re.split(r'(\+|\-)', matchDict['matchKey']):
if key in ('+', ''):
priorKey = '+'
elif key == '-':
priorKey = '-'
elif priorKey == '-':
badSegments.append(key)
else:
goodSegments.append(key)
if goodSegments:
matchStr = colorize('+'.join(goodSegments), 'good')
else:
matchStr = ''
if badSegments:
matchStr += colorize('-' + '-'.join(badSegments), 'bad')
if matchDict.get('ruleCode'):
matchStr += f"\n {colorize(matchDict['ruleCode'], 'dim')}"
#else:
# matchStr += f"\n {colorize('no principles satisfied!', 'bad')}"
if 'entityId' in matchDict and 'entityName' in matchDict:
matchStr += f"\n to {colorize_entity(matchDict['entityId'])} {matchDict['entityName']}"
elif 'entityId' in matchDict:
matchStr += f" to {colorize_entity(matchDict['entityId'])}"
return matchStr
# --------------------------------------
def print_message(msg_text, msg_type_or_color = ''):
if msg_type_or_color.upper() == 'ERROR':
msg_color = 'FG_RED'
elif msg_type_or_color.upper() == 'WARNING':
msg_color = 'FG_YELLOW'
elif msg_type_or_color.upper() == 'INFO':
msg_color = 'FG_CYAN'
elif msg_type_or_color.upper() == 'SUCCESS':
msg_color = 'FG_GREEN'
else:
msg_color = msg_type_or_color
print(f"\n{Colors.apply(msg_text, msg_color)}\n")
# ==============================
class Node(object):
def __init__(self, node_id):
self.node_id = node_id
self.node_desc = node_id
self.node_text = None
self.children = []
self.parents = []
def add_child(self, obj):
self.children.append(obj)
def add_parent(self, obj):
self.parents.append(obj)
def render_tree(self, filter_str=None):
tree = ''
tree += (self.node_desc + '\n')
if self.node_text:
tree += (self.node_text + '\n')
parents = [{'node': self, 'next_child': 0, 'prior_nodes': [self]}]
while parents:
if parents[-1]['next_child'] == len(parents[-1]['node'].children):
parents.pop()
continue
next_node = parents[-1]['node'].children[parents[-1]['next_child']]
parents[-1]['next_child'] += 1
prefix = ''
for i in range(len(parents)):
if i < len(parents) - 1: # prior level
prefix += (' ' if parents[i]['next_child'] == len(parents[i]['node'].children) else '\u2502 ')
else:
prefix += ('\u2514\u2500\u2500 ' if parents[i]['next_child'] == len(parents[i]['node'].children) else '\u251c\u2500\u2500 ')
filter_str_in_desc = False
node_desc = next_node.node_desc
if node_desc and filter_str:
if filter_str in node_desc:
node_desc = node_desc.replace(filter_str, colorize(filter_str, 'bg_red, fg_white'))
filter_str_in_desc = True
for line in node_desc.split('\n'):
tree += (prefix + line + '\n')
if prefix[-4:] == '\u251c\u2500\u2500 ':
prefix = prefix[0:-4] + '\u2502 '
elif prefix[-4:] == '\u2514\u2500\u2500 ':
prefix = prefix[0:-4] + ' '
if next_node.node_text:
node_text = next_node.node_text
if filter_str:
if filter_str in node_text:
node_text = node_text.replace(filter_str, colorize(filter_str, 'bg_red, fg_white'))
elif not filter_str_in_desc:
node_text = ''
for line in node_text.split('\n'):
tree += (prefix + line + '\n')
if next_node not in parents[-1]['prior_nodes'] and next_node.children:
# gather all prior level nodes so don't render twice
prior_nodes = []
for parent in parents:
prior_nodes += parent['node'].children
parents.append({'node': next_node, 'next_child': 0, 'prior_nodes': prior_nodes})
return tree
# ==============================
class G2CmdShell(cmd.Cmd):
# ---------------------------
def __init__(self):
cmd.Cmd.__init__(self)
readline.set_completer_delims(' ')
self.intro = '\nType help or ? to list commands.\n'
self.prompt = prompt
# store config dicts for fast lookup
self.cfgData = cfgData
self.dsrcLookup = {}
for cfgRecord in self.cfgData['G2_CONFIG']['CFG_DSRC']:
self.dsrcLookup[cfgRecord['DSRC_ID']] = cfgRecord
self.dsrcCodeLookup = {}
for cfgRecord in self.cfgData['G2_CONFIG']['CFG_DSRC']:
self.dsrcCodeLookup[cfgRecord['DSRC_CODE']] = cfgRecord
self.erruleLookup = {}
for cfgRecord in self.cfgData['G2_CONFIG']['CFG_ERRULE']:
self.erruleLookup[cfgRecord['ERRULE_ID']] = cfgRecord
self.erruleCodeLookup = {}
for cfgRecord in self.cfgData['G2_CONFIG']['CFG_ERRULE']:
self.erruleCodeLookup[cfgRecord['ERRULE_CODE']] = cfgRecord
self.ftypeLookup = {}
for cfgRecord in self.cfgData['G2_CONFIG']['CFG_FTYPE']:
self.ftypeLookup[cfgRecord['FTYPE_ID']] = cfgRecord
self.ftypeCodeLookup = {}
for cfgRecord in self.cfgData['G2_CONFIG']['CFG_FTYPE']:
self.ftypeCodeLookup[cfgRecord['FTYPE_CODE']] = cfgRecord
self.ftypeAttrLookup = {}
for cfgRecord in self.cfgData['G2_CONFIG']['CFG_ATTR']:
if cfgRecord['FTYPE_CODE'] not in self.ftypeAttrLookup:
self.ftypeAttrLookup[cfgRecord['FTYPE_CODE']] = {}
self.ftypeAttrLookup[cfgRecord['FTYPE_CODE']][cfgRecord['FELEM_CODE']] = cfgRecord
self.cfuncLookup = {}
for cfgRecord in self.cfgData['G2_CONFIG']['CFG_CFUNC']:
self.cfuncLookup[cfgRecord['CFUNC_ID']] = cfgRecord
self.cfrtnLookup = {}
for cfgRecord in self.cfgData['G2_CONFIG']['CFG_CFRTN']:
self.cfrtnLookup[cfgRecord['CFUNC_ID']] = cfgRecord
self.scoredFtypeCodes = {}
for cfgRecord in self.cfgData['G2_CONFIG']['CFG_CFCALL']:
cfgRecord['FTYPE_CODE'] = self.ftypeLookup[cfgRecord['FTYPE_ID']]['FTYPE_CODE']
cfgRecord['CFUNC_CODE'] = self.cfuncLookup[cfgRecord['CFUNC_ID']]['CFUNC_CODE']
self.scoredFtypeCodes[cfgRecord['FTYPE_CODE']] = cfgRecord
self.ambiguousFtypeID = self.ftypeCodeLookup['AMBIGUOUS_ENTITY']['FTYPE_ID']
# set feature display sequence
self.featureSequence = {}
self.featureSequence[self.ambiguousFtypeID] = 1 # ambiguous is first
featureSequence = 2
# scored features second
for cfgRecord in sorted(self.cfgData['G2_CONFIG']['CFG_CFCALL'], key=lambda k: k['FTYPE_ID']):
if cfgRecord['FTYPE_ID'] not in self.featureSequence:
self.featureSequence[cfgRecord['FTYPE_ID']] = featureSequence
featureSequence += 1
# then the rest
for cfgRecord in sorted(self.cfgData['G2_CONFIG']['CFG_FTYPE'], key=lambda k: k['FTYPE_ID']):
if cfgRecord['FTYPE_ID'] not in self.featureSequence:
self.featureSequence[cfgRecord['FTYPE_ID']] = featureSequence
featureSequence += 1
# misc
self.dsrc_record_sep = '~|~'
self.__hidden_methods = ('do_shell')
self.doDebug = False
self.searchMatchLevels = {1: 'Match', 2: 'Possible Match', 3: 'Possibly Related', 4: 'Name Only'}
self.relatedMatchLevels = {1: 'Ambiguous Match', 2: 'Possible Match', 3: 'Possibly Related', 4: 'Name Only', 11: 'Disclosed Relation'}
self.validMatchLevelParameters = {'0': 'SINGLE_SAMPLE',
'1': 'DUPLICATE_SAMPLE',
'2': 'AMBIGUOUS_MATCH_SAMPLE',
'3': 'POSSIBLE_MATCH_SAMPLE',
'4': 'POSSIBLY_RELATED_SAMPLE',
'S': 'SINGLE_SAMPLE',
'D': 'DUPLICATE_SAMPLE',
'M': 'DUPLICATE_SAMPLE',
'A': 'AMBIGUOUS_MATCH_SAMPLE',
'P': 'POSSIBLE_MATCH_SAMPLE',
'R': 'POSSIBLY_RELATED_SAMPLE',
'SINGLE': 'SINGLE_SAMPLE',
'DUPLICATE': 'DUPLICATE_SAMPLE',
'MATCH': 'DUPLICATE_SAMPLE',
'AMBIGUOUS': 'AMBIGUOUS_MATCH_SAMPLE',
'POSSIBLE': 'POSSIBLE_MATCH_SAMPLE',
'POSSIBLY': 'POSSIBLY_RELATED_SAMPLE',
'RELATED': 'POSSIBLY_RELATED_SAMPLE'}
self.categorySortOrder = {'MATCH': 1,
'AMBIGUOUS_MATCH': 2,
'POSSIBLE_MATCH': 3,
'POSSIBLY_RELATED': 4,
'DISCLOSED_RELATION': 5}
self.lastEntityID = 0
# get settings
settingsFileName = '.' + os.path.basename(sys.argv[0].lower().replace('.py', '')) + '_settings'
self.settingsFileName = os.path.join(os.path.expanduser("~"), settingsFileName)
try:
self.current_settings = json.load(open(self.settingsFileName))
except:
self.current_settings = {}
# default last snapshot/audit file from parameters
if args.snapshot_file_name:
self.current_settings['snapshotFile'] = args.snapshot_file_name
if args.audit_file_name:
self.current_settings['auditFile'] = args.audit_file_name
# load prior snapshot file
if 'snapshotFile' in self.current_settings and os.path.exists(self.current_settings['snapshotFile']):
self.do_load(self.current_settings['snapshotFile'])
else:
self.snapshotFile = None
self.snapshotData = {}
# load prior audit file
if 'auditFile' in self.current_settings and os.path.exists(self.current_settings['auditFile']):
self.do_load(self.current_settings['auditFile'])
else:
self.auditFile = None
self.auditData = {}
# default settings for data and cross sources summary reports
self.configurable_settings_list = [
{'setting': 'color_scheme', 'values': ['default', 'light', 'dark'], 'description': 'light works better on dark backgrounds and vice-versa'},
{'setting': 'data_source_suppression', 'values': ['off', 'on'], 'description': 'restricts the data and crossSourceSummary reports to only applicable data sources'},
{'setting': 'show_relations_on_get', 'values': ['tree', 'grid', 'none'], 'description': 'display relationships on get in tree or grid or not at all'},
{'setting': 'audit_measure', 'values': ['pairwise', 'legacy'], 'description': 'show official pairwise or legacy (record based) statistics'},
{'setting': 'auto_scroll', 'values': ['off', 'on'], 'description': 'automatically go into scrolling mode if table larger than screen'}
]
for setting_data in self.configurable_settings_list:
self.current_settings[setting_data['setting']] = self.current_settings.get(setting_data['setting'], setting_data['values'][0])
# set the color scheme
self.do_set(f"color_scheme {self.current_settings['color_scheme']}")
self.lastSearchResult = []
self.currentReviewList = None
self.currentRenderString = None
# history
self.readlineAvail = True if 'readline' in sys.modules else False
self.histDisable = histDisable
self.histCheck()
# feedback file
self.feedback_log = []
self.feedback_updated = False
self.feedback_filename = json.loads(iniParams)['PIPELINE']['CONFIGPATH'] + os.sep + 'feedback.log'
if os.path.exists(self.feedback_filename):
with open(self.feedback_filename,'r') as f:
self.feedback_log = [json.loads(x) for x in f.readlines()]
# ---------------------------
def get_names(self):
'''hides functions from available list of Commands. Seperate help sections for some '''
return [n for n in dir(self.__class__) if n not in self.__hidden_methods]
def completenames(self, text, *ignored):
dotext = 'do_' + text
return [a[3:] for a in self.get_names() if a.lower().startswith(dotext.lower())]
# ---------------------------
def emptyline(self):
return
# ---------------------------
def do_quit(self, arg):
removeFromHistory()
return True
# ---------------------------
def do_exit(self, arg):
self.do_quit(self)
return True
# ---------------------------
def cmdloop(self):
while True:
try:
cmd.Cmd.cmdloop(self)
break
except KeyboardInterrupt:
ans = input('\n\nAre you sure you want to exit? ')
if ans in ['y', 'Y', 'yes', 'YES']:
break
except TypeError as ex:
print_message(str(ex), 'error')
type_, value_, traceback_ = sys.exc_info()
for item in traceback.format_tb(traceback_):
print(item)
# ---------------------------
def postloop(self):
try:
with open(self.settingsFileName, 'w') as f:
json.dump(self.current_settings, f)
except:
pass
if self.feedback_updated:
print(f"merges logged to {self.feedback_filename}")
with open(self.feedback_filename,'w') as f:
for record in self.feedback_log:
f.write(json.dumps(record) + '\n')
def do_help(self, help_topic):
if not help_topic:
print(textwrap.dedent(f'''\
{colorize('Adhoc entity commands:', 'highlight2')}
search {colorize('- search for entities by name and/or other attributes.', 'dim')}
get {colorize('- get an entity by entity ID or record_id.', 'dim')}
compare {colorize('- place two or more entities side by side for easier comparison.', 'dim')}
how {colorize('- get a step by step replay of how an entity came together.', 'dim')}
why {colorize('- see why entities or records either did or did not resolve.', 'dim')}
tree {colorize("- see a tree view of an entity's relationships through 1 or 2 degrees.", 'dim')}
export {colorize("- export the json records for an entity for debugging or correcting and reloading.", 'dim')}
{colorize('Snapshot reports:', 'highlight2')} {colorize('(requires a json file created with G2Snapshot)', 'italics')}
dataSourceSummary {colorize('– shows how many duplicates were detected within each data source, as well as ', 'dim')}
{colorize('the possible matches and relationships that were derived. For example, how many duplicate customers ', 'dim')}
{colorize('there are, and are any of them related to each other.', 'dim')}
crossSourceSummary {colorize('– shows how many matches were made across data sources. For example, how many ', 'dim')}
{colorize('employees are related to customers.', 'dim')}
entitySizeBreakdown {colorize("– shows how many entities of what size were created. For instance, some entities ", 'dim')}
{colorize("are singletons, some might have connected 2 records, some 3, etc. This report is primarily used to", 'dim')}
{colorize("ensure there are no instances of over matching. For instance, it’s ok for an entity to have hundreds", 'dim')}
{colorize("of records as long as there are not too many different names, addresses, identifiers, etc.", 'dim')}
{colorize('Audit report:', 'highlight2')} {colorize('(requires a json file created with G2Audit)', 'italics')}
auditSummary {colorize("- shows the precision, recall and F1 scores with the ability to browse the entities that", 'dim')}
{colorize("were split or merged.", 'dim')}
{colorize('Other commands:', 'highlight2')}
quickLook {colorize("- show the number of records in the repository by data source without a snapshot.", 'dim')}
load {colorize("- load a snapshot or audit report json file.", 'dim')}
score {colorize("- show the scores of any two names, addresses, identifiers, or combination thereof.", 'dim')}
set {colorize("- various settings affecting how entities are displayed.", 'dim')}
{colorize('Senzing Knowledge Center:', 'dim')} {colorize('https://senzing.zendesk.com/hc/en-us', 'highlight2, underline')}
{colorize('Senzing Support Request:', 'dim')} {colorize('https://senzing.zendesk.com/hc/en-us/requests/new', 'highlight2, underline')}
'''))
else:
cmd.Cmd.do_help(self, help_topic)
# ---------------------------
def help_knowledgeCenter(self):
print(f"\nSenzing Knowledge Center: {colorize('https://senzing.zendesk.com/hc/en-us', 'highlight2, underline')}\n")
# ---------------------------
def help_support(self):
print(f"\nSenzing Support Request: {colorize('https://senzing.zendesk.com/hc/en-us/requests/new', 'highlight2, underline')}\n")
# ---------------------------
def histCheck(self):
self.histFileName = None
self.histFileError = None
self.histAvail = False
if not self.histDisable:
if readline:
tmpHist = '.' + os.path.basename(sys.argv[0].lower().replace('.py', '_history'))
self.histFileName = os.path.join(os.path.expanduser('~'), tmpHist)
# Try and open history in users home first for longevity
try:
open(self.histFileName, 'a').close()
except IOError as e:
self.histFileError = f'{e} - Couldn\'t use home, trying /tmp/...'
# Can't use users home, try using /tmp/ for history useful at least in the session
if self.histFileError:
self.histFileName = f'/tmp/{tmpHist}'
try:
open(self.histFileName, 'a').close()
except IOError as e:
self.histFileError = f'{e} - User home dir and /tmp/ failed!'
return
hist_size = 2000
readline.read_history_file(self.histFileName)
readline.set_history_length(hist_size)
atexit.register(readline.set_history_length, hist_size)
atexit.register(readline.write_history_file, self.histFileName)
self.histFileName = self.histFileName
self.histFileError = None
self.histAvail = True
# ---------------------------
def do_history(self, arg):
if self.histAvail:
print()
for i in range(readline.get_current_history_length()):
print(readline.get_history_item(i + 1))
print()
else:
print_message("History isn\'t available in this session", 'warning')
# ---------------------------
def do_shell(self, line):
'''\nRun OS shell commands: !<command>\n'''
if line:
output = os.popen(line).read()
print(f"\n{output}\n")
# ---------------------------
def help_set(self):
print(textwrap.dedent(f'''\
{colorize('Syntax:', 'highlight2')}
set <setting> <value>
{colorize('settings:', 'highlight2')} '''))
print(colorize(f" {'setting':<23} {'[possible values]':<22} {'current':<13} {'description'}", 'dim'))
for setting_data in self.configurable_settings_list:
current_value = colorize(self.current_settings[setting_data['setting']], 'bold')
print(f" {setting_data['setting']:<23} {'[' + ', '.join(setting_data['values']) + ']':<22} {current_value:<22} {colorize(setting_data['description'], 'dim')}")
print()
# ---------------------------
def complete_set(self, text, line, begidx, endidx):
before_arg = line.rfind(" ", 0, begidx)
fixed = line[before_arg + 1:begidx] # fixed portion of the arg
arg = line[before_arg + 1:endidx]
possibles = []
spaces = line.count(' ')
if spaces <= 1:
possibles = [x['setting'] for x in self.configurable_settings_list]
elif spaces == 2:
setting = line.split()[1]
for setting_data in self.configurable_settings_list:
if setting_data['setting'] == setting:
possibles = setting_data['values']
return [i for i in possibles if i.lower().startswith(arg.lower())]
# ---------------------------
def do_set(self, arg):
if not arg:
self.help_set()
return
settings_dict = {}
for setting_data in self.configurable_settings_list:
settings_dict[setting_data['setting']] = setting_data['values']
if settings_dict:
arg_list = arg.split()
if len(arg_list) != 2 or (arg_list[0] not in settings_dict) or (arg_list[1] not in settings_dict[arg_list[0]]):
print_message('Invalid setting', 'error')
return
self.current_settings[arg_list[0]] = arg_list[1]
if arg_list[0] == 'color_scheme':
Colors.set_theme(arg_list[1])
# ---------------------------
def do_version(self, arg):
print(f"\nSenzing api version is: {api_version['BUILD_VERSION']}\n")
# ---------------------------
def help_load(self):
print(textwrap.dedent(f'''\
{colorize('Syntax:', 'highlight2')}
load <snapshotFile.json> {colorize('loads a snapshot file for review', 'dim')}
load <auditFile.json> {colorize('loads an audit file for review', 'dim')}
'''))
# ---------------------------
def do_load(self, arg):
statpackFileName = arg
if not os.path.exists(statpackFileName):
print_message('File not found!', 'error')
return
try:
jsonData = json.load(open(statpackFileName, encoding='utf-8'))
except ValueError as err:
print_message(err, 'error')
return
if 'SOURCE' in jsonData and jsonData['SOURCE'] in ('G2Snapshot'): # 'pocSnapshot',
self.current_settings['snapshotFile'] = statpackFileName
self.snapshotFile = statpackFileName
self.snapshotData = jsonData
print_message(f"sucessfully loaded {statpackFileName}", 'info')
elif 'SOURCE' in jsonData and jsonData['SOURCE'] in ('G2Audit'): # 'pocAudit',
self.current_settings['auditFile'] = statpackFileName
self.auditFile = statpackFileName
self.auditData = jsonData
print_message(f"sucessfully loaded {statpackFileName}", 'info')
else:
print_message('Invalid G2Explorer statistics file', 'error')
# ---------------------------
def complete_load(self, text, line, begidx, endidx):
before_arg = line.rfind(" ", 0, begidx)
if before_arg == -1:
return # arg not found
fixed = line[before_arg + 1:begidx] # fixed portion of the arg
arg = line[before_arg + 1:endidx]
pattern = arg + '*'
completions = []
for path in glob.glob(pattern):
path = _append_slash_if_dir(path)
completions.append(path.replace(fixed, "", 1))
return completions
# ---------------------------
def help_quickLook(self):
print('\nDisplays current data source stats without a snapshot\n')
# ---------------------------
def do_quickLook(self, arg):
try:
g2_diagnostic_module = G2Diagnostic()
g2_diagnostic_module.init('pyG2Diagnostic', iniParams, False)
response = bytearray()
g2_diagnostic_module.getDataSourceCounts(response)
response = response.decode() if response else ''
g2_diagnostic_module.destroy()
except G2Exception as err:
print_message(err, 'error')
return
jsonResponse = json.loads(response)
tblTitle = 'Data source counts'
tblColumns = []
tblColumns.append({'name': 'id', 'width': 5, 'align': 'center'})
tblColumns.append({'name': 'DataSource', 'width': 30, 'align': 'left'})
tblColumns.append({'name': 'ActualRecordCount', 'width': 20, 'align': 'right'})
tblColumns.append({'name': 'DistinctRecordCount', 'width': 20, 'align': 'right'})
tblRows = []
actual_count = distinct_count = 0
for row in jsonResponse:
tblRow = []
tblRow.append(colorize(row['DSRC_ID'], 'row_title'))
tblRow.append(colorize_dsrc(row['DSRC_CODE']))
tblRow.append("{:,}".format(row['DSRC_RECORD_COUNT']))
tblRow.append("{:,}".format(row['OBS_ENT_COUNT']))
tblRows.append(tblRow)
actual_count += row['DSRC_RECORD_COUNT']
distinct_count += row['OBS_ENT_COUNT']
tblRows.append(['', colorize(' Totals', 'row_title'), colorize("{:,}".format(actual_count), 'row_title'), colorize("{:,}".format(distinct_count), 'row_title')])
self.renderTable(tblTitle, tblColumns, tblRows)
# ---------------------------
def move_pointer(self, reply, current_item, max_items):
''' moves the sample record pointer for all reports '''
if reply.upper().startswith('P'): # previous
if current_item == 0:
input('\nNo prior records, press enter to continue')
else:
return current_item - 1
elif reply.upper().startswith('N'): # next
if current_item == max_items - 1:
input('\nno more records, press enter to continue')
else:
return current_item + 1
elif reply.upper().startswith('G'): # goto
reply = reply[1:]
if not reply:
reply = input('\nSample item number to go to? ')
if reply:
removeFromHistory()
if reply:
if reply.isnumeric() and int(reply) > 0 and int(reply) <= max_items:
return int(reply) - 1
else:
print_message('Invalid sample item number for this sample set!', 'warning')
return current_item
# ---------------------------
def export_report_sample(self, reply, currentRecords, fileName):
if 'TO ' in reply.upper():
fileName = reply[reply.upper().find('TO') + 2:].strip()
if fileName:
self.do_export(','.join(currentRecords) + ' to ' + fileName)
# ---------------------------
def help_auditSummary(self):
print(textwrap.dedent(f'''\
Displays audit statistics and examples.
{colorize('Syntax:', 'highlight2')}
auditSummary {colorize('with no parameters displays the overall stats', 'dim')}
auditSummary merge {colorize('shows a list of merge sub-categories', 'dim')}
auditSummary merge 1 {colorize('shows examples of merges in sub-category 1', 'dim')}
auditSummary split {colorize('shows a list of split sub-categories', 'dim')}
auditSummary split 1 {colorize('shows examples of splits in sub-category 1', 'dim')}
auditSummary save to <filename.csv> {colorize('saves the entire audit report to a csv file', 'dim')}
'''))
# ---------------------------
def complete_auditSummary(self, text, line, begidx, endidx):
before_arg = line.rfind(" ", 0, begidx)
fixed = line[before_arg + 1:begidx] # fixed portion of the arg
arg = line[before_arg + 1:endidx]
spaces = line.count(' ')
if spaces <= 1:
possibles = []
if self.auditData:
for category in self.auditData['AUDIT']:
possibles.append(category)
else:
possibles = []
return [i for i in possibles if i.lower().startswith(arg.lower())]
# ---------------------------
def do_auditSummary(self, arg):
if not self.auditData or 'AUDIT' not in self.auditData:
print_message('Please load a json file created with G2Audit.py to use this command', 'warning')
return
elif not self.auditData['ENTITY'].get('PRIOR_COUNT'):
print_message('Prior version audit file detected. Please review with the prior version or re-create for this one.', 'warning')
return
categoryColors = {}
categoryColors['MERGE'] = 'good'
categoryColors['SPLIT'] = 'bad'
categoryColors['SPLIT+MERGE'] = 'fg_red,bg_green'
categoryColors['unknown'] = 'bg_red,fg_white'
# display the summary if no arguments
if not arg:
auditCategories = []
categoryOrder = {'MERGE': 0, 'SPLIT': 1, 'SPLIT+MERGE': 2}
for category in sorted(self.auditData['AUDIT'].keys(), key=lambda x: categoryOrder[x] if x in categoryOrder else 9):
categoryColor = categoryColors[category] if category in categoryColors else categoryColors['unknown']
categoryData = [colorize(category, categoryColor), colorize(fmtStatistic(self.auditData['AUDIT'][category]['COUNT']), 'bold')]
auditCategories.append(categoryData)
while len(auditCategories) < 3:
auditCategories.append(['', 0])
# show records or pairs
if self.current_settings['audit_measure'] == 'pairwise':
audit_measure = 'PAIRS'
audit_header = 'Pairs'
else:
audit_measure = 'RECORDS'
audit_header = 'Matches'
tblTitle = 'Audit Summary from %s' % self.auditFile
tblColumns = []
tblColumns.append({'name': 'Statistic1', 'width': 25, 'align': 'left'})
tblColumns.append({'name': 'Entities', 'width': 25, 'align': 'right'})
tblColumns.append({'name': audit_header, 'width': 25, 'align': 'right'})
tblColumns.append({'name': colorize('-', 'invisible'), 'width': 5, 'align': 'center'})
tblColumns.append({'name': 'Statistic2', 'width': 25, 'align': 'left'})
tblColumns.append({'name': 'Accuracy', 'width': 25, 'align': 'right'})
tblRows = []
row = []
row.append(colorize('Prior Count', 'highlight2'))
row.append(fmtStatistic(self.auditData['ENTITY'].get('PRIOR_COUNT', -1)))
row.append(fmtStatistic(self.auditData[audit_measure].get('PRIOR_COUNT', -1)))
row.append('')
row.append(colorize('Same Positives', 'highlight2'))
row.append(colorize(fmtStatistic(self.auditData[audit_measure]['SAME_POSITIVE']), None))
tblRows.append(row)
row = []
row.append(colorize('Newer Count', 'highlight2'))
row.append(fmtStatistic(self.auditData['ENTITY'].get('NEWER_COUNT', -1)))
row.append(fmtStatistic(self.auditData[audit_measure].get('NEWER_COUNT', -1)))
row.append('')
row.append(colorize('New Positives', categoryColors['MERGE']))
row.append(colorize(fmtStatistic(self.auditData[audit_measure]['NEW_POSITIVE']), None))
tblRows.append(row)
row = []