-
Notifications
You must be signed in to change notification settings - Fork 3
/
PrimerPrep.py
3349 lines (2990 loc) · 163 KB
/
PrimerPrep.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/python3
# -*- coding: utf-8 -*-
#
# PrimerPrep
#
# This program is a tool that helps in preparing a primer. The
# program loads language texts, counts words and letters, and
# suggests a teaching order for introducing the letters of the
# language in a primer. It can test lesson texts for untaught
# residue. It can also produce word concordances and sequences
# of available words in a specific lesson.
#
# When run directly, this script will create and execute an instance
# of the PrimerPrepWindow class.
#
# by Jeff Heath, SIL Chad
#
# © 2024 SIL International
#
# Modifications:
# 3.36 JCH Jul 2024
# Improve project handling - add new menus (New, Open, Save, Save As)
# Add .ppdata extension to project file name if it's not there, but allow user to modify
# Remove Clear Texts button, add Choose Lexicon button
# 3.35 JCH Jun 2024
# Fix loss of affixes in display when you change UI language
# Add Give Feedback feature (which uses a Google form) in Help menu
# Match longer affixes before shorter ones
# Make LoadProject more robust in error handling, prepare for loading old data models
# 3.34 JCH Jun 2024
# Fix word counts for affixes that are analyzed separately (words with affixes were
# overcounted, causing them to appear too early in the word Examples in the Teaching Order)
# 3.33 JCH Jun 2024
# Some tweaks to font selection and rendering
# Removed Auto-Search for Digraphs option from Configure menu
# 3.32 JCH May 2024
# Returned to a flatter project directory structure
# Help files (including en_US) now all use the %locale_with_underscore% marking
# (Helper batch and python files now manage Crowdin integration, creation of localized Help files)
# 3.31 JCH Apr 2024
# Fixed up some problems with the splash screen on startup
# 3.30 JCH Apr 2024
# For concordance, turn tabs in the text into spaces (tabs are used for the columns)
# 3.29 JCH Mar 2024
# Fixed some font issues on startup
# 3.28 JCH Mar 2024
# Added splash screen on startup, since the startup can be quite slow at times
# 3.27 JCH Jan 2024
# Use built-in set_do_overwrite_confirmation in chooser, since it seems to work now
# If you choose not to overwrite, or project file name is bad, keep the save dialog open with same settings
# 3.26 JCH Jan 2024
# Improved analysis with affixes - words with affixes weren't appearing in the Teaching Order example word list
# Added confirmation to quit without saving if there are changes to the data
# 3.20 JCH Sep 2023-Jan 2024
# Sort multigraphs (longest first) when processing, so that shorter don't hide longer
# Reworked marking of untaught residue (didn't handle digraphs correctly)
# Initial work on implementing CSS styles, handler for sight words font
# Fix depricated use of FileChooserDialog - buttons added afterwards
# Fixed some comments
# 3.14 JCH Mar 2022
# Bug fix: Allow saving the teaching order right after loading from a saved project file
# 3.13 JCH Nov 2021
# Bug fix: If first lesson is sight word, typing into its Lesson Text field causes infinite loop
# 3.12 JCH Nov 2020
# Bug fix: Handle ugly input (combining diacritics on '-', '[' and tab)
# Bug fix: Make sure concordance data doesn't have tabs, to confuse column output routine
# 3.11 JCH Jul 2020
# Make script more platform-agnostic, put conditionals on Windows-specific code
# 3.10 JCH Jun 2020
# Add help files in Dari and Pashto
# 3.05 JCH Oct 2019
# Use Word Joiner (U+2060) instead of ZWSP (U+200B) in ZWJ attachment code
# (ZWSP is needed for Khmer and other languages)
# 3.04 JCH Jun 2019
# Bug fix - unbalanced paren if separate combining diacritics is checked
# 3.03 JCH Jun 2019
# Handle input from FreezeArabicForms (ZWJs for contextual forms)
# 3.02 JCH Jun 2019
# Make sure isRTL gets initialized, even if interface isn't set
# Fix logger code, fix WordEdit path when there are no roots
# 3.01 JCH Jun 2019
# Base dialogs on window not analysis object, don't show zero counts in teaching order
# Verify data model number on project save/load, be smarter about SFM load based on markers
# Handle change of separate combining diacritics more accurately (updates character lists)
# Don't open sightWordsDialog if there is no row selected
# 3.00 JCH May 2019
# Switch to Glade UI, implemented internationalization with gettext
# 2.06 JCH Apr 2019
# After adding a sight word lesson, select that lesson to make sure it is displayed
# 2.05 JCH Apr 2019
# Fix teachingOrder existance code
# Add 'nj' to recommended digraphs (from Maba)
# 2.04 JCH Apr 2019
# Fix French word-forming and word-breaking terms
# 2.03 JCH Apr 2019
# Implement Save/Load Project
# Fix teaching order calculation by types (words only once)
# Fix double-click in WordList, sometimes updated wrong word
# Fix word sort order - wasn't using the custom sort routine
# 2.02 JCH Mar 2019
# Deactive Save Teaching Order menu item, until it makes sense
# Manual change in word divisions also provokes recalculation of teaching order
# On manual word divisions, get confirmation if word is too different (LevDist < 0.5)
# 2.01 JCH Mar 2019
# Rewrote help page to reflect major changes with screen shots
# Made draft of French help page
# 2.00 JCH Feb 2019
# Redesigned interface with tabbed interface
# Word Discovery tab contains all tools for defining files to load/words/affixes/breaks/digraphs/etc
# Double-clicking a word allows manual editing of affixes (or excluding the word entirely)
# Addition of a filter text box allows filtering/finding words in the word list
# Allow addition of sight word "lessons" (lines) in teaching order
# Track texts for each lesson, and show untaught residue (word-forming characters only) in red
# Handle letters and combining marks based on unicodedata (so works better on non-Roman scripts)
# 1.04 JCH Feb 2018
# Corrections in French help file (thanks to Dominique Henchoz)
# 1.03 JCH Feb 2018
# Save interface selection and two configuration options to .ini file in APPDATA
# Added French help file (.html)
# Corrections to French interface (thanks to Dominique Henchoz)
# 1.02 JCH Feb 2018
# Add French interface
# 1.01 JCH Feb 2018
# Sort concordance entries so longest ones appear first
# 1.00 JCH Jan 2018
# Add option to treat combining diacritics separately
# 0.98 JCH Nov 2017
# Correctly processes SFMs that contain an underscore
# Write text files with a BOM for easier identification
# Use only spaces to separate example words in teaching order list
# (commas considered vowel marks in Scheherazade Compact with Graphite)
APP_NAME = "PrimerPrep"
progVersion = "3.36"
progYear = "2024"
dataModelVersion = 1
DEBUG = False
import sys
import logging
logger = logging.getLogger(APP_NAME)
if DEBUG:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.WARNING)
if sys.version_info[0] < 3:
logger.error('This script requires Python 3')
exit()
from gi import require_version
require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, Pango
import os
import subprocess
import platform
import re
import codecs
import unicodedata
import xml.etree.ElementTree as ET
import pickle
class UnknownProjectType(Exception):
pass
import numpy as np
import configparser
import webbrowser
# for internationalization
import gettext
import json
# global variable to store the program path
myGlobalProgramPath = ''
# global variable to store the current working directory path
myGlobalPath = ''
# global variable to store the current working project path
# (note that this interacts with myGlobalPath, but is not the same, as our project could be in one place - and
# we need to remember where it is! - but we might be saving word lists or teaching orders elsewhere)
myGlobalProjectPath = ''
# global variable to store the current working project name (without path, but including the .ppdata extension)
myGlobalProjectName = ''
# global instance of Renderer for managing fonts in the program (esp. TreeView)
myGlobalRenderer = None
# global variable to hold the Glade builder - needed for loading UI elements
myGlobalBuilder = None
# global variable to hold the main window - needed as parent for various dialogs
myGlobalWindow = None
# global variable for the interface language (English by default)
myGlobalInterface = 'en_US'
# global variable for the config file (with complete path)
myGlobalConfigFile = ''
# global variable for the config object (so we can update settings and save them out)
myGlobalConfig = configparser.ConfigParser()
# global variable for holding the page index of the GTK notebook
myGlobalNotebookPage = 0
# defaults for global CSS (Cascading Style Sheets) formatting
GlobalCSS = """
notebook tab {
background-color: silver;
border: 1px black;
border-style: solid solid none solid;
color: gray;
}
notebook tab:hover {
color: #606060;
}
notebook tab:checked {
background-color: white;
color: black;
}
"""
# present a message to the user
def SimpleMessage(title, msgType, msg):
global myGlobalBuilder
dlg = myGlobalBuilder.get_object('simpleMessageDialog')
dlg.set_title(title)
myGlobalBuilder.get_object('simpleMessageImage').set_from_icon_name(msgType, Gtk.IconSize.DIALOG)
myGlobalBuilder.get_object('simpleMessageLabel').set_text(msg)
dlg.show_all()
dlg.run()
dlg.hide()
# present a Y/N question to the user
def SimpleYNQuestion(title, msgType, msg):
global myGlobalBuilder
dlg = myGlobalBuilder.get_object('simpleYNQuestionDialog')
myGlobalBuilder.get_object('simpleYNQuestionImage').set_from_icon_name(msgType, Gtk.IconSize.DIALOG)
myGlobalBuilder.get_object('simpleYNQuestionLabel').set_text(msg)
dlg.show_all()
response = dlg.run()
dlg.hide()
return (response == 1)
class VernacularRenderer:
'''A class used to hold vernacular font rendering information
Creating an instance of this class loads the standard renderer used
in PrimerPrep. Use SelectFont to select/change to a new vernacular font.
Attributes:
fontName (str) - current font selected for displaying vernacular text
global_style_provider (Gtk.CssProvider) - holds global (static) CSS configuration
vernacular_style_provider (Gtk.CssProvider) - holds CSS configuration for vernacular class
vernFontDesc (Pango.FontDescription) - font info for vernacular text
vernRendererText (Gtk.CellRendererText) - renderer for vernacular text
'''
def SelectFont(self):
'''Let user select a font using the standard dialog, modify vernacular renderer.
Parameter: parent (Window object) - parent window for centering dialog
Return value: True if font was selected and changed
'''
global myGlobalWindow
fontDlg = Gtk.FontChooserDialog(_("Select the font for displaying vernacular text"))
fontDlg.set_transient_for(myGlobalWindow.window)
fontDlg.set_font(self.fontName)
result = fontDlg.run()
if result == Gtk.ResponseType.OK:
self.fontName = fontDlg.get_font()
# set up the font description and CellRendererText for vernacular text in TreeViews
self.vernFontDesc = Pango.FontDescription(self.fontName)
self.vernRendererText.set_property('font-desc', self.vernFontDesc)
# parse the fontName to get the family and size
m = re.match('(.+) (\d+)$', self.fontName)
if m:
# set up the CSS vernacular class (which will automatically update fields with this class)
VernacularCSS = """
.vernacular {{
font-family: {}, 'Charis SIL Semi-Condensed', 'Charis SIL', Gentium, Ubuntu, serif;
font-size: {}pt;
}}""".format(m.group(1), m.group(2))
self.vernacular_style_provider.load_from_data(bytes(VernacularCSS.encode()))
fontDlg.destroy()
return result == Gtk.ResponseType.OK
def __init__(self):
'''Initialize this Renderer object's attributes with the defaults.
'''
# Initially tried Charis SIL Semi-Condensed, but had some difficulties
if platform.system() == "Windows":
self.fontName = "Charis SIL Semi-Condensed 14"
else:
self.fontName = "Ubuntu 14"
#self.fontName = "Gentium 14"
# modifiable vernacular class CSS formatting
VernacularCSS = """
.vernacular {
font-family: 'Charis SIL Semi-Condensed', 'Charis SIL', Gentium, Ubuntu, serif;
font-size: 14pt;
}"""
# set up the global (static) CSS provider
self.global_style_provider = Gtk.CssProvider()
self.global_style_provider.load_from_data(bytes(GlobalCSS.encode()))
Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), self.global_style_provider,
Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
# set up the vernacular (modifiable) CSS provider
self.vernacular_style_provider = Gtk.CssProvider()
self.vernacular_style_provider.load_from_data(bytes(VernacularCSS.encode()))
Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), self.vernacular_style_provider,
Gtk.STYLE_PROVIDER_PRIORITY_USER)
# set up the font description and CellRendererText for vernacular text in TreeViews
self.vernFontDesc = Pango.FontDescription(self.fontName)
self.vernRendererText = Gtk.CellRendererText()
self.vernRendererText.set_property('font-desc', self.vernFontDesc)
class AffixesDialog:
'''A class used to present a dialog for specifying the affixes in the language.
Attributes:
dialog (Dialog object) - dialog for managing word-breaking/forming chars
'''
def __init__(self):
'''Prepare dialog for defining affixes, for running later.'''
global myGlobalBuilder
global myGlobalRenderer
self.dialog = myGlobalBuilder.get_object('affixesDialog')
self.textview = myGlobalBuilder.get_object('affixesDialogTextView')
# set up the textview to use the vernacular font
self.textview.get_style_context().add_class("vernacular")
# monitor keypresses so we can close the dialog on Enter
self.textview.connect('key-press-event', self.on_keyPress)
def Run(self):
self.textview.grab_focus()
self.textview.get_buffer().place_cursor(self.textview.get_buffer().get_end_iter())
self.dialog.show_all()
response = self.dialog.run()
# don't hide the dialog yet, as we run it until valid or cancel
#self.dialog.hide()
return (response == 1)
def SetAffixes(self, affixes):
# put the affix list into the textview
buf = self.textview.get_buffer()
buf.set_text(' '.join(affixes))
def GetAffixes(self):
buf = self.textview.get_buffer()
txt = buf.get_text(buf.get_start_iter(), buf.get_end_iter(), False)
return txt
def on_keyPress(self, widget, event):
if event.get_keycode()[1] == 13:
# Enter was typed, click OK
self.dialog.activate_default()
return True
return False
class WordBreaksDialog:
'''A class used to present a dialog for specifying the
word-breaking and word-forming characters in the language.
Attributes:
dialog (Dialog object) - dialog for managing word-breaking/forming chars
wordBreakStore (listStore) - data store for word breaking chars
wordFormStore (listStore) - data store for word forming chars
'''
def __init__(self):
'''Prepare dialog for defining word breaking/forming characters, for running later.'''
global myGlobalBuilder
global myGlobalRenderer
self.dialog = myGlobalBuilder.get_object('wordBreaksDialog')
self.wordBreakStore = myGlobalBuilder.get_object('wordBreakListStore')
self.wordBreakTreeView = myGlobalBuilder.get_object('wordBreakTreeView')
#column = myGlobalBuilder.get_object('wordBreakColumn')
#column.set_cell_data_func(myGlobalRenderer.vernRendererText, None)
#Gtk.TreeViewColumn(_("Word-Breaking"), myGlobalRenderer.vernRendererText, text=0)
#wordBreakTreeView.append_column(column)
# put in ascending letter order
self.wordBreakStore.set_sort_column_id(0, Gtk.SortType.ASCENDING)
self.wordBreakTreeView.connect("row-activated", self.on_WordBreak_doubleClick)
self.wordFormStore = myGlobalBuilder.get_object('wordFormListStore')
self.wordFormTreeView = myGlobalBuilder.get_object('wordFormTreeView')
#column = myGlobalBuilder.get_object('wordFormColumn')
#column = Gtk.TreeViewColumn(_("Word-Forming"), myGlobalRenderer.vernRendererText, text=0)
#self.wordFormTreeView.append_column(column)
# put in ascending letter order
self.wordFormStore.set_sort_column_id(0, Gtk.SortType.ASCENDING)
self.wordFormTreeView.connect("row-activated", self.on_WordForm_doubleClick)
def Run(self, wordBreakChars, wordFormChars):
# make sure TreeViews are using current vernacular font
myGlobalBuilder.get_object('wordBreakCellRenderer').set_property('font-desc', myGlobalRenderer.vernFontDesc)
myGlobalBuilder.get_object('wordFormCellRenderer').set_property('font-desc', myGlobalRenderer.vernFontDesc)
# clear the store and add each of the letters in the wordBreakChars list
self.wordBreakStore.clear()
for letter in wordBreakChars:
if letter != ' ' and letter != '\xa0':
# don't add the space or non-breaking space - they always word break, so hide
dispLetter = letter
# if the first character is a combining diacritic
if unicodedata.category(dispLetter[0]) == 'Mn':
# then prepend the dotted circle base character
dispLetter = '\u25CC' + dispLetter
self.wordBreakStore.append([dispLetter])
# clear the store and add each of the letters in the wordFormChars list
self.wordFormStore.clear()
for letter in wordFormChars:
dispLetter = letter
# if the first character is a combining diacritic
if unicodedata.category(dispLetter[0]) == 'Mn':
# then prepend the dotted circle base character
dispLetter = '\u25CC' + dispLetter
self.wordFormStore.append([dispLetter])
self.dialog.show_all()
response = self.dialog.run()
self.dialog.hide()
return (response == 1)
def on_WordBreak_doubleClick(self, widget, row, col):
'''Shift the activated letter to the word-forming (non-break) list
Parameters: widget, row - for accessing the active row in the TreeView
'''
model = widget.get_model()
# Get the letter for this row
letter = model[row][0]
# remove this letter from the breaking list and add it to the forming list
self.wordBreakStore.remove(model[row].iter)
self.wordFormStore.append([letter])
# make sure it is selected and visible
for row in self.wordFormStore:
if row[0] == letter:
self.wordFormTreeView.get_selection().select_path(row.path)
self.wordFormTreeView.scroll_to_cell(row.path)
break
def on_WordForm_doubleClick(self, widget, row, col):
'''Shift the activated letter to the word-breaking list
Parameters: widget, row - for accessing the active row in the TreeView
'''
model = widget.get_model()
# Get the letter for this row
letter = model[row][0]
# remove this letter from the forming list and add it to the breaking list
self.wordFormStore.remove(model[row].iter)
self.wordBreakStore.append([letter])
# make sure it is selected and visible
for row in self.wordBreakStore:
if row[0] == letter:
self.wordBreakTreeView.get_selection().select_path(row.path)
self.wordBreakTreeView.scroll_to_cell(row.path)
break
def GetWordBreakChars(self):
chars = []
for row in self.wordBreakStore:
letter = row[0]
if letter[0] == '\u25CC':
# remove dotted circle base before a combining diacritic
letter = letter[1:]
chars.append(letter)
return chars
def GetWordFormChars(self):
chars = []
for row in self.wordFormStore:
letter = row[0]
if letter[0] == '\u25CC':
# remove dotted circle base before a combining diacritic
letter = letter[1:]
chars.append(letter)
return chars
class DigraphsDialog:
'''A class used to present a dialog for specifying the digraphs in the language.
Attributes:
dialog (Dialog object) - dialog for entering diagraphs (and multigraphs)
textview (TextView object) - text field where user types/edits digraph list
'''
def __init__(self):
'''Prepare dialog for defining digraphs, for running later.'''
global myGlobalBuilder
global myGlobalRenderer
# keep track of some builder UI objects
self.dialog = myGlobalBuilder.get_object('digraphsDialog')
self.textview = myGlobalBuilder.get_object('digraphsDialogTextView')
# set up the textview to use the vernacular font
self.textview.get_style_context().add_class("vernacular")
# monitor keypresses so we can close the dialog on Enter
self.textview.connect('key-press-event', self.on_keyPress)
def Run(self):
self.textview.grab_focus()
self.textview.get_buffer().place_cursor(self.textview.get_buffer().get_end_iter())
response = self.dialog.run()
# don't hide the dialog yet, as we run it until valid or cancel
#self.dialog.hide()
return (response == 1)
def SetDigraphs(self, digraphs):
# put the digraph list into the textview
buf = self.textview.get_buffer()
buf.set_text(' '.join(digraphs))
def GetDigraphs(self):
# get the digraph list (as text) from the textview
buf = self.textview.get_buffer()
txt = buf.get_text(buf.get_start_iter(), buf.get_end_iter(), False)
return txt
def on_keyPress(self, widget, event):
if event.get_keycode()[1] == 13:
# Enter was typed, click OK
self.dialog.activate_default()
return True
return False
class WordEditDialog:
'''WordEditDialog - class to create and run a dialog to edit word info.
Creating an instance of this class creates a dialog which presents
a concordance view of the given data. Each line of the data should contain
2 tabs, separating the data into 3 columns: prefix, item, postfix. In this
way the item being concorded can be aligned in the middle column. A label is
also passed in the __init__ method, so that information on what is being
concorded can be displayed.
Attributes:
dialog (Dialog object) - dialog for displaying the concordance
excludeWord (CheckButton object) - checked if the word should be excluded
divideView (TextView object) - text field where user edits word divisions
concordanceListStore (ListStore object) - list that holds the concordance
'''
def __init__(self):
'''Prepare dialog for editing individual words, for running later.'''
global myGlobalBuilder
global myGlobalRenderer
# keep track of some builder UI objects
self.dialog = myGlobalBuilder.get_object("wordEditDialog")
self.excludeWord = myGlobalBuilder.get_object("excludeWordCheckButton")
self.divideView = myGlobalBuilder.get_object("divideWordTextView")
self.divideBuffer = myGlobalBuilder.get_object("divideWordTextBuffer")
self.concordanceListStore = myGlobalBuilder.get_object("concordanceListStore")
# set up the textview to use the vernacular font
self.divideView.get_style_context().add_class("vernacular")
# monitor clicks of the exclude CheckButton
self.excludeWord.connect("clicked", self.on_ExcludeWord_click)
# monitor keypresses so we can close the dialog on Enter
self.divideView.connect('key-press-event', self.on_keyPress)
def Run(self, word, affix_word, wordExcluded, data):
'''Run dialog for editing a word and displaying a concordance.
Parameters: word (str) - word to edit (no formatting)
affix_word (str) - word with affixes marked, e.g. re- work -ing
wordExcluded (bool) - set if the word was marked as excluded
data (str) - multiline string of prefix \t item \t postfix
'''
global myGlobalRenderer
global myGlobalBuilder
global myGlobalWindow
# make sure TreeView columns are using current font
myGlobalBuilder.get_object('wordConcordPreCellRenderer').set_property('font-desc', myGlobalRenderer.vernFontDesc)
myGlobalBuilder.get_object('wordConcordWordCellRenderer').set_property('font-desc', myGlobalRenderer.vernFontDesc)
myGlobalBuilder.get_object('wordConcordPostCellRenderer').set_property('font-desc', myGlobalRenderer.vernFontDesc)
label = '<b>' + _("Indicate how you want to analyze the word: '{}'").format(word) + '</b>'
myGlobalBuilder.get_object('wordEditDialogLabel').set_markup(label)
self.excludeWord.set_active(wordExcluded)
self.divideBuffer.set_text(affix_word)
self.concordanceListStore.clear()
if len(data) > 0:
# we will need the data split into lines
lines = re.split('\n', data)
# create the label with the number of occurrences
label = _("Concordance of the word: <b>{}</b>").format(word)
if myGlobalWindow.isRTL:
label += '\u200f'
label += _(" ({} occurrences)").format(len(lines))
myGlobalBuilder.get_object('wordConcordanceLabel').set_markup(label)
# populate the list store with the concordance data
for line in lines:
preword, word, postword = re.split('\t', line)
self.concordanceListStore.append([preword, word, postword])
# make sure concordance is scrolled to the top
myGlobalBuilder.get_object('wordEditScrolledWindow').get_vadjustment().set_value(0)
response = self.dialog.run()
# don't hide the dialog yet, as we run it until valid or cancel
#self.dialog.hide()
return (response == 1)
def on_ExcludeWord_click(self, button):
'''Toggle the check box for excluding the word.
Parameters: button (unused)
'''
self.divideView.set_editable(not self.excludeWord.get_active())
self.divideView.set_cursor_visible(not self.excludeWord.get_active())
self.divideView.set_opacity(1.0 - float(self.excludeWord.get_active()) / 2)
def on_keyPress(self, widget, event):
if event.get_keycode()[1] == 13:
# Enter was typed, click OK
self.dialog.activate_default()
return True
return False
class ConfigureSFMDialog:
'''A dialog class used collect user preferences for handling SFM files.
Attributes:
dialog (Dialog object) - dialog for managing SFM handling preferences
btnProcessSFMs (RadioButton object) - tells us to process SFMs
btnIgnoreSFMs (RadioButton object) - tells us to ignore certain SFMs
textIgnoreSFMs (Entry object) - text field of SFMs to ignore
btnOnlySFMs (RadioButton object) - tells us to only process certain SFMs
textOnlySFMs (Entry object) - text field of only SFMs to process
btnDontProcessSFMs (RadioButton object) - tells us to ignore SFMs
'''
def __init__(self):
global myGlobalBuilder
# keep track of some builder UI objects
self.dialog = myGlobalBuilder.get_object('configureSFMDialog')
self.textview = myGlobalBuilder.get_object('configureSFMTextView')
self.textbuffer = myGlobalBuilder.get_object('configureSFMTextBuffer')
self.removeButton = myGlobalBuilder.get_object("configureSFMRemoveButton")
self.ignoreButton = myGlobalBuilder.get_object("configureSFMIgnoreButton")
self.processButton = myGlobalBuilder.get_object("configureSFMProcessButton")
self.ignoreEntry = myGlobalBuilder.get_object("configureSFMIgnoreEntry")
self.processEntry = myGlobalBuilder.get_object("configureSFMProcessEntry")
# set up the textview to use the vernacular font
self.textview.get_style_context().add_class("vernacular")
def Run(self, introText, initIgnoreLines, initProcessLines):
self.textbuffer.set_text(introText)
self.ignoreEntry.set_text(initIgnoreLines)
self.processEntry.set_text(initProcessLines)
self.dialog.run()
self.dialog.hide()
class ConcordanceDialog:
'''A class to create and run a dialog to show a concordance.
Creating an instance of this class creates and runs a dialog which presents
a concordance view of the given data. Each line of the data should contain
2 tabs, separating the data into 3 columns: prefix, item, postfix. In this
way the item being concorded can be aligned in the middle column. A label is
also passed in the __init__ method, so that information on what is being
concorded can be displayed.
Attributes:
dialog (Dialog object) - dialog for displaying the concordance
'''
def __init__(self):
global myGlobalBuilder
# keep track of some builder UI objects
self.dialog = myGlobalBuilder.get_object('concordanceDialog')
def Run(self, letter, data):
'''Run a concordance dialog to display the given data.
Parameters: letter (str) - letter in the teaching order for the concordance
data (str) - multiline string of prefix \t item \t postfix
'''
global myGlobalBuilder
global myGlobalRenderer
# make sure TreeView columns are using current font
myGlobalBuilder.get_object('concordancePreCellRendererText').set_property('font-desc', myGlobalRenderer.vernFontDesc)
myGlobalBuilder.get_object('concordanceWordCellRendererText').set_property('font-desc', myGlobalRenderer.vernFontDesc)
myGlobalBuilder.get_object('concordancePostCellRendererText').set_property('font-desc', myGlobalRenderer.vernFontDesc)
# we will need the data split into lines
lines = re.split('\n', data)
# create the label with the number of occurrences
label = _("Text fragments available (from your loaded texts) in the lesson for '{}'").format(letter)
if myGlobalWindow.isRTL:
label += '\u200f'
label += _(" ({} occurrences)").format(len(lines))
myGlobalBuilder.get_object('concordanceDialogLabel').set_text(label)
# populate the list store with the data parameter
listStore = myGlobalBuilder.get_object("concordanceListStore")
listStore.clear()
for line in lines:
preword, word, postword = re.split('\t', line)
listStore.append([preword, word, postword])
# make sure concordance is scrolled to the top
myGlobalBuilder.get_object('concordanceScrolledWindow').get_vadjustment().set_value(0)
self.dialog.run()
self.dialog.hide()
class SightWordsDialog:
'''A class used to present a dialog for specifying sight words.
Attributes:
dialog (Dialog object) - dialog for managing sight word entry
textview (TextView object) - text field where user types/edits digraph list
'''
def __init__(self):
'''Prepare dialog for defining digraphs, for running later.'''
global myGlobalBuilder
# keep track of some builder UI objects
self.dialog = myGlobalBuilder.get_object('sightWordsDialog')
self.textview = myGlobalBuilder.get_object('sightWordsDialogTextView')
self.textbuf = myGlobalBuilder.get_object('sightWordsTextBuffer')
# set up the textview to use the vernacular font
self.textview.get_style_context().add_class("vernacular")
# monitor keypresses so we can close the dialog on Enter
self.textview.connect('key-press-event', self.on_keyPress)
def Run(self):
self.textview.grab_focus()
self.textbuf.place_cursor(self.textbuf.get_end_iter())
response = self.dialog.run()
self.dialog.hide()
return (response == 1)
def SetSightWords(self, sightWords):
buf = self.textview.get_buffer()
buf.set_text(' '.join(sightWords))
def GetSightWords(self):
# get the sight words list (as text) from the textview
buf = self.textview.get_buffer()
txt = buf.get_text(buf.get_start_iter(), buf.get_end_iter(), False)
return txt
def on_keyPress(self, widget, event):
if event.get_keycode()[1] == 13:
# Enter was typed, click OK
self.dialog.activate_default()
return True
return False
class WordAnalysis:
'''A class used to load/process/hold word analysis info
Attributes: described in the comments of the __init__ method.'''
def AddWordsFromFile(self, file):
'''Load all lines from the given text file and store them in the class
object. Consider whether file is an SFM file, and handle it properly.
Once data is loaded, send it to FindWords to add word data to object.
Parameter: file (str) - file name and path of file to check
Return value: True if the file was loaded without error
'''
# check if this is an SFM file, configure if not done yet
isSFMFile = self.CheckIfSFM(file)
# load in entire file in 'lines' list, processing SFMs as we go
lines = []
try:
f = codecs.open(file, 'r', encoding='utf-8')
firstline = True
prevLineRemoved = False
for line in f:
if firstline:
# get rid of any Unicode BOM at the beginning of the file
line = re.sub('^\ufeff', '', line)
firstline = False
if isSFMFile and not re.match(r'^\\', line) and len(lines)>0:
# no SFM on this line
if not prevLineRemoved:
# attach to previous (with SFM) line
lines[-1] = lines[-1] + ' ' + line.strip()
else:
prevLineRemoved = False
if self.sfmProcessSFMs:
# remove certain SFM markers/lines in text
if len(self.sfmIgnoreLines) > 0:
if re.match(r'\\(' + self.sfmIgnoreLines + ')( |\n)', line):
# remove entire line including text for certain SFMs
line = ''
# keep only certain SFM markers/lines in text
if len(self.sfmOnlyLines) > 0:
if not re.match(r'\\(' + self.sfmOnlyLines + ')( |\n)', line):
# this SFM is not a keeper so remove entire line including text
line = ''
line = re.sub(r'\\\w+', '', line) # remove any other SFMs
line = line.strip() # remove leading/trailing spaces
# check to see if we have anything left in the line
if len(line) > 0:
# append the line to the list of lines
lines.append(line)
else:
prevLineRemoved = True
f.close()
except Exception:
title = _("File error")
msg = _("Error. File could not be read.")
SimpleMessage(title, 'dialog-information', msg)
return False
# store the file name/path, and all the lines in the file
self.fileNames.append(file)
self.fileLines.append(lines)
# process the lines to find the characters and words
self.FindChars(lines)
self.FindWords(lines)
return True
def CheckIfSFM(self, file):
'''Check if the file is an SFM file, and configure appropriately.
Parameter: file (str) - file name and path of file to check
Return value: True if the file is an SFM file
'''
global myGlobalWindow
# assume we won't process SFMs
self.sfmProcessSFMs = False
try:
f = codecs.open(file, 'r', encoding='utf-8')
combinedLines = ""
line = f.readline()
# get rid of BOM from beginning of file, if present
line = re.sub('^\ufeff', '', line)
countSFMs = 0
markers = []
for i in range(10):
combinedLines = combinedLines + line[0:40]
if combinedLines[-1] != "\n":
# we only got part of the line, so put in ellipsis and end of line
if combinedLines[-1] != "\r":
# put in ellipsis except special case where we got \r of \r\n
combinedLines = combinedLines + '...'
combinedLines = combinedLines + '\n'
m = re.match(r'\\(\w*) ', line)
if m:
# line begins with backslash so we assume it is an SFM; count it
countSFMs = countSFMs + 1
markers.append(m.group(1))
# get the next line; if file is short, resulting empty string should be OK
line = f.readline()
f.close()
except Exception:
return False
# remove newline from the end
combinedLines = combinedLines[:-1]
# consider the file an SFM file if it has at least 4 lines that start with '\'
if countSFMs > 4:
isSFMFile = True
else:
isSFMFile = False
# We used to only configure once, but it might be a different kind of SFM file (Scripture vs lexicon)
# so run configuration every time we find an SFM file
if isSFMFile:
# this is an SFM file
if 'lx' in markers:
self.sfmIgnoreLines = ''
self.sfmProcessLines = 'lx|pdv|xv'
myGlobalWindow.theConfigureSFMDialog.removeButton.set_active(True)
myGlobalWindow.theConfigureSFMDialog.processButton.set_active(True)
elif 'h' in markers or 'toc1' in markers or 'mt1' in markers:
self.sfmIgnoreLines = 'id|rem|restore|h|toc1|toc2|toc3'
self.sfmProcessLines = ''
myGlobalWindow.theConfigureSFMDialog.removeButton.set_active(True)
myGlobalWindow.theConfigureSFMDialog.ignoreButton.set_active(True)
# run the dialog
initIgnoreLines = self.sfmIgnoreLines.replace('|',' ')
initProcessLines = self.sfmProcessLines.replace('|', ' ')
myGlobalWindow.theConfigureSFMDialog.Run(combinedLines, initIgnoreLines, initProcessLines)
self.sfmProcessSFMs = myGlobalWindow.theConfigureSFMDialog.removeButton.get_active()
if self.sfmProcessSFMs:
# user chose to remove SFMs
if myGlobalWindow.theConfigureSFMDialog.ignoreButton.get_active():
# user chose to ignore certain SFMs, keep the list
text = myGlobalWindow.theConfigureSFMDialog.ignoreEntry.get_text()
text = text.strip()
markers = re.split(r'\s+', text)
self.sfmIgnoreLines = '|'.join(markers)
self.sfmOnlyLines = ''
else:
# user chose to only process certain SFMs, keep the list
text = myGlobalWindow.theConfigureSFMDialog.processEntry.get_text()
text = text.strip()
markers = re.split(r'\s+', text)
self.sfmOnlyLines = '|'.join(markers)
self.sfmIgnoreLines = ''
return isSFMFile
def FindChars(self, lines):
'''Takes a list of lines and for each line, check each character
(making sure to combine diacritics or not) and record it as
word forming or word breakinng.
Parameter: lines (list of str) - lines of text to be analyzed
'''
# build a RegExp that can split out individual characters
# built outside loop because it is the same for every line
# make sure to attach any zero width joiners (ZWJs U+200d)
# but remove Word Joiners (WJs U+2060) - they are there to ensure
# that the ZWJs get attached to the right character
if self.separateCombDiacritics:
# RegExp that treats combining diacritics separately
findChars = re.compile(r'(\u200d?.(?<!\u2060)\u200d?)')
else:
# RegExp that includes combining diacritics with their preceding base characters
findChars = re.compile(r'(\u200d?.(?:[\u0300-\u036f]+)?(?<!\u2060)\u200d?)')
# make sure we have identified all characters in the file
for line in lines:
# check all characters in line and if not seen before, add it
# to word forming or breaking list (based on unicodedata.category)
for char in re.findall(findChars, line):
if ord(char[-1]) in range(0x300, 0x36f):
# last character is a combining diacritic
# get base character
ch = char[0]
if ch == '\u200d':
# skip over ZWJ, if present
ch = char[1]
if unicodedata.category(ch)[0] not in 'LM':
# base is not a letter or a mark
# just ignore it for building the character list
# this addresses problems like when the base character is '-' or ']', messing up regexes
char = ' '
if char not in self.chars:
# this char has not been seen yet, mark as seen
self.chars[char] = 1
ch = char[0]
if ch == '\u200d':
# if it's a ZWJ, get the next letter
ch = char[1]
# add to either word forming/breaking character list
if unicodedata.category(ch)[0] in 'LM':
# only letters or combining marks
self.wordFormChars.append(char)
else:
# this would include punctuation, symbols, spaces, control codes
self.wordBreakChars.append(char)
def FindWords(self, lines):
'''Takes a list of lines and for each line, break it into words which
are added into the words dictionary (which keeps a frequency count).
Also do auto-search for digraphs in each word.
Parameter: lines (list of str) - lines of text to be analyzed
'''
# build 'breaks' string with all word breaking characters for RegExp splitting
breaks = ''
for char in self.wordBreakChars:
# need to put '\' before special characters
if char in '.^$*+-?{}\\[]|()':
breaks = breaks + '\\'
breaks = breaks + char
kWordCnt = 0
kWordManual = 1
kWordExclude = 2
kWordAffixForm = 3
kWordMarkupForm = 4
# process each line individually
for line in lines:
# make list of words split by spaces, punctuation, other word break chars
linewords = re.split('[\\s' + breaks + ']+', line)
for word in linewords:
#logger.debug('"', repr(word), '"')
if (len(word) == 0) or re.match(r'^[-\d]+$', word):
# this word is empty or just numbers/hyphens, skip to next word