forked from wang0109/Transana
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpreadsheetDataImport.py
More file actions
1063 lines (931 loc) · 55.6 KB
/
Copy pathSpreadsheetDataImport.py
File metadata and controls
1063 lines (931 loc) · 55.6 KB
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
# Copyright (C) 2002-2016 Spurgeon Woods LLC
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
""" This module implements the Spreadsheet Data Import function for Transana """
__author__ = 'David Woods <dwoods@transana.com>'
# Import wxPython
import wx
# Import wxPython's Wizard
import wx.wizard as wiz
# Import Transana's Dialogs
import Dialogs
# Import Transana's Document Object
import Document
# Import Transana's Keyword Object
import KeywordObject
# Import Transana's Library Object
import Library
# Import Transana's Constants
import TransanaConstants
# Import Transana's Exceptions
import TransanaExceptions
# Import Transana's Global Variables
import TransanaGlobal
# import Python's csv module, which reads Comma Separated Values files
import csv
# import Python's datetime module
import datetime
# Import Python's os module
import os
# Import Python's sys module
import sys
class EditBoxFileDropTarget(wx.FileDropTarget):
""" This simple derived class let's the user drop files onto an edit box """
def __init__(self, editbox):
""" Initialize a File Drop Target """
# Initialize the FileDropTarget object
wx.FileDropTarget.__init__(self)
# Make the Edit Box passed in a File Drop Target
self.editbox = editbox
def OnDropFiles(self, x, y, files):
"""Called when a file is dragged onto the edit box."""
# Insert the FIRST file name into the edit box
self.editbox.SetValue(files[0])
class WizPage(wiz.PyWizardPage):
""" Base class for individual wizard pages. Provides:
Title
Back / Forward / Cancel button """
def __init__(self, parent, title):
""" Initialize the Wizard Page """
# Initialize the Previous and Next pointer to None
self.prev = self.next = None
# Remember the parent
self.parent = parent
# Initialize the PyWizardPage object
wiz.PyWizardPage.__init__(self, parent)
# Define a main Sizer for the page
self.sizer = wx.BoxSizer(wx.VERTICAL)
# Display the Page Title
title = wx.StaticText(self, -1, title)
title.SetFont(wx.Font(14, wx.SWISS, wx.NORMAL, wx.BOLD))
self.sizer.Add(title, 0, wx.ALIGN_CENTER | wx.ALL, 5)
self.sizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND|wx.ALL, 5)
# Set the main Sizer
self.SetSizer(self.sizer)
# Identify the Previous and Next buttons so they can be manipulated
self.prevButton = parent.FindWindowById(wx.ID_BACKWARD)
self.nextButton = parent.FindWindowById(wx.ID_FORWARD)
def GetPrev(self):
""" Get Previous Page function """
return self.prev
def SetPrev(self, prev):
""" Set Previous Page function """
self.prev = prev
def GetNext(self):
""" Get Next Page function """
return self.next
def SetNext(self, next):
""" Set Next Page function """
self.next = next
def IsComplete(self):
""" Has this page been completed? Defaults to False, must be over-ridden! """
return False
class GetFileNamePage(WizPage):
""" Get File Name wizard page """
def __init__(self, parent, title):
""" Define the Wizard Page that gets the File to be imported """
# Inherit from WizPage
WizPage.__init__(self, parent, title)
# Add the Source File label
lblSource = wx.StaticText(self, -1, _("Source Data File:"))
self.sizer.Add(lblSource, 0, wx.TOP | wx.LEFT | wx.RIGHT, 10)
# Create the box1 sizer, which will hold the source file and its browse button
box1 = wx.BoxSizer(wx.HORIZONTAL)
# Create the Source File text box
self.txtSrcFileName = wx.TextCtrl(self, -1)
# Make the Source File a File Drop Target
self.txtSrcFileName.SetDropTarget(EditBoxFileDropTarget(self.txtSrcFileName))
# Handle ALL changes to the source filename
self.txtSrcFileName.Bind(wx.EVT_TEXT, self.OnSrcFileNameChange)
# Add the text box to the sizer
box1.Add(self.txtSrcFileName, 1, wx.EXPAND)
# Spacer
box1.Add((4, 0))
# Create the Source File Browse button
self.srcBrowse = wx.Button(self, -1, _("Browse"))
self.srcBrowse.Bind(wx.EVT_BUTTON, self.OnBrowse)
box1.Add(self.srcBrowse, 0, wx.LEFT, 10)
# Add the Source Sizer to the Main Sizer
self.sizer.Add(box1, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 10)
# Add Encoding label
lblEncoding = wx.StaticText(self, -1, _("File Encoding:"))
self.sizer.Add(lblEncoding, 0, wx.TOP | wx.LEFT | wx.RIGHT, 10)
# Add Encoding selection
choices = ["ascii", "big5", "big5hkscs", "cp037", "cp424", "cp437", "cp500", "cp720", "cp737", "cp775", "cp850", "cp852", "cp855", "cp856", "cp857",
"cp858", "cp860", "cp861", "cp862", "cp863", "cp864", "cp865", "cp866", "cp869", "cp874", "cp875", "cp932", "cp949", "cp950", "cp1006",
"cp1026", "cp1140", "cp1250", "cp1251", "cp1252", "cp1253", "cp1254", "cp1255", "cp1256", "cp1257", "cp1258", "euc_jp", "euc_jis_2004",
"euc_jisx0213", "euc_kr", "gb2312", "gbk", "gb18030", "hz", "iso2022_jp", "iso2022_jp_1", "iso2022_jp_2", "iso2022_jp_2004", "iso2022_jp_3",
"iso2022_jp_ext", "iso2022_kr", "latin_1", "iso8859_2", "iso8859_3", "iso8859_4", "iso8859_5", "iso8859_6", "iso8859_7", "iso8859_8",
"iso8859_9", "iso8859_10", "iso8859_13", "iso8859_14", "iso8859_15", "iso8859_16", "johab", "koi8_r", "koi8_u", "mac_cyrillic",
"mac_greek", "mac_iceland", "mac_latin2", "mac_roman", "mac_turkish", "ptcp154", "shift_jis", "shift_jis_2004", "shift_jisx0213",
"utf_32", "utf_32_be", "utf_32_le", "utf_16", "utf_16_be", "utf_16_le", "utf_7", "utf_8", "utf_8_sig"]
self.txtSrcEncoding = wx.Choice(self, -1, choices = choices)
self.txtSrcEncoding.SetStringSelection('cp1252')
self.sizer.Add(self.txtSrcEncoding, 0, wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, 10)
self.sizer.Add((1, 24))
prompt = _("For more information on file formats and encoding, please see the Help page.")
info = wx.StaticText(self, -1, prompt)
font = wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD)
info.SetFont(font)
self.sizer.Add(info, 0, wx.TOP | wx.LEFT | wx.RIGHT, 10)
def IsComplete(self):
""" IsComplete signals whether an EXISTING file has been selected """
return os.path.exists(self.txtSrcFileName.GetValue())
def OnBrowse(self, event):
""" Browse Button event handler """
# Get Transana's File Filter definitions
fileTypesString = _("All supported files (*.csv, *.txt)|*.csv;*.txt|Comma Separated Values files (*.csv)|*.csv|Tab Delimited Text files (*.txt)|*.txt|All files (*.*)|*.*")
# Create a File Open dialog.
fs = wx.FileDialog(self, _('Select a spreadsheet data file:'),
TransanaGlobal.configData.videoPath,
"",
fileTypesString,
wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
# Select "All supported files" as the initial Filter
fs.SetFilterIndex(0)
# Show the dialog and get user response. If OK ...
if fs.ShowModal() == wx.ID_OK:
# ... get the selected file name
self.fileName = fs.GetPath()
# If not OK ...
else:
# ... signal Cancel by return a blank file name
self.fileName = ''
# Destroy the File Dialog
fs.Destroy()
# Add the selected File Name to the File Name text box
self.txtSrcFileName.SetValue(self.fileName)
def OnSrcFileNameChange(self, event):
""" Process changes to the File Name Text Box """
# If we have a valid, existing file ...
if self.IsComplete():
# ... enable the Next button
self.nextButton.Enable(True)
# If we don't have a valid file ...
else:
# ... disable the Next button
self.nextButton.Enable(False)
class GetRowsOrColumnsPage(WizPage):
""" Wizard page to find out if the data is organized by Rows or by Columns """
def __init__(self, parent, title):
""" Define the Wizard Page that gets the File's Data Orientation """
# Inherit from WizPage
WizPage.__init__(self, parent, title)
# Add a Text Field for the File Name
self.fileName = wx.StaticText(self, -1, '')
self.sizer.Add(self.fileName, 0, wx.ALL, 5)
self.sizer.Add((1, 5))
# Add a Hozizontal Box Sizer
boxH = wx.BoxSizer(wx.HORIZONTAL)
# A Vertical Box Sizer 1 (left)
boxV1 = wx.BoxSizer(wx.VERTICAL)
# Add direction prompt
prompt1 = wx.StaticText(self, -1, _('Contents of the first Column'))
boxV1.Add(prompt1, 0)
# Add a multi-line TextCtrl to hold first Column items
self.txt1 = wx.TextCtrl(self, -1, style=wx.TE_MULTILINE)
boxV1.Add(self.txt1, 1, wx.EXPAND | wx.ALL, 3)
# Add a checkbox for selecting COLUMNS
self.chkColumns = wx.CheckBox(self, -1, " " + _("Prompts shown in first Column"), style=wx.CHK_2STATE)
boxV1.Add(self.chkColumns, 0)
# A Vertical Box Sizer 2 (right)
boxV2 = wx.BoxSizer(wx.VERTICAL)
# Add direction prompt
prompt2 = wx.StaticText(self, -1, _('Contents of the first Row'))
boxV2.Add(prompt2, 0)
# Add a multi-line TextCtrl to hold first Row items
self.txt2 = wx.TextCtrl(self, -1, style=wx.TE_MULTILINE)
boxV2.Add(self.txt2, 1, wx.EXPAND | wx.ALL, 3)
# Add a checkbox for selecting ROWS
self.chkRows = wx.CheckBox(self, -1, " " + _("Prompts shown in first Row"), style=wx.CHK_2STATE)
boxV2.Add(self.chkRows, 0)
# Add the Vertical Sizers to the Horizontal Sizer
boxH.Add(boxV1, 1, wx.EXPAND)
boxH.Add(boxV2, 1, wx.EXPAND)
# Add the Horizontal Sizer to the Main Sizer
self.sizer.Add(boxH, 1, wx.EXPAND)
# Set the processor for CheckBoxes
self.Bind(wx.EVT_CHECKBOX, self.OnCheckbox)
def IsComplete(self):
""" IsComplete signals whether either Checkbox has been checked """
return self.chkColumns.GetValue() or self.chkRows.GetValue()
def OnCheckbox(self, event):
""" Process Checkbox Activity """
# If the Columns Checkbox is clicked ...
if event.GetId() == self.chkColumns.GetId():
# ... and has been CHECKED ...
if self.chkColumns.GetValue():
# ... un-check the Rows checkbox ...
self.chkRows.SetValue(False)
# ... and enable the Next Button
self.nextButton.Enable(True)
# ... and has been UN-CHECKED ...
else:
# ... disable the Next Button
self.nextButton.Enable(False)
# If the Rows Checkbox is clicked ...
else:
# ... and has been CHECKED ...
if self.chkRows.GetValue():
# ... un-check the Columns checkbox ...
self.chkColumns.SetValue(False)
# ... and enable the Next Button
self.nextButton.Enable(True)
# ... and has been UN-CHECKED ...
else:
# ... disable the Next Button
self.nextButton.Enable(False)
class GetItemsToIncludePage(WizPage):
""" Wizard page to find out which items to include and how to present them """
def __init__(self, parent, title):
""" Define the Wizard Page that information about organizing and including data """
# Inherit from WizPage
WizPage.__init__(self, parent, title)
# Add the first Instruction Text
instructions1 = _("Please select the item used to uniquely identify Participants")
txtInstructions1 = wx.StaticText(self, -1, instructions1)
self.sizer.Add(txtInstructions1, 0, wx.ALL, 5)
# Add a Choice Box for Unique Identifier
self.identifier = wx.Choice(self, -1)
self.sizer.Add(self.identifier, 0, wx.EXPAND | wx.ALL, 5)
# Add a spacer
self.sizer.Add((1, 5))
# Add the second Instruction Text
instructions2 = _("Please select which items to include in the Transana Documents to be created.")
txtInstructions2 = wx.StaticText(self, -1, instructions2)
self.sizer.Add(txtInstructions2, 0, wx.ALL, 5)
# Add a ListBox for the Prompts / Questions with multi-select enabled
self.questions = wx.ListBox(self, -1, style = wx.LB_EXTENDED)
self.sizer.Add(self.questions, 1, wx.EXPAND | wx.ALL, 5)
# Bind a handler for Item Selection
self.Bind(wx.EVT_LISTBOX, self.OnItemSelect)
# Add a spacer
self.sizer.Add((1, 5))
# Add a Radio Box to specify organization by Participant or by Question
self.organize = wx.RadioBox(self, -1, label = _('Create Documents to contain data for ...'),
choices = [_('Participants (allows auto-coding)'), _('Questions (no auto-coding)')])
self.sizer.Add(self.organize, 0, wx.EXPAND | wx.ALL, 5)
# Bind a handler for Radio Box Selection
self.organize.Bind(wx.EVT_RADIOBOX, self.OnOrganizationSelect)
def IsComplete(self):
""" IsComplete signals whether ANY questions have been selected """
return len(self.questions.GetSelections()) > 0
def OnItemSelect(self, event):
""" Handler for Question / Prompt Selection """
# Check Next Button Enabling on each change
self.nextButton.Enable(self.IsComplete())
def OnOrganizationSelect(self, event):
""" Handler for Organization Radio Box """
# If we are organizing by Participant ...
if self.organize.GetSelection() == 0:
# ... then we should go to Page 4 after this page ...
self.SetNext(self.parent.AutoCodePage)
# ... and the Next Button should be "Next"
self.nextButton.SetLabel(_('Next >'))
# If we are organizing by Question ...
else:
# ... then we should SKIP Page 4 and are done with the Wizard ...
self.SetNext(None)
# ... and the Next button should be labelled "Finish".
self.nextButton.SetLabel(_('Finish'))
class GetAutoCodePage(WizPage):
""" Wizard page to find out which items to auto-code """
def __init__(self, parent, title):
""" Define the Wizard Page that gets the auto-code information """
# Inherit from WizPage
WizPage.__init__(self, parent, title)
# Add the first Instruction Text
instructions3 = _("Please select which items to auto-code at the Document level.")
txtInstructions3 = wx.StaticText(self, -1, instructions3)
self.sizer.Add(txtInstructions3, 0, wx.ALL, 5)
# Add a ListBox that allows selection of what items to auto-code, with multi-select enabled.
self.autocode = wx.ListBox(self, -1, style = wx.LB_EXTENDED)
self.sizer.Add(self.autocode, 1, wx.EXPAND | wx.ALL, 5)
# Add a handler for auto-code item selection
self.Bind(wx.EVT_LISTBOX, self.OnItemSelect)
def IsComplete(self):
""" Selections are NOT required on this page, so it's always complete. """
return True
def OnItemSelect(self, event):
""" Handler for Auto-Code Item Selection """
# Check Next Button Enabling on each change
self.nextButton.Enable(self.IsComplete())
class SpreadsheetDataImport(wiz.Wizard):
""" This displays the main Spreadsheet Data Import Wizard window. """
def __init__(self, parent, treeCtrl):
""" Initialize the Spreadsheet Data Import Wizard """
# Remember the TreeCtrl
self.treeCtrl = treeCtrl
# Initialize data for the Wizard
# This list holds the data imported from the file in a list of lists
self.all_data = []
# This list holds the Questions / Prompts from the data file
self.questions = []
# This dictionary holds Keyword Groups (keys) and Keywords (data) for Auto-Codes
self.all_codes = {}
# Create the Wizard
wiz.Wizard.__init__(self, parent, -1, _('Import Spreadsheet Data'))
self.SetPageSize(wx.Size(600, 450))
# To look right, the Mac needs the Small Window Variant.
if "__WXMAC__" in wx.PlatformInfo:
self.SetWindowVariant(wx.WINDOW_VARIANT_SMALL)
# Define the individual Wizard Pages
self.FileNamePage = GetFileNamePage(self, _("Select a Spreadsheet Data File"))
self.RowsOrColumnsPage = GetRowsOrColumnsPage(self, _("Identify Data Orientation"))
self.ItemsToIncludePage = GetItemsToIncludePage(self, _("Organize Data for Import"))
self.AutoCodePage = GetAutoCodePage(self, _("Select Items for Auto-Coding."))
# Define the page order / relationships
self.FileNamePage.SetNext(self.RowsOrColumnsPage)
self.RowsOrColumnsPage.SetPrev(self.FileNamePage)
self.RowsOrColumnsPage.SetNext(self.ItemsToIncludePage)
self.ItemsToIncludePage.SetPrev(self.RowsOrColumnsPage)
self.ItemsToIncludePage.SetNext(self.AutoCodePage)
self.AutoCodePage.SetPrev(self.ItemsToIncludePage)
# Bind Wizard Events
self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnPageChanged)
self.Bind(wiz.EVT_WIZARD_FINISHED, self.OnWizardFinished)
# We need to add a HELP button to the Wizard Object.
# First, let's create a Help Button
self.helpButton = wx.Button(self, -1, _("Help"))
self.helpButton.Bind(wx.EVT_BUTTON, self.OnHelp)
# We need to figure out where to insert it into the existing Wizard Infrastructure. It should go into the LAST
# sizer we find in the Wizard object. Let's initialize a variable so we can seek that sizer out.
lastSizer = None
# Sizers can be nested inside sizers. So we iterate through the Wizard's Sizer's Children's sizer's Children to find it!
for x in self.GetSizer().GetChildren()[0].Sizer.GetChildren():
# If the current child is a sizer ...
if x.IsSizer():
# ... it's a candidate for the LAST sizer. Remember it.
lastSizer = x.Sizer
# Add the Help button to the last sizer found!!
if lastSizer != None:
lastSizer.Add(self.helpButton, 0, wx.ALL, 5)
# Run the Wixard
self.FitToPage(self.FileNamePage)
self.RunWizard(self.FileNamePage)
def strip_quotes(self, text):
""" Process text items from a Streadsheet Data File to strip leading and trailing quotes """
# Remove leading and trailing whitespace
text = text.strip()
# Replace triple quotes with single quotes
text = text.replace('"""', '"')
# Replace double quotes with single quotes
text = text.replace('""', '"')
# If we have text that starts and ends with quotes ...
if (len(text) > 1) and (text[0] == '"') and (text[-1] == '"'):
# Strip a quote from the first and last positions in the string
text = text[1:]
text = text[:-1]
# Return the processed string
return text
def OnPageChanging(self, event):
""" Process Wizard Page changes, with VETO option """
if event.GetPage() == self.FileNamePage:
prompt = unicode(_('File: %s'), 'utf8')
# ... set the File Name to the file selected on the File Name Page
self.RowsOrColumnsPage.fileName.SetLabel(prompt % self.FileNamePage.txtSrcFileName.GetValue())
# If we're moving FORWARD ...
if event.GetDirection():
# Initialize the File Data list
self.all_data = []
# Note the filename
filename = self.FileNamePage.txtSrcFileName.GetValue()
# Get the Character Encoding
encoding = self.FileNamePage.txtSrcEncoding.GetStringSelection()
# Open the file
with open(filename, 'r') as f:
try:
# Use the csv Sniffer to determine the dialect of the file
dialect = csv.Sniffer().sniff(f.read(1024))
# Reset the file to the beginning
f.seek(0)
# use the csv Reader to read the data file
csvReader = csv.reader(f, dialect=dialect)
# For each row of data read ...
for row in csvReader:
# ... create a list for the Unicode encoded data
encRow = []
# For each element in the row ...
for element in row:
# ... decode the data (convert string to unicode) using the import encoding ...
encRow.append(element.decode(encoding))
# ... add that encoded row to the data list
self.all_data.append(encRow)
except UnicodeDecodeError:
prompt = _("Unicode Error. The encoding you selected does not match the data file you selected.")
tmpDlg = Dialogs.ErrorDialog(self, prompt)
tmpDlg.ShowModal()
tmpDlg.Destroy()
event.Veto()
return
except (csv.Error, IndexError, TypeError):
self.all_data = []
try:
f.seek(0)
data = f.read()
data = data.decode(encoding)
if data[-1] == '\n':
data = data[:-1]
rows = data.split('\n')
for x in rows:
row_data = []
for y in x.split('\t'):
row_data.append(self.strip_quotes(y))
self.all_data.append(row_data)
except UnicodeDecodeError:
prompt = _("Unicode Error. The encoding you selected does not match the data file you selected.")
tmpDlg = Dialogs.ErrorDialog(self, prompt)
tmpDlg.ShowModal()
tmpDlg.Destroy()
event.Veto()
return
except:
print sys.exc_info()[0]
print sys.exc_info()[1]
# Place the first item in each row (that is, the first COLUMN of data) in the Column TextCtrl
self.RowsOrColumnsPage.txt1.Clear()
for row in self.all_data:
self.RowsOrColumnsPage.txt1.AppendText(self.strip_quotes(row[0]) + '\n')
self.RowsOrColumnsPage.txt2.Clear()
# Place the items from the first row (that is,the first ROW of data) in the Row TextCtrl
for col in self.all_data[0]:
self.RowsOrColumnsPage.txt2.AppendText(self.strip_quotes(col) + '\n')
# Disable the Column and Row TextCtrls
self.RowsOrColumnsPage.txt1.Enable(False)
self.RowsOrColumnsPage.txt2.Enable(False)
# If we move to the Organize and Include Items page ...
elif event.GetPage() == self.RowsOrColumnsPage:
# If we're moving FORWARD ...
if event.GetDirection():
# Initialize the Questions list
self.questions = []
# Determine the Questions if the user selected Columns ...
if self.RowsOrColumnsPage.chkColumns.GetValue():
# ... by iterating through each row of data ...
for row in self.all_data:
# ... and selecting the row's first item
self.questions.append(self.strip_quotes(row[0]))
# Determine the Questions if the user selected Rows ...
else:
# ... by iterating through the first row of data
for col in self.all_data[0]:
# ... and selecting the column's header
self.questions.append(self.strip_quotes(col))
# Populate the combo of Questions / Prompts used to select the Unique Identifier after adding an automatic creation option
self.ItemsToIncludePage.identifier.SetItems([_('Create one automatically')] + self.questions)
self.ItemsToIncludePage.identifier.SetSelection(0)
# Populate the list of Questions / Prompts
self.ItemsToIncludePage.questions.SetItems(self.questions)
# If we move to the Auto-Code Page ...
elif event.GetPage() == self.ItemsToIncludePage:
# If we're moving FORWARD ...
if event.GetDirection():
# ... set the Auto-Code options to match the Questions
self.AutoCodePage.autocode.SetItems(self.questions)
def OnPageChanged(self, event):
""" Process Wizard Page changes with no veto option """
# If we move BACKWARDS to the File Name Page ...
if event.GetPage() == self.FileNamePage:
# Reset the Questions and Codes
self.questions = []
self.all_codes = {}
# Identify the Next button
nextButton = self.FindWindowById(wx.ID_FORWARD)
# Enable (or not) the Next Button depending the new page's "completeness"
nextButton.Enable(event.GetPage().IsComplete())
def OnWizardFinished(self, event):
""" Process the data when the Wizard is completed """
# The Wizard is triggered on one of the Tree's Library nodes. Get the Record Number for this node.
libraryNumber = self.treeCtrl.GetPyData(self.treeCtrl.GetSelections()[0]).recNum
# Get the full Library record
library = Library.Library(libraryNumber)
# Get the Unique Identifier selected by the user
id_col = self.ItemsToIncludePage.identifier.GetSelection() - 1
# Initialize the Participant Counter to 1 (the first participant) rather than 0.
participantCount = 1
# Get the Character Encoding
encoding = self.FileNamePage.txtSrcEncoding.GetStringSelection()
# We need to move through the data differently if the source file is organized by Columns or by Rows.
# We need to present data differently if we're organizing output data by Participant or by Question.
# It might be possible to do this more efficiently, but I don't have time to abstract that right now.
# As a result, there's a lot of duplication in the following code.
# If source data Questions / Prompts are in the first Column ...
if self.RowsOrColumnsPage.chkColumns.GetValue():
# ... and if we're organizing output by Participant ...
if self.ItemsToIncludePage.organize.GetSelection() == 0:
# ... initialize the auto-codes found for THIS participant
codes = {}
# For each COLUMN ...
for x in range(1, len(self.all_data[0])):
# If the user requested automatic unique Participant IDs ...
if (id_col == -1) or (self.all_data[id_col][x] == ''):
# ... create a unique Participant ID and increment the Participant Counter
participantID = unicode(_('Participant %04d'), 'utf8') % participantCount
participantCount += 1
# Otherwise, use the data the user requested
else:
participantID = self.all_data[id_col][x] # self.strip_quotes(self.all_data[id_col][x].decode(encoding))
# Create Document by participantID
tmpDoc = Document.Document()
# Populate essential Document Properties
tmpDoc.id = participantID
tmpDoc.library_num = libraryNumber
tmpDoc.imported_file = self.FileNamePage.txtSrcFileName.GetValue()
tmpDoc.import_date = datetime.datetime.now().strftime('%Y-%m-%d')
# Initialize Document Text with the initial XML for a Transana-XML document
tmpDoc.text = """<?xml version="1.0" encoding="UTF-8"?>
<richtext version="1.0.0.0" xmlns="http://www.wxwidgets.org">
<paragraphlayout textcolor="#000000" bgcolor="#FFFFFF" fontpointsize="12" fontstyle="90" fontweight="90" fontunderlined="0" fontface="Courier New" alignment="1" leftindent="0" leftsubindent="0" rightindent="0" parspacingafter="10" parspacingbefore="0" linespacing="10" tabs="">
"""
tmpDoc.plaintext = ''
# For each Question that should be included in the output ...
for q in sorted(self.ItemsToIncludePage.questions.GetSelections()):
# ... extract the question and answer ...
question = self.strip_quotes(self.questions[q])
answer = self.strip_quotes(self.all_data[q][x])
# ... populate the Document Text and Plain Text with Question and Response
# Start with a Paragraph declaration
tmpDoc.text += """ <paragraph tabs="762">
<text textcolor="#000000" bgcolor="#FFFFFF" fontpointsize="12" fontstyle="90" fontweight="90" fontunderlined="0" fontface="Courier New">"""
# Add the actual DATA
tmpDoc.text += question.encode('utf8') + '\t' + answer.encode('utf8') + '\n'
# Close the Paragraph declaration
tmpDoc.text += """</text>
</paragraph>
"""
tmpDoc.plaintext += question + '\t' + answer + '\n'
# Complete the Transana-XML documeht specification
tmpDoc.text += """ </paragraphlayout>
</richtext>
"""
# Remove trailing carriage return
tmpDoc.plaintext = tmpDoc.plaintext[:-1]
# For each selected Auto-Code category ...
for c in self.AutoCodePage.autocode.GetSelections():
# Define the Keyword Group
kwg = unicode(_('Auto-code'), 'utf8')
# Define the Keyword
kw = unicode("%s : %s", 'utf8') % (self.strip_quotes(self.questions[c]), self.strip_quotes(self.all_data[c][x]))
# Replace Parentheses (illegal in Keywords) with Brackets
kw = kw.replace('(', '[')
kw = kw.replace(')', ']')
# If there was no missing data in the Keyword Definition ...
if (self.strip_quotes(self.questions[c]) != '') and (self.strip_quotes(self.all_data[c][x]) != ''):
# ... Add the Keyword to the Document
tmpDoc.add_keyword(kwg, kw)
# If the Keyword Group had not been defined ...
if not kwg in self.all_codes.keys():
# ... define the Keyword Group using a list containing the Keyword
self.all_codes[kwg] = [kw]
# Try to load the keyword to see if it already exists.
try:
keyword = KeywordObject.Keyword(kwg, kw)
# If the Keyword doesn't exist yet ...
except TransanaExceptions.RecordNotFoundError:
# ... create the Keyword.
keyword = KeywordObject.Keyword()
keyword.keywordGroup = kwg
keyword.keyword = kw
keyword.definition = unicode(_('Created during Spreadsheet Data Import for file "%s."'), 'utf8') % self.FileNamePage.txtSrcFileName.GetValue()
# Try to save the Keyword
keyword.db_save()
# Add the new Keyword to the database tree
self.treeCtrl.add_Node('KeywordNode', (_('Keywords'), keyword.keywordGroup, keyword.keyword), 0, keyword.keywordGroup)
# Now let's communicate with other Transana instances if we're in Multi-user mode
if not TransanaConstants.singleUserVersion:
if TransanaGlobal.chatWindow != None:
TransanaGlobal.chatWindow.SendMessage("AK %s >|< %s" % (keyword.keywordGroup, keyword.keyword))
# If the Keyword Group HAS been defined ...
else:
# ... if the Keyword has NOT been defined ...
if not kw in self.all_codes[kwg]:
# ... add the Keyword to the Keyword Group's Keyword List
self.all_codes[kwg].append(kw)
# Try to load the keyword to see if it already exists.
try:
keyword = KeywordObject.Keyword(kwg, kw)
# If the Keyword doesn't exist yet ...
except TransanaExceptions.RecordNotFoundError:
# ... create the Keyword.
keyword = KeywordObject.Keyword()
keyword.keywordGroup = kwg
keyword.keyword = kw
keyword.definition = unicode(_('Created during Spreadsheet Data Import for file "%s."'), 'utf8') % self.FileNamePage.txtSrcFileName.GetValue()
# Try to save the Keyword
keyword.db_save()
# Add the new Keyword to the database tree
self.treeCtrl.add_Node('KeywordNode', (_('Keywords'), keyword.keywordGroup, keyword.keyword), 0, keyword.keywordGroup)
# Now let's communicate with other Transana instances if we're in Multi-user mode
if not TransanaConstants.singleUserVersion:
if TransanaGlobal.chatWindow != None:
TransanaGlobal.chatWindow.SendMessage("AK %s >|< %s" % (keyword.keywordGroup, keyword.keyword))
# Try to save the new Document
try:
tmpDoc.db_save()
# If there is a SaveError (duplicate name is most likely) ...
except TransanaExceptions.SaveError:
# ... try to give it a unique identifier
tmpDoc.id += ' (%04d)' % participantCount
participantCount += 1
# Try to save it again
tmpDoc.db_save()
finally:
# Add the new Document to the Database Tree
nodeData = (_('Libraries'), library.id, tmpDoc.id)
self.treeCtrl.add_Node('DocumentNode', nodeData, tmpDoc.number, library.number)
# Now let's communicate with other Transana instances if we're in Multi-user mode
if not TransanaConstants.singleUserVersion:
if TransanaGlobal.chatWindow != None:
TransanaGlobal.chatWindow.SendMessage("AD %s >|< %s" % (nodeData[-2], nodeData[-1]))
# ... and if we're organizing output by Question ...
elif self.ItemsToIncludePage.organize.GetSelection() == 1:
# For each Question that should be included in the output ...
for q in sorted(self.ItemsToIncludePage.questions.GetSelections()):
# Note the Question
questionID = self.strip_quotes(self.all_data[q][0])
# Create Document by QuestionID
tmpDoc = Document.Document()
# Populate essential Document Properties
tmpDoc.id = questionID
tmpDoc.library_num = libraryNumber
tmpDoc.imported_file = self.FileNamePage.txtSrcFileName.GetValue()
tmpDoc.import_date = datetime.datetime.now().strftime('%Y-%m-%d')
# Initialize Document Text with the initial XML for a Transana-XML document
tmpDoc.text = """<?xml version="1.0" encoding="UTF-8"?>
<richtext version="1.0.0.0" xmlns="http://www.wxwidgets.org">
<paragraphlayout textcolor="#000000" bgcolor="#FFFFFF" fontpointsize="12" fontstyle="90" fontweight="90" fontunderlined="0" fontface="Courier New" alignment="1" leftindent="0" leftsubindent="0" rightindent="0" parspacingafter="10" parspacingbefore="0" linespacing="10" tabs="">
"""
tmpDoc.plaintext = ''
# We have to re-initialize the Participant Counter for each Question
participantCount = 1
# For each COLUMN ...
for x in range(1, len(self.all_data[0])):
# If the user requested automatic unique Participant IDs ...
if (id_col == -1) or (self.strip_quotes(self.all_data[id_col][x]) == ''):
# ... create a unique Participant ID and increment the Participant Counter
participantID = unicode(_('Participant %04d'), 'utf8') % participantCount
participantCount += 1
# Otherwise, use the data the user requested
else:
participantID = self.strip_quotes(self.all_data[id_col][x])
# ... extract the question and answer ...
answer = self.strip_quotes(self.all_data[q][x])
# ... populate the Document Text and Plain Text with Question and Response
# Start with a Paragraph declaration
tmpDoc.text += """ <paragraph tabs="762">
<text textcolor="#000000" bgcolor="#FFFFFF" fontpointsize="12" fontstyle="90" fontweight="90" fontunderlined="0" fontface="Courier New">"""
# Add the actual DATA
tmpDoc.text += participantID.encode('utf8') + '\t' + answer.encode('utf8') + '\n'
# Close the Paragraph declaration
tmpDoc.text += """</text>
</paragraph>
"""
tmpDoc.plaintext += participantID + '\t' + answer + '\n'
# Complete the Transana-XML document specification
tmpDoc.text += """ </paragraphlayout>
</richtext>
"""
# Remove trailing carriage returns
tmpDoc.plaintext = tmpDoc.plaintext[:-2]
# Try to save the new Document
try:
tmpDoc.db_save()
# If there is a SaveError (duplicate name is most likely) ...
except TransanaExceptions.SaveError:
# ... try to give it a unique identifier
tmpDoc.id += ' (%04d)' % participantCount
participantCount += 1
# Try to save it again
tmpDoc.db_save()
finally:
# Add the new Document to the Database Tree
nodeData = (_('Libraries'), library.id, tmpDoc.id)
self.treeCtrl.add_Node('DocumentNode', nodeData, tmpDoc.number, library.number)
# Now let's communicate with other Transana instances if we're in Multi-user mode
if not TransanaConstants.singleUserVersion:
if TransanaGlobal.chatWindow != None:
TransanaGlobal.chatWindow.SendMessage("AD %s >|< %s" % (nodeData[-2], nodeData[-1]))
# If source data Questions / Prompts are organized in Rows ...
elif self.RowsOrColumnsPage.chkRows.GetValue():
# ... and if we're organizing output by Participant ...
if self.ItemsToIncludePage.organize.GetSelection() == 0:
# ... initialize the auto-codes found for THIS participant
codes = {}
# For each ROW ...
for x in range(1, len(self.all_data)):
# If the user requested automatic unique Participant IDs ...
if (id_col == -1) or (self.strip_quotes(self.all_data[x][id_col]) == ''):
# ... create a unique Participant ID and increment the Participant Counter
participantID = unicode(_('Participant %04d'), 'utf8') % participantCount
participantCount += 1
# Otherwise, use the data the user requested
else:
participantID = self.strip_quotes(self.all_data[x][id_col])
# Create Document by participantID
tmpDoc = Document.Document()
# Populate essential Document Properties
tmpDoc.id = participantID
tmpDoc.library_num = libraryNumber
tmpDoc.imported_file = self.FileNamePage.txtSrcFileName.GetValue()
tmpDoc.import_date = datetime.datetime.now().strftime('%Y-%m-%d')
# Initialize Document Text with the initial XML for a Transana-XML document
tmpDoc.text = """<?xml version="1.0" encoding="UTF-8"?>
<richtext version="1.0.0.0" xmlns="http://www.wxwidgets.org">
<paragraphlayout textcolor="#000000" bgcolor="#FFFFFF" fontpointsize="12" fontstyle="90" fontweight="90" fontunderlined="0" fontface="Courier New" alignment="1" leftindent="0" leftsubindent="0" rightindent="0" parspacingafter="10" parspacingbefore="0" linespacing="10" tabs="">
"""
tmpDoc.plaintext = ''
# For each Question that should be included in the output ...
for q in sorted(self.ItemsToIncludePage.questions.GetSelections()):
# ... populate the Document Text and Plain Text with Question and Response
# ... extract the question and answer ...
question = self.strip_quotes(self.questions[q])
answer = self.strip_quotes(self.all_data[x][q])
# ... populate the Document Text and Plain Text with Question and Response
# Start with a Paragraph declaration
tmpDoc.text += """ <paragraph tabs="762">
<text textcolor="#000000" bgcolor="#FFFFFF" fontpointsize="12" fontstyle="90" fontweight="90" fontunderlined="0" fontface="Courier New">"""
# Add the actual DATA
tmpDoc.text += question.encode('utf8') + '\t' + answer.encode('utf8') + '\n'
# Close the Paragraph declaration
tmpDoc.text += """</text>
</paragraph>
"""
tmpDoc.plaintext += question + '\t' + answer + '\n'
# Complete the Transana-XML documeht specification
tmpDoc.text += """ </paragraphlayout>
</richtext>
"""
# Remove trailing carriage returns
tmpDoc.plaintext = tmpDoc.plaintext[:-2]
# For each selected Auto-Code category ...
for c in self.AutoCodePage.autocode.GetSelections():
# Define the Keyword Group
kwg = unicode(_('Auto-code'), 'utf8')
# Define the Keyword
kw = unicode("%s : %s", 'utf8') % (self.strip_quotes(self.questions[c]), self.strip_quotes(self.all_data[x][c]))
# Replace Parentheses (illegal in Keywords) with Brackets
kw = kw.replace('(', '[')
kw = kw.replace(')', ']')
# If there was no missing data in the Keyword Definition ...
if (self.strip_quotes(self.questions[c]) != '') and (self.strip_quotes(self.all_data[x][c]) != ''):
# ... Add the Keyword to the Document
tmpDoc.add_keyword(kwg, kw)
# If the Keyword Group had not been defined ...
if not kwg in self.all_codes.keys():
# ... define the Keyword Group using a list containing the Keyword
self.all_codes[kwg] = [kw]
# Try to load the keyword to see if it already exists.
try:
keyword = KeywordObject.Keyword(kwg, kw)
# If the Keyword doesn't exist yet ...
except TransanaExceptions.RecordNotFoundError:
# ... create the Keyword.
keyword = KeywordObject.Keyword()
keyword.keywordGroup = kwg
keyword.keyword = kw
keyword.definition = unicode(_('Created during Spreadsheet Data Import for file "%s."'), 'utf8') % self.FileNamePage.txtSrcFileName.GetValue()
# Try to save the keyword
keyword.db_save()
# Add the new Keyword to the database tree
self.treeCtrl.add_Node('KeywordNode', (_('Keywords'), keyword.keywordGroup, keyword.keyword), 0, keyword.keywordGroup)
# Now let's communicate with other Transana instances if we're in Multi-user mode
if not TransanaConstants.singleUserVersion:
if TransanaGlobal.chatWindow != None:
TransanaGlobal.chatWindow.SendMessage("AK %s >|< %s" % (keyword.keywordGroup, keyword.keyword))
# If the Keyword Group HAS been defined ...
else:
# ... if the Keyword has NOT been defined ...
if not kw in self.all_codes[kwg]:
# ... add the Keyword to the Keyword Group's Keyword List
self.all_codes[kwg].append(kw)
# Try to load the keyword to see if it already exists.
try:
keyword = KeywordObject.Keyword(kwg, kw)
# If the Keyword doesn't exist yet ...
except TransanaExceptions.RecordNotFoundError:
# ... create the Keyword.
keyword = KeywordObject.Keyword()
keyword.keywordGroup = kwg
keyword.keyword = kw
keyword.definition = unicode(_('Created during Spreadsheet Data Import for file "%s."'), 'utf8') % self.FileNamePage.txtSrcFileName.GetValue()
# Try to save the Keyword
keyword.db_save()
# Add the new Keyword to the database tree
self.treeCtrl.add_Node('KeywordNode', (_('Keywords'), keyword.keywordGroup, keyword.keyword), 0, keyword.keywordGroup)
# Now let's communicate with other Transana instances if we're in Multi-user mode
if not TransanaConstants.singleUserVersion:
if TransanaGlobal.chatWindow != None:
TransanaGlobal.chatWindow.SendMessage("AK %s >|< %s" % (keyword.keywordGroup, keyword.keyword))
# Try to save the new Document
try:
tmpDoc.db_save()
# If there is a SaveError (duplicate name is most likely) ...
except TransanaExceptions.SaveError:
# ... try to give it a unique identifier
tmpDoc.id += ' (%04d)' % participantCount
participantCount += 1
# Try to save it again
tmpDoc.db_save()
finally:
# Add the new Document to the Database Tree
nodeData = (_('Libraries'), library.id, tmpDoc.id)
self.treeCtrl.add_Node('DocumentNode', nodeData, tmpDoc.number, library.number)
# Now let's communicate with other Transana instances if we're in Multi-user mode
if not TransanaConstants.singleUserVersion:
if TransanaGlobal.chatWindow != None:
TransanaGlobal.chatWindow.SendMessage("AD %s >|< %s" % (nodeData[-2], nodeData[-1]))
# ... and if we're organizing output by Question ...
elif self.ItemsToIncludePage.organize.GetSelection() == 1:
# For each Question that should be included in the output ...
for q in sorted(self.ItemsToIncludePage.questions.GetSelections()):
# Note the Question
questionID = self.strip_quotes(self.all_data[0][q])
# Create Document by QuestionID
tmpDoc = Document.Document()
# Populate essential Document Properties
tmpDoc.id = questionID
tmpDoc.library_num = libraryNumber
tmpDoc.imported_file = self.FileNamePage.txtSrcFileName.GetValue()
tmpDoc.import_date = datetime.datetime.now().strftime('%Y-%m-%d')
# Initialize Document Text with the initial XML for a Transana-XML document
tmpDoc.text = """<?xml version="1.0" encoding="UTF-8"?>
<richtext version="1.0.0.0" xmlns="http://www.wxwidgets.org">
<paragraphlayout textcolor="#000000" bgcolor="#FFFFFF" fontpointsize="12" fontstyle="90" fontweight="90" fontunderlined="0" fontface="Courier New" alignment="1" leftindent="0" leftsubindent="0" rightindent="0" parspacingafter="10" parspacingbefore="0" linespacing="10" tabs="">
"""
tmpDoc.plaintext = ''
# We have to re-initialize the Participant Counter with each Question
participantCount = 1
# For each ROW ...
for x in range(1, len(self.all_data)):
# If the user requested automatic unique Participant IDs ...
if (id_col == -1) or (self.strip_quotes(self.all_data[x][id_col]) == ''):
# ... create a unique Participant ID and increment the Participant Counter