forked from Freely-Given-org/BibleOrgSys
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OSISXMLBible.py
executable file
·2983 lines (2857 loc) · 220 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/python3
# -*- coding: utf-8 -*-
#
# OSISXMLBible.py
# Last modified: 2014-05-05 by RJH (also update ProgVersion below)
#
# Module handling OSIS XML Bibles
#
# Copyright (C) 2010-2014 Robert Hunt
# Author: Robert Hunt <robert316@users.sourceforge.net>
# 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".
"""
ProgName = "OSIS XML Bible format handler"
ProgVersion = "0.37"
ProgNameVersion = "{} v{}".format( ProgName, ProgVersion )
debuggingThisModule = False
import logging, os
from gettext import gettext as _
from xml.etree.ElementTree import ElementTree
import Globals
from ISO_639_3_Languages import ISO_639_3_Languages
from Bible import Bible, BibleBook
FILENAME_ENDINGS_TO_IGNORE = ('.ZIP.GO', '.ZIP.DATA',) # Must be UPPERCASE
EXTENSIONS_TO_IGNORE = ( 'ASC', 'BAK', 'BBLX', 'BC', 'CCT', 'CSS', 'DOC', 'DTS', 'HTM','HTML', 'JAR',
'LDS', 'LOG', 'MYBIBLE', 'NT','NTX', 'ODT', 'ONT','ONTX', 'OSIS', 'OT','OTX', 'PDB',
'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 OSISXMLBibleFileCheck( givenFolderName, strictCheck=True, autoLoad=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 Globals.verbosityLevel > 2: print( "OSISXMLBibleFileCheck( {}, {}, {} )".format( givenFolderName, strictCheck, autoLoad ) )
if Globals.debugFlag: assert( givenFolderName and isinstance( givenFolderName, str ) )
if Globals.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 '{}' folder is unreadable").format( givenFolderName ) )
return False
if not os.path.isdir( givenFolderName ):
logging.critical( _("OSISXMLBibleFileCheck: Given '{}' path is not a folder").format( givenFolderName ) )
return False
# Find all the files and folders in this folder
if Globals.verbosityLevel > 3: print( " OSISXMLBibleFileCheck: Looking for files in given {}".format( givenFolderName ) )
foundFolders, foundFiles = [], []
for something in os.listdir( givenFolderName ):
somepath = os.path.join( givenFolderName, something )
if os.path.isdir( somepath ): 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 )
if '__MACOSX' in foundFolders:
foundFolders.remove( '__MACOSX' ) # don't visit these directories
#print( 'ff', foundFiles )
# 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 Globals.strictCheckingFlag:
firstLines = Globals.peekIntoFile( thisFilename, givenFolderName, numLines=3 )
if not firstLines or len(firstLines)<2: continue
if not firstLines[0].startswith( '<?xml version="1.0"' ) \
and not firstLines[0].startswith( '\ufeff<?xml version="1.0"' ): # same but with BOM
if Globals.verbosityLevel > 2: print( "OB (unexpected) first line was '{}' in {}".format( firstLines, thisFilename ) )
continue
if not (firstLines[1].startswith( '<osis ' ) or firstLines[2].startswith( '<osis ' )):
continue
lastFilenameFound = thisFilename
numFound += 1
if numFound:
if Globals.verbosityLevel > 2: print( "OSISXMLBibleFileCheck got", numFound, givenFolderName, lastFilenameFound )
if numFound == 1 and autoLoad:
ub = OSISXMLBible( givenFolderName, lastFilenameFound )
ub.load() # Load and process the file
return ub
return numFound
elif looksHopeful and Globals.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 Globals.verbosityLevel > 3: print( " OSISXMLBibleFileCheck: Looking for files in {}".format( tryFolderName ) )
foundSubfolders, foundSubfiles = [], []
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 )
#print( 'fsf', foundSubfiles )
# See if there's an OSIS project here in this folder
for thisFilename in sorted( foundSubfiles ):
if strictCheck or Globals.strictCheckingFlag:
firstLines = Globals.peekIntoFile( thisFilename, tryFolderName, numLines=2 )
if not firstLines or len(firstLines)<2: continue
if not firstLines[0].startswith( '<?xml version="1.0"' ) \
and not firstLines[0].startswith( '\ufeff<?xml version="1.0"' ): # same but with BOM
if Globals.verbosityLevel > 2: print( "OB (unexpected) first line was '{}' in {}".format( firstLines, thisFilename ) )
continue
if not firstLines[1].startswith( '<osis ' ):
continue
foundProjects.append( (tryFolderName, thisFilename,) )
lastFilenameFound = thisFilename
numFound += 1
if numFound:
if Globals.verbosityLevel > 2: print( "OSISXMLBibleFileCheck foundProjects", numFound, foundProjects )
if numFound == 1 and autoLoad:
if Globals.debugFlag: assert( len(foundProjects) == 1 )
ub = OSISXMLBible( foundProjects[0][0], foundProjects[0][1] ) # Folder and filename
ub.load() # Load and process the file
return ub
return numFound
# end of OSISXMLBibleFileCheck
def clean( elementText ):
"""
Given some text from an XML element (which might be None)
return a stripped value and with internal CRLF characters replaced by spaces.
"""
if elementText is not None:
return elementText.strip().replace( '\r\n', ' ' ).replace( '\n', ' ' ).replace( '\r', ' ' )
# 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, encoding='utf-8' ):
"""
Constructor: just sets up the OSIS Bible object.
"""
# 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.encoding = sourceFilepath, givenName, encoding
self.title = self.version = self.date = self.source = None
self.tree = 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 = []
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
for filename in fileList:
if filename.lower().endswith('.xml'):
self.sourceFilepath = os.path.join( self.sourceFolder, filename )
if Globals.debugFlag: print( "Trying {}...".format( self.sourceFilepath ) )
if os.access( self.sourceFilepath, os.R_OK ): # we can read that file
self.possibleFilenames.append( filename )
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 {} is unreadable".format( repr(self.sourceFilepath) ) )
return # No use continuing
self.name = self.givenName
# end of OSISXMLBible.__init__
def load( self ):
"""
Loads the OSIS XML file or files.
"""
loadErrors = []
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, loadErrors )
elif os.path.isfile( self.sourceFilepath ): # most often we have all the Bible books in one file
self.__loadFile( self.sourceFilepath, loadErrors )
else:
logging.critical( "OSISXMLBible: Didn't find anything to load at {}".format( repr(self.sourceFilepath) ) )
loadErrors.append( _("OSISXMLBible: Didn't find anything to load at {}").format( repr(self.sourceFilepath) ) )
if loadErrors:
self.errorDictionary['Load Errors'] = loadErrors
#if Globals.debugFlag: print( "loadErrors", len(loadErrors), loadErrors ); halt
self.doPostLoadProcessing()
# end of OSISXMLBible.load
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 Globals.verbosityLevel > 1: print( _("Loading {}...").format( OSISFilepath ) )
self.tree = ElementTree().parse( OSISFilepath )
if Globals.debugFlag: assert( len ( self.tree ) ) # Fail here if we didn't load anything at all
# Find the main (osis) container
if self.tree.tag == OSISXMLBible.treeTag:
location = "OSIS file"
Globals.checkXMLNoText( self.tree, location, '4f6h', loadErrors )
Globals.checkXMLNoTail( self.tree, location, '1wk8', loadErrors )
# Process the attributes first
self.schemaLocation = None
for attrib,value in self.tree.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 ) )
# Find the submain (osisText) container
if len(self.tree)==1 and self.tree[0].tag == OSISXMLBible.textTag:
sublocation = "osisText in " + location
textElement = self.tree[0]
Globals.checkXMLNoText( textElement, sublocation, '3b5g', loadErrors )
Globals.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
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 self.osisRefWork:
if self.osisRefWork not in ('bible','Bible','defaultReferenceScheme',):
logging.warning( "New variety of osisRefWork: '{}'".format( self.osisRefWork ) )
loadErrors.append( "New variety of osisRefWork: '{}'".format( self.osisRefWork ) )
if self.lang:
if self.lang in ('en','he',): # Only specifically recognise these ones so far (English, Hebrew)
if Globals.verbosityLevel > 2: print( " Language is '{}'".format( self.lang ) )
else:
logging.info( "Discovered an unknown '{}' language".format( self.lang ) )
if Globals.verbosityLevel > 2: print( " osisIDWork is '{}'".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 '{}' tag)".format( OSISXMLBible.headerTag ) )
loadErrors.append( "Missing header element (looking for '{}' tag)".format( OSISXMLBible.headerTag ) )
# Find (and move) the optional front matter (div) container
if textElement[0].tag == OSISXMLBible.OSISNameSpace + "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 div0Type == 'front':
self.frontMatter = textElement[0]
textElement.remove( self.frontMatter )
self.validateFrontMatter( self.frontMatter )
else: logging.info( "No front matter division" )
self.divs, self.divTypesString = [], None
for element in textElement:
if element.tag == OSISXMLBible.divTag:
sub2location = "div in " + sublocation
Globals.checkXMLNoText( element, sub2location, '3a2s', loadErrors )
Globals.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 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 '{}' but got '{}'".format( OSISXMLBible.divTag, element.tag ) )
loadErrors.append( "Expected to find '{}' but got '{}'".format( OSISXMLBible.divTag, element.tag ) )
else:
logging.error( "Expected to find '{}' but got '{}'".format( OSISXMLBible.textTag, self.tree[0].tag ) )
loadErrors.append( "Expected to find '{}' but got '{}'".format( OSISXMLBible.textTag, self.tree[0].tag ) )
else:
logging.error( "Expected to load '{}' but got '{}'".format( OSISXMLBible.treeTag, self.tree.tag ) )
loadErrors.append( "Expected to load '{}' but got '{}'".format( OSISXMLBible.treeTag, self.tree.tag ) )
if self.tree.tail is not None and self.tree.tail.strip():
logging.error( "Unexpected '{}' tail data after {} element".format( self.tree.tail, self.tree.tag ) )
loadErrors.append( "Unexpected '{}' tail data after {} element".format( self.tree.tail, self.tree.tag ) )
# end of OSISXMLBible.loadFile
def validateHeader( self, header, loadErrors ):
"""
Check/validate the given OSIS header record.
"""
if Globals.verbosityLevel > 3: print( _("Loading OSIS header...") )
headerlocation = "header"
Globals.checkXMLNoText( header, headerlocation, '2s90', loadErrors )
Globals.checkXMLNoTail( header, headerlocation, '0k6l', loadErrors )
Globals.checkXMLNoAttributes( header, headerlocation, '4f6h', loadErrors )
numWorks = 0
for element in header:
if element.tag == OSISXMLBible.OSISNameSpace+"revisionDesc":
location = "revisionDesc of " + headerlocation
Globals.checkXMLNoText( header, location, '2t5y', loadErrors )
Globals.checkXMLNoTail( header, location, '3a1l', loadErrors )
Globals.checkXMLNoAttributes( header, location, '6hj8', loadErrors )
# Process the attributes first
resp = None
for attrib,value in element.items():
if attrib=="resp": resp = value
else:
logging.warning( "4j6a Unprocessed {} attribute ({}) in {}".format( attrib, value, location ) )
loadErrors.append( "Unprocessed {} attribute ({}) in {} (4j6a)".format( attrib, value, location ) )
# Now process the subelements
for subelement in element.getchildren():
Globals.checkXMLNoSubelements( subelement, location, '4f3f', loadErrors )
if len(subelement):
logging.error( "Unexpected {} subelements in subelement {} in {} revisionDesc".format( len(subelement), subelement.tag, osisWork ) )
loadErrors.append( "Unexpected {} subelements in subelement {} in {} revisionDesc".format( len(subelement), subelement.tag, osisWork ) )
if subelement.tag == OSISXMLBible.OSISNameSpace+"date":
sublocation = "date of " + location
Globals.checkXMLNoTail( subelement, sublocation, '4sd2', loadErrors )
Globals.checkXMLNoAttributes( subelement, sublocation, '9hj5', loadErrors )
Globals.checkXMLNoSubelements( subelement, sublocation, '6g3s', loadErrors )
date = subelement.text
elif subelement.tag == OSISXMLBible.OSISNameSpace+"p":
sublocation = "p of " + location
Globals.checkXMLNoTail( subelement, sublocation, '9k5a', loadErrors )
Globals.checkXMLNoAttributes( subelement, sublocation, '4f4s', loadErrors )
Globals.checkXMLNoSubelements( subelement, sublocation, '3c5g', loadErrors )
p = element.text
else:
logging.error( "6g4g Unprocessed '{}' sub-element ({}) in revisionDesc element".format( subelement.tag, subelement.text ) )
loadErrors.append( "Unprocessed '{}' sub-element ({}) in revisionDesc element (6g4g)".format( subelement.tag, subelement.text ) )
elif element.tag == OSISXMLBible.OSISNameSpace+"work":
location = "work of " + headerlocation
Globals.checkXMLNoText( header, location, '5h9k', loadErrors )
Globals.checkXMLNoTail( header, location, '1d4f', loadErrors )
Globals.checkXMLNoAttributes( header, location, '2s3d', loadErrors )
# Process the attributes first
osisWork = lang = None
for attrib,value in element.items():
if attrib=="osisWork":
osisWork = value
if Globals.verbosityLevel > 2: print( " Have a '{}' work".format( osisWork ) )
elif attrib==OSISXMLBible.XMLNameSpace+"lang": lang = value
else:
logging.warning( "2k5s Unprocessed {} attribute ({}) in work element".format( attrib, value ) )
loadErrors.append( "Unprocessed {} attribute ({}) in work element (2k5s)".format( attrib, value ) )
# Now process the subelements
for subelement in element.getchildren():
if len(subelement):
logging.error( "hf54 Unexpected {} subelements in subelement {} in {} work".format( len(subelement), subelement.tag, osisWork ) )
loadErrors.append( "Unexpected {} subelements in subelement {} in {} work (hf54)".format( len(subelement), subelement.tag, osisWork ) )
if subelement.tag == OSISXMLBible.OSISNameSpace+"title":
sublocation = "title of " + location
Globals.checkXMLNoTail( subelement, sublocation, '8k0k', loadErrors )
Globals.checkXMLNoSubelements( subelement, sublocation, '0k5f', loadErrors )
if not self.title: self.title = subelement.text # Take the first title
titleType = None
for attrib,value in subelement.items():
if attrib=="type": titleType = value
else:
logging.warning( "8f83 Unprocessed '{}' attribute ({}) in {}".format( attrib, value, sublocation ) )
loadErrors.append( "Unprocessed '{}' attribute ({}) in {} (8f83)".format( attrib, value, sublocation ) )
elif subelement.tag == OSISXMLBible.OSISNameSpace+"version":
sublocation = "version of " + location
Globals.checkXMLNoText( subelement, sublocation, '3g1h', loadErrors )
Globals.checkXMLNoTail( subelement, sublocation, '0k3d', loadErrors )
Globals.checkXMLNoAttributes( subelement, sublocation, '7h4f', loadErrors )
Globals.checkXMLNoSubelements( subelement, sublocation, '2j9z', loadErrors )
self.version = subelement.text
for attrib,value in subelement.items():
logging.warning( "93d2 Unprocessed '{}' attribute ({}) in {}".format( attrib, value, sublocation ) )
loadErrors.append( "Unprocessed '{}' attribute ({}) in {} (93d2)".format( attrib, value, sublocation ) )
elif subelement.tag == OSISXMLBible.OSISNameSpace+"date":
sublocation = "date of " + location
Globals.checkXMLNoTail( subelement, sublocation, '3f9j', loadErrors )
Globals.checkXMLNoSubelements( subelement, sublocation, '4x5h', loadErrors )
date = subelement.text
dateType = dateEvent = None
for attrib,value in subelement.items():
if attrib=="type": dateType = value
elif attrib=="event": dateEvent = value
else:
logging.warning( "2k4d Unprocessed '{}' attribute ({}) in {}".format( attrib, value, sublocation ) )
loadErrors.append( "Unprocessed '{}' attribute ({}) in {} (2k4d)".format( attrib, value, sublocation ) )
if Globals.debugFlag: assert( dateType in (None,'Gregorian',) )
if Globals.debugFlag: assert( dateEvent in (None,'eversion',) )
elif subelement.tag == OSISXMLBible.OSISNameSpace+"creator":
sublocation = "creator of " + location
Globals.checkXMLNoTail( subelement, sublocation, '3n5z', loadErrors )
Globals.checkXMLNoSubelements( subelement, sublocation, '9n3z', loadErrors )
self.creator = subelement.text
creatorRole = creatorType = None
for attrib,value in subelement.items():
if attrib=="role": creatorRole = value
elif attrib=="type": creatorType = value
else:
logging.warning( "9f2d Unprocessed '{}' attribute ({}) in {}".format( attrib, value, sublocation ) )
loadErrors.append( "Unprocessed '{}' attribute ({}) in {} (9f2d)".format( attrib, value, sublocation ) )
if Globals.verbosityLevel > 2: print( " Creator (role='{}'{}) was '{}'".format( creatorRole, ", type='{}'".format(creatorType) if creatorType else '', self.creator ) )
elif subelement.tag == OSISXMLBible.OSISNameSpace+"contributor":
sublocation = "contributor of " + location
Globals.checkXMLNoTail( subelement, sublocation, '3z4o', loadErrors )
Globals.checkXMLNoSubelements( subelement, sublocation, '2u5z', loadErrors )
self.contributor = subelement.text
contributorRole = None
for attrib,value in subelement.items():
if attrib=="role": contributorRole = value
else:
logging.warning( "1s5g Unprocessed '{}' attribute ({}) in {}".format( attrib, value, sublocation ) )
loadErrors.append( "Unprocessed '{}' attribute ({}) in {} (1s5g)".format( attrib, value, sublocation ) )
if Globals.verbosityLevel > 2: print( " Contributor ({}) was '{}'".format( contributorRole, self.contributor ) )
elif subelement.tag == OSISXMLBible.OSISNameSpace+"subject":
sublocation = "subject of " + location
Globals.checkXMLNoTail( subelement, sublocation, 'c35g', loadErrors )
Globals.checkXMLNoAttributes( subelement, sublocation, 'frg3', loadErrors )
Globals.checkXMLNoSubelements( subelement, sublocation, 'ft4g', loadErrors )
self.subject = subelement.text
if Globals.verbosityLevel > 2: print( " Subject was '{}'".format( self.subject ) )
elif subelement.tag == OSISXMLBible.OSISNameSpace+"description":
sublocation = "description of " + location
Globals.checkXMLNoTail( subelement, sublocation, '1j6z', loadErrors )
Globals.checkXMLNoSubelements( subelement, sublocation, '4a7s', loadErrors )
self.description = subelement.text
descriptionType = descriptionSubType = resp = None
for attrib,value in subelement.items():
if attrib=="type": descriptionType = value
elif attrib=="subType": descriptionSubType = value
elif attrib=="resp": resp = value
else:
logging.warning( "6f3d Unprocessed '{}' attribute ({}) in {}".format( attrib, value, sublocation ) )
loadErrors.append( "Unprocessed '{}' attribute ({}) in {} (6f3d)".format( attrib, value, sublocation ) )
if descriptionType: assert( descriptionType in ('usfm','x-english','x-lwc',) )
if descriptionType or self.description and Globals.verbosityLevel > 2: print( " Description{} is '{}'".format( " ({})".format(descriptionType) if descriptionType else '', self.description ) )
elif subelement.tag == OSISXMLBible.OSISNameSpace+"format":
sublocation = "format of " + location
Globals.checkXMLNoTail( subelement, sublocation, '5n3x', loadErrors )
Globals.checkXMLNoSubelements( subelement, sublocation, '8v3x', loadErrors )
self.format = subelement.text
formatType = None
for attrib,value in subelement.items():
if attrib=="type": formatType = value
else:
logging.warning( "2f5s Unprocessed '{}' attribute ({}) in {}".format( attrib, value, sublocation ) )
loadErrors.append( "Unprocessed '{}' attribute ({}) in {} (2f5s)".format( attrib, value, sublocation ) )
if Globals.debugFlag: assert( formatType == 'x-MIME' )
if Globals.verbosityLevel > 2: print( " Format ({}) is '{}'".format( formatType, self.format ) )
elif subelement.tag == OSISXMLBible.OSISNameSpace+"type":
sublocation = "type of " + location
Globals.checkXMLNoTail( subelement, sublocation, '3b4z', loadErrors )
Globals.checkXMLNoSubelements( subelement, sublocation, '8j8b', loadErrors )
self.type = subelement.text
typeType = None
for attrib,value in subelement.items():
if attrib=="type": typeType = value
else:
logging.warning( "7j3f Unprocessed '{}' attribute ({}) in {}".format( attrib, value, sublocation ) )
loadErrors.append( "Unprocessed '{}' attribute ({}) in {} (7j3f)".format( attrib, value, sublocation ) )
if Globals.debugFlag: assert( typeType == 'OSIS' )
if Globals.verbosityLevel > 2: print( " Type ({}) is '{}'".format( typeType, self.type ) )
elif subelement.tag == OSISXMLBible.OSISNameSpace+"identifier":
sublocation = "identifier of " + location
Globals.checkXMLNoTail( subelement, sublocation, '5a2m', loadErrors )
Globals.checkXMLNoSubelements( subelement, sublocation, '2x6e', loadErrors )
identifier = subelement.text
identifierType = None
for attrib,value in subelement.items():
if attrib=="type": identifierType = value
else:
logging.warning( "2d5g Unprocessed '{}' attribute ({}) in {}".format( attrib, value, sublocation ) )
loadErrors.append( "Unprocessed '{}' attribute ({}) in {} (2d5g)".format( attrib, value, sublocation ) )
#print( "id", repr(identifierType) )
if Globals.debugFlag: assert( identifierType in ('OSIS','URL','x-ebible-id',) )
if Globals.verbosityLevel > 2: print( " Identifier ({}) is '{}'".format( identifierType, identifier ) )
#print( "Here vds1", repr(self.name), repr(self.abbreviation) )
if identifierType=='OSIS':
if not self.name: self.name = identifier
if identifier.startswith( 'Bible.' ) and not self.abbreviation:
self.abbreviation = identifier[6:]
self.identifier = identifier
#print( "Here vds2", repr(self.name), repr(self.abbreviation) )
elif subelement.tag == OSISXMLBible.OSISNameSpace+"source":
sublocation = "source of " + location
Globals.checkXMLNoTail( subelement, sublocation, '1i8p', loadErrors )
Globals.checkXMLNoAttributes( subelement, sublocation, '4gh7', loadErrors )
Globals.checkXMLNoSubelements( subelement, sublocation, '6p3a', loadErrors )
self.source = subelement.text
sourceRole = None
for attrib,value in subelement.items():
if attrib=="role": sourceRole = value
else:
logging.warning( "6h7h Unprocessed '{}' attribute ({}) in {}".format( attrib, value, sublocation ) )
loadErrors.append( "Unprocessed '{}' attribute ({}) in {} (6h7h)".format( attrib, value, sublocation ) )
if Globals.verbosityLevel > 2: print( " Source{} was '{}'".format( " ({})".format(sourceRole) if sourceRole else '', self.source ) )
elif subelement.tag == OSISXMLBible.OSISNameSpace+"publisher":
sublocation = "publisher of " + location
Globals.checkXMLNoTail( subelement, sublocation, '3z7g', loadErrors )
Globals.checkXMLNoSubelements( subelement, sublocation, '8n3x', loadErrors )
self.publisher = subelement.text.replace( '&', '&' )
publisherType = None
for attrib,value in subelement.items():
if attrib=='type': publisherType = value
else:
logging.warning( "7g5g Unprocessed '{}' attribute ({}) in {}".format( attrib, value, sublocation ) )
loadErrors.append( "Unprocessed '{}' attribute ({}) in {} (7g5g)".format( attrib, value, sublocation ) )
if Globals.verbosityLevel > 2: print( " Publisher {}is/was '{}'".format( '({}) '.format(publisherType) if publisherType else '', self.publisher ) )
elif subelement.tag == OSISXMLBible.OSISNameSpace+"scope":
sublocation = "scope of " + location
Globals.checkXMLNoTail( subelement, sublocation, '1z4i', loadErrors )
Globals.checkXMLNoAttributes( subelement, sublocation, '3d4d', loadErrors )
Globals.checkXMLNoSubelements( subelement, sublocation, '2g5z', loadErrors )
self.scope = subelement.text
if Globals.verbosityLevel > 2: print( " Scope is '{}'".format( self.scope ) )
elif subelement.tag == OSISXMLBible.OSISNameSpace+"coverage":
sublocation = "coverage of " + location
Globals.checkXMLNoTail( subelement, sublocation, '9l2p', loadErrors )
Globals.checkXMLNoAttributes( subelement, sublocation, '3d6g', loadErrors )
Globals.checkXMLNoSubelements( subelement, sublocation, '3a6p', loadErrors )
self.coverage = subelement.text
if Globals.verbosityLevel > 2: print( " Coverage is '{}'".format( self.coverage ) )
elif subelement.tag == OSISXMLBible.OSISNameSpace+"refSystem":
sublocation = "refSystem of " + location
Globals.checkXMLNoTail( subelement, sublocation, '3p65', loadErrors )
Globals.checkXMLNoAttributes( subelement, sublocation, '2s4f', loadErrors )
Globals.checkXMLNoSubelements( subelement, sublocation, '3mtp', loadErrors )
self.refSystem = subelement.text
if self.refSystem in ('Bible','Bible.KJV','Bible.NRSVA','Dict.Strongs','Dict.Robinsons','Dict.strongMorph',):
if Globals.verbosityLevel > 2: print( " Reference system is '{}'".format( self.refSystem ) )
else:
logging.info( "Discovered an unknown '{}' refSystem".format( self.refSystem ) )
loadErrors.append( "Discovered an unknown '{}' refSystem".format( self.refSystem ) )
elif subelement.tag == OSISXMLBible.OSISNameSpace+"language":
sublocation = "language of " + location
Globals.checkXMLNoTail( subelement, sublocation, '4v2n', loadErrors )
Globals.checkXMLNoSubelements( subelement, sublocation, '8n34', loadErrors )
self.language = subelement.text
languageType = None
for attrib,value in subelement.items():
if attrib=="type": languageType = value
else:
logging.warning( "6g4f Unprocessed '{}' attribute ({}) in {}".format( attrib, value, sublocation ) )
loadErrors.append( "Unprocessed '{}' attribute ({}) in {} (6g4f)".format( attrib, value, sublocation ) )
if languageType in ('SIL','IETF','x-ethnologue','x-in-english','x-vernacular',):
if ISOLanguages.isValidLanguageCode( self.language ):
if Globals.verbosityLevel > 2: print( " Language is: {}".format( ISOLanguages.getLanguageName( self.language ) ) )
else: print( "Discovered an unknown '{}' language".format( self.language ) )
else: print( "Discovered an unknown '{}' languageType".format( languageType ) )
elif subelement.tag == OSISXMLBible.OSISNameSpace+"rights":
sublocation = "rights of " + location
Globals.checkXMLNoTail( subelement, sublocation, '6v2x', loadErrors )
Globals.checkXMLNoSubelements( subelement, sublocation, '9l5b', loadErrors )
self.rights = subelement.text
copyrightType = None
for attrib,value in subelement.items():
if attrib=="type": copyrightType = value
else:
logging.warning( "1s3d Unprocessed '{}' attribute ({}) in {}".format( attrib, value, sublocation ) )
loadErrors.append( "Unprocessed '{}' attribute ({}) in {} (1s3d)".format( attrib, value, sublocation ) )
if Globals.debugFlag: assert( copyrightType in (None,'x-copyright','x-license','x-license-url',) )
if Globals.verbosityLevel > 2: print( " Rights{} are/were '{}'".format( " ({})".format(copyrightType) if copyrightType else '', self.rights ) )
elif subelement.tag == OSISXMLBible.OSISNameSpace+"relation":
sublocation = "relation of " + location
Globals.checkXMLNoText( subelement, sublocation, 'g4h2', loadErrors )
Globals.checkXMLNoTail( subelement, sublocation, 'gh53', loadErrors )
Globals.checkXMLNoAttributes( subelement, sublocation, 'd2fd', loadErrors )
Globals.checkXMLNoSubelements( subelement, sublocation, 's2fy', loadErrors )
else:
logging.error( "7h5g Unprocessed '{}' sub-element ({}) in {}".format( subelement.tag, subelement.text, location) )
loadErrors.append( "Unprocessed '{}' sub-element ({}) in {} (7h5g)".format( subelement.tag, subelement.text, location) )
#if element.find("date") is not None: self.date = element.find("date").text
#if element.find("title") is not None: self.title = element.find("title").text
numWorks += 1
elif element.tag == OSISXMLBible.OSISNameSpace+"workPrefix":
location = "workPrefix of " + headerlocation
Globals.checkXMLNoText( header, location, 'f5h8', loadErrors )
Globals.checkXMLNoTail( header, location, 'f2g7', loadErrors )
Globals.checkXMLNoAttributes( header, location, '6g4f', loadErrors )
# Process the attributes first
workPrefixPath = workPrefixWork = None
for attrib,value in element.items():
if attrib=="path": workPrefixPath = value
elif attrib=="osisWork": workPrefixWork = value
else:
logging.warning( "7yh4 Unprocessed {} attribute ({}) in workPrefix element".format( attrib, value ) )
loadErrors.append( "Unprocessed {} attribute ({}) in workPrefix element (7yh4)".format( attrib, value ) )
# Now process the subelements
for subelement in element.getchildren():
if subelement.tag == OSISXMLBible.OSISNameSpace+"revisionDesc":
sublocation = "revisionDesc of " + location
Globals.checkXMLNoText( subelement, sublocation, 'c3t5', loadErrors )
Globals.checkXMLNoTail( subelement, sublocation, 'z2f8', loadErrors )
Globals.checkXMLNoAttributes( subelement, sublocation, '2w3e', loadErrors )
Globals.checkXMLNoSubelements( subelement, sublocation, 'm5o0', loadErrors )
#self.something = subelement.text
for attrib,value in subelement.items():
logging.warning( "3h6r Unprocessed '{}' attribute ({}) in {} subelement of workPrefix element".format( attrib, value, subelement.tag ) )
loadErrors.append( "Unprocessed '{}' attribute ({}) in {} subelement of workPrefix element (3h6r)".format( attrib, value, subelement.tag ) )
else:
logging.error( "8h4g Unprocessed '{}' sub-element ({}) in workPrefix element".format( subelement.tag, subelement.text ) )
loadErrors.append( "Unprocessed '{}' sub-element ({}) in workPrefix element (8h4g)".format( subelement.tag, subelement.text ) )
else:
logging.error( "Expected to load '{}' but got '{}'".format( OSISXMLBible.OSISNameSpace+"work", element.tag ) )
loadErrors.append( "Expected to load '{}' but got '{}'".format( OSISXMLBible.OSISNameSpace+"work", element.tag ) )
if element.tail is not None and element.tail.strip():
logging.error( "Unexpected '{}' tail data after {} element in header element".format( element.tail, element.tag ) )
loadErrors.append( "Unexpected '{}' tail data after {} element in header element".format( element.tail, element.tag ) )
if not numWorks:
logging.warning( "OSIS header doesn't specify any work records." )
loadErrors.append( "OSIS header doesn't specify any work records." )
# end of OSISXMLBible.validateHeader
def validateFrontMatter( self, frontMatter,loadErrors ):
"""
Check/validate the given OSIS front matter (div) record.
"""
if Globals.verbosityLevel > 3: print( _("Loading OSIS front matter...") )
frontMatterLocation = "frontMatter"
Globals.checkXMLNoText( frontMatter, frontMatterLocation, 'c3a2', loadErrors )
Globals.checkXMLNoTail( frontMatter, frontMatterLocation, 'm7s9', loadErrors )
# Process the attributes first
for attrib,value in frontMatter.items():
if attrib=="type":
pass # We've already processed this
else:
logging.warning( "98h4 Unprocessed {} attribute ({}) in {}".format( attrib, value, frontMatterLocation ) )
loadErrors.append( "Unprocessed {} attribute ({}) in {} (98h4)".format( attrib, value, frontMatterLocation ) )
for element in frontMatter:
if element.tag == OSISXMLBible.OSISNameSpace+"titlePage":
location = "titlePage of " + frontMatterLocation
Globals.checkXMLNoText( element, location, 'k9l3', loadErrors )
Globals.checkXMLNoTail( element, location, 'a3s4', loadErrors )
Globals.checkXMLNoAttributes( element, location, '1w34', loadErrors )
# Process the attributes first
for attrib,value in element.items():
if attrib=="type":
if Globals.debugFlag: assert( value == 'front' ) # We've already processed this in the calling routine
else:
logging.warning( "3f5d Unprocessed {} attribute ({}) in {}".format( attrib, value, location ) )
loadErrors.append( "Unprocessed {} attribute ({}) in {} (3f5d)".format( attrib, value, location ) )
# Now process the subelements
for subelement in element.getchildren():
Globals.checkXMLNoSubelements( subelement, location, 'dv61', loadErrors )
if subelement.tag == OSISXMLBible.OSISNameSpace+"p":
sublocation = "p of " + location
Globals.checkXMLNoTail( subelement, sublocation, 'h3x5', loadErrors )
Globals.checkXMLNoAttributes( subelement, sublocation, '5ygg', loadErrors )
Globals.checkXMLNoSubelements( subelement, sublocation, '8j54', loadErrors )
p = element.text
else:
logging.error( "1dc5 Unprocessed '{}' sub-element ({}) in {}".format( subelement.tag, subelement.text, location ) )
loadErrors.append( "Unprocessed '{}' sub-element ({}) in {} (1dc5)".format( subelement.tag, subelement.text, location ) )
elif element.tag == OSISXMLBible.OSISNameSpace+"div":
location = "div of " + frontMatterLocation
Globals.checkXMLNoText( element, location, 'b3f4', loadErrors )
Globals.checkXMLNoTail( element, location, 'd3s2', loadErrors )
# Process the attributes first
divType = None
for attrib,value in element.items():
if attrib=="type": divType = value
else:
logging.warning( "7h4g Unprocessed {} attribute ({}) in {}".format( attrib, value, location ) )
loadErrors.append( "Unprocessed {} attribute ({}) in {} (7h4g)".format( attrib, value, location ) )
if Globals.debugFlag: assert( divType == 'x-license' )
# Now process the subelements
for subelement in element.getchildren():
if subelement.tag == OSISXMLBible.OSISNameSpace+"title":
sublocation = "title of " + location
Globals.checkXMLNoTail( subelement, sublocation, 'k8j8', loadErrors )
Globals.checkXMLNoAttributes( subelement, sublocation, '48j6', loadErrors )
Globals.checkXMLNoSubelements( subelement, sublocation, 'l0l0', loadErrors )
date = subelement.text
logging.warning( "sdh3 Not handled yet", subelement.text )
loadErrors.append( "sdh3 Not handled yet", subelement.text )
elif subelement.tag == OSISXMLBible.OSISNameSpace+"p":
sublocation = "p of " + location
Globals.checkXMLNoTail( subelement, sublocation, 'd4d4', loadErrors )
Globals.checkXMLNoAttributes( subelement, sublocation, '2de5', loadErrors )
p = element.text
# Now process the subelements
for sub2element in subelement.getchildren():
Globals.checkXMLNoSubelements( sub2element, sublocation, 's3s3', loadErrors )
if sub2element.tag == OSISXMLBible.OSISNameSpace+"a":
sub2location = "a of " + sublocation
Globals.checkXMLNoSubelements( sub2element, sub2location, 'j4h3', loadErrors )
aText, aTail = element.text, element.tail
# Process the attributes
href = None
for attrib,value in sub2element.items():
if attrib=="href": href = value
else:
logging.warning( "7g4a Unprocessed {} attribute ({}) in {}".format( attrib, value, sub2location ) )
loadErrors.append( "Unprocessed {} attribute ({}) in {} (7g4a)".format( attrib, value, sub2location ) )
else:
logging.error( "3d45 Unprocessed '{}' sub2-element ({}) in {}".format( sub2element.tag, sub2element.text, sublocation ) )
loadErrors.append( "Unprocessed '{}' sub2-element ({}) in {} (3d45)".format( sub2element.tag, sub2element.text, sublocation ) )
else:
logging.error( "034f Unprocessed '{}' sub-element ({}) in {}".format( subelement.tag, subelement.text, location ) )
loadErrors.append( "Unprocessed '{}' sub-element ({}) in {} (034f)".format( subelement.tag, subelement.text, location ) )
else:
logging.error( "2sd4 Unprocessed '{}' sub-element ({}) in {}".format( element.tag, element.text, frontMatterLocation ) )
loadErrors.append( "Unprocessed '{}' sub-element ({}) in {} (2sd4)".format( element.tag, element.text, frontMatterLocation ) )
if element.tail is not None and element.tail.strip():
logging.error( "Unexpected '{}' tail data after {} element in header element".format( element.tail, element.tag ) )
loadErrors.append( "Unexpected '{}' tail data after {} element in header element".format( element.tail, element.tag ) )
# end of OSISXMLBible.validateFrontMatter
def validateAndExtractMainDiv( self, div, loadErrors ):
"""
Check/validate and extract data from the given OSIS div record.
This may be a book group, or directly into a book
"""
if Globals.verbosityLevel > 3: print( _("Loading OSIS main div...") )
haveEIDs = False
self.haveBook = False
def validateGroupTitle( element, locationDescription ):
"""
Check/validate and process a OSIS Bible paragraph, including all subfields.
"""
location = "validateGroupTitle: " + locationDescription
Globals.checkXMLNoTail( element, location, 'c4vd', loadErrors )
titleText = element.text
titleType = titleSubType = titleShort = titleLevel = None
for attrib,value in element.items():
#if attrib=="type":
#titleType = value
#elif attrib=="subType":
#titleSubType = value
if attrib=="short":
titleShort = value
#elif attrib=="level":
#titleLevel = value # Not used anywhere yet :(
else:
logging.warning( "vdv3 Unprocessed '{}' attribute ({}) in {} at {}".format( attrib, value, location, verseMilestone ) )
loadErrors.append( "Unprocessed '{}' attribute ({}) in {} at {} (vdv3)".format( attrib, value, location, verseMilestone ) )
#if titleSubType: assert( titleSubType == 'x-preverse' )
Globals.checkXMLNoSubelements( element, location+" at book group", 'js21', loadErrors )
if Globals.debugFlag: assert( titleText )
if titleText:
if Globals.verbosityLevel > 2: print( " Got book group title", repr(titleText) )
self.divisions[titleText] = []
# end of OSISXMLBible.validateGroupTitle
# Process the div attributes first
mainDivType = mainDivOsisID = mainDivCanonical = None
BBB = USFMAbbreviation = USFMNumber = ''
for attrib,value in div.items():
if attrib=="type":
mainDivType = value
if mainDivOsisID and Globals.verbosityLevel > 2: print( _("Loading {} {}...").format( mainDivOsisID, mainDivType ) )
elif attrib=="osisID":
mainDivOsisID = value
if mainDivType and Globals.verbosityLevel > 2: print( _("Loading {} {}...").format( mainDivOsisID, mainDivType ) )
elif attrib=="canonical":
mainDivCanonical = value
else:
logging.warning( "93f5 Unprocessed '{}' attribute ({}) in main div element".format( attrib, value ) )
loadErrors.append( "Unprocessed '{}' attribute ({}) in main div element (93f5)".format( attrib, value ) )
if not mainDivType or not (mainDivOsisID or mainDivCanonical):
logging.warning( "Incomplete mainDivType '{}' and mainDivOsisID '{}' attributes in main div element".format( mainDivType, mainDivOsisID ) )
loadErrors.append( "Incomplete mainDivType '{}' and mainDivOsisID '{}' attributes in main div element".format( mainDivType, mainDivOsisID ) )
if mainDivType == 'bookGroup': # this is all the books lumped in together into one big div
if Globals.debugFlag: assert( mainDivCanonical == "true" )
# We have to set BBB when we get a chapter reference
if Globals.verbosityLevel > 2: print( _(" Loading a book group...") )
self.haveBook = False
for element in div:
if element.tag == OSISXMLBible.OSISNameSpace+"title":
location = "title of {} div".format( mainDivType )
validateGroupTitle( element, location )
elif element.tag == OSISXMLBible.OSISNameSpace+"div": # Assume it's a book
self.validateAndExtractBookDiv( element )
else:
logging.error( "hfs6 Unprocessed '{}' sub-element ({}) in {} div".format( element.tag, element.text, mainDivType ) )
loadErrors.append( "Unprocessed '{}' sub-element ({}) in {} div (hfs6)".format( element.tag, element.text, mainDivType ) )
elif mainDivType == 'book': # this is a single book (not in a group)
self.validateAndExtractBookDiv( div, loadErrors )
else:
logging.critical( "What kind of OSIS book div is this? {} {} {}".format( repr(mainDivType), repr(mainDivOsisID), repr(mainDivCanonical) ) )
loadErrors.append( "What kind of OSIS book div is this? {} {} {}".format( repr(mainDivType), repr(mainDivOsisID), repr(mainDivCanonical) ) )
if Globals.debugFlag: halt
# end of OSISXMLBible.validateAndExtractMainDiv
def validateAndExtractBookDiv( self, div, loadErrors ):
"""
Check/validate and extract data from the given OSIS div record.
This should be a book division.
"""
def validateChapterElement( element, chapterMilestone, verseMilestone, locationDescription ):
"""
Check/validate and process a chapter element.
Returns one of the following:
OSIS chapter ID string for a startMilestone
'' for an endMilestone
'chapter' + chapter number string for a container
"""
nonlocal BBB, USFMAbbreviation, USFMNumber #, bookResults, USFMResults
#print( "validateChapterElement at {} with {} and {}".format( locationDescription, chapterMilestone, verseMilestone ) )
location = "validateChapterElement: " + locationDescription
Globals.checkXMLNoText( element, location+" at "+verseMilestone, 's2a8', loadErrors )
Globals.checkXMLNoTail( element, location+" at "+verseMilestone, 'j9k7', loadErrors )
OSISChapterID = sID = eID = chapterN = canonical = chapterTitle = None
for attrib,value in element.items():
if attrib=="osisID": OSISChapterID = value
elif attrib=="sID": sID = value
elif attrib=="eID": eID = value
elif attrib=="n": chapterN = value
elif attrib=="canonical": canonical = value
elif attrib=="chapterTitle": chapterTitle = value
else:
displayTag = element.tag[len(self.OSISNameSpace):] if element.tag.startswith(self.OSISNameSpace) else element.tag
logging.warning( _("5f3d Unprocessed '{}' attribute ({}) in {} subelement of {}").format( attrib, value, displayTag, location ) )
loadErrors.append( _("Unprocessed '{}' attribute ({}) in {} subelement of {} (5f3d)").format( attrib, value, displayTag, location ) )
if sID and not OSISChapterID:
logging.error( _("Missing chapter ID attribute in {}: {}").format( location, element.items() ) )
loadErrors.append( _("Missing chapter ID attribute in {}: {}").format( location, element.items() ) )
if len(element)==0 and ( sID or eID or OSISChapterID): # it's a chapter milestone (no sub-elements)
# No verse milestone should be open because verses can't cross chapter boundaries
if verseMilestone:
if haveEIDs:
logging.error( _("Unexpected {} chapter milestone while {} verse milestone is still open at {}").format( element.items(), verseMilestone, location ) )
loadErrors.append( _("Unexpected {} chapter milestone while {} verse milestone is still open at {}").format( element.items(), verseMilestone, location ) )
if OSISChapterID and sID and not eID:
chapterMilestone = sID
#if not chapterMilestone.count('.')==1: logging.warning( "{} chapter milestone seems wrong format for {} at {}".format( chapterMilestone, OSISChapterID, location ) )
elif eID and not OSISChapterID and not sID:
if chapterMilestone and eID==chapterMilestone: chapterMilestone = ''
else:
logging.error( _("Chapter milestone {} end didn't match {} at {}").format( eID, chapterMilestone, location ) )
loadErrors.append( _("Chapter milestone {} end didn't match {} at {}").format( eID, chapterMilestone, location ) )
elif OSISChapterID and not (sID or eID): # some OSIS formats use this
if Globals.debugFlag: assert( canonical == "true" )
chapterMilestone = OSISChapterID
else:
print( repr(OSISChapterID), repr(sID), repr(eID) )
logging.error( _("Unrecognized chapter milestone in {}: {} at {}").format( location, element.items(), location ) )
loadErrors.append( _("Unrecognized chapter milestone in {}: {} at {}").format( location, element.items(), location ) )
if chapterMilestone: # Have a chapter milestone like Jas.1
if not OSISChapterID:
logging.error( "Missing chapter ID for {} at {}".format( chapterMilestone, location ) )
loadErrors.append( "Missing chapter ID for {} at {}".format( chapterMilestone, location ) )
else:
if not OSISChapterID.count('.')==1:
logging.error( "{} chapter ID seems wrong format for {} at {}".format( OSISChapterID, chapterMilestone, location ) )
loadErrors.append( "{} chapter ID seems wrong format for {} at {}".format( OSISChapterID, chapterMilestone, location ) )
bits = OSISChapterID.split( '.' )
if Globals.debugFlag: assert( len(bits) == 2 )
cmBBB = None
try:
cmBBB = Globals.BibleBooksCodes.getBBBFromOSIS( bits[0] )
except:
logging.critical( _("'{}' is not a valid OSIS book identifier").format( bits[0] ) )
loadErrors.append( _("'{}' is not a valid OSIS book identifier").format( bits[0] ) )
if cmBBB and cmBBB != BBB: # We've started on a new book
#if BBB and ( len(bookResults)>20 or len(USFMResults)>20 ): # Save the previous book
if BBB and len(self.thisBook._rawLines) > 5: # Save the previous book
#print( verseMilestone )
if Globals.verbosityLevel > 2: print( "Saving previous {} book into results...".format( BBB ) )
#print( mainDivOsisID, "results", BBB, bookResults[:10], "..." )
# Remove the last titles
#lastBookResult = bookResults.pop()
#if lastBookResult[0]!='sectionTitle':
#lastBookResult = None
#lastUSFMResult = USFMResults.pop()
#if lastUSFMResult[0]!='s':
#lastUSFMResult = None
lastLineTuple = self.thisBook._rawLines.pop()
if Globals.debugFlag: assert( len(lastLineTuple) == 2 )
if lastLineTuple[0] != 's':
self.thisBook._rawLines.append( lastLineTuple ) # No good -- put it back
lastLineTuple = None
#if bookResults: self.bkData[BBB] = bookResults
#if USFMResults: self.USFMBooks[BBB] = USFMResults
self.saveBook( self.thisBook )
#bookResults, USFMResults = [], []
#if lastBookResult:
#lastBookResultList = list( lastBookResult )
#lastBookResultList[0] = 'mainTitle'
#adjBookResult = tuple( lastBookResultList )
##print( lastBookResultList )
#if lastUSFMResult:
#lastUSFMResultList = list( lastUSFMResult )
#lastUSFMResultList[0] = 'mt1'
##print( lastUSFMResultList )
#adjSFMResult = tuple( lastUSFMResultList )
if lastLineTuple:
self.thisBook.appendLine( 'id', (USFMAbbreviation if USFMAbbreviation else mainDivOsisID).upper() + " converted to USFM from OSIS by {} V{}".format( ProgName, ProgVersion ) )
self.thisBook.appendLine( 'h', USFMAbbreviation if USFMAbbreviation else mainDivOsisID )
self.thisBook.appendLine( 'mt1', lastLineTuple[1] ) # Change from s to mt1
chapterMilestone = verseMilestone = ''
foundH = False