forked from Freely-Given-org/BibleOrgSys
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OSISXMLBible.py
executable file
·3571 lines (3394 loc) · 270 KB
/
OSISXMLBible.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 -*-
#
# OSISXMLBible.py
#
# Module handling OSIS XML Bibles
#
# Copyright (C) 2010-2018 Robert Hunt
# Author: Robert Hunt <[email protected]>
# 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 the reading and import of OSIS XML Bibles.
Unfortunately, the OSIS specification (designed by committee for many different tasks)
allows many different ways of encoding Bibles so the variations are very many.
This is a quickly updated version of an early module,
and it's both ugly and fragile :-(
Updated Sept 2013 to also handle Kahunapule's "modified OSIS".
NOTE: We could use multiprocessing in loadBooks()
"""
from gettext import gettext as _
LastModifiedDate = '2018-02-10' # by RJH
ShortProgName = "OSISBible"
ProgName = "OSIS XML Bible format handler"
ProgVersion = '0.63'
ProgNameVersion = '{} v{}'.format( ShortProgName, ProgVersion )
ProgNameVersionDate = '{} {} {}'.format( ProgNameVersion, _("last modified"), LastModifiedDate )
debuggingThisModule = False
import logging, os, sys
from xml.etree.ElementTree import ElementTree, ParseError
import BibleOrgSysGlobals
from ISO_639_3_Languages import ISO_639_3_Languages
from USFMMarkers import USFM_BIBLE_PARAGRAPH_MARKERS
from Bible import Bible, BibleBook
FILENAME_ENDINGS_TO_IGNORE = ('.ZIP.GO', '.ZIP.DATA') # Must be UPPERCASE
EXTENSIONS_TO_IGNORE = ( 'ASC', 'BAK', 'BAK2', 'BAK3', 'BAK4', 'BBLX', 'BC', 'CCT', 'CSS', 'DOC', 'DTS', 'HTM','HTML',
'JAR', 'LDS', 'LOG', 'MYBIBLE', 'NT','NTX', 'ODT', 'ONT','ONTX', 'OSIS', 'OT','OTX', 'PDB',
'SAV', 'SAVE', 'STY', 'SSF', 'TXT', 'USFM', 'USX', 'VRS', 'YET', 'ZIP', ) # Must be UPPERCASE and NOT begin with a dot
# Get the data tables that we need for proper checking
ISOLanguages = ISO_639_3_Languages().loadData()
def exp( messageString ):
"""
Expands the message string in debug mode.
Prepends the module name to a error or warning message string
if we are in debug mode.
Returns the new string.
"""
try: nameBit, errorBit = messageString.split( ': ', 1 )
except ValueError: nameBit, errorBit = '', messageString
if BibleOrgSysGlobals.debugFlag or debuggingThisModule:
nameBit = '{}{}{}'.format( ShortProgName, '.' if nameBit else '', nameBit )
return '{}{}'.format( nameBit+': ' if nameBit else '', errorBit )
# end of exp
def OSISXMLBibleFileCheck( givenFolderName, strictCheck=True, autoLoad=False, autoLoadBooks=False ):
"""
Given a folder, search for OSIS XML Bible files or folders in the folder and in the next level down.
Returns False if an error is found.
if autoLoad is false (default)
returns None, or the number found.
if autoLoad is true and exactly one OSIS Bible is found,
returns the loaded OSISXMLBible object.
"""
if BibleOrgSysGlobals.verbosityLevel > 2: print( "OSISXMLBibleFileCheck( {}, {}, {}, {} )".format( givenFolderName, strictCheck, autoLoad, autoLoadBooks ) )
if BibleOrgSysGlobals.debugFlag: assert givenFolderName and isinstance( givenFolderName, str )
if BibleOrgSysGlobals.debugFlag: assert autoLoad in (True,False)
# Check that the given folder is readable
if not os.access( givenFolderName, os.R_OK ):
logging.critical( _("OSISXMLBibleFileCheck: Given {!r} folder is unreadable").format( givenFolderName ) )
return False
if not os.path.isdir( givenFolderName ):
logging.critical( _("OSISXMLBibleFileCheck: Given {!r} path is not a folder").format( givenFolderName ) )
return False
# Find all the files and folders in this folder
# OSIS is tricky coz a whole Bible can be in one file (normally), or in lots of separate (book) files
# and we don't want to think that 66 book files are 66 different OSIS Bibles
if BibleOrgSysGlobals.verbosityLevel > 3: print( " OSISXMLBibleFileCheck: Looking for files in given {}".format( givenFolderName ) )
foundFolders, foundFiles, foundBookFiles = [], [], []
for something in os.listdir( givenFolderName ):
somepath = os.path.join( givenFolderName, something )
if os.path.isdir( somepath ):
if something == '__MACOSX': continue # don't visit these directories
foundFolders.append( something )
elif os.path.isfile( somepath ):
somethingUpper = something.upper()
somethingUpperProper, somethingUpperExt = os.path.splitext( somethingUpper )
ignore = False
for ending in FILENAME_ENDINGS_TO_IGNORE:
if somethingUpper.endswith( ending): ignore=True; break
if ignore: continue
if not somethingUpperExt[1:] in EXTENSIONS_TO_IGNORE: # Compare without the first dot
foundFiles.append( something )
for osisBkCode in BibleOrgSysGlobals.BibleBooksCodes.getAllOSISBooksCodes():
# osisBkCodes are all UPPERCASE
#print( 'obc', osisBkCode, upperFilename )
if osisBkCode in somethingUpper:
foundBookFiles.append( something ); break
#print( 'ff', foundFiles, foundBookFiles )
# See if there's an OSIS project here in this folder
numFound = 0
looksHopeful = False
lastFilenameFound = None
for thisFilename in sorted( foundFiles ):
if strictCheck or BibleOrgSysGlobals.strictCheckingFlag:
firstLines = BibleOrgSysGlobals.peekIntoFile( thisFilename, givenFolderName, numLines=3 )
if not firstLines or len(firstLines)<2: continue
if not ( firstLines[0].startswith( '<?xml version="1.0"' ) or firstLines[0].startswith( "<?xml version='1.0'" ) ) \
and not ( firstLines[0].startswith( '\ufeff<?xml version="1.0"' ) or firstLines[0].startswith( "\ufeff<?xml version='1.0'" ) ): # same but with BOM
if BibleOrgSysGlobals.verbosityLevel > 3: print( "OsisB (unexpected) first line was {!r} in {}".format( firstLines, thisFilename ) )
continue
if not (firstLines[1].startswith( '<osis ' ) or firstLines[2].startswith( '<osis ' )):
continue
lastFilenameFound = thisFilename
numFound += 1
if numFound>1 and numFound==len(foundBookFiles): # Assume they are all book files
lastFilenameFound = None
numFound = 1
if numFound:
if BibleOrgSysGlobals.verbosityLevel > 2: print( "OSISXMLBibleFileCheck got", numFound, givenFolderName, lastFilenameFound )
if numFound == 1 and (autoLoad or autoLoadBooks):
ub = OSISXMLBible( givenFolderName, lastFilenameFound ) # lastFilenameFound can be None
if autoLoadBooks: ub.loadBooks() # Load and process the file(s)
return ub
return numFound
elif looksHopeful and BibleOrgSysGlobals.verbosityLevel > 2: print( " Looked hopeful but no actual files found" )
# Look one level down
numFound = 0
foundProjects = []
for thisFolderName in sorted( foundFolders ):
tryFolderName = os.path.join( givenFolderName, thisFolderName+'/' )
if BibleOrgSysGlobals.verbosityLevel > 3: print( " OSISXMLBibleFileCheck: Looking for files in {}".format( tryFolderName ) )
foundSubfolders, foundSubfiles, foundSubBookFiles = [], [], []
for something in os.listdir( tryFolderName ):
somepath = os.path.join( givenFolderName, thisFolderName, something )
if os.path.isdir( somepath ): foundSubfolders.append( something )
elif os.path.isfile( somepath ):
somethingUpper = something.upper()
somethingUpperProper, somethingUpperExt = os.path.splitext( somethingUpper )
ignore = False
for ending in FILENAME_ENDINGS_TO_IGNORE:
if somethingUpper.endswith( ending): ignore=True; break
if ignore: continue
if not somethingUpperExt[1:] in EXTENSIONS_TO_IGNORE: # Compare without the first dot
foundSubfiles.append( something )
for osisBkCode in BibleOrgSysGlobals.BibleBooksCodes.getAllOSISBooksCodes():
# osisBkCodes are all UPPERCASE
#print( 'obc', osisBkCode, upperFilename )
if osisBkCode in somethingUpper:
foundSubBookFiles.append( something ); break
#print( 'fsf', foundSubfiles, foundSubBookFiles )
# See if there's an OSIS project here in this folder
for thisFilename in sorted( foundSubfiles ):
if strictCheck or BibleOrgSysGlobals.strictCheckingFlag:
firstLines = BibleOrgSysGlobals.peekIntoFile( thisFilename, tryFolderName, numLines=2 )
if not firstLines or len(firstLines)<2: continue
if not ( firstLines[0].startswith( '<?xml version="1.0"' ) or firstLines[0].startswith( "<?xml version='1.0'" ) ) \
and not ( firstLines[0].startswith( '\ufeff<?xml version="1.0"' ) or firstLines[0].startswith( "\ufeff<?xml version='1.0'" ) ): # same but with BOM
if BibleOrgSysGlobals.verbosityLevel > 3: print( "OsisB (unexpected) first line was {!r} in {}".format( firstLines, thisFilename ) )
continue
if not firstLines[1].startswith( '<osis ' ):
continue
foundProjects.append( (tryFolderName, thisFilename) )
lastFilenameFound = thisFilename
numFound += 1
if numFound>1 and numFound==len(foundSubBookFiles): # Assume they are all book files
lastFilenameFound = None
numFound = 1
if numFound:
if BibleOrgSysGlobals.verbosityLevel > 2: print( "OSISXMLBibleFileCheck foundProjects", numFound, foundProjects )
if numFound == 1 and (autoLoad or autoLoadBooks):
if BibleOrgSysGlobals.debugFlag: assert len(foundProjects) == 1
ub = OSISXMLBible( foundProjects[0][0], foundProjects[0][1] ) # Folder and filename
if autoLoadBooks: ub.loadBooks() # Load and process the file(s)
return ub
return numFound
# end of OSISXMLBibleFileCheck
def clean( elementText, loadErrors=None, location=None, verseMilestone=None ):
"""
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
"""
if elementText is None: return None
# else it's not None
info = ''
if location: info += ' at ' + location
if verseMilestone: info += ' at ' + verseMilestone
result = elementText
while result.endswith('\n') or result.endswith('\r'): result = result[:-1] # Drop off trailing newlines (assumed to be irrelevant)
if ' ' in result:
errorMsg = exp("clean: found multiple spaces in {!r}{}").format( result, info )
if debuggingThisModule: logging.warning( errorMsg )
if loadErrors is not None: loadErrors.append( errorMsg )
if '\t' in result:
errorMsg = exp("clean: found tab in {!r}{}").format( result, info )
if debuggingThisModule: logging.warning( errorMsg )
if loadErrors is not None: loadErrors.append( errorMsg )
result = result.replace( '\t', ' ' )
if '\n' in result or '\r' in result:
errorMsg = exp("clean: found CR or LF characters in {!r}{}").format( result, info )
if debuggingThisModule: logging.error( errorMsg )
if loadErrors is not None: loadErrors.append( errorMsg )
result = result.replace( '\r\n', ' ' ).replace( '\n', ' ' ).replace( '\r', ' ' )
while ' ' in result: result = result.replace( ' ', ' ' )
return result
# end of clean
class OSISXMLBible( Bible ):
"""
Class for reading, validating, and converting OSISXMLBible XML.
This is only intended as a transitory class (used at start-up).
The OSISXMLBible class has functions more generally useful.
"""
filenameBase = 'OSISXMLBible'
XMLNameSpace = '{http://www.w3.org/XML/1998/namespace}'
#OSISNameSpace = '{http://ebible.org/2003/OSIS/namespace}'
OSISNameSpace = '{http://www.bibletechnologies.net/2003/OSIS/namespace}'
treeTag = OSISNameSpace + 'osis'
textTag = OSISNameSpace + 'osisText'
headerTag = OSISNameSpace + 'header'
divTag = OSISNameSpace + 'div'
def __init__( self, sourceFilepath, givenName=None, givenAbbreviation=None, encoding='utf-8' ):
"""
Constructor: just sets up the OSIS Bible object.
sourceFilepath can be a folder (esp. if each book is in a separate file)
or the path of a specific file (probably containing the whole Bible -- most common)
"""
if BibleOrgSysGlobals.debugFlag or BibleOrgSysGlobals.verbosityLevel > 2 or debuggingThisModule:
print( "OSISXMLBible.__init__( {}, {!r}, {!r}, {} )".format( sourceFilepath, givenName, givenAbbreviation, encoding ) )
# Setup and initialise the base class first
Bible.__init__( self )
self.objectNameString = 'OSIS XML Bible object'
self.objectTypeString = 'OSIS'
# Now we can set our object variables
self.sourceFilepath, self.givenName, self.givenAbbreviation, self.encoding = sourceFilepath, givenName, givenAbbreviation, encoding
self.title = self.version = self.date = self.source = None
self.XMLTree = self.header = self.frontMatter = self.divs = self.divTypesString = None
#self.bkData, self.USFMBooks = OrderedDict(), OrderedDict()
self.lang = self.language = None
# Do a preliminary check on the readability of our file(s)
self.possibleFilenames = []
self.possibleFilenameDict = {}
if os.path.isdir( self.sourceFilepath ): # We've been given a folder -- see if we can find the files
self.sourceFolder = self.sourceFilepath
# There's no standard for OSIS xml file naming
fileList = os.listdir( self.sourceFilepath )
# First try looking for OSIS book names
BBBList = []
for filename in fileList:
if 'VerseMap' in filename: continue # For WLC
if filename.lower().endswith('.xml'):
self.sourceFilepath = os.path.join( self.sourceFolder, filename )
if BibleOrgSysGlobals.debugFlag and debuggingThisModule:
print( "Trying {}…".format( self.sourceFilepath ) )
if os.access( self.sourceFilepath, os.R_OK ): # we can read that file
self.possibleFilenames.append( filename )
foundBBB = None
upperFilename = filename.upper()
for osisBkCode in BibleOrgSysGlobals.BibleBooksCodes.getAllOSISBooksCodes():
# osisBkCodes are all UPPERCASE
#print( 'obc', osisBkCode, upperFilename )
if osisBkCode in upperFilename:
#print( "OSISXMLBible.__init__ found {!r} in {!r}".format( osisBkCode, upperFilename ) )
if 'JONAH' in upperFilename and osisBkCode=='NAH': continue # Handle bad choice
if 'ZEPH' in upperFilename and osisBkCode=='EPH': continue # Handle bad choice
assert not foundBBB # Don't expect duplicates
foundBBB = BibleOrgSysGlobals.BibleBooksCodes.getBBBFromOSISAbbreviation( osisBkCode, strict=True )
#print( " FoundBBB1 = {!r}".format( foundBBB ) )
if not foundBBB: # Could try a USFM/Paratext book code -- what writer creates these???
for bkCode in BibleOrgSysGlobals.BibleBooksCodes.getAllUSFMBooksCodes( toUpper=True ):
# returned bkCodes are all UPPERCASE
#print( 'bc', bkCode, upperFilename )
if bkCode in upperFilename:
#print( 'OSISXMLBible.__init__ ' + _("found {!r} in {!r}").format( bkCode, upperFilename ) )
if foundBBB: # already -- don't expect doubles
logging.warning( 'OSISXMLBible.__init__: ' + _("Found a second possible book abbreviation for {} in {}").format( foundBBB, filename ) )
foundBBB = BibleOrgSysGlobals.BibleBooksCodes.getBBBFromUSFMAbbreviation( bkCode, strict=True )
#print( " FoundBBB2 = {!r}".format( foundBBB ) )
if foundBBB:
if isinstance( foundBBB, list ): foundBBB = foundBBB[0] # Take the first option
assert isinstance( foundBBB, str )
BBBList.append( foundBBB )
self.availableBBBs.add( foundBBB )
self.possibleFilenameDict[foundBBB] = filename
# Now try to sort the booknames in self.possibleFilenames to a better order
#print( "Was", len(self.possibleFilenames), self.possibleFilenames )
#print( " have", len(BBBList), BBBList )
assert (len(BBBList)==0 and len(self.possibleFilenames)==1) \
or len(BBBList) == len(self.possibleFilenames) # Might be no book files (if all in one file)
newCorrectlyOrderedList = []
for BBB in BibleOrgSysGlobals.BibleBooksCodes: # ordered by reference number
#print( BBB )
if BBB in BBBList:
ix = BBBList.index( BBB )
newCorrectlyOrderedList.append( self.possibleFilenames[ix] )
self.possibleFilenames = newCorrectlyOrderedList
#print( "Now", self.possibleFilenames ); halt
else: # it's presumably a file name
self.sourceFolder = os.path.dirname( self.sourceFilepath )
if not os.access( self.sourceFilepath, os.R_OK ):
logging.critical( 'OSISXMLBible: ' + _("File {!r} is unreadable").format( self.sourceFilepath ) )
return # No use continuing
if debuggingThisModule: print( "OSISXMLBible possibleFilenames: {}".format( self.possibleFilenames ) )
self.name, self.abbreviation = self.givenName, self.givenAbbreviation
self.workNames, self.workPrefixes = [], {}
if self.suppliedMetadata is None: self.suppliedMetadata = {}
self.suppliedMetadata['OSIS'] = {}
self.loadErrors = []
# end of OSISXMLBible.__init__
def loadBooks( self ):
"""
Loads the OSIS XML file or files.
NOTE: We could use multiprocessing here
"""
if BibleOrgSysGlobals.debugFlag or BibleOrgSysGlobals.verbosityLevel > 2 or debuggingThisModule:
print( "OSISXMLBible.loadBooks()" )
if self.possibleFilenames: # then we possibly have multiple files, probably one for each book
for filename in self.possibleFilenames:
pathname = os.path.join( self.sourceFolder, filename )
self.__loadFile( pathname, self.loadErrors )
elif os.path.isfile( self.sourceFilepath ): # most often we have all the Bible books in one file
self.__loadFile( self.sourceFilepath, self.loadErrors )
else:
logging.critical( "OSISXMLBible: Didn't find anything to load at {!r}".format( self.sourceFilepath ) )
loadErrors.append( _("OSISXMLBible: Didn't find anything to load at {!r}").format( self.sourceFilepath ) )
if self.loadErrors:
self.errorDictionary['Load Errors'] = self.loadErrors
#if BibleOrgSysGlobals.debugFlag: print( "loadErrors", len(loadErrors), loadErrors ); halt
self.applySuppliedMetadata( 'OSIS' ) # Copy some to self.settingsDict
self.doPostLoadProcessing()
# end of OSISXMLBible.loadBooks
def load( self ):
self.loadBooks()
def loadBook( self, BBB, filename=None ):
"""
Load the requested book into self.books if it's not already loaded.
#NOTE: You should ensure that preload() has been called first.
"""
if BibleOrgSysGlobals.debugFlag or BibleOrgSysGlobals.verbosityLevel > 2 or debuggingThisModule:
print( "OSISXMLBible.loadBook( {}, {} )".format( BBB, filename ) )
#assert self.preloadDone
if not self.possibleFilenames: # then the whole Bible was probably in one file
if debuggingThisModule: print( " Unable to load OSIS by book -- returning" )
return # nothing to do here
if BBB not in self.bookNeedsReloading or not self.bookNeedsReloading[BBB]:
if BBB in self.books:
if BibleOrgSysGlobals.debugFlag: print( " {} is already loaded -- returning".format( BBB ) )
return # Already loaded
if BBB in self.triedLoadingBook:
logging.warning( "We had already tried loading OSIS {} for {}".format( BBB, self.name ) )
return # We've already attempted to load this book
self.triedLoadingBook[BBB] = True
if BibleOrgSysGlobals.verbosityLevel > 2 or BibleOrgSysGlobals.debugFlag:
print( _(" OSISXMLBible: Loading {} from {} from {}…").format( BBB, self.name, self.sourceFolder ) )
if filename is None and BBB in self.possibleFilenameDict: filename = self.possibleFilenameDict[BBB]
if filename is None: raise FileNotFoundError( "OSISXMLBible.loadBook: Unable to find file for {}".format( BBB ) )
#BB = BibleBook( self, BBB )
#BB.load( filename, self.sourceFolder, self.encoding )
#if BB._rawLines:
#BB.validateMarkers() # Usually activates InternalBibleBook.processLines()
#self.stashBook( BB )
#else: logging.info( "OSIS book {} was completely blank".format( BBB ) )
self.loadErrors = []
pathname = os.path.join( self.sourceFolder, filename )
self.__loadFile( pathname, self.loadErrors )
self.bookNeedsReloading[BBB] = False
if self.loadErrors:
if 'Load Errors' not in self.errorDictionary: self.errorDictionary['Load Errors'] = []
self.errorDictionary['Load Errors'].extend( self.loadErrors )
#if BibleOrgSysGlobals.debugFlag: print( "loadErrors", len(loadErrors), loadErrors ); halt
self.applySuppliedMetadata( 'OSIS' ) # Copy some to self.settingsDict
#self.doPostLoadProcessing() # Should only be done after loading ALL books
# end of OSISXMLBible.loadBook
def __loadFile( self, OSISFilepath, loadErrors ):
"""
Load a single source XML file and remove the header from the tree.
Also, extracts some useful elements from the header element.
"""
if BibleOrgSysGlobals.verbosityLevel > 2 or debuggingThisModule:
print( _(" OSISXMLBible loading {}…").format( OSISFilepath ) )
try: self.XMLTree = ElementTree().parse( OSISFilepath )
except ParseError as err:
logging.critical( exp("Loader parse error in xml file {}: {} {}").format( OSISFilepath, sys.exc_info()[0], err ) )
loadErrors.append( exp("Loader parse error in xml file {}: {} {}").format( OSISFilepath, sys.exc_info()[0], err ) )
return
if BibleOrgSysGlobals.debugFlag: assert len( self.XMLTree ) # Fail here if we didn't load anything at all
# Find the main (osis) container
if self.XMLTree.tag == OSISXMLBible.treeTag:
location = 'OSIS file'
BibleOrgSysGlobals.checkXMLNoText( self.XMLTree, location, '4f6h', loadErrors )
BibleOrgSysGlobals.checkXMLNoTail( self.XMLTree, location, '1wk8', loadErrors )
# Process the attributes first
self.schemaLocation = None
for attrib,value in self.XMLTree.items():
if attrib.endswith("schemaLocation"):
self.schemaLocation = value
else:
logging.warning( "fv6g Unprocessed {} attribute ({}) in {}".format( attrib, value, location ) )
loadErrors.append( "Unprocessed {} attribute ({}) in {} (fv6g)".format( attrib, value, location ) )
if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag and BibleOrgSysGlobals.haltOnXMLWarning: halt
# Find the submain (osisText) container
if len(self.XMLTree)==1 and (self.XMLTree[0].tag == OSISXMLBible.textTag or (not BibleOrgSysGlobals.strictCheckingFlag and self.XMLTree[0].tag == 'osisText')):
sublocation = "osisText in " + location
textElement = self.XMLTree[0]
BibleOrgSysGlobals.checkXMLNoText( textElement, sublocation, '3b5g', loadErrors )
BibleOrgSysGlobals.checkXMLNoTail( textElement, sublocation, '7h9k', loadErrors )
# Process the attributes first
self.osisIDWork = self.osisRefWork = canonical = None
for attrib,value in textElement.items():
if attrib=='osisIDWork':
self.osisIDWork = value
if not self.name: self.name = value
elif attrib=='osisRefWork': self.osisRefWork = value
elif attrib=='canonical':
canonical = value
assert canonical in ('true','false')
elif attrib==OSISXMLBible.XMLNameSpace+'lang': self.lang = value
else:
logging.warning( "gb2d Unprocessed {} attribute ({}) in {}".format( attrib, value, sublocation ) )
loadErrors.append( "Unprocessed {} attribute ({}) in {} (gb2d)".format( attrib, value, sublocation ) )
if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag and BibleOrgSysGlobals.haltOnXMLWarning: halt
if self.osisRefWork:
if self.osisRefWork not in ('bible','Bible','defaultReferenceScheme'):
logging.warning( "New variety of osisRefWork: {!r}".format( self.osisRefWork ) )
loadErrors.append( "New variety of osisRefWork: {!r}".format( self.osisRefWork ) )
if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag and BibleOrgSysGlobals.haltOnXMLWarning: halt
if self.lang:
if self.lang in ('en','de','he'): # Only specifically recognise these ones so far (English, German, Hebrew)
if BibleOrgSysGlobals.verbosityLevel > 2: print( " Language is {!r}".format( self.lang ) )
else:
logging.info( "Discovered unknown {!r} language".format( self.lang ) )
if BibleOrgSysGlobals.verbosityLevel > 2: print( " osisIDWork is {!r}".format( self.osisIDWork ) )
# Find (and move) the header container
if textElement[0].tag == OSISXMLBible.headerTag:
self.header = textElement[0]
textElement.remove( self.header )
self.validateHeader( self.header, loadErrors )
else:
logging.warning( "Missing header element (looking for {!r} tag)".format( OSISXMLBible.headerTag ) )
loadErrors.append( "Missing header element (looking for {!r} tag)".format( OSISXMLBible.headerTag ) )
if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag and BibleOrgSysGlobals.haltOnXMLWarning: halt
# Find (and move) the optional front matter (div) container
if textElement[0].tag == OSISXMLBible.divTag or (not BibleOrgSysGlobals.strictCheckingFlag and textElement[0].tag == 'div'):
sub2location = "div of " + sublocation
# Process the attributes first
div0Type = div0OsisID = canonical = None
for attrib,value in textElement[0].items():
if attrib=='type': div0Type = value
elif attrib=='osisID': div0OsisID = value
elif attrib=='canonical':
assert canonical is None
canonical = value
assert canonical in ('true','false')
else:
logging.warning( "7j4d Unprocessed {} attribute ({}) in {}".format( attrib, value, sub2location ) )
loadErrors.append( "Unprocessed {} attribute ({}) in {} (7j4d)".format( attrib, value, sub2location ) )
if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag and BibleOrgSysGlobals.haltOnXMLWarning: halt
if div0Type == 'front':
self.frontMatter = textElement[0]
textElement.remove( self.frontMatter )
self.validateFrontMatter( self.frontMatter, loadErrors )
else: logging.info( "No front matter division" )
self.divs, self.divTypesString = [], None
for element in textElement:
if element.tag == OSISXMLBible.divTag or (not BibleOrgSysGlobals.strictCheckingFlag and element.tag == 'div'):
sub2location = "div in " + sublocation
BibleOrgSysGlobals.checkXMLNoText( element, sub2location, '3a2s', loadErrors )
BibleOrgSysGlobals.checkXMLNoTail( element, sub2location, '4k8a', loadErrors )
divType = element.get( 'type' )
if divType is None:
logging.error( "Missing div type in OSIS file" )
loadErrors.append( "Missing div type in OSIS file" )
if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag and BibleOrgSysGlobals.haltOnXMLWarning: halt
if divType != self.divTypesString:
if not self.divTypesString: self.divTypesString = divType
else: self.divTypesString = 'MixedTypes'
self.validateAndExtractMainDiv( element, loadErrors )
self.divs.append( element )
else:
logging.error( "Expected to find {!r} but got {!r}".format( OSISXMLBible.divTag, element.tag ) )
loadErrors.append( "Expected to find {!r} but got {!r}".format( OSISXMLBible.divTag, element.tag ) )
if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag and BibleOrgSysGlobals.haltOnXMLWarning: halt
else:
logging.error( "Expected to find {!r} but got {!r}".format( OSISXMLBible.textTag, self.XMLTree[0].tag ) )
loadErrors.append( "Expected to find {!r} but got {!r}".format( OSISXMLBible.textTag, self.XMLTree[0].tag ) )
if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag and BibleOrgSysGlobals.haltOnXMLWarning: halt
else:
logging.error( "Expected to load {!r} but got {!r}".format( OSISXMLBible.treeTag, self.XMLTree.tag ) )
loadErrors.append( "Expected to load {!r} but got {!r}".format( OSISXMLBible.treeTag, self.XMLTree.tag ) )
if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag and BibleOrgSysGlobals.haltOnXMLWarning: halt
if self.XMLTree.tail is not None and self.XMLTree.tail.strip():
logging.error( "Unexpected {!r} tail data after {} element".format( self.XMLTree.tail, self.XMLTree.tag ) )
loadErrors.append( "Unexpected {!r} tail data after {} element".format( self.XMLTree.tail, self.XMLTree.tag ) )
if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag and BibleOrgSysGlobals.haltOnXMLWarning: halt
# end of OSISXMLBible.loadFile
def validateDivineName( self, element, locationDescription, verseMilestone, loadErrors ):
"""
"""
location = "validateDivineName: " + locationDescription
BibleOrgSysGlobals.checkXMLNoAttributes( element, location+" at "+verseMilestone, '3f7h', loadErrors )
BibleOrgSysGlobals.checkXMLNoSubelements( element, location+" at "+verseMilestone, 'v4g7', loadErrors )
divineName, trailingText = element.text, element.tail
self.thisBook.appendToLastLine( '\\nd {}\\nd*'.format( clean(divineName) ) )
if trailingText and trailingText.strip(): self.thisBook.appendToLastLine( clean(trailingText) )
# end of validateDivineName
def validateAndLoadSEG( self, element, locationDescription, verseMilestone, loadErrors ):
"""
Also handles the tail.
Might be nested like:
<hi type="bold"><hi type="italic">buk</hi></hi> tainoraun ämän
Nesting doesn't currently work here.
"""
#print( "validateAndLoadSEG( {}, {}, {} )".format( BibleOrgSysGlobals.elementStr(element), locationDescription, verseMilestone ) )
location = 'validateAndLoadSEG: ' + locationDescription
SegText = element.text
# Process the attributes
theType = None
for attrib,value in element.items():
if attrib=='type': theType = value
else:
logging.warning( "lj06 Unprocessed {!r} attribute ({}) in {} -element of {} at {}".format( attrib, value, element.tag, location, verseMilestone ) )
loadErrors.append( "Unprocessed {!r} attribute ({}) in {} -element of {} at {} (lj06)".format( attrib, value, element.tag, location, verseMilestone ) )
if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag and BibleOrgSysGlobals.haltOnXMLWarning: halt
#if debuggingThisModule: print( "khf8", "Have", location, repr(element.text), repr(theType) )
markerOpen = False
if theType:
if theType=='verseNumber': marker = 'fv'
elif theType=='keyword': marker = 'fk'
elif theType=='otPassage': marker = 'qt'
elif theType in ('section',
'x-small','x-large','x-suspended',
'x-maqqef','x-sof-pasuq','x-pe','x-paseq','x-samekh','x-reversednun'):
marker = theType # invented -- used below
else:
marker = 'x--' # Gets ignored below
if BibleOrgSysGlobals.debugFlag: print( theType, location, verseMilestone ); halt
else: # What marker do we need ???
marker = 'fv'
if marker == 'section': # We don't have marker for this
self.thisBook.appendToLastLine( ' ' + clean(SegText) + ' ' )
elif marker.startswith( 'x-' ): # We don't have marker for this
self.thisBook.appendToLastLine( clean(SegText) )
else:
self.thisBook.appendToLastLine( '\\{} {}'.format( marker, clean(SegText) ) )
markerOpen = True
for subelement in element:
sublocation = element.tag + ' in ' + location
if subelement.tag == OSISXMLBible.OSISNameSpace+'divineName':
self.validateDivineName( subelement, sublocation, verseMilestone, loadErrors )
else:
logging.error( "8k1w Unprocessed {!r} sub-element ({}) in {} at {}".format( subelement.tag, subelement.text, sublocation, verseMilestone ) )
loadErrors.append( "Unprocessed {!r} sub-element ({}) in {} at {} (8k3s)".format( subelement.tag, subelement.text, sublocation, verseMilestone ) )
if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag and BibleOrgSysGlobals.haltOnXMLWarning: halt
if markerOpen: self.thisBook.appendToLastLine( '\\{}*'.format( marker ) )
segTail = clean( element.tail, loadErrors, location, verseMilestone )
if segTail: self.thisBook.appendToLastLine( segTail )
# end of validateAndLoadSEG
def validateAndLoadWord( self, element, location, verseMilestone, loadErrors ):
"""
Handle a 'w' element and submit a string (which may include embedded Strongs' numbers, etc.).
"""
#print( "validateAndLoadWord( {}, {}, {}, … )".format( element, location, verseMilestone ) )
sublocation = "validateAndLoadWord: w of " + location
word = clean( element.text, loadErrors, sublocation, verseMilestone )
#if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag or debuggingThisModule:
#assert word -- might be false, e.g., in <w lemma="strong:H03069"><divineName>God</divineName></w>
self.thisBook.appendToLastLine( '\\w ' + (word if word else '' ) )
# Process the sub-elements (formatted parts of the word) first
assert len(element) <= 1
for subelement in element:
if subelement.tag == OSISXMLBible.OSISNameSpace+'divineName':
self.validateDivineName( subelement, sublocation, verseMilestone, loadErrors )
elif subelement.tag == OSISXMLBible.OSISNameSpace+'seg':
self.validateAndLoadSEG( subelement, sublocation, verseMilestone, loadErrors )
else:
logging.error( "8k3s Unprocessed {!r} sub-element ({}) in {} at {}".format( subelement.tag, subelement.text, sublocation, verseMilestone ) )
loadErrors.append( "Unprocessed {!r} sub-element ({}) in {} at {} (8k3s)".format( subelement.tag, subelement.text, sublocation, verseMilestone ) )
if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag and BibleOrgSysGlobals.haltOnXMLWarning: halt
# Process the attributes
lemma = morph = wType = src = gloss = n = None
for attrib,value in element.items():
#print( "{} {}={} @ {}".format( word, attrib, value, location ) )
if attrib=='lemma':
lemma = self.workPrefixes['w/@lemma']+':'+value if 'w/@lemma' in self.workPrefixes else value
elif attrib=='morph':
morph = self.workPrefixes['w/@morph']+':'+value if 'w/@morph' in self.workPrefixes else value
elif attrib=='type': wType = value
elif attrib=='src': src = value
elif attrib=='gloss': gloss = value
elif attrib=='n': n = value # Might be something like 1.1.1 (in morphhb/wlc)
else:
logging.warning( "2h6k Unprocessed {!r} attribute ({}) in {} at {}".format( attrib, value, sublocation, verseMilestone ) )
loadErrors.append( "Unprocessed {!r} attribute ({}) in {} at {} (2h6k)".format( attrib, value, sublocation, verseMilestone ) )
if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag and BibleOrgSysGlobals.haltOnXMLWarning: halt
if wType and (BibleOrgSysGlobals.debugFlag or BibleOrgSysGlobals.strictCheckingFlag or debuggingThisModule):
assert wType.startswith( 'x-split-' ) # Followed by a number 1-10 or more
attributeDict = {}
if lemma \
and ( lemma.startswith('strong:') or lemma.startswith('Strong:') ):
if len(lemma)>7:
lemma = lemma[7:]
if lemma:
#self.thisBook.appendToLastLine( '\\str {}\\str*'.format( lemma ) )
attributeDict['strong'] = lemma
lemma = None # we've used it
elif gloss and gloss.startswith('s:'):
if len(gloss)>2:
gloss = gloss[2:]
if gloss:
self.thisBook.appendToLastLine( '\\str {}\\str*'.format( gloss ) )
attributeDict['strong'] = gloss
gloss = None # we've used it
if lemma: attributeDict['lemma'] = lemma
if morph: attributeDict['x-morph'] = morph
if wType: attributeDict['x-wType'] = wType
if src: attributeDict['x-src'] = src
if gloss: attributeDict['x-gloss'] = gloss
if n: attributeDict['x-cantillationLevel'] = n
#if lemma or morph or wType or src or gloss:
#logging.warning( "Losing lemma or morph or wType or src or gloss here at {} from {}".format( verseMilestone, BibleOrgSysGlobals.elementStr(element) ) )
#loadErrors.append( "Losing lemma or morph or wType or src or gloss here at {}".format( verseMilestone ) )
#if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag and BibleOrgSysGlobals.haltOnXMLWarning: halt
if attributeDict:
attributeString = '|'
for attributeName,attributeValue in attributeDict.items():
if len(attributeString) > 1: attributeString += ' '
attributeString += '{}="{}"'.format( attributeName, attributeValue )
#print( "attributeString", attributeString )
self.thisBook.appendToLastLine( attributeString )
self.thisBook.appendToLastLine( '\\w*')
trailingPunctuation = clean( element.tail, loadErrors, sublocation, verseMilestone )
if trailingPunctuation: self.thisBook.appendToLastLine( trailingPunctuation )
#combinedWord = word + trailingPunctuation
#return combinedWord
# end of validateAndLoadWord
def validateHighlight( self, element, locationDescription, verseMilestone, loadErrors ):
"""
Also handles the tail.
Might be nested like:
<hi type="bold"><hi type="italic">buk</hi></hi> tainoraun ämän
Nesting doesn't currently work here.
"""
location = "validateHighlight: " + locationDescription
#BibleOrgSysGlobals.checkXMLNoSubelements( element, location+" at "+verseMilestone, 'gb5g', loadErrors )
highlightedText, highlightedTail = element.text, element.tail
#if not highlightedText: print( "validateHighlight", repr(highlightedText), repr(highlightedTail), repr(location), repr(verseMilestone) )
#if BibleOrgSysGlobals.debugFlag: assert highlightedText # No text if nested!
highlightType = None
for attrib,value in element.items():
if attrib=='type':
highlightType = value
else:
logging.warning( "7kj3 Unprocessed {!r} attribute ({}) in {} element of {} at {}".format( attrib, value, element.tag, location, verseMilestone ) )
loadErrors.append( "Unprocessed {!r} attribute ({}) in {} element of {} at {} (7kj3)".format( attrib, value, element.tag, location, verseMilestone ) )
if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag and BibleOrgSysGlobals.haltOnXMLWarning: halt
if highlightType == 'italic': marker = 'it'
elif highlightType == 'bold': marker = 'bd'
elif highlightType == 'emphasis': marker = 'em'
elif highlightType == 'small-caps': marker = 'sc'
elif highlightType == 'super': marker = 'ord'
elif highlightType == 'normal': marker = 'no'
elif BibleOrgSysGlobals.debugFlag:
print( 'validateHighlight: highlightX', highlightType, locationDescription, verseMilestone )
if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag or debuggingThisModule: halt
self.thisBook.appendToLastLine( '\\{} {}\\{}*'.format( marker, clean(highlightedText), marker ) )
for subelement in element:
if subelement.tag == OSISXMLBible.OSISNameSpace+'hi':
sublocation = "hi of " + locationDescription
self.validateHighlight( subelement, sublocation, verseMilestone, loadErrors ) # recursive call
elif subelement.tag == OSISXMLBible.OSISNameSpace+'note':
sublocation = "note of " + locationDescription
self.validateCrossReferenceOrFootnote( subelement, sublocation, verseMilestone, loadErrors )
else:
logging.error( "bdhj Unprocessed {!r} sub-element ({}) in {} at {}".format( subelement.tag, subelement.text, location, verseMilestone ) )
loadErrors.append( "Unprocessed {!r} sub-element ({}) in {} at {} (bdhj)".format( subelement.tag, subelement.text, location, verseMilestone ) )
if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag and BibleOrgSysGlobals.haltOnXMLWarning: halt
if highlightedTail and highlightedTail.strip(): self.thisBook.appendToLastLine( clean(highlightedTail) )
# end of validateHighlight
def validateRDG( self, element, locationDescription, verseMilestone, loadErrors ):
"""
Also handles the tail.
Might be nested like:
<hi type="bold"><hi type="italic">buk</hi></hi> tainoraun ämän
Doesn't currently add any pseudo-USFM markers for the reading XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Nesting doesn't currently work here.
"""
location = 'validateRDG: ' + locationDescription
BibleOrgSysGlobals.checkXMLNoTail( element, location+" at "+verseMilestone, 'c54b', loadErrors )
# Process the attributes first
readingType = None
for attrib,value in element.items():
if attrib=='type':
readingType = value
#print( 'readingType', readingType )
if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag:
assert readingType in ('x-qere','x-accent')
else:
logging.warning( "2s3d Unprocessed {!r} attribute ({}) in {} sub2-element of {} at {}".format( attrib, value, element.tag, location, verseMilestone ) )
loadErrors.append( "Unprocessed {!r} attribute ({}) in {} sub2-element of {} at {} (2s3d)".format( attrib, value, element.tag, location, verseMilestone ) )
if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag and BibleOrgSysGlobals.haltOnXMLWarning: halt
if element.text: self.thisBook.appendToLastLine( element.text )
for subelement in element:
if subelement.tag == OSISXMLBible.OSISNameSpace+'w': # cross-references ???
sublocation = "validateRDG: w of rdg of " + locationDescription
self.validateAndLoadWord( subelement, sublocation, verseMilestone, loadErrors )
##print( " Have", sublocation, "6n83" )
#rdgW = subelement.text
#BibleOrgSysGlobals.checkXMLNoSubelements( subelement, sublocation+" at "+verseMilestone, 's2vb', loadErrors )
#BibleOrgSysGlobals.checkXMLNoTail( subelement, sublocation+" at "+verseMilestone, '5b3f', loadErrors )
## Process the attributes
#lemma = morph = n = None
#for attrib,value in subelement.items():
##print( "Attribute RDG1 {}={!r}".format( attrib, value ) )
#if attrib=='lemma': lemma = value # e.g., 'l/5649'
#elif attrib=='morph': morph = value # e.g., 'HC/Ncfdc'
#elif attrib=='n': n = value # e.g., '0.0'
#else:
#logging.warning( "6b8m Unprocessed {!r} attribute ({}) in {} sub2-element of {} at {}".format( attrib, value, subelement.tag, sublocation, verseMilestone ) )
#loadErrors.append( "Unprocessed {!r} attribute ({}) in {} sub2-element of {} at {} (6b8m)".format( attrib, value, subelement.tag, sublocation, verseMilestone ) )
#if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag and BibleOrgSysGlobals.haltOnXMLWarning: halt
#self.thisBook.appendToLastLine( rdgW )
elif subelement.tag == OSISXMLBible.OSISNameSpace+'seg': # cross-references ???
sublocation = "validateRDG: seg of rdg of " + locationDescription
self.validateAndLoadSEG( subelement, sublocation, verseMilestone, loadErrors )
elif subelement.tag == OSISXMLBible.OSISNameSpace+'hi':
sublocation = "validateRDG: hi of rdg of " + locationDescription
self.validateHighlight( subelement, sublocation, verseMilestone, loadErrors )
else:
logging.error( "3dxm Unprocessed {!r} subelement ({}) in {} at {}".format( subelement.tag, subelement.text, location, verseMilestone ) )
loadErrors.append( "Unprocessed {!r} subelement ({}) in {} at {} (3dxm)".format( subelement.tag, subelement.text, location, verseMilestone ) )
if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag and BibleOrgSysGlobals.haltOnXMLWarning: halt
if element.tail and element.tail.strip(): self.thisBook.appendToLastLine( clean(element.tail) )
# end of validateRDG
def validateProperName( self, element, locationDescription, verseMilestone, loadErrors ):
"""
"""
location = "validateProperName: " + locationDescription
BibleOrgSysGlobals.checkXMLNoAttributes( element, location+" at "+verseMilestone, 'hsd8', loadErrors )
BibleOrgSysGlobals.checkXMLNoSubelements( element, location+" at "+verseMilestone, 'ks91', loadErrors )
divineName = element.text
self.thisBook.appendToLastLine( '\\pn {}\\pn*'.format( clean(divineName) ) )
if element.tail and element.tail.strip(): self.thisBook.appendToLastLine( clean(element.tail) )
# end of validateProperName
def validateCrossReferenceOrFootnote( self, element, locationDescription, verseMilestone, loadErrors ):
"""
Check/validate and process a cross-reference or footnote.
"""
#print( "validateCrossReferenceOrFootnote at", locationDescription, verseMilestone )
#print( "element tag={!r} text={!r} tail={!r} attr={} ch={}".format( element.tag, element.text, element.tail, element.items(), element ) )
location = "validateCrossReferenceOrFootnote: " + locationDescription
noteType = noteN = noteOsisRef = noteOsisID = notePlacement = noteResp = None
for attrib,value in element.items():
if attrib=='type': noteType = value # cross-reference or empty for a footnote
elif attrib=='n': noteN = value
elif attrib=='osisRef': noteOsisRef = value
elif attrib=='osisID': noteOsisID = value
elif attrib=='placement': notePlacement = value
elif attrib=='resp': noteResp = value
else:
logging.warning( "2s4d Unprocessed {!r} attribute ({}) in {} sub-element of {} at {}".format( attrib, value, element.tag, location, verseMilestone ) )
loadErrors.append( "Unprocessed {!r} attribute ({}) in {} sub-element of {} at {} (2s4d)".format( attrib, value, element.tag, location, verseMilestone ) )
if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag and BibleOrgSysGlobals.haltOnXMLWarning: halt
#print( notePlacement )
if notePlacement and BibleOrgSysGlobals.debugFlag: assert notePlacement in ('foot','inline')
if BibleOrgSysGlobals.debugFlag and debuggingThisModule:
print( " Note attributes: noteType={!r} noteN={!r} noteOsisRef={!r} noteOsisID={!r} at {}".format( noteType, noteN, noteOsisRef, noteOsisID, verseMilestone ) )
guessed = False
openFieldname = None
if not noteType: # easier to handle later if we decide what it is now
if not element.items(): # it's just a note with NO ATTRIBUTES at all
noteType = 'footnote'
else: # we have some attributes
noteType = 'footnote' if noteN else 'crossReference'
guessed = True
#assert noteType and noteN
if noteType == 'crossReference':
#print( " noteType =", noteType, "noteN =", noteN, "notePlacement =", notePlacement )
if BibleOrgSysGlobals.debugFlag:
if notePlacement: assert notePlacement == 'inline'
if not noteN: noteN = '-'
self.thisBook.appendToLastLine( '\\x {}'.format( noteN ) )
openFieldname = 'x'
elif noteType == 'footnote':
#print( " noteType =", noteType, "noteN =", noteN )
if BibleOrgSysGlobals.debugFlag: assert not notePlacement
if not noteN: noteN = '+'
self.thisBook.appendToLastLine( '\\f {} '.format( noteN ) )
openFieldname = 'f'
elif noteType == 'study':
#print( " noteType =", noteType, "noteN =", noteN )
if BibleOrgSysGlobals.debugFlag: assert not notePlacement
if not noteN: noteN = '+'
self.thisBook.appendToLastLine( '\\f {} '.format( noteN ) )
openFieldname = 'f'
#print( "study note1", location, "Type =", noteType, "N =", noteN, "Ref =", noteOsisRef, "ID =", noteOsisID, "p =", notePlacement ); halt
elif noteType == 'translation':
#print( " noteType =", noteType, "noteN =", noteN, "notePlacement =", notePlacement )
if BibleOrgSysGlobals.debugFlag:
if notePlacement: assert notePlacement == 'foot'
if not noteN: noteN = '+'
self.thisBook.appendToLastLine( '\\f {} '.format( noteN ) )
openFieldname = 'f'
#print( "study note1", location, "Type =", noteType, "N =", noteN, "Ref =", noteOsisRef, "ID =", noteOsisID, "p =", notePlacement ); halt
elif noteType == 'variant':
#print( " noteType =", noteType, "noteN =", noteN )
if BibleOrgSysGlobals.debugFlag: assert not notePlacement
# What do we do here ???? XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
if not noteN: noteN = '+'
self.thisBook.appendToLastLine( '\\f {} '.format( noteN ) )
openFieldname = 'f'
elif noteType == 'alternative':
#print( " noteType =", noteType, "noteN =", noteN )
if BibleOrgSysGlobals.debugFlag: assert not notePlacement
# What do we do here ???? XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
if not noteN: noteN = '+'
self.thisBook.appendToLastLine( '\\f {} '.format( noteN ) )
openFieldname = 'f'
elif noteType == 'exegesis':
#print( " noteType =", noteType, "noteN =", noteN )
if BibleOrgSysGlobals.debugFlag: assert not notePlacement
# What do we do here ???? XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
if not noteN: noteN = '+'
self.thisBook.appendToLastLine( '\\f {} '.format( noteN ) )
openFieldname = 'f'
elif noteType == 'x-index':
#print( " noteType =", noteType, "noteN =", noteN )
if BibleOrgSysGlobals.debugFlag: assert notePlacement in ('inline',)
if not noteN: noteN = '~'
self.thisBook.appendToLastLine( '\\f {} '.format( noteN ) ) # Not sure what this is ???
openFieldname = 'f'
elif noteType == 'x-strongsMarkup':
#print( " noteType =", noteType, "noteN =", noteN, repr(notePlacement) )
if BibleOrgSysGlobals.debugFlag: assert notePlacement is None
if not noteN: noteN = '+ '
self.thisBook.appendToLastLine( '\\str {} '.format( noteN ) )
openFieldname = 'str'
else:
if debuggingThisModule: print( "validateCrossReferenceOrFootnote note1", repr(noteType) )
if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag: halt
noteText = clean( element.text, loadErrors, location, verseMilestone )
#if not noteText or noteText.isspace(): # Maybe we can infer the anchor reference
# if verseMilestone and verseMilestone.count('.')==2: # Something like Gen.1.3
# noteText = verseMilestone.split('.',1)[1] # Just get the verse reference like "1.3"
# else: noteText = ''
if noteText and not noteText.isspace(): # In some OSIS files, this is the anchor reference (in others, that's put in the tail of an enclosed reference subelement)
#print( "vm", verseMilestone, repr(noteText) ); halt
#if verseMilestone.startswith( 'Matt.6'): halt
#print( " noteType = {}, noteText = {!r}".format( noteType, noteText ) )
if noteType == 'crossReference': # This could be something like '1:6:' or '1:8: a'
self.thisBook.appendToLastLine( '\\xt {}'.format( clean(noteText) ) )
elif noteType == 'footnote': # This could be something like '4:3 In Greek: some note.' or it could just be random text
#print( " noteType =", noteType, "noteText =", noteText )
if BibleOrgSysGlobals.debugFlag: assert noteText
if ':' in noteText and noteText[0].isdigit(): # Let's roughly assume that it starts with a chapter:verse reference
bits = noteText.split( None, 1 )
if BibleOrgSysGlobals.debugFlag: assert len(bits) == 2
sourceText, footnoteText = bits
if BibleOrgSysGlobals.debugFlag: assert sourceText and footnoteText
#print( " footnoteSource = {!r}, sourceText = {!r}".format( footnoteSource, sourceText ) )
if not sourceText[-1] == ' ': sourceText += ' '
self.thisBook.appendToLastLine( '\\fr {}'.format( sourceText ) )
self.thisBook.appendToLastLine( '\\ft {}'.format( footnoteText ) )
else: # Let's assume it's a simple note
self.thisBook.appendToLastLine( '\\ft {}'.format( noteText ) )
elif noteType == 'study':
#print( "Need to handle study note properly here" ) # … xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
self.thisBook.appendToLastLine( '\\ft {}'.format( clean(noteText) ) )
#print( "study note dg32", location, "Type =", noteType, "N =", repr(noteN), "Ref =", noteOsisRef, "ID =", noteOsisID, "p =", notePlacement )
elif noteType == 'translation':
#print( "Need to handle translation note properly here" ) # … xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
self.thisBook.appendToLastLine( '\\ft {}'.format( clean(noteText) ) )
#print( "translation note fgd1", location, "Type =", noteType, "N =", noteN, "Ref =", noteOsisRef, "ID =", noteOsisID, "p =", notePlacement )
elif noteType == 'x-index':
#print( "Need to handle index note properly here" ) # … xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
#self.thisBook.addLine( 'ix~', noteText )
self.thisBook.appendToLastLine( '\\ft {}'.format( clean(noteText) ) )
elif noteType == 'x-strongsMarkup':
self.thisBook.appendToLastLine( '\\ft {}'.format( noteText ) )
else:
print( "note2", noteType )
if BibleOrgSysGlobals.strictCheckingFlag or BibleOrgSysGlobals.debugFlag: halt
for subelement in element:
if subelement.tag == OSISXMLBible.OSISNameSpace+'reference': # cross-references
sublocation = "validateCrossReferenceOrFootnote: reference of " + locationDescription
#print( " Have", sublocation, "7h3f" )
referenceText = subelement.text.strip()
referenceTail = (subelement.tail if subelement.tail is not None else '').strip()
referenceOsisRef = referenceType = None
for attrib,value in subelement.items():
if attrib=='osisRef': referenceOsisRef = value
elif attrib=='type': referenceType = value
else:
logging.warning( "1sc5 Unprocessed {!r} attribute ({}) in {} sub-element of {} at {}".format( attrib, value, subelement.tag, sublocation, verseMilestone ) )
loadErrors.append( "Unprocessed {!r} attribute ({}) in {} sub-element of {} at {} (1sc5)".format( attrib, value, subelement.tag, sublocation, verseMilestone ) )