forked from Freely-Given-org/BibleOrgSys
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ESwordBible.py
executable file
·1837 lines (1608 loc) · 99.2 KB
/
ESwordBible.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 -*-
#
# ESwordBible.py
#
# Module handling "e-Sword" Bible module files
#
# Copyright (C) 2013-2019 Robert Hunt
# Author: Robert Hunt <Freely.Given.org@gmail.com>
# License: See gpl-3.0.txt
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Module reading and loading e-Sword Bible files.
These can be downloaded from: http://www.BibleSupport.com and http://www.biblemodulesresource.com.
e-Sword Bible modules use RTF internally for formatting.
See http://en.wikipedia.org/wiki/Rich_Text_Format
and http://e-sword-users.org/users/node/3969
Database has one verse per entry (KJV versification)
OT has 23145 lines
NT has 7957 lines
Bible has 31102 lines.
e.g.,
In the beginning of God's preparing the heavens and the earth--
the earth hath existed waste and void, and darkness <FI>is<Fi> on the face of the deep, and the Spirit of God fluttering on the face of the waters,<CM>
and God saith, `Let light be;' and light is.
And God seeth the light that <FI>it is<Fi> good, and God separateth between the light and the darkness,
and God calleth to the light `Day,' and to the darkness He hath called `Night;' and there is an evening, and there is a morning--day one.<CM>
And God saith, `Let an expanse be in the midst of the waters, and let it be separating between waters and waters.'
And God maketh the expanse, and it separateth between the waters which <FI>are<Fi> under the expanse, and the waters which <FI>are<Fi> above the expanse: and it is so.
And God calleth to the expanse `Heavens;' and there is an evening, and there is a morning--day second.<CM>
"""
from gettext import gettext as _
LastModifiedDate = '2019-02-04' # by RJH
ShortProgName = "e-SwordBible"
ProgName = "e-Sword Bible format handler"
ProgVersion = '0.40'
ProgNameVersion = '{} v{}'.format( ShortProgName, ProgVersion )
ProgNameVersionDate = '{} {} {}'.format( ProgNameVersion, _("last modified"), LastModifiedDate )
debuggingThisModule = False
import logging, os, re
import sqlite3
import multiprocessing
import BibleOrgSysGlobals
from Bible import Bible, BibleBook
from BibleOrganisationalSystems import BibleOrganisationalSystem
FILENAME_ENDINGS_TO_ACCEPT = ('.BBLX',) # Must be UPPERCASE here
BIBLE_FILENAME_ENDINGS_TO_ACCEPT = ('.BBLX',) # Must be UPPERCASE here
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 ESwordBibleFileCheck( givenFolderName, strictCheck=True, autoLoad=False, autoLoadBooks=False ):
"""
Given a folder, search for e-Sword 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 of Bibles found.
if autoLoad is true and exactly one e-Sword Bible is found,
returns the loaded ESwordBible object.
"""
if BibleOrgSysGlobals.verbosityLevel > 2: print( "ESwordBibleFileCheck( {}, {}, {}, {} )".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( _("ESwordBibleFileCheck: Given {!r} folder is unreadable").format( givenFolderName ) )
return False
if not os.path.isdir( givenFolderName ):
logging.critical( _("ESwordBibleFileCheck: Given {!r} path is not a folder").format( givenFolderName ) )
return False
# Find all the files and folders in this folder
if BibleOrgSysGlobals.verbosityLevel > 3: print( " ESwordBibleFileCheck: 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 ):
if something in BibleOrgSysGlobals.COMMONLY_IGNORED_FOLDERS:
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 filenameEndingsToIgnore:
#if somethingUpper.endswith( ending): ignore=True; break
#if ignore: continue
#if not somethingUpperExt[1:] in extensionsToIgnore: # Compare without the first dot
if somethingUpperExt in FILENAME_ENDINGS_TO_ACCEPT:
foundFiles.append( something )
# See if there's an ESwordBible project here in this given folder
numFound = 0
looksHopeful = False
lastFilenameFound = None
for thisFilename in sorted( foundFiles ):
lastFilenameFound = thisFilename
numFound += 1
if numFound:
if BibleOrgSysGlobals.verbosityLevel > 2: print( "ESwordBibleFileCheck got", numFound, givenFolderName, lastFilenameFound )
if numFound == 1 and (autoLoad or autoLoadBooks):
if BibleOrgSysGlobals.verbosityLevel > 1: print( "{} doing autoload of {}…".format( ProgNameVersion, lastFilenameFound ) )
eSB = ESwordBible( givenFolderName, lastFilenameFound )
if autoLoad or autoLoadBooks: eSB.preload()
if autoLoadBooks: eSB.load() # Load and process the database
return eSB
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 not os.access( tryFolderName, os.R_OK ): # The subfolder is not readable
logging.warning( _("ESwordBibleFileCheck: {!r} subfolder is unreadable").format( tryFolderName ) )
continue
if BibleOrgSysGlobals.verbosityLevel > 3: print( " ESwordBibleFileCheck: Looking for files in {!r}".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 filenameEndingsToIgnore:
#if somethingUpper.endswith( ending): ignore=True; break
#if ignore: continue
#if not somethingUpperExt[1:] in extensionsToIgnore: # Compare without the first dot
if somethingUpperExt in FILENAME_ENDINGS_TO_ACCEPT:
foundSubfiles.append( something )
# See if there's an e-Sword project here in this folder
for thisFilename in sorted( foundSubfiles ):
foundProjects.append( (tryFolderName, thisFilename,) )
lastFilenameFound = thisFilename
numFound += 1
if numFound:
if BibleOrgSysGlobals.verbosityLevel > 2: print( "ESwordBibleFileCheck foundProjects", numFound, foundProjects )
if numFound == 1 and (autoLoad and autoLoadBooks):
if BibleOrgSysGlobals.verbosityLevel > 1: print( "{} doing autoload of {}…".format( ProgNameVersion, foundProjects[0][1] ) )
if BibleOrgSysGlobals.debugFlag: assert len(foundProjects) == 1
eSB = ESwordBible( foundProjects[0][0], foundProjects[0][1] )
if autoLoad or autoLoadBooks: eSB.preload()
if autoLoadBooks: eSB.load() # Load and process the database
return eSB
return numFound
# end of ESwordBibleFileCheck
def handleRTFLine( self, myName, BBB, C, V, originalLine, bookObject, myGlobals ):
"""
self here is a BibleObject
Adjusts the formatting of the RTF line for Bible reference BBB C:V
and then writes it to the bookObject.
C and V might be strings or integers
Try to convert display formatting to semantic formatting as much as possible
myGlobals dict contains flags.
Appends pseudo-USFM results to the supplied bookObject.
NOTE: originalLine can be None here.
NOTE: There are no checks in here yet to discover nested character-formatting markers. :-(
"""
if BibleOrgSysGlobals.debugFlag or BibleOrgSysGlobals.strictCheckingFlag:
#if debuggingThisModule:
print( "ESwordModule.handleRTFLine( {} {} {}:{} {!r} … {}".format( myName, BBB, C, V, originalLine, myGlobals ) )
assert originalLine is None or '\r' not in originalLine
#print( "ESwordModule.handleRTFLine: {} {}:{} {!r}".format( BBB, C, V, originalLine ) )
line = originalLine
writtenV = False
if V==1: appendedCFlag = False
if C!=1 and V==1: bookObject.addLine( 'c', str(C) ); appendedCFlag = True
# It seems that some commentaries can have newlines in the entries
line = line.replace( '\n', '#$#' ) # Replace \n with our temporary newline sequence
# Now we have to convert RTF codes to our internal codes
# First do special characters
line = line.replace( '\\ldblquote', '“' ).replace( '\\rdblquote', '”' ) \
.replace( '\\lquote', '‘' ).replace( '\\rquote', '’' ) \
.replace( '\\emdash', '—' ).replace( '\\endash', '–' )
# Now do Unicode characters
while True: # Find patterns like \\'d3
match = re.search( r"\\'[0-9a-f][0-9a-f]", line )
if not match: break
#print( originalLine )
#print( line )
#h1, h2 = line[match.start()+2], line[match.start()+3]
i = int( line[match.start()+2:match.end()], 16 ) # Convert two hex characters to decimal
#print( h1, h2, i, chr(i) )
line = line[:match.start()] + chr( i ) + line[match.end():]
#print( line )
#print( repr(line) )
while True: # Find patterns like \\u253?
match = re.search( r'\\u[1-2][0-9][0-9]\?', line )
if not match: break
#print( originalLine )
#print( line )
#h1, h2 = line[match.start()+2], line[match.start()+3]
i = int( line[match.start()+2:match.end()-1] ) # Convert three digits to decimal
#print( h1, h2, i, chr(i) )
line = line[:match.start()] + chr( i ) + line[match.end():]
#print( line )
#print( repr(line) )
# We will temporarily use ~^~ instead of backslash so we can distinguish our own codes from the RTF codes
# Try to guess some semantic formatting
#line = re.sub( r'\\cf14 (.+?)\\cf0', r'~^~add \1~^~add*', line )
#line = re.sub( r'\\cf15\\i (.+?)\\cf0\\i0', r'~^~add \1~^~add*', line )
line = re.sub( r'\\cf6\\super (.{1,5})\\cf1\\nosupersub[ —”]', r'~^~ord \1~^~ord*', line ) # For Free Bible -- ordinal gives superscript
line = re.sub( r'\\cf6\\super (.{1,5})\\cf0\\i0\\b0\\ulnone\\nosupersub', r'~^~ord \1~^~ord*', line ) # For Free Bible at end of line -- ordinal gives superscript
# Stuff to just remove -- not sure what most of this RTF stuff is about yet
while True:
line = line.lstrip()
changed = False
for stuff in ( '\\viewkind4', '\\uc1', '\\nowidctlpar',
'\\paperw12240', '\\paperh15840',
'\\fi-360','\\li360',
'\\tx360','\\tx720', '\\tx1440', '\\tx2160' '\\tx2880', '\\tx3600', '\\tx4320','\\tx5040','\\tx5760','\\tx6480','\\tx7200', '\\tx7920', '\\tx8640', '\\tx9360', '\\tx10080',
'\\margl1440', '\\margt1440', '\\margr1440', '\\margb1440', '\\deftab1134', '\\widowctrl',
'\\formshade', '\\sectd', '\\pard', '\\keepn',
'\\headery720', '\\footery720', '\\pgwsxn12240', '\\pghsxn15840', '\\marglsxn1800',
'\\margtsxn1440', '\\margrsxn1800', '\\margbsxn1440', '\\pgbrdropt32',
'\\s17', '\\s1', '\\sa120','\\sb120'
'\\itap0', '\\nosupersub', '\\ulnone',
'\\cf15','\\cf14','\\cf10', '\\cf1','\\cf0',
'\\lang1030', '\\lang1033', '\\f0', '\\i0', '\\b0', ):
if line.startswith( stuff ): line = line[len(stuff):]; changed = True
#print( "stuff", repr(stuff) )
#print( "line", repr(line[:20]) )
#if line.startswith( '\\pd' ): halt
if not changed: break
for stuff in ( '\\nosupersub', '\\ulnone', '\\b0', '\\i0', '\\cf0', ):
if line.endswith( stuff ): line = line[:-len(stuff)]
if BibleOrgSysGlobals.debugFlag: savedLine = line
# Try to guess some semantic formatting
line = re.sub( r'\\b\\i\\f0 (.+?)\\cf0\\b0\\i0\\line', r'~^~s1 \1*#$#', line ) # section heading
line = re.sub( r'\\cf10\\b\\i (.+?)\\cf0\\b0\\i0\\line', r'~^~s1 \1*#$#', line ) # section heading in LEB
line = re.sub( r'\\cf14 (.+?)\\cf0', r'~^~add \1~^~add*', line )
line = re.sub( r'\\cf15\\i (.+?)\\cf0\\i0', r'~^~add \1~^~add*', line )
line = re.sub( r'\\cf15\\i(.+?)\\cf0\\i0 ', r'~^~add \1~^~add*', line ) # LEB (error???)
line = re.sub( r'^\\i (.+?)\\cf0\\i0 ', r'~^~add \1~^~add*', line ) # LEB (error???)
line = re.sub( r'{\\cf15\\I (.+?)}', r'~^~add \1~^~add*', line )
line = re.sub( r'{\\cf15 (.+?)}', r'~^~add \1~^~add*', line )
line = re.sub( r'\\i\\f0 (.+?)\\cf0\\i0', r'~^~add \1~^~add*', line )
# Unfortunately, it's all display formatting, no semantic formatting :-(
# NOTE: This doesn't handle nesting yet
line = re.sub( r'{\\cf10\\b\\i (.+?)\\cf0\\b0\\i0', r'~^~bdit \1~^~bdit*', line )
line = re.sub( r'{\\b (.+?)}', r'~^~bd \1~^~bd*', line )
line = re.sub( r'{\\cf15\\i (.+?)}', r'~^~it \1~^~it*', line )
line = re.sub( r'{\\cf10\\i (.+?)}', r'~^~it \1~^~it*', line ) # What is different about these?
line = re.sub( r'{\\cf2\\i (.+?)}', r'~^~it \1~^~it*', line )
line = re.sub( r'{\\i (.+?)}', r'~^~it \1~^~it*', line )
line = re.sub( r'{\\i(.+?)}', r'~^~it \1~^~it*', line ) # Also occurs without the space in some modules
line = re.sub( r'{\\qc (.+?)}', r'~^~qc \1~^~qc*', line )
line = line.replace( '\\b1', '~^~bd ' ).replace( '\\b0', '~^~bd*' )
line = line.replace( '\\cf15\\i ', '~^~+it ' ).replace( '\\cf14\\i0', '~^~it*' ) # Attempt to handle some nesting in LEB
line = line.replace( '\\i ', '~^~it ' ).replace( '\\i1', '~^~it ' ).replace( '\\i0', '~^~it*' )
# Not sure what this is
line = re.sub( r'{\\cf2\\super (.+?)}', r'', line ) # Notes like '[2]' -- deleted for now
line = line.replace( '\\cf2 \\cf0', '' ) # LEB
line = line.replace( '\\cf0 ', '' ) # Calvin
line = line.replace( '\\loch\\f0', '' ).replace( '\\hich\\f0', '' ) # Calvin
line = line.replace( '\\par\\par', '\\par' )
#line = line.replace( '\\par', '#$#~^~p' ) # Hits \\pard wrongly
line = re.sub( r'\\par([^d])', r'#$#~^~p\1', line )
line = line.replace( '\\m ', '#$#~^~m ' )
# Handle module formatting errors -- formatting that goes across verses!
line = line.replace( '{\\cf2\\super [ ','[ ' ) # In one module Luke 22:42 -- weird
line = line.replace( '{\\cf 2 [','[' ) # In one module John 1:4 -- weird
line = line.replace( ']}',']' ) # In one module Luke 22:44; 23:34 -- weird
if myName=="Lexham English Bible": line = line.replace( '\\cf14 ','') # Not sure what this is in LEB
# Handle other left-overs
line = line \
.replace( '\\pard', '' ) \
.replace( '\\keepn', '' ) \
.replace( '\\sa120', '' ) \
.replace( '\\sb120', '' )
# Check what's left at the end
line = line.replace( '\\line', '#$#' ) # Use this for our newline marker
line = line.strip() # There seem to be extra spaces in many modules
if '\\' in line or '{' in line or '}' in line:
if BibleOrgSysGlobals.debugFlag:
logging.error( "{} original line: {!r}".format( myName, originalLine ) )
logging.error( "Saved line: {!r}".format( savedLine ) )
logging.error( "ESwordModule.load: Doesn't handle {} {}:{} formatted line yet: {!r}".format( BBB, C, V, line ) )
if 1: # Unhandled stuff -- not done properly yet… xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line = re.sub( '<(.+?)>', '', line ) # Remove all remaining sets of angle brackets
if 0 and BibleOrgSysGlobals.debugFlag: halt
line = line.replace( '~^~', '\\' ) # Restore our internal formatting codes
if '#$#' in line: # We need to break the original line into different USFM markers
#print( "\nMessing with segments: {} {}:{} {!r}".format( BBB, C, V, line ) )
segments = line.split( '#$#' )
assert len(segments) >= 2
#print( " segments (split by backslash):", segments )
leftovers = ''
for segment in segments:
if segment and segment[0] == '\\':
bits = segment.split( None, 1 )
#print( " bits", bits )
marker = bits[0][1:]
if len(bits) == 1:
#if bits[0] in ('\\p','\\b'):
if BibleOrgSysGlobals.USFMMarkers.isNewlineMarker( marker ):
if C==1 and V==1 and not appendedCFlag: bookObject.addLine( 'c', str(C) ); appendedCFlag = True
bookObject.addLine( marker, '' )
else:
logging.error( "It seems that we had a blank {!r} field in {!r}".format( bits[0], originalLine ) )
#halt
else:
assert len(bits) == 2
if 0 and BibleOrgSysGlobals.debugFlag and debuggingThisModule:
print( "\n{} {}:{} {!r}".format( BBB, C, V, originalLine ) )
print( "line", repr(line) )
print( "seg", repr(segment) )
print( "segments:", segments )
print( "bits", bits )
print( "marker", marker )
print( "leftovers", repr(leftovers) )
if BibleOrgSysGlobals.USFMMarkers.isNewlineMarker( marker ):
if BibleOrgSysGlobals.debugFlag:
assert marker in ('mt1','mt2','mt3', 's1','s2','s3', 'p', 'q1','q2','q3', 'm', 'r', 'b',)
bookObject.addLine( marker, bits[1] )
elif not writtenV:
bookObject.addLine( 'v', '{} \\{} {}'.format( V, marker, segment ) )
writtenV = True
else: leftovers += '\\{} {}'.format( marker, segment )
else: # What is segment is blank (\\NL* at end of line)???
if C==1 and V==1 and not appendedCFlag: bookObject.addLine( 'c', str(C) ); appendedCFlag = True
if not writtenV:
bookObject.addLine( 'v', '{} {}'.format( V, leftovers+segment ) )
writtenV = True
else:
bookObject.addLine( 'v~', leftovers+segment )
leftovers = ''
#if myGlobals['haveParagraph']:
#bookObject.addLine( 'p', '' )
#myGlobals['haveParagraph'] = False
if leftovers:
if 1 or BibleOrgSysGlobals.debugFlag or debuggingThisModule:
logging.critical( "ESwordModule.handleRTFLine: Had leftovers {!r} from {!r}".format( leftovers, originalLine ) )
else:
logging.critical( "ESwordModule.handleRTFLine: Had leftovers {!r}".format( leftovers ) )
if BibleOrgSysGlobals.debugFlag or BibleOrgSysGlobals.strictCheckingFlag: assert not leftovers
else: # no newlines in the middle
if C in (0,'0') and V in (0,'0'):
bookObject.addLine( 'ip', line )
else:
if C==1 and V==1 and not appendedCFlag: bookObject.addLine( 'c', str(C) ); appendedCFlag = True
#print( BBB, C, V, repr(line) )
bookObject.addLine( 'v', '{} {}'.format( V, line ) )
# end of ESwordModule.handleRTFLine
def handleHTMLLine( self, myName, BBB, C, V, originalLine, bookObject, myGlobals ):
"""
self here is a BibleObject
Adjusts the formatting of the RTF line for Bible reference BBB C:V
and then writes it to the bookObject.
C and V might be strings or integers
Try to convert display formatting to semantic formatting as much as possible
myGlobals dict contains flags.
Appends pseudo-USFM results to the supplied bookObject.
NOTE: originalLine can be None here.
NOTE: There are no checks in here yet to discover nested character-formatting markers. :-(
"""
if BibleOrgSysGlobals.debugFlag or BibleOrgSysGlobals.strictCheckingFlag:
#if debuggingThisModule:
#print( "ESwordModule.handleHTMLLine( {} {} {}:{} {!r} … {}".format( myName, BBB, C, V, originalLine, myGlobals ) )
assert originalLine is None or '\r' not in originalLine
#print( "ESwordModule.handleHTMLLine: {} {}:{} {!r}".format( BBB, C, V, originalLine ) )
line = originalLine
if line and line[0]=='\n': line = line[1:] # Remove leading newline
if line and line[-1]=='\n': line = line[:-1] # Remove trailing newline
line = line.replace( '\n', '<br />' )
writtenV = False
if V==1: appendedCFlag = False
if C!=1 and V==1: bookObject.addLine( 'c', str(C) ); appendedCFlag = True
if '#$#' in line: # We need to break the original line into different USFM markers
#print( "\nMessing with segments: {} {}:{} {!r}".format( BBB, C, V, line ) )
segments = line.split( '#$#' )
assert len(segments) >= 2
#print( " segments (split by backslash):", segments )
leftovers = ''
for segment in segments:
if segment and segment[0] == '\\':
bits = segment.split( None, 1 )
#print( " bits", bits )
marker = bits[0][1:]
if len(bits) == 1:
#if bits[0] in ('\\p','\\b'):
if BibleOrgSysGlobals.USFMMarkers.isNewlineMarker( marker ):
if C==1 and V==1 and not appendedCFlag: bookObject.addLine( 'c', str(C) ); appendedCFlag = True
bookObject.addLine( marker, '' )
else:
logging.error( "It seems that we had a blank {!r} field in {!r}".format( bits[0], originalLine ) )
#halt
else:
assert len(bits) == 2
if 0 and BibleOrgSysGlobals.debugFlag and debuggingThisModule:
print( "\n{} {}:{} {!r}".format( BBB, C, V, originalLine ) )
print( "line", repr(line) )
print( "seg", repr(segment) )
print( "segments:", segments )
print( "bits", bits )
print( "marker", marker )
print( "leftovers", repr(leftovers) )
if BibleOrgSysGlobals.USFMMarkers.isNewlineMarker( marker ):
if BibleOrgSysGlobals.debugFlag:
assert marker in ('mt1','mt2','mt3', 's1','s2','s3', 'p', 'q1','q2','q3', 'm', 'r', 'b',)
bookObject.addLine( marker, bits[1] )
elif not writtenV:
bookObject.addLine( 'v', '{} \\{} {}'.format( V, marker, segment ) )
writtenV = True
else: leftovers += '\\{} {}'.format( marker, segment )
else: # What is segment is blank (\\NL* at end of line)???
if C==1 and V==1 and not appendedCFlag: bookObject.addLine( 'c', str(C) ); appendedCFlag = True
if not writtenV:
bookObject.addLine( 'v', '{} {}'.format( V, leftovers+segment ) )
writtenV = True
else:
bookObject.addLine( 'v~', leftovers+segment )
leftovers = ''
#if myGlobals['haveParagraph']:
#bookObject.addLine( 'p', '' )
#myGlobals['haveParagraph'] = False
if leftovers: logging.critical( "ESwordModule.handleRTFLine: Had leftovers {!r}".format( leftovers ) )
if BibleOrgSysGlobals.debugFlag: assert not leftovers
#halt
else: # no newlines in the middle
if C in (0,'0') and V in (0,'0'):
bookObject.addLine( 'ip', line )
else:
if C==1 and V==1 and not appendedCFlag: bookObject.addLine( 'c', str(C) ); appendedCFlag = True
#print( BBB, C, V, repr(line) )
bookObject.addLine( 'v', '{} {}'.format( V, line ) )
# end of ESwordModule.handleHTMLLine
def handleESwordLine( self, myName, BBB, C, V, originalLine, bookObject, myGlobals ):
"""
self here is a BibleObject
Adjusts the formatting of the RTF line for Bible reference BBB C:V
and then writes it to the bookObject.
C and V might be strings or integers
Try to convert display formatting to semantic formatting as much as possible
myGlobals dict contains flags.
Appends pseudo-USFM results to the supplied bookObject.
NOTE: originalLine can be None here.
NOTE: There are no checks in here yet to discover nested character-formatting markers. :-(
"""
if BibleOrgSysGlobals.debugFlag or BibleOrgSysGlobals.strictCheckingFlag:
if debuggingThisModule:
print( "ESwordModule.handleESwordLine( {} {} {}:{} {!r} … {}".format( myName, BBB, C, V, originalLine, myGlobals ) )
assert originalLine is None or '\r' not in originalLine
#print( "ESwordModule.handleESwordLine: {} {}:{} {!r}".format( BBB, C, V, originalLine ) )
if originalLine is None: # We don't have an entry for this C:V
return
if '<span ' in originalLine or '<p ' in originalLine: # Seems to be HTML
handleHTMLLine( self, myName, BBB, C, V, originalLine, bookObject, myGlobals )
return
elif '\\viewkind' in originalLine or '\\uc1' in originalLine \
or '\\paper' in originalLine or '\\par' in originalLine: # Seems to be RTF
handleRTFLine( self, myName, BBB, C, V, originalLine, bookObject, myGlobals )
return
else:
if debuggingThisModule:
print( "ESwordModule.handleESwordLine: What's this: {} {} {}:{} {!r}".format( myName, BBB, C, V, originalLine ) )
if BibleOrgSysGlobals.debugFlag or BibleOrgSysGlobals.strictCheckingFlag: halt # What's this???
bookObject.addLine( 'v', '{} {}'.format( V, originalLine ) )
# end of ESwordModule.handleESwordLine
class ESwordBible( Bible ):
"""
Class for reading, validating, and converting ESwordBible files.
"""
def __init__( self, sourceFolder, givenFilename, encoding='utf-8' ):
"""
Constructor: just sets up the Bible object.
"""
if BibleOrgSysGlobals.debugFlag and debuggingThisModule:
print( "ESwordBible.init( {!r}, {!r}, {!r} )".format( sourceFolder, givenFilename, encoding ) )
# Setup and initialise the base class first
Bible.__init__( self )
self.objectNameString = 'e-Sword Bible object'
self.objectTypeString = 'e-Sword-Bible'
# Now we can set our object variables
self.sourceFolder, self.sourceFilename, self.encoding = sourceFolder, givenFilename, encoding
self.sourceFilepath = os.path.join( self.sourceFolder, self.sourceFilename )
# Do a preliminary check on the readability of our file
if not os.access( self.sourceFilepath, os.R_OK ):
logging.critical( _("ESwordBible: File {!r} is unreadable").format( self.sourceFilepath ) )
filenameBits = os.path.splitext( self.sourceFilename )
self.name = filenameBits[0]
self.fileExtension = filenameBits[1]
#if self.fileExtension.upper().endswith('X'):
#logging.warning( _("ESwordBible: File {!r} is encrypted").format( self.sourceFilepath ) )
self.preloaded = False
# end of ESwordBible.__init__
#def handleRTFLine( self, myName, BBB, C, V, originalLine, bookObject, myGlobals ):
#"""
#Adjusts the formatting of the RTF line for Bible reference BBB C:V
#and then writes it to the bookObject.
#Try to convert display formatting to semantic formatting as much as possible
#myGlobals dict contains flags.
#Appends pseudo-USFM results to the supplied bookObject.
#NOTE: originalLine can be None here.
#NOTE: There are no checks in here yet to discover nested character-formatting markers. :-(
#"""
#if BibleOrgSysGlobals.debugFlag:
#if 0 and debuggingThisModule:
#print( "ESwordBible.handleRTFLine( {} {} {}:{} {!r} … {}".format( myName, BBB, C, V, originalLine, myGlobals ) )
#assert originalLine is None or ('\n' not in originalLine and '\r' not in originalLine )
##print( BBB, C, V, repr(originalLine) )
#line = originalLine
#writtenV = False
#if V==1: appendedCFlag = False
#if C!=1 and V==1: bookObject.addLine( 'c', str(C) ); appendedCFlag = True
#if line is None: # We don't have an entry for this C:V
#return
## Now we have to convert RTF codes to our internal codes
## First do special characters
#line = line.replace( '\\ldblquote', '“' ).replace( '\\rdblquote', '”' ).replace( '\\lquote', '‘' ).replace( '\\rquote', '’' )
#line = line.replace( '\\emdash', '—' ).replace( '\\endash', '–' )
## Now do Unicode characters
#while True: # Find patterns like \\'d3
#match = re.search( r"\\'[0-9a-f][0-9a-f]", line )
#if not match: break
##print( originalLine )
##print( line )
##h1, h2 = line[match.start()+2], line[match.start()+3]
#i = int( line[match.start()+2:match.end()], 16 ) # Convert two hex characters to decimal
##print( h1, h2, i, chr(i) )
#line = line[:match.start()] + chr( i ) + line[match.end():]
##print( line )
##print( repr(line) )
#while True: # Find patterns like \\u253?
#match = re.search( r"\\u[1-2][0-9][0-9]\?", line )
#if not match: break
##print( originalLine )
##print( line )
##h1, h2 = line[match.start()+2], line[match.start()+3]
#i = int( line[match.start()+2:match.end()-1] ) # Convert three digits to decimal
##print( h1, h2, i, chr(i) )
#line = line[:match.start()] + chr( i ) + line[match.end():]
##print( line )
##print( repr(line) )
## We will temporarily use ~^~ instead of backslash so we can distinguish our own codes from the RTF codes
## Try to guess some semantic formatting
##line = re.sub( r'\\cf14 (.+?)\\cf0', r'~^~add \1~^~add*', line )
##line = re.sub( r'\\cf15\\i (.+?)\\cf0\\i0', r'~^~add \1~^~add*', line )
## Stuff to just remove -- not sure what most of this is about yet
#while True:
#line = line.lstrip()
#changed = False
#for stuff in ( '\\viewkind4', '\\uc1', '\\nowidctlpar',
#'\\paperw12240', '\\paperh15840',
#'\\tx720', '\\tx1440', '\\tx2160' '\\tx2880', '\\tx3600', '\\tx4320', '\\tx5040', '\\tx5760', '\\tx6480', '\\tx7200', '\\tx7920', '\\tx8640', '\\tx9360', '\\tx10080',
#'\\margl1440', '\\margt1440', '\\margr1440', '\\margb1440', '\\deftab1134', '\\widowctrl',
#'\\formshade', '\\sectd',
#'\\headery720', '\\footery720', '\\pgwsxn12240', '\\pghsxn15840', '\\marglsxn1800',
#'\\margtsxn1440', '\\margrsxn1800', '\\margbsxn1440', '\\pgbrdropt32', '\\s17',
#'\\itap0', '\\nosupersub', '\\ulnone',
#'\\cf15', '\\cf14', '\\cf10', '\\cf0', '\\lang1030', '\\lang1033', '\\f0', '\\i0', '\\b0', ):
#if line.startswith( stuff ): line = line[len(stuff):]; changed = True
#if not changed: break
#for stuff in ( '\\nosupersub', '\\ulnone', '\\b0', '\\i0', '\\cf0', ):
#if line.endswith( stuff ): line = line[:-len(stuff)]
#if BibleOrgSysGlobals.debugFlag: savedLine = line
## Try to guess some semantic formatting
#line = re.sub( r'\\b\\i\\f0 (.+?)\\cf0\\b0\\i0\\line', r'~^~s1 \1*#$#', line ) # section heading
#line = re.sub( r'\\cf10\\b\\i (.+?)\\cf0\\b0\\i0\\line', r'~^~s1 \1*#$#', line ) # section heading in LEB
#line = re.sub( r'\\cf14 (.+?)\\cf0', r'~^~add \1~^~add*', line )
#line = re.sub( r'\\cf15\\i (.+?)\\cf0\\i0', r'~^~add \1~^~add*', line )
#line = re.sub( r'\\cf15\\i(.+?)\\cf0\\i0 ', r'~^~add \1~^~add*', line ) # LEB (error???)
#line = re.sub( r'^\\i (.+?)\\cf0\\i0 ', r'~^~add \1~^~add*', line ) # LEB (error???)
#line = re.sub( r'{\\cf15\\I (.+?)}', r'~^~add \1~^~add*', line )
#line = re.sub( r'{\\cf15 (.+?)}', r'~^~add \1~^~add*', line )
#line = re.sub( r'\\i\\f0 (.+?)\\cf0\\i0', r'~^~add \1~^~add*', line )
## Unfortunately, it's all display formatting, no semantic formatting :-(
## NOTE: This doesn't handle nesting yet
#line = re.sub( r'{\\cf10\\b\\i (.+?)\\cf0\\b0\\i0', r'~^~bdit \1~^~bdit*', line )
#line = re.sub( r'{\\b (.+?)}', r'~^~bd \1~^~bd*', line )
#line = re.sub( r'{\\cf15\\i (.+?)}', r'~^~it \1~^~it*', line )
#line = re.sub( r'{\\cf10\\i (.+?)}', r'~^~it \1~^~it*', line ) # What is different about these?
#line = re.sub( r'{\\cf2\\i (.+?)}', r'~^~it \1~^~it*', line )
#line = re.sub( r'{\\i (.+?)}', r'~^~it \1~^~it*', line )
#line = re.sub( r'{\\i(.+?)}', r'~^~it \1~^~it*', line ) # Also occurs without the space in some modules
#line = re.sub( r'{\\qc (.+?)}', r'~^~qc \1~^~qc*', line )
#line = line.replace( '\\b1', '~^~bd ' ).replace( '\\b0', '~^~bd*' )
#line = line.replace( '\\cf15\\i ', '~^~+it ' ).replace( '\\cf14\\i0', '~^~it*' ) # Attempt to handle some nesting in LEB
#line = line.replace( '\\i ', '~^~it ' ).replace( '\\i1', '~^~it ' ).replace( '\\i0', '~^~it*' )
## Not sure what this is
#line = re.sub( r'{\\cf2\\super (.+?)}', r'', line ) # Notes like '[2]' -- deleted for now
#line = line.replace( '\\cf2 \\cf0', '' ) # LEB
#line = line.replace( '\\cf0 ', '' ) # Calvin
#line = line.replace( '\\loch\\f0', '' ).replace( '\\hich\\f0', '' ) # Calvin
#line = line.replace( '\\par\\par', '#$#~^~p' )
#line = line.replace( '\\par', '#$#~^~p' )
#line = line.replace( '\\m ', '#$#~^~m ' )
## Handle module formatting errors -- formatting that goes across verses!
#line = line.replace( '{\\cf2\\super [ ','[ ' ) # In one module Luke 22:42 -- weird
#line = line.replace( '{\\cf 2 [','[' ) # In one module John 1:4 -- weird
#line = line.replace( ']}',']' ) # In one module Luke 22:44; 23:34 -- weird
#if myName=="Lexham English Bible": line = line.replace( '\\cf14 ','') # Not sure what this is in LEB
## Check what's left at the end
#line = line.replace( '\\line', '#$#' ) # Use this for our newline marker
#line = line.strip() # There seem to be extra spaces in many modules
#if '\\' in line or '{' in line or '}' in line:
#if BibleOrgSysGlobals.debugFlag:
#logging.error( "{} original line: {!r}".format( myName, originalLine ) )
#logging.error( "Saved line: {!r}".format( savedLine ) )
#logging.error( "ESwordBible.load: Doesn't handle {} {}:{} formatted line yet: {!r}".format( BBB, C, V, line ) )
#if 1: # Unhandled stuff -- not done properly yet… xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
#line = re.sub( '<(.+?)>', '', line ) # Remove all remaining sets of angle brackets
#if 0 and BibleOrgSysGlobals.debugFlag: halt
#line = line.replace( '~^~', '\\' ) # Restore our internal formatting codes
#if '#$#' in line: # We need to break the original line into different USFM markers
##print( "\nMessing with segments: {} {}:{} {!r}".format( BBB, C, V, line ) )
#segments = line.split( '#$#' )
#assert len(segments) >= 2
##print( " segments (split by backslash):", segments )
#leftovers = ''
#for segment in segments:
#if segment and segment[0] == '\\':
#bits = segment.split( None, 1 )
##print( " bits", bits )
#marker = bits[0][1:]
#if len(bits) == 1:
##if bits[0] in ('\\p','\\b'):
#if BibleOrgSysGlobals.USFMMarkers.isNewlineMarker( marker ):
#if C==1 and V==1 and not appendedCFlag: bookObject.addLine( 'c', str(C) ); appendedCFlag = True
#bookObject.addLine( marker, '' )
#else:
#logging.error( "It seems that we had a blank {!r} field in {!r}".format( bits[0], originalLine ) )
##halt
#else:
#assert len(bits) == 2
#if 0 and BibleOrgSysGlobals.debugFlag and debuggingThisModule:
#print( "\n{} {}:{} {!r}".format( BBB, C, V, originalLine ) )
#print( "line", repr(line) )
#print( "seg", repr(segment) )
#print( "segments:", segments )
#print( "bits", bits )
#print( "marker", marker )
#print( "leftovers", repr(leftovers) )
#if BibleOrgSysGlobals.USFMMarkers.isNewlineMarker( marker ):
#if BibleOrgSysGlobals.debugFlag:
#assert marker in ('mt1','mt2','mt3', 's1','s2','s3', 'p', 'q1','q2','q3', 'm', 'r', 'b',)
#bookObject.addLine( marker, bits[1] )
#elif not writtenV:
#bookObject.addLine( 'v', '{} \\{} {}'.format( V, marker, segment ) )
#writtenV = True
#else: leftovers += '\\{} {}'.format( marker, segment )
#else: # What is segment is blank (\\NL* at end of line)???
#if C==1 and V==1 and not appendedCFlag: bookObject.addLine( 'c', str(C) ); appendedCFlag = True
#if not writtenV:
#bookObject.addLine( 'v', '{} {}'.format( V, leftovers+segment ) )
#writtenV = True
#else:
#bookObject.addLine( 'v~', leftovers+segment )
#leftovers = ''
##if myGlobals['haveParagraph']:
##bookObject.addLine( 'p', '' )
##myGlobals['haveParagraph'] = False
#if leftovers: logging.critical( "Had leftovers {!r}".format( leftovers ) )
#if BibleOrgSysGlobals.debugFlag: assert not leftovers
##halt
#else: # no newlines in the middle
#if C==1 and V==1 and not appendedCFlag: bookObject.addLine( 'c', str(C) ); appendedCFlag = True
##print( BBB, C, V, repr(line) )
#bookObject.addLine( 'v', '{} {}'.format( V, line ) )
## end of ESwordBible.handleRTFLine
def checkForExtraMaterial( self, cursor, BOS ):
"""
"""
if BibleOrgSysGlobals.debugFlag and debuggingThisModule:
print( exp("checkForExtraMaterial( …, … )") )
if BibleOrgSysGlobals.verbosityLevel > 0: print( _("Checking {} for extra material…").format( self.sourceFilepath ) )
cursor.execute('select * from Bible' )
for row in cursor:
assert len(row) == 4
BBBn, C, V, text = row # First three are integers, the last is a string
#print( repr(BBBn), repr(C), repr(V), repr(text) )
if BBBn<1 or BBBn>66: print( "Found book number {}".format( BBBn ) )
BBB = BibleOrgSysGlobals.BibleBooksCodes.getBBBFromReferenceNumber( BBBn )
if not BOS.isValidBCVRef( (BBB,str(C),str(V),''), 'checkForExtraMaterial' ):
logging.error( "checkForExtraMaterial: {} contains {} {}:{} {!r}".format( self.name, BBB, C, V, text ) )
if BibleOrgSysGlobals.debugFlag and debuggingThisModule:
print( "checkForExtraMaterial: {} contains {} {}:{} {!r}".format( self.name, BBB, C, V, text ) )
#halt
# end of ESwordBible.checkForExtraMaterial
def preload( self ):
"""
Load Bible details out of the SQLite3 database.
"""
if BibleOrgSysGlobals.debugFlag and debuggingThisModule:
print( exp("preload()") )
if BibleOrgSysGlobals.verbosityLevel > 2: print( _("Preloading {}…").format( self.sourceFilepath ) )
loadErrors = []
fileExtensionUpper = self.fileExtension.upper()
if fileExtensionUpper not in FILENAME_ENDINGS_TO_ACCEPT:
logging.critical( "{} doesn't appear to be a e-Sword file".format( self.sourceFilename ) )
elif not self.sourceFilename.upper().endswith( BIBLE_FILENAME_ENDINGS_TO_ACCEPT[0] ):
logging.critical( "{} doesn't appear to be a e-Sword Bible file".format( self.sourceFilename ) )
connection = sqlite3.connect( self.sourceFilepath )
connection.row_factory = sqlite3.Row # Enable row names
self.cursor = connection.cursor()
# First get the settings
if self.suppliedMetadata is None: self.suppliedMetadata = {}
self.suppliedMetadata['e-Sword-Bible'] = {}
self.cursor.execute( 'select * from Details' )
row = self.cursor.fetchone()
for key in row.keys():
self.suppliedMetadata['e-Sword-Bible'][key] = row[key]
#print( self.suppliedMetadata['e-Sword-Bible'] ); halt
#if 'Description' in self.settingsDict and len(self.settingsDict['Description'])<40: self.name = self.settingsDict['Description']
#if 'Abbreviation' in self.settingsDict: self.abbreviation = self.settingsDict['Abbreviation']
if 'encryption' in self.suppliedMetadata['e-Sword-Bible']:
logging.critical( "{} is encrypted: level {}".format( self.sourceFilename, self.suppliedMetadata['e-Sword-Bible']['encryption'] ) )
## Just get some information from the file
#self.cursor.execute( 'select * from Bible' )
#rows = self.cursor.fetchall()
#numRows = len(rows)
#if BibleOrgSysGlobals.debugFlag or BibleOrgSysGlobals.verbosityLevel>2: print( '{} rows found'.format( numRows ) )
#BBBn1 = rows[0][0]
#if BibleOrgSysGlobals.debugFlag or BibleOrgSysGlobals.verbosityLevel>2: print( 'First book number is {}'.format( BBBn1 ) )
#del rows
#BBB1 = None
#if BBBn1 <= 66: BBB1 = BibleOrgSysGlobals.BibleBooksCodes.getBBBFromReferenceNumber( BBBn1 )
#testament = BBB = None
#booksExpected = textLineCountExpected = 0
#if self.suppliedMetadata['e-Sword-Bible']['OT'] and self.suppliedMetadata['e-Sword-Bible']['NT']:
#testament, BBB = 'BOTH', 'GEN'
#booksExpected, textLineCountExpected = 66, 31102
#elif self.suppliedMetadata['e-Sword-Bible']['OT']:
#testament, BBB = 'OT', 'GEN'
#booksExpected, textLineCountExpected = 39, 23145
#elif self.suppliedMetadata['e-Sword-Bible']['NT']:
#testament, BBB = 'NT', 'MAT'
#booksExpected, textLineCountExpected = 27, 7957
#elif self.suppliedMetadata['e-Sword-Bible']['Abbreviation'] == 'VIN2011': # Handle encoding error
#logging.critical( "e-Sword settings encoding error -- no testament set: {}".format( self.suppliedMetadata['e-Sword-Bible'] ) )
#loadErrors.append( "e-Sword settings encoding error -- no testament set: {}".format( self.suppliedMetadata['e-Sword-Bible'] ) )
#testament, BBB = 'BOTH', 'GEN'
#booksExpected, textLineCountExpected = 66, 31102
#elif self.suppliedMetadata['e-Sword-Bible']['Apocrypha']: # incomplete
#testament, BBB = 'AP', 'XXX'
#booksExpected, textLineCountExpected = 99, 999999
#halt
#if not BBB:
#logging.critical( "e-Sword settings encoding error -- no testament set: {}".format( self.suppliedMetadata['e-Sword-Bible'] ) )
#loadErrors.append( "e-Sword settings encoding error -- no testament set: {}".format( self.suppliedMetadata['e-Sword-Bible'] ) )
#if 0:
#cursor.execute( 'select * from Bible' )
#rows = cursor.fetchall()
#print( "rows", len(rows) )
#for row in rows:
#assert len(row) == 4
#BBBn, C, V, text = row # First three are integers, the last is a string
#print( BBBn, C, V, repr(text) )
#if C==2: break
#del rows # Takes a lot of memory
#if BibleOrgSysGlobals.debugFlag or BibleOrgSysGlobals.verbosityLevel>2:
#print( "Testament={} BBB={} BBB1={}, bE={}, tLCE={} nR={}".format( testament, BBB, BBB1, booksExpected, textLineCountExpected, numRows ) )
#if BBB1 != BBB:
#logging.critical( "First book seems wrong: {} instead of {}".format( BBB1, BBB ) )
#loadErrors.append( "First book seems wrong: {} instead of {}".format( BBB1, BBB ) )
#if not BBB: BBB = BBB1
#if numRows != textLineCountExpected:
#logging.critical( "Row count for {} seems wrong: {} instead of {}".format( self.sourceFilename, numRows, textLineCountExpected ) )
#loadErrors.append( "Row count for {} seems wrong: {} instead of {}".format( self.sourceFilename, numRows, textLineCountExpected ) )
##halt
self.BibleOrganisationalSystem = BibleOrganisationalSystem( 'GENERIC-KJV-66-ENG' )
self.preloaded = True
# end of ESwordBible.preload
def load( self ):
"""
Load all the books out of the SQLite3 database.
"""
if BibleOrgSysGlobals.debugFlag and debuggingThisModule:
print( exp("load()") )
if not self.preloaded: self.preload()
if BibleOrgSysGlobals.verbosityLevel > 2: print( _("Loading {}…").format( self.sourceFilepath ) )
loadErrors = []
#fileExtensionUpper = self.fileExtension.upper()
#if fileExtensionUpper not in FILENAME_ENDINGS_TO_ACCEPT:
#logging.critical( "{} doesn't appear to be a e-Sword file".format( self.sourceFilename ) )
#elif not self.sourceFilename.upper().endswith( BIBLE_FILENAME_ENDINGS_TO_ACCEPT[0] ):
#logging.critical( "{} doesn't appear to be a e-Sword Bible file".format( self.sourceFilename ) )
#connection = sqlite3.connect( self.sourceFilepath )
#connection.row_factory = sqlite3.Row # Enable row names
#cursor = connection.cursor()
## First get the settings
#if self.suppliedMetadata is None: self.suppliedMetadata = {}
#self.suppliedMetadata['e-Sword-Bible'] = {}
#cursor.execute( 'select * from Details' )
#row = cursor.fetchone()
#for key in row.keys():
#self.suppliedMetadata['e-Sword-Bible'][key] = row[key]
##print( self.suppliedMetadata['e-Sword-Bible'] ); halt
##if 'Description' in self.settingsDict and len(self.settingsDict['Description'])<40: self.name = self.settingsDict['Description']
##if 'Abbreviation' in self.settingsDict: self.abbreviation = self.settingsDict['Abbreviation']
#if 'encryption' in self.suppliedMetadata['e-Sword-Bible']:
#logging.critical( "{} is encrypted: level {}".format( self.sourceFilename, self.suppliedMetadata['e-Sword-Bible']['encryption'] ) )
# Just get some information from the file
# NOTE: Isn't this a highly inefficient way to find the number of rows in the database???
self.cursor.execute( 'select * from Bible' )
rows = self.cursor.fetchall()
numRows = len(rows)
if BibleOrgSysGlobals.debugFlag or BibleOrgSysGlobals.verbosityLevel>2: print( '{} rows found'.format( numRows ) )
BBBn1 = rows[0][0]
if BibleOrgSysGlobals.debugFlag or BibleOrgSysGlobals.verbosityLevel>2: print( 'First book number is {}'.format( BBBn1 ) )
del rows
BBB1 = None
if BBBn1 <= 66: BBB1 = BibleOrgSysGlobals.BibleBooksCodes.getBBBFromReferenceNumber( BBBn1 )
testament = BBB = None
booksExpected = textLineCountExpected = 0
if self.suppliedMetadata['e-Sword-Bible']['OT'] and self.suppliedMetadata['e-Sword-Bible']['NT']:
testament, BBB = 'BOTH', 'GEN'
booksExpected, textLineCountExpected = 66, 31102
elif self.suppliedMetadata['e-Sword-Bible']['OT']:
testament, BBB = 'OT', 'GEN'
booksExpected, textLineCountExpected = 39, 23145
elif self.suppliedMetadata['e-Sword-Bible']['NT']:
testament, BBB = 'NT', 'MAT'
booksExpected, textLineCountExpected = 27, 7957
elif self.suppliedMetadata['e-Sword-Bible']['Abbreviation'] == 'VIN2011': # Handle encoding error
logging.critical( "e-Sword settings encoding error -- no testament set: {}".format( self.suppliedMetadata['e-Sword-Bible'] ) )
loadErrors.append( "e-Sword settings encoding error -- no testament set: {}".format( self.suppliedMetadata['e-Sword-Bible'] ) )
testament, BBB = 'BOTH', 'GEN'
booksExpected, textLineCountExpected = 66, 31102
elif self.suppliedMetadata['e-Sword-Bible']['Apocrypha']: # incomplete
testament, BBB = 'AP', 'XXX'
booksExpected, textLineCountExpected = 99, 999999
halt
if not BBB:
logging.critical( "e-Sword settings encoding error -- no testament set: {}".format( self.suppliedMetadata['e-Sword-Bible'] ) )
loadErrors.append( "e-Sword settings encoding error -- no testament set: {}".format( self.suppliedMetadata['e-Sword-Bible'] ) )
#if 0:
#self.cursor.execute( 'select * from Bible' )
#rows = self.cursor.fetchall()
#print( "rows", len(rows) )
#for row in rows:
#assert len(row) == 4
#BBBn, C, V, text = row # First three are integers, the last is a string
#print( BBBn, C, V, repr(text) )
#if C==2: break
#del rows # Takes a lot of memory
if BibleOrgSysGlobals.debugFlag or BibleOrgSysGlobals.verbosityLevel>2:
print( "Testament={} BBB={} BBB1={}, bE={}, tLCE={} nR={}".format( testament, BBB, BBB1, booksExpected, textLineCountExpected, numRows ) )
if BBB1 != BBB:
logging.critical( "First book seems wrong: {} instead of {}".format( BBB1, BBB ) )
loadErrors.append( "First book seems wrong: {} instead of {}".format( BBB1, BBB ) )
if not BBB: BBB = BBB1
if numRows != textLineCountExpected:
logging.critical( "Row count for {} seems wrong: {} instead of {}".format( self.sourceFilename, numRows, textLineCountExpected ) )
loadErrors.append( "Row count for {} seems wrong: {} instead of {}".format( self.sourceFilename, numRows, textLineCountExpected ) )
#halt
#BOS = BibleOrganisationalSystem( 'GENERIC-KJV-66-ENG' )
# Create the first book