forked from J535D165/FEBRL-fork-v0.4.2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
guiFebrl.py
executable file
·10470 lines (8586 loc) · 428 KB
/
guiFebrl.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 python
# =============================================================================
# AUSTRALIAN NATIONAL UNIVERSITY OPEN SOURCE LICENSE (ANUOS LICENSE)
# VERSION 1.3
#
# The contents of this file are subject to the ANUOS License Version 1.3
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at:
#
# https://sourceforge.net/projects/febrl/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
# the License for the specific language governing rights and limitations
# under the License.
#
# The Original Software is: "guiFebrl.py"
#
# The Initial Developer of the Original Software is:
# Dr Peter Christen (Research School of Computer Science, The Australian
# National University)
#
# Copyright (C) 2002 - 2011 the Australian National University and
# others. All Rights Reserved.
#
# Contributors:
#
# Alternatively, the contents of this file may be used under the terms
# of the GNU General Public License Version 2 or later (the "GPL"), in
# which case the provisions of the GPL are applicable instead of those
# above. The GPL is available at the following URL: http://www.gnu.org/
# If you wish to allow use of your version of this file only under the
# terms of the GPL, and not to allow others to use your version of this
# file under the terms of the ANUOS License, indicate your decision by
# deleting the provisions above and replace them with the notice and
# other provisions required by the GPL. If you do not delete the
# provisions above, a recipient may use your version of this file under
# the terms of any one of the ANUOS License or the GPL.
# =============================================================================
#
# Freely extensible biomedical record linkage (Febrl) - Version 0.4.2
#
# See: http://datamining.anu.edu.au/linkage.html
#
# =============================================================================
#!/usr/bin/env python
# =============================================================================
# Define some constants
#
FEBRL_GLADE_FILE = "gui/febrl.glade" # Name of Febrl GUI Glade file
NUM_DATA_ROWS = 15 # Number of rows from data set(s) to show in Data page
# =============================================================================
# Import necessary modules (Python standard modules first, then Febrl modules)
import csv
import gzip
import logging
import math
import os
import sys
import time
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
FEBRL_DIR = sys.path[0] # Get the directory where Febrl is located
print 'Febrl directory: %s' % (FEBRL_DIR)
# May have to include non system wide site-packages
#
sys.path = ['/home/christen/lib/python2.5/site-packages/']+sys.path
import auxiliary
import classification
import comparison
import dataset
import encode
import indexing
import lookup
import measurements
import mymath
import output
import simplehmm
import stringcmp
import standardisation
# Adjust full file name where Glade file is - - - - - - - - - - - - - - - - - -
#
FEBRL_GLADE_FILE = FEBRL_DIR+os.sep+FEBRL_GLADE_FILE
#sys.path.append("/home/christen/lib/python2.5/site-packages")
#sys.path.append(FEBRL_DIR) # Make sure Febrl modules can be imported
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Import graphics library for Evaluate page
try:
import matplotlib
matplotlib.use('GTK')
import matplotlib.figure
import matplotlib.backends.backend_gtk
imp_matplot = True
except:
imp_matplot = False
logging.warn('Matplotlib module not installed.')
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Import GTK related modules, make sure correct version is imported
try:
import pygtk
pygtk.require("2.0")
except:
pass
try:
import gtk
import gtk.glade
import pango
except:
print "GTK and PyGTK not installed."
sys.exit(1)
# Set the logging level to warnings - - - - - - - - - - - - - - - - - - - - - -
#
my_logger = logging.getLogger() # New logger at root level
my_logger.setLevel(logging.WARNING)
# =============================================================================
# Main class for the main GUI window, handles all events from the GUI
class MainFebrlWindow:
def __init__(self):
# Initialise all Febrl project related variables - - - - - - - - - - - - -
#
self.initFebrlProjectVariables()
#--------------------------------------------------------------------------
# Initialise GUI related variables
# Glade file name and top level window names
#
self.glade_file_name = FEBRL_GLADE_FILE
self.main_window_name = 'febrl_main_window'
self.about_dialog_name = 'febrl_about_dialog'
self.license_dialog_name = 'febrl_license_dialog'
self.new_project_dialog_name = 'febrl_new_project_dialog'
self.save_file_dialog_name = 'febrl_save_file_dialog'
# self.current_folder = None # Currently selected folder
# Current page and page names in main notebook
#
self.main_notebook_curr_page = 0 # Set to Data page at beginning
self.main_notebook_page_names = ['Data', 'Explore', 'Standardise',
'Index', 'Compare', 'Classify', 'Run',
'Evaluate', 'Review', 'Log']
# A dictionary, for each notebook page flag if it is active or not
#
self.main_notebook_page_active_dict = {'Data':True, 'Explore':False,
'Standardise':False,
'Index':False,
'Compare':False,
'Classify':False, 'Run':False,
'Evaluate':False, 'Review':False,
'Log':True}
# Mappings for data set types into Data page notebook page numbers
#
self.data_set_type_page_dict = {'CSV':0, 'COL':1, 'TAB':2, 'SQL':3}
# Last value of the save file dialog (file name)
#
self.save_dialog_file_name = None
# Load the Glade file and initialise widgets tree - - - - - - - - - - - - -
#
self.mainTree = gtk.glade.XML(self.glade_file_name, self.main_window_name)
self.mainWin = self.mainTree.get_widget(self.main_window_name)
self.setWindowTitle() # Set window title to project name
self.setProjectTypeDataButtons() # Set the project type buttons
# Set up the log buffer - - - - - - - - - - - - - - - - - - - - - - - - - -
#
self.log_page_textview = self.mainTree.get_widget('log_text_view')
# Set font to fixed width
#
self.log_page_textview.modify_font(pango.FontDescription("courier 10"))
self.log_page_buffer = self.log_page_textview.get_buffer()
# Build dictionary of signals - - - - - - - - - - - - - - - - - - - - - - -
#
dict = {'main_window_quit':self.quitMain,
'main_window_execute':self.executeMain,
'main_window_new':self.newMain,
'main_window_save':self.saveMain,
'project_type_toggle':self.projectTypeButtonToggle,
'main_notebook_switch_page':self.mainNotebookSwitchPage,
'online_help_activate':self.activateOnlineHelp,
'about_activate':self.activateAbout,
'license_activate':self.activateLicense,
# Data page signals
'data_set_type_toggle':self.dataSetTypeButtonToggle,
'data_set_header_line_toggle':self.dataSetTypeHeaderLineToggle,
'data_set_strip_fields_toggle':self.dataSetTypeStripFieldsToggle,
'file_name_changed':self.dataFileSelect,
'miss_val_activate':self.dataSetMissValueActivate,
'delimiter_activate':self.dataSetDelimiterActivate,
# Explore page signals
# Indexing page signals
'index_method_changed':self.indexChangeMethod,
# Classification page signals
'classifier_method_changed':self.classifierChangeMethod,
# Output/run page signals
'clicked_file_name_button':self.runClickedFileNameButton,
'save_file_button_toggle':self.runSaveFileButtonToggle,
}
self.mainTree.signal_autoconnect(dict)
# Special handling of click on close window (x) - - - - - - - - - - - - - -
#
self.mainWin.connect('delete-event', self.closeMainWindow)
self.displayCurrentNotebookPage() # Diplay the current page
# ===========================================================================
# Method to initialise all Febrl project related variables
# (default is a deduplication project)
#
def initFebrlProjectVariables(self, project_type='Deduplicate'):
if (project_type not in ['Standardise', 'Deduplicate', 'Link', 'Geocode']):
raise Exception, 'Illegal project type provided: %s' % (project_type)
self.project_type = project_type
self.project_name = None # Will be set by New, Load or Save project
# A dictionary with flags for modified components corresponding to code
# (set to False initially as no code has been generated)
#
self.modified = {'data':False, 'standardise':False, 'indexing':False,
'comparison':False, 'classification':False,
'output':False} # Set to True when values change
# A dictionary with flags used when running all code to determine if data
# set have to be re-initialised or not, and if weight vectors have to be
# re-calculated or not.
#
self.re_run = {'data_init':False, 'w_vec_generate':False}
# A dictionary with the generated python codes - - - - - - - - - - - - - -
#
self.febrl_code = {'data':None, 'standardise':None, 'indexing':None,
'comparison':None, 'classification':None, 'output':None}
# A dictionary with the available string comparison methods (names and
# corresponding stringcmp methods)
#
self.stringcmp_dict = {'Jaro':'jaro', 'Winkler':'winkler',
'Q-Gram':'qgram', 'Pos-Q-Gram':'posqgram',
'S-Gram':'sgram', 'Edit-Dist':'editdist',
'Mod-Edit-Dist':'mod_editdist',
'Bag-Dist':'bagdist','Smith-Water-Dist':'swdist',
'Syll-Align-Dist':'syllaligndist',
'Seq-Match':'seqmatch', 'Long-Common-Seq':'lcs',
'Onto-LCS':'ontolcs', 'Editex':'editex',
'Perm-Winkler':'permwinkler',
'Sort-Winkler':'sortwinkler'}
# A dictionary with the available string encoding methods (names and
# corresponding encoding methods)
#
self.stringencode_dict = {'None':'', 'Soundex':'soundex',
'Mod-Soundex':'mod_soundex', 'Phonex':'phonex',
'NYSIIS':'nysiis',
'Double-Metaphone':'dmetaphone',
'Phonix':'phonix',
'Fuzzy-Soundex':'fuzzysoundex',
'Substring':'get_substring'}
# Data (page) related variables -------------------------------------------
#
if (self.project_type == 'Link'): # Initialise data set(s) as of type CSV
self.data_set_type_list = ['CSV', 'CSV']
else:
self.data_set_type_list = ['CSV', None]
# A list, one entry per data set (both entries only used for a linkage),
# that will contain default values for data set related variables once they
# have been initialised (one dictionary per data set)
#
self.data_set_default_values = {'header_line':True, 'strip_fields':True,
'header_data':None, 'file_name':None,
'file_data':None, 'miss_val':[''],
'delimiter':',', 'field_names':None,
'rec_id_field':'__rec_id'}
default_vals = self.data_set_default_values
# The dictionaries (one per data set) which hold the actual values
#
self.data_set_info_list = [{'header_line':default_vals['header_line'],
'strip_fields':default_vals['strip_fields'],
'header_data':default_vals['header_data'],
'file_name':default_vals['file_name'],
'file_data':default_vals['file_data'],
'miss_val':default_vals['miss_val'],
'delimiter':default_vals['delimiter'],
'field_names':default_vals['field_names'],
'rec_id_field':default_vals['rec_id_field']},
{'header_line':default_vals['header_line'],
'strip_fields':default_vals['strip_fields'],
'header_data':default_vals['header_data'],
'file_name':default_vals['file_name'],
'file_data':default_vals['file_data'],
'miss_val':default_vals['miss_val'],
'delimiter':default_vals['delimiter'],
'field_names':default_vals['field_names'],
'rec_id_field':default_vals['rec_id_field']}]
self.list_data_store = [None, None]
# The number of rows (records) to show from data set(s)
#
self.num_data_rows = NUM_DATA_ROWS*2 # Double for deduplication
# Dictionary with file filter data (data set type, name for widget, filter)
self.file_filters = {'CSV':['CSV files',('*.csv', '*.CSV', '*.csv.gz',
'*.CSV.GZ')],
'COL':['COL files',('*.col', '*.COL', '*.col.gz',
'*.COL.GZ')],
'TAB':['TAB files',('*.tab', '*.TAB', '*.tab.gz',
'*.TAB.GZ')],
'TXT':['Text files',('*.csv', '*.CSV', '*.csv.gz',
'*.CSV.GZ', '*.col', '*.COL',
'*.col.gz', '*.COL.GZ', '*.tab',
'*.TAB', '*.tab.gz', '*.TAB.GZ',
'*.txt', '*.TXT', '*.txt.gz',
'*.TXT.GZ')],
'ALL':['All files', ('*',)]}
# Standardisation (page) related variables --------------------------------
# A dictionary with component standardiser types names as keys and their
# corresponding output fields as lists
#
self.comp_std_out_fields = {'Date':['day','month','year'],
'Phon':['country_code', 'country_name',
'area_code', 'number', 'extension'],
'Name':['title', 'gender_guess',
'given_name', 'alt_given_name',
'surname', 'alt_surname'],
'Addr':['building_name', 'post_address_type',
'post_address_number',
'lot_number_prefix', 'lot_number',
'lot_number_suffix',
'flat_number_prefix',
'flat_number', 'flat_number_suffix',
'flat_type', 'level_number_prefix',
'level_number', 'level_number_suffix',
'level_type', 'number_first_prefix',
'number_first', 'number_first_suffix',
'number_last_prefix', 'number_last',
'number_last_suffix', 'street_name',
'street_suffix', 'street_type',
'locality_name', 'postcode',
'state_abbrev', 'country']}
self.comp_std_list = []
# Date parsing formats for data standardiser
#
self.parse_format_str = '%d %m %Y, %d %B %Y, %d %b %Y, %m %d %Y, ' + \
'%B %d %Y, %b %d %Y, %Y %m %d, %Y %B %d, ' + \
'%Y %b %d, %d %m %y, %d %B %y, %d %b %y, ' + \
'%y %m %d, %y %B %d, %y %b %d, %m %d %y, ' + \
'%B %d %y, %b %d %y'
# Indexing (page) related variables ---------------------------------------
# A list with the names of the possible index method types
#
self.index_names = ['FullIndex', 'BlockingIndex', 'SortingIndex',
'QGramIndex', 'CanopyIndex', 'StringMapIndex',
'SuffixArrayIndex']
# The following dictionary will include the parameters of the selected
# indxing method as keys and their values as values. The name will be one
# of the above names.
# (default values for general parameters)
#
self.index_method = {'name':None, 'index_sep_str':'', 'skip_missing':True}
# The following list will contain the index definitions, with each being a
# dictionary with the corresponding index definition details
#
self.index_def = []
self.index_num = 0 # Number of indices defined
# Comparison (page) related variables -------------------------------------
# A list with the names of the possible field comparison method types
#
self.field_comp_dict = {'Age':'FieldComparatorAge',
'Bag-Dist':'FieldComparatorBagDist',
'Compression':'FieldComparatorCompress',
'Dam-Le-Edit-Dist':'FieldComparatorDaLeDist',
'Edit-Dist':'FieldComparatorEditDist',
'Editex':'FieldComparatorEditex',
'Jaro':'FieldComparatorJaro',
'Long-Common-Seq':'FieldComparatorLCS',
'Onto-LCS':'FieldComparatorOntoLCS',
'Pos-Q-Gram':'FieldComparatorPosQGram',
'Q-Gram':'FieldComparatorQGram',
'S-Gram':'FieldComparatorSGram',
'Smith-Water-Dist':'FieldComparatorSWDist',
'Seq-Match':'FieldComparatorSeqMatch',
'Syll-Align-Dist':'FieldComparatorSyllAlDist',
'Winkler':'FieldComparatorWinkler',
'Date':'FieldComparatorDate',
### TODO 'Distance':'FieldComparatorDistance',
'Str-Encode':'FieldComparatorEncodeString',
'Str-Exact':'FieldComparatorExactString',
'Str-Contains':'FieldComparatorContainsString',
'Key-Diff':'FieldComparatorKeyDiff',
'Num-Abs':'FieldComparatorNumericAbs',
'Num-Perc':'FieldComparatorNumericPerc',
'Time':'FieldComparatorTime',
'Str-Truncate':'FieldComparatorTruncateString',
'Token-Set':'FieldComparatorTokenSet'}
# The following list will contain the field comparisons, with each being a
# dictionary with the corresponding details
#
self.field_comp_list = []
# Classification (page) related variables ---------------------------------
# A list with the names of the possible classification method types
#
self.classifier_names = ['FellegiSunter', 'OptimalThreshold', 'KMeans',
'FarthestFirst', 'SuppVecMachine', 'TwoStep']
# The following dictionary will include the parameters of the selected
# classification method as keys and their values as values. The name will
# be one of the above names.
# (default values for general parameters)
#
self.classifier_method = {'name':None}
# Output/Run page related variables ---------------------------------------
#
self.output_dict = {'w_vec_file':(False, '(None)'),
'histo_file':(False, '(None)', '1.0'),
'm_status_file':(False, '(None)'),
'm_datasets':(False, ('(None)', 'match_id'),
('(None)', 'match_id')),
'progress_perc':'10',
'length_filter_perc':None,
'cut_off_threshold':None,
# Following variables are for a standardisation
'std_out_file':'(None)',
'pass_field_list':[]}
self.w_vec_dict = None
self.class_w_vec_dict = None
# Evaluation (page) related variables -------------------------------------
#
self.result_sets = None # Will become a list with three sets (matches,
# non-matches, and possible matches)
# Results will be added into here
self.evaluation_dict = {'available':False} # No results available yet
# Log (page) related variables --------------------------------------------
#
self.log_page_text = '# Febrl log.\n'
# ===========================================================================
# Methods that handle GUI events
# ===========================================================================
# ---------------------------------------------------------------------------
# Set the project type data buttons
#
def setProjectTypeDataButtons(self):
# Get widgets of the four radion buttons
#
standard_project_widget = self.mainTree.get_widget('standard_radio_button')
dedup_project_widget = self.mainTree.get_widget('dedup_radio_button')
link_project_widget = self.mainTree.get_widget('link_radio_button')
geocode_project_widget = self.mainTree.get_widget('geocode_radio_button')
standard_project_widget.set_active(False) # De-activate all four first
dedup_project_widget.set_active(False)
link_project_widget.set_active(False)
geocode_project_widget.set_active(False)
if (self.project_type == 'Standardise'): # Now activate the correct one
standard_project_widget.set_active(True)
elif (self.project_type == 'Deduplicate'):
dedup_project_widget.set_active(True)
elif (self.project_type == 'Link'):
link_project_widget.set_active(True)
elif (self.project_type == 'Geocode'):
geocode_project_widget.set_active(True)
else:
raise Exception, 'Illegal project type: %s' % (self.project_type)
# ---------------------------------------------------------------------------
# Handle toggle of the project type button
#
def projectTypeButtonToggle(self, widget):
if (widget.get_active() != True): # Do nothing if not the active widget
return
widget_name = widget.get_name()
if (widget_name == 'standard_radio_button'):
self.project_type = 'Standardise'
elif (widget_name == 'dedup_radio_button'):
self.project_type = 'Deduplicate'
elif (widget_name == 'link_radio_button'):
self.project_type = 'Link'
elif (widget_name == 'geocode_radio_button'):
self.project_type = 'Geocode'
else:
raise Exception, 'Illegal project type widget name: %s' % (widget_name)
print
print ' *** Changed project type to:', self.project_type,'***'
# For different project types set settings and visible pages - - - - - - -
#
if (self.project_type in ['Standardise','Deduplicate']):
self.num_data_rows = NUM_DATA_ROWS*2 # Only one data set
else: # Linkage
self.num_data_rows = NUM_DATA_ROWS # Two data sets
if (self.data_set_type_list[1] == None): # If not initialised set to
self.data_set_type_list[1] = 'CSV' # default type
# Make all pages invisible except Data and Log - - - - - - - - - - - - - -
#
for page_name in ['Explore', 'Standardise','Index', 'Compare', 'Classify',
'Run', 'Evaluate', 'Review']:
self.main_notebook_page_active_dict[page_name] = False
self.modified['data'] = True # Project type has changed
self.index_def = [] # Delete all previous index definitions
self.index_num = 0
self.field_comp_list = [] # Delete previous field comparison functions
self.setWindowTitle()
# If current page is already Data only display it, otherwise trigger switch
#
if (self.main_notebook_curr_page == 0):
self.displayCurrentNotebookPage()
else: # Set new current page to Data
notebook_widget = self.mainTree.get_widget('main_notebook')
notebook_widget.set_current_page(0)
gtk.main_iteration(False) # Do a main iteration to update notebook
gtk.main_iteration(False) # Do a main iteration to update notebook
# This will trigger a call to the method mainNotebookSwitchPage()
# ---------------------------------------------------------------------------
# Handle switch of main notebook page
#
def mainNotebookSwitchPage(self, widget, dummy, curr_page):
# PyGTK FAQ 17.1: Needs these parameters!
print
print '*** Main notebook page switch ***'
notebook_widget = self.mainTree.get_widget('main_notebook')
prev_page = self.main_notebook_curr_page # Get the previous page number
prev_page2 = notebook_widget.get_current_page() # Current before switch
# Special case where pages are 'hidden' results in a switch-page' signal
# when an active page is hidden. This happens when the project type is
# changed. As a consequence, the prev_page and prev_page2 values will be
# different.
#
if (prev_page == prev_page2):
prev_page_name = self.main_notebook_page_names[prev_page]
curr_page_name = self.main_notebook_page_names[curr_page]
curr_page_active = self.main_notebook_page_active_dict[curr_page_name]
if (curr_page_active == True):
self.main_notebook_curr_page = curr_page
print 'Switched from page %s to page %s' % \
(prev_page_name, curr_page_name)
print ' Current page number:', curr_page
else:
print ' ************ else:', curr_page_name
self.displayCurrentNotebookPage() # Re-display current notebook page
else: # Must be a page is being hidden, do nothing
print ' Stored current page: ', self.main_notebook_curr_page
print ' Widget.get_curr_page:', prev_page2
print ' Received curr page: ', curr_page
# ---------------------------------------------------------------------------
# Display the current main notebook page
#
def displayCurrentNotebookPage(self):
# Hide all non-active pages first
#
for (page_name, active) in self.main_notebook_page_active_dict.items():
page_box_widget = self.mainTree.get_widget(page_name.lower()+'_page_box')
if (active == True):
page_box_widget.show()
else:
page_box_widget.hide()
curr_page = self.main_notebook_curr_page
curr_page_name = self.main_notebook_page_names[curr_page]
print 'Display current page:', curr_page, curr_page_name
# If switched to Log or Evaluate page disable the Execute button - - - - -
#
execute_button_widget = self.mainTree.get_widget('execute_button')
if (curr_page_name in ['Evaluate','Log']):
execute_button_widget.set_sensitive(False)
else:
execute_button_widget.set_sensitive(True)
# Handle switches to different pages - - - - - - - - - - - - - - - - - - -
#
if (curr_page_name == 'Data'):
self.dataView()
elif(curr_page_name == 'Explore'):
self.exploreView()
elif(curr_page_name == 'Standardise'):
self.standardView()
elif(curr_page_name == 'Index'):
self.indexView()
elif(curr_page_name == 'Compare'):
self.compareView()
elif(curr_page_name == 'Classify'):
self.classifyView()
elif(curr_page_name == 'Run'):
self.runView()
elif(curr_page_name == 'Evaluate'):
self.evaluateView()
elif(curr_page_name == 'Review'):
self.reviewView()
elif(curr_page_name == 'Log'):
self.logView()
else:
raise Exception, 'Illegal notebook page name: %s' % (curr_page_name)
# ---------------------------------------------------------------------------
# Handle clicks on Execute button
#
def executeMain(self, widget):
notebook_widget = self.mainTree.get_widget('main_notebook')
curr_page_name =self.main_notebook_page_names[self.main_notebook_curr_page]
# Handle executes on different pages - - - - - - - - - - - - - - - - -
#
if (curr_page_name == 'Data'):
self.dataExecute()
elif(curr_page_name == 'Explore'):
self.exploreExecute()
elif(curr_page_name == 'Standardise'):
self.standardExecute()
elif(curr_page_name == 'Index'):
self.indexExecute()
elif(curr_page_name == 'Compare'):
self.compareExecute()
elif(curr_page_name == 'Classify'):
self.classifyExecute()
elif(curr_page_name == 'Run'):
self.runExecute()
elif(curr_page_name == 'Evaluate'):
self.evaluateExecute()
elif(curr_page_name == 'Review'):
self.reviewExecute()
else:
raise Exception
# ---------------------------------------------------------------------------
# Handle clicks on Quit button or activate of Quit menu
#
def quitMain(self, widget):
print 'Clicked Quit or activated Quit menu'
# Check if project is modified or not, if not, ask for save
#
if (sum(self.modified.values()) > 0):
do_save = self.messageDialog('Current project is not saved!\n' + \
'Do you want to save it?', 'c_question')
if (do_save == True):
self.saveMain(widget)
if (sum(self.modified.values()) > 0): # Saving has been canceled
do_save = None # Don't quit
else: # Not modified, so no saving needed
do_save = False # So quit will be performed
if (do_save != None): # If message dialog response was cancel don't quit
gtk.main_quit()
# Handle click on close window (x) - - - - - - - - - - - - - - - - - - - - -
#
def closeMainWindow(self, widget, event):
print 'Clicked close window'
self.quitMain(widget)
return True
# ---------------------------------------------------------------------------
# Handle clicks on New button or activate of New menu
#
def newMain(self, widget):
print 'Clicked New or activated New menu'
# Check if project is modified or not, if not, ask for save
#
if (sum(self.modified.values()) > 0):
do_save = self.messageDialog('Current project is not saved!\n' + \
'Do you want to save it?', 'question')
if (do_save == True):
self.saveMain(widget)
newProjTree = gtk.glade.XML(self.glade_file_name,
self.new_project_dialog_name)
newProjDialog = newProjTree.get_widget(self.new_project_dialog_name)
# Add the standard buttons and their responses
#
newProjDialog.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
newProjDialog.add_button(gtk.STOCK_OK, gtk.RESPONSE_OK)
newProjDialog.show()
response = newProjDialog.run()
# Only get project values if OK was clicked
#
if (response == int(gtk.RESPONSE_OK)):
standard_widget = newProjTree.get_widget('new_standard_button')
dedup_widget = newProjTree.get_widget('new_dedup_button')
link_widget = newProjTree.get_widget('new_link_button')
geocode_widget = newProjTree.get_widget('new_geocode_button')
# Find the active widget
#
if (standard_widget.get_active() == True):
self.project_type = 'Standardise'
elif (dedup_widget.get_active() == True):
self.project_type = 'Deduplicate'
elif (link_widget.get_active() == True):
self.project_type = 'Link'
elif (geocode_widget.get_active() == True):
self.project_type = 'Geocode'
else:
raise Exception, 'No project type activated'
print
print ' *** New project type:', self.project_type,'***'
self.initFebrlProjectVariables(self.project_type)
# Set the corresponding project type button (first de-activate all)
#
standard_proj_widget = self.mainTree.get_widget('standard_radio_button')
dedup_proj_widget = self.mainTree.get_widget('dedup_radio_button')
link_proj_widget = self.mainTree.get_widget('link_radio_button')
geocode_proj_widget = self.mainTree.get_widget('geocode_radio_button')
standard_proj_widget.set_active(False) # De-activate all four first
dedup_proj_widget.set_active(False)
link_proj_widget.set_active(False)
geocode_proj_widget.set_active(False)
if (self.project_type == 'Standardise'): # Now activate the correct one
standard_proj_widget.set_active(True)
elif (self.project_type == 'Deduplicate'):
dedup_proj_widget.set_active(True)
elif (self.project_type == 'Link'):
link_proj_widget.set_active(True)
elif (self.project_type == 'Geocode'):
geocode_proj_widget.set_active(True)
newProjDialog.destroy()
# self.displayCurrentNotebookPage() # Re-display current notebook page
# ---------------------------------------------------------------------------
# Handle clicks on Save button or activate of Save or Save As menu
#
def saveMain(self, widget):
print 'Clicked Save or activated Save or Save As menu, or Execute on' + \
'Output/Run page'
widget_name = widget.get_name()
# Check if a project file name is set, if not activate save file first, or
# if Save as was activated, always ask for a file name
#
if (self.project_name == None) or (widget_name == 'save_as'):
saveFileTree = gtk.glade.XML(self.glade_file_name,
self.save_file_dialog_name)
saveFileDialog = saveFileTree.get_widget(self.save_file_dialog_name)
# if (self.current_folder != None):
# saveFileDialog.set_current_folder(self.current_folder)
# Create a file filter (Python files only)
#
file_filter = gtk.FileFilter() # Add a file filter for python files only
file_filter.set_name('Python files')
file_filter.add_pattern('*.py')
saveFileDialog.add_filter(file_filter)
saveFileDialog.show()
save_file_response = saveFileDialog.run()
self.save_dialog_file_name = saveFileDialog.get_filename()
# self.current_folder = saveFileDialog.get_current_folder()
# print 'current folder:', self.current_folder
saveFileDialog.destroy()
# Only process if 'OK' was clicked, not 'Cancel' - - - - - - - - - - - -
#
if (self.save_dialog_file_name == None):
return
print 'Selected file name in save dialog: %s' % \
(self.save_dialog_file_name)
# Make sure it is a Python file
#
if (self.save_dialog_file_name.endswith('.py') == False):
self.save_dialog_file_name = self.save_dialog_file_name+'.py'
self.project_name = self.save_dialog_file_name
self.setWindowTitle()
# Generate and save code only if a project file name is given - - - - - - -
#
if (self.project_name != None):
# Check if file exists, if so ask if over-writing is OK
#
if (os.access(self.project_name, os.F_OK) == True):
overwrite = self.messageDialog('File "%s" exists. ' % \
(self.project_name) + \
'Do you want to overwrite it?', 'ques')
if (overwrite == False):
return
print 'Generate code and save it into file:', self.project_name
febrl_project_code = self.generateAllCode()
print 'Generated %d lines of code' % (len(febrl_project_code))
try:
f = open(self.project_name, 'w') # Save into a text file
except:
self.messageDialog('Cannot write project file: %s' (self.project_name),
'error')
return
for line in febrl_project_code:
# Replace 'XXXXXXXXXX' with project file name
#
if ('XXXXXXXXXX' in line):
line = line.replace('XXXXXXXXXX',self.project_name.split(os.sep)[-1])
f.write(line + os.linesep)
f.close()
for component in self.modified: # Set all components to False
self.modified[component] = False
self.setWindowTitle()
# ---------------------------------------------------------------------------
# Handle activation of Online Help menu item
#
def activateOnlineHelp(self):
print 'Online help activated - to be implemented...'
# How to open the Web browser and an URL?
# from Rattle:
#on_rattle_menu_activate <- function(action, window)
#{
#browseURL("http://rattle.togaware.com")
#}
# ---------------------------------------------------------------------------
# Handle activation of About menu item
#
def activateAbout(self, widget):
print 'About activated'
self.aboutTree = gtk.glade.XML(self.glade_file_name,
self.about_dialog_name)
self.aboutDialog = self.aboutTree.get_widget(self.about_dialog_name)
self.aboutDialog.show()
self.aboutDialog.run()
self.aboutDialog.destroy()
print 'About finished'
# ---------------------------------------------------------------------------
# Handle activation of License menu item
#
def activateLicense(self, widget):
print 'License activated'
self.licenseTree = gtk.glade.XML(self.glade_file_name,
self.license_dialog_name)
self.licenseDialog = self.licenseTree.get_widget(self.license_dialog_name)
self.licenseDialog.show()
self.licenseDialog.run()
self.licenseDialog.destroy()
print 'License finished'
# ---------------------------------------------------------------------------
# Generate a message dialog for information, warning, error, question or
# cancel_question (c_question).
# - Returns None, except for a question where it returns True (if Yes was
# answered) or False (No was answered), or None (if cancel was clicked).
#
def messageDialog(self, message_str, message_type):
if (message_type[:4] not in ['info','warn','ques','erro','c_qu']):
raise Exception, 'Illegal message type: %s' % (message_type)
gtk_msg_type = {'info':gtk.MESSAGE_INFO,
'warn':gtk.MESSAGE_WARNING,
'ques':gtk.MESSAGE_QUESTION,
'c_qu':gtk.MESSAGE_QUESTION,
'erro':gtk.MESSAGE_ERROR}[message_type[:4]]
# Message dialog buttons depend upon message type
#
gtk_msg_buttons = {'info':gtk.BUTTONS_CLOSE,
'warn':gtk.BUTTONS_CLOSE,
'erro':gtk.BUTTONS_CLOSE,
'c_qu':gtk.BUTTONS_CANCEL,
'ques':gtk.BUTTONS_YES_NO}[message_type[:4]]
msgDialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk_msg_type,