forked from Freely-Given-org/BibleOrgSys
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BibleOrgSysGlobals.py
executable file
·1456 lines (1241 loc) · 65.4 KB
/
BibleOrgSysGlobals.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# BibleOrgSysGlobals.py
#
# Module handling Global variables for our Bible Organisational System
#
# Copyright (C) 2010-2019 Robert Hunt
# Author: Robert Hunt <Freely.Given.org@gmail.com>
# License: See gpl-3.0.txt
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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, see <http://www.gnu.org/licenses/>.
"""
Module handling global variables
and some useful general functions.
Contains functions:
setupLoggingToFile( ProgName, ProgVersion, loggingFolderPath=None )
addConsoleLogging()
addLogfile( projectName, folderName=None )
removeLogfile( projectHandler )
findHomeFolderPath()
findUsername()
getLatestPythonModificationDate()
makeSafeFilename( someName )
makeSafeXML( someString )
makeSafeString( someString )
removeAccents( someString )
backupAnyExistingFile( filenameOrFilepath, numBackups=1 )
peekIntoFile( filenameOrFilepath, folderName=None, numLines=1 )
totalSize( obj, handlers={} )
fileCompare( filename1, filename2, folder1=None, folder2=None, printFlag=True, exitCount=10 )
fileCompareUSFM( filename1, filename2, folder1=None, folder2=None, printFlag=True, exitCount=10 )
fileCompareXML( filename1, filename2, folder1=None, folder2=None, printFlag=True, exitCount=10, ignoreWhitespace=True )
elementStr( element )
checkXMLNoAttributes( element, locationString, idString=None )
checkXMLNoText( element, locationString, idString=None )
checkXMLNoTail( element, locationString, idString=None )
checkXMLNoSubelements( element, locationString, idString=None )
checkXMLNoSubelementsWithText( element, locationString, idString=None )
getFlattenedXML( element, locationString, idString=None, level=0 )
isBlank( elementText )
applyStringAdjustments( originalText, adjustmentList )
stripWordPunctuation( wordToken )
pickleObject( theObject, filename, folderName=None )
unpickleObject( filename, folderName=None )
setup( ProgName, ProgVersion, loggingFolder=None )
setVerbosity( verbosityLevelParameter )
setDebugFlag( newValue=True )
setStrictCheckingFlag( newValue=True )
addStandardOptionsAndProcess( parserObject )
printAllGlobals( indent=None )
closedown( ProgName, ProgVersion )
demo()
"""
from gettext import gettext as _
LastModifiedDate = '2019-05-12' # by RJH
ShortProgName = "BOSGlobals"
ProgName = "BibleOrgSys Globals"
ProgVersion = '0.81'
ProgNameVersion = '{} v{}'.format( ShortProgName, ProgVersion )
ProgNameVersionDate = '{} {} {}'.format( ProgNameVersion, _("last modified"), LastModifiedDate )
debuggingThisModule = False
haltOnXMLWarning = False # Used for XML debugging
import sys, logging, os.path, pickle
from datetime import datetime
import unicodedata
from argparse import ArgumentParser
try: import pwd
except ImportError:
pwd = None
import getpass
# Global variables
#=================
programStartTime = datetime.now()
DOWNLOADED_RESOURCES_FOLDER = '../BibleOrgSys/DownloadedResources/'
# TODO: Should be https as soon as supported by the site
DISTRIBUTABLE_RESOURCES_URL = 'http://Freely-Given.org/Software/BibleOrganisationalSystem/DistributableResources/'
commandLineArguments = None
strictCheckingFlag = debugFlag = False
maxProcesses = 1
alreadyMultiprocessing = False # Not used in this module, but set to prevent multiple levels of multiprocessing (illegal)
verbosityLevel = None
verbosityString = 'Normal'
DEFAULT_LOG_FOLDER = 'Logs/' # Relative path
DEFAULT_CACHE_FOLDER = 'ObjectCache/' # Relative path
DEFAULT_OUTPUT_FOLDER = 'OutputFiles/' # Relative path
COMMONLY_IGNORED_FOLDERS = '.hg/', '.git/', '__MACOSX' # Used when searching for Bibles
if debuggingThisModule:
LOGGING_NAME_DICT = {logging.DEBUG:'DEBUG', logging.INFO:'INFO', logging.WARNING:'WARNING', logging.ERROR:'ERROR', logging.CRITICAL:'CRITICAL'}
# Some language independant punctuation help
OPENING_SPEECH_CHARACTERS = """“«"‘‹¿¡""" # The length and order of these two strings must match
CLOSING_SPEECH_CHARACTERS = """”»"’›?!"""
MATCHING_OPENING_CHARACTERS = {'(':')', '[':']', '{':'}', '<':'>', '<<':'>>', '“':'”', '‘':'‘', '«':'»', '‹':'›', '¿':'?', '¡':'!', }
MATCHING_CLOSING_CHARACTERS = {')':'(', ']':'[', '}':'{', '>':'<', '>>':'<<', '”':'“', '‘':'‘', '»':'«', '›':'‹', '?':'¿', '!':'¡', }
MATCHING_CHARACTERS = {'(':')',')':'(', '[':']',']':'[', '{':'}','}':'{', '<':'>','>':'<', '<<':'>>','>>':'<<',
'“':'”','”':'“', '‘':'’','’':'‘', '«':'»','»':'«', '‹':'›','›':'‹', '¿':'?','?':'¿', '¡':'!','!':'¡', }
LEADING_WORD_PUNCT_CHARS = """“«„"‘¿¡‹'([{<"""
MEDIAL_WORD_PUNCT_CHARS = '-'
DASH_CHARS = '–—' # en-dash and em-dash
TRAILING_WORD_PUNCT_CHARS = """,.”»"’›'?)!;:]}>…"""
TRAILING_WORD_END_CHARS = ' ' + TRAILING_WORD_PUNCT_CHARS
ALL_WORD_PUNCT_CHARS = LEADING_WORD_PUNCT_CHARS + MEDIAL_WORD_PUNCT_CHARS + DASH_CHARS + TRAILING_WORD_PUNCT_CHARS
MAX_NESTED_QUOTE_LEVELS = 5
if debuggingThisModule:
assert len(OPENING_SPEECH_CHARACTERS) == len(CLOSING_SPEECH_CHARACTERS)
assert len(MATCHING_OPENING_CHARACTERS) == len(MATCHING_CLOSING_CHARACTERS)
assert len(MATCHING_OPENING_CHARACTERS) + len(MATCHING_CLOSING_CHARACTERS) == len(MATCHING_CHARACTERS)
for char in OPENING_SPEECH_CHARACTERS: assert char in LEADING_WORD_PUNCT_CHARS
for char in CLOSING_SPEECH_CHARACTERS: assert char in TRAILING_WORD_PUNCT_CHARS
##import unicodedata
#BibleOrgSysGlobals.printUnicodeInfo( LEADING_WORD_PUNCT_CHARS, "LEADING_WORD_PUNCT_CHARS" )
#BibleOrgSysGlobals.printUnicodeInfo( TRAILING_WORD_PUNCT_CHARS, "TRAILING_WORD_PUNCT_CHARS" )
##########################################################################################################
#
# Handling logging
#
#def function_with_a_bug(params):
# """Just sitting here to remind me how to do it"""
# old_log_level = logging.getLogger().getEffectiveLevel()
# logging.getLogger().setLevel( logging.DEBUG )
# logging.debug( "Entering function_with_a_bug" )
# logging.debug( "Params were {}", params )
# for item in params:
# logging.debug( "Processing {}", item )
# result = do_something_with( item )
# logging.debug( "Result was: {}", result )
# logging.getLogger().setLevel( old_log_level )
## end of function_with_a_bug
loggingDateFormat = "%Y-%m-%d %H:%M"
loggingConsoleFormat = '%(levelname)s: %(message)s'
loggingShortFormat = '%(levelname)8s: %(message)s'
loggingLongFormat = '%(asctime)s %(levelname)8s: %(message)s'
def setupLoggingToFile( ShortProgName, ProgVersion, folderPath=None ):
"""
Sets up the main logfile for the program and returns the full pathname.
Gets called from our demo() function when program starts up.
"""
if debuggingThisModule:
print( "BibleOrgSysGlobals.setupLoggingToFile( {!r}, {!r}, {!r} )".format( ShortProgName, ProgVersion, folderPath ) )
filename = ShortProgName.replace('/','-').replace(':','_').replace('\\','_') + '_log.txt'
if folderPath is None: folderPath = DEFAULT_LOG_FOLDER # relative path
filepath = os.path.join( folderPath, filename )
# Create the folderPath if necessary
if not os.access( folderPath, os.W_OK ):
os.makedirs( folderPath ) # Works for an absolute or a relative pathname
# Rename the existing file to a backup copy if it already exists
backupAnyExistingFile( filepath, numBackups=4 )
#if os.access( filepath, os.F_OK ):
#if debuggingThisModule or __name__ == '__main__':
#print( "setupLoggingToFile: {!r} already exists -- renaming it first!".format( filepath ) )
#if os.access( filepath+'.bak', os.F_OK ):
#os.remove( filepath+'.bak' )
#os.rename( filepath, filepath+'.bak' )
# Now setup our new log file -- DOESN'T SEEM TO WORK IN WINDOWS!!!
# In Windows, doesn't seem to create the log file, even if given a filename rather than a filepath
setLevel = logging.DEBUG if debugFlag else logging.INFO
if debuggingThisModule:
print( "BibleOrgSysGlobals.setBasicConfig to( {!r}, {}={}, {!r}, {!r} )".format( filepath, setLevel, LOGGING_NAME_DICT[setLevel], loggingLongFormat, loggingDateFormat ) )
# NOTE: This call to basicConfig MUST occur BEFORE any modules make any logging calls
# i.e., be careful of putting executable calls at module level that might log at module load time
logging.basicConfig( filename=filepath, level=setLevel, format=loggingLongFormat, datefmt=loggingDateFormat )
#return filepath
# end of BibleOrgSysGlobals.setupLoggingToFile
def addConsoleLogging( consoleLoggingLevel=None ):
"""
Adds a handler to also send ERROR and higher to console (depending on verbosity)
"""
if debuggingThisModule:
print( "BibleOrgSysGlobals.addConsoleLogging( {}={} )".format( consoleLoggingLevel, LOGGING_NAME_DICT[consoleLoggingLevel] ) )
stderrHandler = logging.StreamHandler() # StreamHandler with no parameters defaults to sys.stderr
stderrHandler.setFormatter( logging.Formatter( loggingConsoleFormat, None ) )
if consoleLoggingLevel is None: # work it out for ourselves
if verbosityLevel == 0: # Silent
consoleLoggingLevel = logging.CRITICAL
elif verbosityLevel == 4: # Verbose
consoleLoggingLevel = logging.WARNING
else: # Quiet or normal
consoleLoggingLevel = logging.ERROR
if debuggingThisModule:
print( " addConsoleLogging setting it to {}={}".format( consoleLoggingLevel, LOGGING_NAME_DICT[consoleLoggingLevel] ) )
stderrHandler.setLevel( consoleLoggingLevel )
root = logging.getLogger() # No param means get the root logger
root.addHandler(stderrHandler)
# end of BibleOrgSysGlobals.addConsoleLogging
def addLogfile( projectName, folderName=None ):
"""
Adds an extra project specific log file to the logger.
"""
if debuggingThisModule:
print( "BibleOrgSysGlobals.addLogfile( {}, {} )".format( projectName, folderName ) )
filename = projectName + '_log.txt'
if folderName is None: folderName = DEFAULT_LOG_FOLDER # relative path
filepath = os.path.join( folderName, filename )
# Create the folderName if necessary
if not os.access( folderName, os.W_OK ):
os.makedirs( folderName ) # Works for an absolute or a relative pathname
# Rename the existing file to a backup copy if it already exists
backupAnyExistingFile( filepath, numBackups=4 )
#if os.access( filepath, os.F_OK ):
#if __name__ == '__main__':
#print( filepath, 'already exists -- renaming it first!' )
#if os.access( filepath+'.bak', os.F_OK ):
#os.remove( filepath+'.bak' )
#os.rename( filepath, filepath+'.bak' )
projectHandler = logging.FileHandler( filepath )
projectHandler.setFormatter( logging.Formatter( loggingShortFormat, loggingDateFormat ) )
projectHandler.setLevel( logging.INFO )
root = logging.getLogger()
root.addHandler( projectHandler )
return filepath, projectHandler
# end of BibleOrgSysGlobals.addLogfile
def removeLogfile( projectHandler ):
"""
Removes the project specific logger.
"""
if debuggingThisModule:
print( "BibleOrgSysGlobals.removeLogfile( {} )".format( projectHandler ) )
root = logging.getLogger() # No param means get the root logger
root.removeHandler( projectHandler )
# end of BibleOrgSysGlobals.removeLogfile
##########################################################################################################
#
def findHomeFolderPath():
"""
Attempt to find the path to the user's home folder and return it.
"""
possibleHomeFolders = ( os.path.expanduser('~'), os.getcwd(), os.curdir, os.pardir )
if debugFlag and debuggingThisModule:
print( "possible home folders", possibleHomeFolders )
for folder in possibleHomeFolders:
if os.path.isdir( folder ) and os.access( folder, os.W_OK ):
return folder
# end of BibleOrgSysGlobals.findHomeFolderPath
def findUsername():
"""
Attempt to find the current user name and return it.
"""
if pwd:
return pwd.getpwuid(os.geteuid()).pw_name
else:
return getpass.getuser()
# end of BibleOrgSysGlobals.findUsername
##########################################################################################################
#
def getLatestPythonModificationDate():
"""
Goes through the .py files in the current folder
and tries to find the latest modification date.
"""
if debugFlag and debuggingThisModule: print( "getLatestPythonModificationDate()…" )
#collectedFilepaths = []
latestYYYY, latestMM, latestDD = 1999, 0, 0
for filepath in os.listdir( '.' ):
#filepath = os.path.join( '.', filename )
if filepath.endswith( '.py' ):
with open( filepath, 'rt', encoding='utf-8' ) as pythonFile:
for line in pythonFile:
if line.startswith( 'LastModifiedDate = ' ):
#print( filepath, line )
#print( filepath )
lineBit = line[19:]
if '#' in lineBit: lineBit = lineBit.split('#',1)[0]
if lineBit[-1]=='\n': lineBit = lineBit[:-1] # Removing trailing newline character
lineBit = lineBit.replace("'",'').replace('"','').strip()
#print( ' {!r}'.format( lineBit ) )
lineBits = lineBit.split( '-' )
assert len(lineBits) == 3 # YYYY MM DD
YYYY, MM, DD = int(lineBits[0]), int(lineBits[1]), int(lineBits[2])
#print( ' ', YYYY, MM, DD )
if YYYY > latestYYYY:
latestYYYY, latestMM, latestDD = YYYY, MM, DD
#collectedFilepaths.append( (filepath,lineBit) )
elif YYYY==latestYYYY and MM>latestMM:
latestMM, latestDD = MM, DD
#collectedFilepaths.append( (filepath,lineBit) )
elif YYYY==latestYYYY and MM==latestMM and DD>latestDD:
latestDD = DD
#collectedFilepaths.append( (filepath,lineBit) )
break
#print( latestYYYY, latestMM, latestDD, collectedFilepaths )
return '{}-{:02}-{:02}'.format( latestYYYY, latestMM, latestDD )
# end of BibleOrgSysGlobals.getLatestPythonModificationDate
##########################################################################################################
#
def printUnicodeInfo( text, description ):
"""
"""
print( "{}:".format( description ) )
for j,char in enumerate(text):
print( "{:2} {:04x} {} {!r} (cat={} bid={} comb={} mirr={})" \
.format(j, ord(char), unicodedata.name(char), char, unicodedata.category(char), unicodedata.bidirectional(char), unicodedata.combining(char), unicodedata.mirrored(char) ) )
##########################################################################################################
#
# Make a string safe if it's going to be used as a filename
#
# We don't want a malicious user to be able to gain access to the filesystem
# by putting a filepath into a filename string.
def makeSafeFilename( someName ):
"""
Replaces potentially unsafe characters in a name to make it suitable for a filename.
NOTE: This leaves spaces as they were.
"""
return someName.replace('/','-') \
.replace('\\','_BACKSLASH_').replace(':','_COLON_').replace(';','_SEMICOLON_') \
.replace('#','_HASH_').replace('?','_QUESTIONMARK_').replace('*','_ASTERISK_') \
.replace('<','_LT_').replace('>','_GT_')
# end of BibleOrgSysGlobals.makeSafeFilename
##########################################################################################################
#
# Make a string safe if it could be used in an XML document
#
def makeSafeXML( someString ):
"""
Replaces special characters in a string to make it for XML.
"""
return someString.replace('&','&').replace('"','"').replace('<','<').replace('>','>')
# end of BibleOrgSysGlobals.makeSafeXML
##########################################################################################################
#
# Make a string safe if it could be used in an HTML or other document
#
# We don't want a malicious user to be able to gain access to the system
# by putting system commands into a string that's then used in a webpage or something.
def makeSafeString( someString ):
"""
Replaces potentially unsafe characters in a string to make it safe for display.
"""
#return someString.replace('&','&').replace('<','<').replace('>','>')
return someString.replace('<','_LT_').replace('>','_GT_')
# end of BibleOrgSysGlobals.makeSafeString
##########################################################################################################
#
# Remove accents
ACCENT_DICT = { 'À':'A','Á':'A','Â':'A','Ã':'A','Ä':'A','Å':'A','Ă':'A','Ą':'A', 'Æ':'AE',
'Ç':'C','Ć':'C','Ĉ':'C','Ċ':'C','Č':'C',
'Ð':'D','Ď':'D','Đ':'D',
'È':'E','É':'E','Ê':'E','Ë':'E','Ē':'E','Ĕ':'E','Ė':'E','Ę':'E','Ě':'E',
'Ĝ':'G','Ğ':'G','Ġ':'G','Ģ':'G',
'Ì':'I','Í':'I','Î':'I','Ï':'I',
'Ñ':'N',
'Ò':'O','Ó':'O','Ô':'O','Õ':'O','Ö':'O','Ø':'O',
'Ù':'U','Ú':'U','Û':'U','Ü':'U',
'Ý':'Y',
'à':'a','á':'a','â':'a','ã':'a','ä':'a','å':'a','ā':'a','ă':'a','ą':'a', 'æ':'ae',
'ç':'c','ć':'c','ĉ':'c','ċ':'c','č':'c',
'ð':'d','ď':'d','đ':'d',
'è':'e','é':'e','ê':'e','ë':'e','ē':'e','ĕ':'e','ė':'e','ę':'e','ě':'e',
'ģ':'g','ğ':'g','ġ':'g',
'ì':'i','í':'i','î':'i','ï':'i',
'ñ':'n',
'ò':'o','ó':'o','ô':'o','õ':'o','ö':'o','ø':'o',
'ù':'u','ú':'u','û':'u','ü':'u',
'ý':'y','ÿ':'y',
}
def removeAccents( someString ):
"""
Remove accents from the string and return it (used for fuzzy matching)
Not that this doesn't remove Hebrew vowel pointing.
"""
# Try 1
#return unicodedata.normalize('NFKD', someString).encode('ASCII', 'ignore')
# Try 2
#resultString = ''
#for someChar in someString:
#desc = unicodedata.name( someChar )
#cutoff = desc.find( ' WITH ' )
##if cutoff != -1:
##desc = desc[:cutoff]
#resultString += someChar if cutoff==-1 else unicodedata.lookup( desc[:cutoff] )
#return resultString
# The next two use our ACCENT_DICT above
# Try 3
#resultString = ''
#for someChar in someString:
#resultString += ACCENT_DICT[someChar] if someChar in ACCENT_DICT else someChar
#return resultString
# Try 4
return ''.join( ACCENT_DICT[someChar] if someChar in ACCENT_DICT else someChar for someChar in someString )
# end of BibleOrgSysGlobals.makeSafeString
##########################################################################################################
#
# Make a backup copy of a file that's about to be written by renaming it
# Note that this effectively "deletes" the file.
def backupAnyExistingFile( filenameOrFilepath, numBackups=1, extension='bak' ):
"""
Make a backup copy/copies of a file if it exists.
"""
if debugFlag and debuggingThisModule:
print( "backupAnyExistingFile( {!r}, {}, {!r} )".format( filenameOrFilepath, numBackups, extension ) )
assert not filenameOrFilepath.lower().endswith( '.bak' )
if extension[0] != '.': extension = '.' + extension
for n in range( numBackups, 0, -1 ): # e.g., 4,3,2,1
source = filenameOrFilepath + ('' if n==1 else (extension + ('' if n<3 else str(n-1))))
destination = filenameOrFilepath + extension + ('' if n==1 else str(n))
if os.access( source, os.F_OK ):
if n==1 and debugFlag:
logging.info( "backupAnyExistingFile: {!r} already exists -- renaming it first!".format( source ) )
if os.access( destination, os.F_OK ): os.remove( destination )
os.rename( source, destination )
# end of BibleOrgSysGlobals.backupAnyExistingFile
##########################################################################################################
#
# Peek at the first line(s) of a file
#
# If one line is requested, returns the line (string)
# Otherwise, returns a list of lines
def peekIntoFile( filenameOrFilepath, folderName=None, numLines=1, encoding=None ):
"""
Reads and returns the first line of a text file as a string
unless more than one line is requested
in which case a list of strings is returned (including empty strings for empty lines).
"""
if debugFlag: assert 1 <= numLines < 5
if encoding is None: encodingList = ['utf-8', 'iso-8859-1', 'iso-8859-15',]
else: encodingList = [encoding]
filepath = os.path.join( folderName, filenameOrFilepath ) if folderName else filenameOrFilepath
for tryEncoding in encodingList:
lines = []
try:
with open( filepath, 'rt', encoding=tryEncoding ) as possibleBibleFile: # Automatically closes the file when done
lineNumber = 0
for line in possibleBibleFile:
lineNumber += 1
if line[-1]=='\n': line = line[:-1] # Removing trailing newline character
#if debuggingThisModule: print( filenameOrFilepath, lineNumber, line )
if numLines==1: return line # Always returns the first line (string)
lines.append( line )
if lineNumber >= numLines: return lines # Return a list of lines
except UnicodeDecodeError: # Could be binary or a different encoding
#if not filepath.lower().endswith( 'usfm-color.sty' ): # Seems this file isn't UTF-8, but we don't need it here anyway so ignore it
logging.warning( "{}peekIntoFile: Seems we couldn't decode Unicode in {!r}".format( 'BibleOrgSysGlobals.' if debugFlag else '', filepath ) )
# end of BibleOrgSysGlobals.peekIntoFile
##########################################################################################################
#
# For debugging, etc.
def totalSize( obj, handlers={} ):
"""
Returns the approximate memory footprint an object and all of its contents.
Automatically finds the contents of the following builtin containers and
their subclasses: tuple, list, deque, dict, set and frozenset.
To search other containers, add handlers to iterate over their contents:
handlers = {SomeContainerClass: iter,
OtherContainerClass: OtherContainerClass.get_elements}
"""
from sys import getsizeof
from itertools import chain
dict_handler = lambda d: chain.from_iterable(d.items())
all_handlers = {tuple: iter,
list: iter,
dict: dict_handler,
set: iter,
frozenset: iter,
}
all_handlers.update(handlers) # user handlers take precedence
seen = set() # track which object id's have already been seen
default_size = getsizeof(0) # estimate sizeof object without __sizeof__
def sizeof(obj):
if id(obj) in seen: # do not double count the same object
return 0
seen.add(id(obj))
s = getsizeof(obj, default_size)
if verbosityLevel > 3: print( s, type(obj), repr(obj) )
for typ, handler in all_handlers.items():
if isinstance(obj, typ):
s += sum(map(sizeof, handler(obj)))
break
return s
return sizeof(obj)
# end of BibleOrgSysGlobals.totalSize
##########################################################################################################
#
# File comparisons
#
def fileCompare( filename1, filename2, folder1=None, folder2=None, printFlag=True, exitCount=10 ):
"""
Compare the two utf-8 files.
"""
filepath1 = os.path.join( folder1, filename1 ) if folder1 else filename1
filepath2 = os.path.join( folder2, filename2 ) if folder2 else filename2
if verbosityLevel > 1:
if filename1==filename2:
print( "Comparing {!r} files in folders {!r} and {!r}…".format( filename1, folder1, folder2 ) )
else: print( "Comparing files {!r} and {!r}…".format( filename1, filename2 ) )
# Do a preliminary check on the readability of our files
if not os.access( filepath1, os.R_OK ):
logging.error( "fileCompare: File1 {!r} is unreadable".format( filepath1 ) )
return None
if not os.access( filepath2, os.R_OK ):
logging.error( "fileCompare: File2 {!r} is unreadable".format( filepath2 ) )
return None
# Read the files into lists
lineCount, lines1 = 0, []
with open( filepath1, 'rt', encoding='utf-8' ) as file1:
for line in file1:
lineCount += 1
if lineCount==1 and line[0]==chr(65279): #U+FEFF
if printFlag and verbosityLevel > 2:
print( " fileCompare: Detected Unicode Byte Order Marker (BOM) in file1" )
line = line[1:] # Remove the Unicode Byte Order Marker (BOM)
if line and line[-1]=='\n': line=line[:-1] # Removing trailing newline character
if not line: continue # Just discard blank lines
lines1.append( line )
lineCount, lines2 = 0, []
with open( filepath2, 'rt', encoding='utf-8' ) as file2:
for line in file2:
lineCount += 1
if lineCount==1 and line[0]==chr(65279): #U+FEFF
if printFlag and verbosityLevel > 2:
print( " fileCompare: Detected Unicode Byte Order Marker (BOM) in file2" )
line = line[1:] # Remove the Unicode Byte Order Marker (BOM)
if line and line[-1]=='\n': line=line[:-1] # Removing trailing newline character
if not line: continue # Just discard blank lines
lines2.append( line )
# Compare the length of the lists/files
len1, len2 = len(lines1), len(lines2 )
equalFlag = True
if len1 != len2:
if printFlag: print( "Count of lines differ: file1={}, file2={}".format( len1, len2 ) )
equalFlag = False
# Now compare the actual lines
diffCount = 0
for k in range( min( len1, len2 ) ):
if lines1[k] != lines2[k]:
if printFlag:
print( " {}a:{!r} ({} chars)\n {}b:{!r} ({} chars)" \
.format( k+1, lines1[k], len(lines1[k]), k+1, lines2[k], len(lines2[k]) ) )
equalFlag = False
diffCount += 1
if diffCount > exitCount:
if printFlag and verbosityLevel > 1:
print( "fileCompare: stopped comparing after {} mismatches".format( exitCount ) )
break
return equalFlag
# end of BibleOrgSysGlobals.fileCompare
def fileCompareUSFM( filename1, filename2, folder1=None, folder2=None, printFlag=True, exitCount=10 ):
"""
Compare the two utf-8 USFM files,
ignoring little things like \s vs \s1.
"""
filepath1 = os.path.join( folder1, filename1 ) if folder1 else filename1
filepath2 = os.path.join( folder2, filename2 ) if folder2 else filename2
if verbosityLevel > 1:
if filename1==filename2:
print( "Comparing USFM {!r} files in folders {!r} and {!r}…".format( filename1, folder1, folder2 ) )
else: print( "Comparing USFM files {!r} and {!r}…".format( filename1, filename2 ) )
# Do a preliminary check on the readability of our files
if not os.access( filepath1, os.R_OK ):
logging.error( "fileCompare: File1 {!r} is unreadable".format( filepath1 ) )
return None
if not os.access( filepath2, os.R_OK ):
logging.error( "fileCompare: File2 {!r} is unreadable".format( filepath2 ) )
return None
# Read the files into lists
lineCount, lines1 = 0, []
with open( filepath1, 'rt', encoding='utf-8' ) as file1:
for line in file1:
lineCount += 1
if lineCount==1 and line[0]==chr(65279): #U+FEFF
if printFlag and verbosityLevel > 2:
print( " fileCompare: Detected Unicode Byte Order Marker (BOM) in file1" )
line = line[1:] # Remove the Unicode Byte Order Marker (BOM)
if line and line[-1]=='\n': line=line[:-1] # Removing trailing newline character
if not line: continue # Just discard blank lines
lines1.append( line )
lineCount, lines2 = 0, []
with open( filepath2, 'rt', encoding='utf-8' ) as file2:
for line in file2:
lineCount += 1
if lineCount==1 and line[0]==chr(65279): #U+FEFF
if printFlag and verbosityLevel > 2:
print( " fileCompare: Detected Unicode Byte Order Marker (BOM) in file2" )
line = line[1:] # Remove the Unicode Byte Order Marker (BOM)
if line and line[-1]=='\n': line=line[:-1] # Removing trailing newline character
if not line: continue # Just discard blank lines
lines2.append( line )
# Compare the length of the lists/files
len1, len2 = len(lines1), len(lines2 )
equalFlag = True
if len1 != len2:
if printFlag: print( "Count of lines differ: file1={}, file2={}".format( len1, len2 ) )
equalFlag = False
# Now compare the actual lines
diffCount = 0
C, V = '-1', '-1' # So first/id line starts at -1:0
for k in range( min( len1, len2 ) ):
originalLine1, originalLine2 = lines1[k], lines2[k]
adjustedLine1, adjustedLine2 = originalLine1, originalLine2
while adjustedLine1 and adjustedLine1[-1]==' ': adjustedLine1 = adjustedLine1[:-1] # Remove the final space
while adjustedLine2 and adjustedLine2[-1]==' ': adjustedLine2 = adjustedLine2[:-1] # Remove the final space
if adjustedLine1.startswith( '\\c '): C = adjustedLine1[3:]
if adjustedLine1.startswith( '\\v '): V = adjustedLine1[3:].split()[0]
for unnumbered,numbered in ( ('mt','mt1'),('mte','mte1'), ('imt','imt1'),('imte','imte1'),
('is','is1'), ('iq','iq1'), ('io','io1'), ('ili','ili1'),
('ms','ms1'), ('s','s1'), ('li','li1'), ('q','q1'), ('pi','pi1'), ('ph','ph1'), ):
if adjustedLine1 == '\\'+unnumbered: adjustedLine1 = '\\'+numbered
else: adjustedLine1 = adjustedLine1.replace( '\\'+unnumbered+' ', '\\'+numbered+' ' )
if adjustedLine2 == '\\'+unnumbered: adjustedLine2 = '\\'+numbered
else: adjustedLine2 = adjustedLine2.replace( '\\'+unnumbered+' ', '\\'+numbered+' ' )
if adjustedLine1 != adjustedLine2:
if printFlag:
print( " {}:{} {}a:{!r} ({} chars)\n {}:{} {}b:{!r} ({} chars)" \
.format( C, V, k+1, originalLine1, len(originalLine1), C, V, k+1, originalLine2, len(originalLine1) ) )
equalFlag = False
diffCount += 1
if diffCount > exitCount:
if printFlag and verbosityLevel > 1:
print( "fileCompare: stopped comparing after {} mismatches".format( exitCount ) )
break
return equalFlag
# end of BibleOrgSysGlobals.fileCompareUSFM
def fileCompareXML( filename1, filename2, folder1=None, folder2=None, printFlag=True, exitCount=10, ignoreWhitespace=True ):
"""
Compare the two files.
"""
filepath1 = os.path.join( folder1, filename1 ) if folder1 else filename1
filepath2 = os.path.join( folder2, filename2 ) if folder2 else filename2
if verbosityLevel > 1:
if filename1==filename2: print( "Comparing XML {!r} files in folders {!r} and {!r}…".format( filename1, folder1, folder2 ) )
else: print( "Comparing XML files {!r} and {!r}…".format( filename1, filename2 ) )
# Do a preliminary check on the readability of our files
if not os.access( filepath1, os.R_OK ):
logging.error( "fileCompareXML: File1 {!r} is unreadable".format( filepath1 ) )
return None
if not os.access( filepath2, os.R_OK ):
logging.error( "fileCompareXML: File2 {!r} is unreadable".format( filepath2 ) )
return None
# Load the files
from xml.etree.ElementTree import ElementTree
tree1 = ElementTree().parse( filepath1 )
tree2 = ElementTree().parse( filepath2 )
def compareElements( element1, element2 ):
"""
"""
nonlocal diffCount, location
if element1.tag != element2.tag:
if printFlag:
print( "Element tags differ ({!r} and {!r})".format( element1.tag, element2.tag ) )
if verbosityLevel > 2: print( " at", location )
diffCount += 1
if diffCount > exitCount: return
location.append( "{}/{}".format( element1.tag, element2.tag ) )
else: location.append( element1.tag )
attribs1, attribs2 = element1.items(), element2.items()
if len(attribs1) != len(attribs2):
if printFlag:
print( "Number of attributes differ ({} and {})".format( len(attribs1), len(attribs2) ) )
if verbosityLevel > 2: print( " at", location )
diffCount += 1
if diffCount > exitCount: return
for avPair in attribs1:
if avPair not in attribs2:
if printFlag:
print( "File1 has {} but not in file2 {}".format( avPair, attribs2 ) )
if verbosityLevel > 2: print( " at", location )
diffCount += 1
if diffCount > exitCount: return
for avPair in attribs2:
if avPair not in attribs1:
if printFlag:
print( "File2 has {} but not in file1 {}".format( avPair, attribs1 ) )
if verbosityLevel > 2: print( " at", location )
diffCount += 1
if diffCount > exitCount: return
if element1.text != element2.text:
if ignoreWhitespace:
if element1.text is None and not element2.text.strip(): pass
elif element2.text is None and not element1.text.strip(): pass
elif element1.text and element2.text and element1.text.strip()==element2.text.strip(): pass
else:
if printFlag:
print( "Element text differs:\n {!r}\n {!r}".format( element1.text, element2.text ) )
if verbosityLevel > 2: print( " at", location )
diffCount += 1
if diffCount > exitCount: return
else:
if printFlag:
print( "Element text differs:\n {!r}\n {!r}".format( element1.text, element2.text ) )
if verbosityLevel > 2: print( " at", location )
diffCount += 1
if diffCount > exitCount: return
if element1.tail != element2.tail:
if ignoreWhitespace:
if element1.tail is None and not element2.tail.strip(): pass
elif element2.tail is None and not element1.tail.strip(): pass
elif element1.tail and element2.tail and element1.tail.strip()==element2.tail.strip(): pass
else:
if printFlag:
print( "Element tail differs:\n {!r}\n {!r}".format( element1.tail, element2.tail ) )
if verbosityLevel > 2: print( " at", location )
diffCount += 1
if diffCount > exitCount: return
else:
if printFlag:
print( "Element tail differs:\n {!r}\n {!r}".format( element1.tail, element2.tail ) )
if verbosityLevel > 2: print( " at", location )
diffCount += 1
if diffCount > exitCount: return
if len(element1) != len(element2):
if printFlag:
print( "Number of subelements differ ({} and {})".format( len(element1), len(element2) ) )
if verbosityLevel > 2: print( " at", location )
diffCount += 1
if diffCount > exitCount: return
# Compare the subelements
for j in range( min( len(element1), len(element2) ) ):
compareElements( element1[j], element2[j] ) # Recursive call
if diffCount > exitCount: return
# Compare the files
diffCount, location = 0, []
compareElements( tree1, tree2 )
if diffCount and verbosityLevel > 1: print( "{} differences discovered.".format( diffCount if diffCount<=exitCount else 'Many' ) )
return diffCount==0
# end of BibleOrgSysGlobals.fileCompareXML
##########################################################################################################
#
# Validating XML fields (from element tree)
#
def elementStr( element, level=0 ):
"""
Return a string representation of an element (from element tree).
This is suitable for debugging
"""
resultStr = '{}Element {!r}: '.format( 'Sub'*level, element.tag )
# Do attributes first
printed = False
for attrib,value in element.items():
if printed: resultStr += ','
else: resultStr += 'Attribs: '; printed = True
resultStr += '{}={!r}'.format( attrib, value )
if element.text is not None:
if resultStr[-1] != ' ': resultStr += ' '
resultStr += 'Text={!r}'.format( element.text )
# Now do subelements
printed = False
for subelement in element:
if printed: resultStr += ','
else:
if resultStr[-1] != ' ': resultStr += ' '
resultStr += 'Children: '; printed = True
resultStr += elementStr( subelement, level+1 ) # recursive call
if element.tail is not None:
if resultStr[-1] != ' ': resultStr += ' '
resultStr += 'Tail={!r}'.format( element.tail )
return resultStr
# end of BibleOrgSysGlobals.elementStr
def checkXMLNoAttributes( element, locationString, idString=None, loadErrorsDict=None ):
"""
Give a warning if the element contains any attributes.
"""
for attrib,value in element.items():
warningString = "{}Unexpected {!r} XML attribute ({}) in {}" \
.format( (idString+' ') if idString else '', attrib, value, locationString )
logging.warning( warningString )
if loadErrorsDict is not None: loadErrorsDict.append( warningString )
if strictCheckingFlag or debugFlag and haltOnXMLWarning: halt
# end of BibleOrgSysGlobals.checkXMLNoAttributes
def checkXMLNoText( element, locationString, idString=None, loadErrorsDict=None ):
"""
Give an error if the element text contains anything other than whitespace.
"""
if element.text and element.text.strip():
errorString = "{}Unexpected {!r} XML element text in {}" \
.format( (idString+' ') if idString else '', element.text, locationString )
logging.error( errorString )
if loadErrorsDict is not None: loadErrorsDict.append( errorString )
if strictCheckingFlag or debugFlag and haltOnXMLWarning: halt
# end of BibleOrgSysGlobals.checkXMLNoText
def checkXMLNoTail( element, locationString, idString=None, loadErrorsDict=None ):
"""
Give a warning if the element tail contains anything other than whitespace.
"""
if element.tail and element.tail.strip():
warningString = "{}Unexpected {!r} XML element tail in {}" \
.format( (idString+' ') if idString else '', element.tail, locationString )
logging.warning( warningString )
if loadErrorsDict is not None: loadErrorsDict.append( warningString )
if strictCheckingFlag or debugFlag and haltOnXMLWarning: halt
# end of BibleOrgSysGlobals.checkXMLNoTail
def checkXMLNoSubelements( element, locationString, idString=None, loadErrorsDict=None ):
"""
Give an error if the element contains any sub-elements.
"""
for subelement in element:
errorString = "{}Unexpected {!r} XML sub-element ({}) in {}" \
.format( (idString+' ') if idString else '', subelement.tag, subelement.text, locationString )
logger = logging.critical if subelement.text else logging.error
logger( errorString )
if loadErrorsDict is not None: loadErrorsDict.append( errorString )
if strictCheckingFlag or debugFlag and haltOnXMLWarning: halt
# end of BibleOrgSysGlobals.checkXMLNoSubelements
def checkXMLNoSubelementsWithText( element, locationString, idString=None, loadErrorsDict=None ):
"""
Checks that the element doesn't have text AND subelements
"""
if ( element.text and element.text.strip() ) \
or ( element.tail and element.tail.strip() ):
for subelement in element.getchildren():
warningString = "{}Unexpected {!r} XML sub-element ({}) in {} with text/tail {}/{}" \
.format( (idString+' ') if idString else '', subelement.tag, subelement.text, locationString,
element.text.strip() if element.text else element.text,
element.tail.strip() if element.tail else element.tail )
logging.warning( warningString )
if loadErrorsDict is not None: loadErrorsDict.append( warningString )
if strictCheckingFlag or debugFlag and haltOnXMLWarning: halt
# end of BibleOrgSysGlobals.checkXMLNoSubelementsWithText
def getFlattenedXML( element, locationString, idString=None, level=0 ):
"""
Return the XML nested inside the element as a text string.
The last two parameters are used for handling recursion.
Strips the tail (which often contains excess nl characters).
"""
result = ''
# Get attributes
attributes = ''
for attribName,attribValue in element.items():
attributes += '{}{}="{}"'.format( ' ' if attributes else '', attribName, attribValue )
if level: # For lower levels (other than the called one) need to add the tags
result += '<' + element.tag
if attributes: result += ' ' + attributes
result += '>'
elif attributes:
#print( "We are losing attributes here:", attributes ); halt
result += '<' + attributes + '>'
if element.text: result += element.text
for subelement in element:
result += getFlattenedXML( subelement, subelement.tag + ' in ' + locationString, idString, level+1 ) # Recursive call
if level:
result += '</' + element.tag + '>'
if element.tail and element.tail.strip(): result += ' ' + element.tail.strip()
#else: print( "getFlattenedXML: Result is {!r}".format( result ) )
return result
# end of BibleOrgSysGlobals.getFlattenedXML
def isBlank( elementText ):
"""
Given some text from an XML element text or tail field (which might be None)
return a stripped value and with internal CRLF characters replaced by spaces.
If the text is None, returns None
"""
#print( "isBlank( {!r} )".format( elementText ) )
if elementText is None: return True
#print( "isspace()", elementText.isspace() )