christopunk commited on
Commit
dcc9dae
·
verified ·
1 Parent(s): dd8208b

Upload src/bible.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. src/bible.py +1591 -0
src/bible.py ADDED
@@ -0,0 +1,1591 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+
3
+ Parse scriptural references and fetch source texts.
4
+
5
+ TODO:
6
+ - [ ] separate out tests
7
+ - [ ] refactor and clean up
8
+
9
+ '''
10
+
11
+ from dataclasses import dataclass
12
+ from functools import reduce
13
+ from typing import Dict, List, Optional, Tuple, Union
14
+ import re
15
+
16
+ from parsy import (
17
+ Parser,
18
+ alt,
19
+ fail,
20
+ generate,
21
+ regex,
22
+ seq,
23
+ string,
24
+ string_from,
25
+ whitespace
26
+ )
27
+
28
+ # Verses are saved as one per line
29
+ paths = {
30
+ 'KJV': 'curated/bible/kjv_king_james_version.txt',
31
+ 'ASV': 'curated/bible/asv_american_standard_version.txt',
32
+ 'CSB': 'curated/bible/csb_christian_standard_bible.txt',
33
+ }
34
+
35
+ # KJV
36
+ # Genesis 1:1 KJV In the beginning God created the heaven and the earth.
37
+ # Genesis 1:2 KJV And the earth was without form, and void; and darkness was upon the face of the deep. And the Spirit of God moved upon the face of the waters.
38
+ # Genesis 1:3 KJV And God said, Let there be light: and there was light.
39
+ #
40
+ # ASV
41
+ # Genesis 1:1 ASV In the beginning God created the heavens and the earth.
42
+ # Genesis 1:2 ASV And the earth was waste and void; and darkness was upon the face of the deep: and the Spirit of God moved upon the face of the waters.
43
+ # Genesis 1:3 ASV And God said, Let there be light: and there was light.
44
+ #
45
+ # CSB
46
+ # Genesis 1:1 CSB In the beginning God created the heavens and the earth.
47
+ # Genesis 1:2 CSB Now the earth was formless and empty, darkness covered the surface of the watery depths, and the Spirit of God was hovering over the surface of the waters.
48
+ # Genesis 1:3 CSB Then God said, Let there be light, and there was light.
49
+
50
+ bible_structure = [
51
+ {
52
+ 'testament': 'OT',
53
+ 'verse_counts': [31, 25, 24, 26, 32, 22, 24, 22, 29, 32, 32, 20, 18, 24, 21, 16, 27, 33, 38, 18, 34, 24, 20, 67, 34, 35, 46, 22, 35, 43, 55, 32, 20, 31, 29, 43, 36, 30, 23, 23, 57, 38, 34, 34, 28, 34, 31, 22, 33, 26],
54
+ 'name': 'Genesis',
55
+ 'abbrs': ['gen', 'ge', 'gn']
56
+ },
57
+ {
58
+ 'testament': 'OT',
59
+ 'verse_counts': [22, 25, 22, 31, 23, 30, 25, 32, 35, 29, 10, 51, 22, 31, 27, 36, 16, 27, 25, 26, 36, 31, 33, 18, 40, 37, 21, 43, 46, 38, 18, 35, 23, 35, 35, 38, 29, 31, 43, 38],
60
+ 'name': 'Exodus',
61
+ 'abbrs': ['exod', 'exo', 'ex']
62
+ },
63
+ {
64
+ 'testament': 'OT',
65
+ 'verse_counts': [17, 16, 17, 35, 19, 30, 38, 36, 24, 20, 47, 8, 59, 57, 33, 34, 16, 30, 37, 27, 24, 33, 44, 23, 55, 46, 34],
66
+ 'name': 'Leviticus',
67
+ 'abbrs': ['lev', 'lv', 'le']
68
+ },
69
+ {
70
+ 'testament': 'OT',
71
+ 'verse_counts': [54, 34, 51, 49, 31, 27, 89, 26, 23, 36, 35, 16, 33, 45, 41, 50, 13, 32, 22, 29, 35, 41, 30, 25, 18, 65, 23, 31, 40, 16, 54, 42, 56, 29, 34, 13],
72
+ 'name': 'Numbers',
73
+ 'abbrs': ['num', 'nm', 'nu']
74
+ },
75
+ {
76
+ 'testament': 'OT',
77
+ 'verse_counts': [46, 37, 29, 49, 33, 25, 26, 20, 29, 22, 32, 32, 18, 29, 23, 22, 20, 22, 21, 20, 23, 30, 25, 22, 19, 19, 26, 68, 29, 20, 30, 52, 29, 12],
78
+ 'name': 'Deuteronomy',
79
+ 'abbrs': ['deut', 'deu', 'de', 'du', 'dt']
80
+ },
81
+ {
82
+ 'testament': 'OT',
83
+ 'verse_counts': [18, 24, 17, 24, 15, 27, 26, 35, 27, 43, 23, 24, 33, 15, 63, 10, 18, 28, 51, 9, 45, 34, 16, 33],
84
+ 'name': 'Joshua',
85
+ 'abbrs': ['josh', 'jos']
86
+ },
87
+ {
88
+ 'testament': 'OT',
89
+ 'verse_counts': [36, 23, 31, 24, 31, 40, 25, 35, 57, 18, 40, 15, 25, 20, 20, 31, 13, 31, 30, 48, 25],
90
+ 'name': 'Judges',
91
+ 'abbrs': ['judg', 'jgs', 'jdg']},
92
+ {
93
+ 'testament': 'OT',
94
+ 'verse_counts': [22, 23, 18, 22],
95
+ 'name': 'Ruth',
96
+ 'abbrs': ['rut', 'ru']
97
+ },
98
+ {
99
+ 'testament': 'OT',
100
+ 'verse_counts': [28, 36, 21, 22, 12, 21, 17, 22, 27, 27, 15, 25, 23, 52, 35, 23, 58, 30, 24, 42, 15, 23, 29, 22, 44, 25, 12, 25, 11, 31, 13],
101
+ 'name': '1 Samuel',
102
+ 'abbrs': ['1samuel', '1sam', '1 sam', '1sm', '1 sm' , '1sa', '1 sa']
103
+ },
104
+ {
105
+ 'testament': 'OT',
106
+ 'verse_counts': [27, 32, 39, 12, 25, 23, 29, 18, 13, 19, 27, 31, 39, 33, 37, 23, 29, 33, 43, 26, 22, 51, 39, 25],
107
+ 'name': '2 Samuel',
108
+ 'abbrs': ['2samuel', '2sam', '2 sam', '2sm', '2 sm', '2sa', '2 sa']
109
+ },
110
+ {
111
+ 'testament': 'OT',
112
+ 'verse_counts': [53, 46, 28, 34, 18, 38, 51, 66, 28, 29, 43, 33, 34, 31, 34, 34, 24, 46, 21, 43, 29, 53],
113
+ 'name': '1 Kings',
114
+ 'abbrs': ['1kings', '1king', '1kgs', '1kg', '1 kg', '1 kgs', '1ki', '1 ki']
115
+ },
116
+ {
117
+ 'testament': 'OT',
118
+ 'verse_counts': [18, 25, 27, 44, 27, 33, 20, 29, 37, 36, 21, 21, 25, 29, 38, 20, 41, 37, 37, 21, 26, 20, 37, 20, 30],
119
+ 'name': '2 Kings',
120
+ 'abbrs': ['2kings', '2king' '2kg 2', 'kg', '2ki', '2 ki']},
121
+ {
122
+ 'testament': 'OT',
123
+ 'verse_counts': [54, 55, 24, 43, 26, 81, 40, 40, 44, 14, 47, 40, 14, 17, 29, 43, 27, 17, 19, 8, 30, 19, 32, 31, 31, 32, 34, 21, 30],
124
+ 'name': '1 Chronicles',
125
+ 'abbrs': ['1chronicles', '1chron', '1 chron', '1ch', '1 ch']
126
+ },
127
+ {
128
+ 'testament': 'OT',
129
+ 'verse_counts': [17, 18, 17, 22, 14, 42, 22, 18, 31, 19, 23, 16, 22, 15, 19, 14, 19, 34, 11, 37, 20, 12, 21, 27, 28, 23, 9, 27, 36, 27, 21, 33, 25, 33, 27, 23],
130
+ 'name': '2 Chronicles',
131
+ 'abbrs': ['2chronicles', '2chron', '2 chron', '2 ch', '2ch']
132
+ },
133
+ {
134
+ 'testament': 'OT',
135
+ 'verse_counts': [11, 70, 13, 24, 17, 22, 28, 36, 15, 44],
136
+ 'name': 'Ezra',
137
+ 'abbrs': ['ezr', 'ez']
138
+ },
139
+ {
140
+ 'testament': 'OT',
141
+ 'verse_counts': [11, 20, 32, 23, 19, 19, 73, 18, 38, 39, 36, 47, 31],
142
+ 'name': 'Nehemiah',
143
+ 'abbrs': ['nehem', 'neh', 'ne']
144
+ },
145
+ {
146
+ 'testament': 'OT',
147
+ 'verse_counts': [22, 23, 15, 17, 14, 14, 10, 17, 32, 3],
148
+ 'name': 'Esther',
149
+ 'abbrs': ['esth', 'est', 'es']
150
+ },
151
+ {
152
+ 'testament': 'OT',
153
+ 'verse_counts': [22, 13, 26, 21, 27, 30, 21, 22, 35, 22, 20, 25, 28, 22, 35, 22, 16, 21, 29, 29, 34, 30, 17, 25, 6, 14, 23, 28, 25, 31, 40, 22, 33, 37, 16, 33, 24, 41, 30, 24, 34, 17],
154
+ 'name': 'Job',
155
+ 'abbrs': ['jb']
156
+ },
157
+ {
158
+ 'testament': 'OT',
159
+ 'verse_counts': [6, 12, 8, 8, 12, 10, 17, 9, 20, 18, 7, 8, 6, 7, 5, 11, 15, 50, 14, 9, 13, 31, 6, 10, 22, 12, 14, 9, 11, 12, 24, 11, 22, 22, 28, 12, 40, 22, 13, 17, 13, 11, 5, 26, 17, 11, 9, 14, 20, 23, 19, 9, 6, 7, 23, 13, 11, 11, 17, 12, 8, 12, 11, 10, 13, 20, 7, 35, 36, 5, 24, 20, 28, 23, 10, 12, 20, 72, 13, 19, 16, 8, 18, 12, 13, 17, 7, 18, 52, 17, 16, 15, 5, 23, 11, 13, 12, 9, 9, 5, 8, 28, 22, 35, 45, 48, 43, 13, 31, 7, 10, 10, 9, 8, 18, 19, 2, 29, 176, 7, 8, 9, 4, 8, 5, 6, 5, 6, 8, 8, 3, 18, 3, 3, 21, 26, 9, 8, 24, 13, 10, 7, 12, 15, 21, 10, 20, 14, 9, 6],
160
+ 'name': 'Psalms',
161
+ 'abbrs': ['psalm', 'psa', 'pss', 'ps']
162
+ },
163
+ {
164
+ 'testament': 'OT',
165
+ 'verse_counts': [33, 22, 35, 27, 23, 35, 27, 36, 18, 32, 31, 28, 25, 35, 33, 33, 28, 24, 29, 30, 31, 29, 35, 34, 28, 28, 27, 28, 27, 33, 31],
166
+ 'name': 'Proverbs',
167
+ 'abbrs': ['prov', 'prv', 'pv', 'pro']},
168
+ {
169
+ 'testament': 'OT',
170
+ 'verse_counts': [18, 26, 22, 16, 20, 12, 29, 17, 18, 20, 10, 14],
171
+ 'name': 'Ecclesiastes',
172
+ 'abbrs': ['eccles', 'ecc', 'ec']
173
+ },
174
+ {
175
+ 'testament': 'OT',
176
+ 'verse_counts': [17, 17, 11, 16, 16, 13, 13, 14],
177
+ 'name': 'Song of Solomon',
178
+ 'abbrs': [ 'song of sol', 'song', 'son', 'sos', 'ss', 'so', 'sg']
179
+ },
180
+ {
181
+ 'testament': 'OT',
182
+ 'verse_counts': [31, 22, 26, 6, 30, 13, 25, 22, 21, 34, 16, 6, 22, 32, 9, 14, 14, 7, 25, 6, 17, 25, 18, 23, 12, 21, 13, 29, 24, 33, 9, 20, 24, 17, 10, 22, 38, 22, 8, 31, 29, 25, 28, 28, 25, 13, 15, 22, 26, 11, 23, 15, 12, 17, 13, 12, 21, 14, 21, 22, 11, 12, 19, 12, 25, 24],
183
+ 'name': 'Isaiah',
184
+ 'abbrs': ['isa', 'is']
185
+ },
186
+ {
187
+ 'testament': 'OT',
188
+ 'verse_counts': [19, 37, 25, 31, 31, 30, 34, 22, 26, 25, 23, 17, 27, 22, 21, 21, 27, 23, 15, 18, 14, 30, 40, 10, 38, 24, 22, 17, 32, 24, 40, 44, 26, 22, 19, 32, 21, 28, 18, 16, 18, 22, 13, 30, 5, 28, 7, 47, 39, 46, 64, 34],
189
+ 'name': 'Jeremiah',
190
+ 'abbrs': ['jerem', 'jer', 'je']
191
+ },
192
+ {
193
+ 'testament': 'OT',
194
+ 'verse_counts': [22, 22, 66, 22, 22],
195
+ 'name': 'Lamentations',
196
+ 'abbrs': ['lamen', 'lam', 'la']
197
+ },
198
+ {
199
+ 'testament': 'OT',
200
+ 'verse_counts': [28, 10, 27, 17, 17, 14, 27, 18, 11, 22, 25, 28, 23, 23, 8, 63, 24, 32, 14, 49, 32, 31, 49, 27, 17, 21, 36, 26, 21, 26, 18, 32, 33, 31, 15, 38, 28, 23, 29, 49, 26, 20, 27, 31, 25, 24, 23, 35],
201
+ 'name': 'Ezekiel',
202
+ 'abbrs': ['ezek', 'eze', 'ezk']
203
+ },
204
+ {
205
+ 'testament': 'OT',
206
+ 'verse_counts': [21, 49, 30, 37, 31, 28, 28, 27, 27, 21, 45, 13],
207
+ 'name': 'Daniel',
208
+ 'abbrs': ['dan', 'da', 'dn']
209
+ },
210
+ {
211
+ 'testament': 'OT',
212
+ 'verse_counts': [11, 23, 5, 19, 15, 11, 16, 14, 17, 15, 12, 14, 16, 9],
213
+ 'name': 'Hosea',
214
+ 'abbrs': ['hos', 'ho']
215
+ },
216
+ {
217
+ 'testament': 'OT',
218
+ 'verse_counts': [20, 32, 21],
219
+ 'name': 'Joel',
220
+ 'abbrs': ['jl', 'joe']
221
+ },
222
+ {
223
+ 'testament': 'OT',
224
+ 'verse_counts': [15, 16, 15, 13, 27, 14, 17, 14, 15],
225
+ 'name': 'Amos',
226
+ 'abbrs': ['am', 'amo']
227
+ },
228
+ {
229
+ 'testament': 'OT',
230
+ 'verse_counts': [21],
231
+ 'name': 'Obadiah',
232
+ 'abbrs': ['obad', 'ob', 'oba']
233
+ },
234
+ {
235
+ 'testament': 'OT',
236
+ 'verse_counts': [17, 10, 10, 11],
237
+ 'name': 'Jonah',
238
+ 'abbrs': ['jon', 'jnh']
239
+ },
240
+ {
241
+ 'testament': 'OT',
242
+ 'verse_counts': [16, 13, 12, 13, 15, 16, 20],
243
+ 'name': 'Micah',
244
+ 'abbrs': ['mi', 'mic']
245
+ },
246
+ {
247
+ 'testament': 'OT',
248
+ 'verse_counts': [15, 13, 19],
249
+ 'name': 'Nahum',
250
+ 'abbrs': ['nah', 'na']
251
+ },
252
+ {
253
+ 'testament': 'OT',
254
+ 'verse_counts': [17, 20, 19],
255
+ 'name': 'Habakkuk',
256
+ 'abbrs': ['hab', 'hb']
257
+ },
258
+ {
259
+ 'testament': 'OT',
260
+ 'verse_counts': [18, 15, 20],
261
+ 'name': 'Zephaniah',
262
+ 'abbrs': ['zeph', 'zep']
263
+ },
264
+ {
265
+ 'testament': 'OT',
266
+ 'verse_counts': [15, 23],
267
+ 'name': 'Haggai',
268
+ 'abbrs': ['hag', 'hg']
269
+ },
270
+ {
271
+ 'testament': 'OT',
272
+ 'verse_counts': [21, 13, 10, 14, 11, 15, 14, 23, 17, 12, 17, 14, 9, 21],
273
+ 'name': 'Zechariah',
274
+ 'abbrs': ['zech', 'zec']
275
+ },
276
+ {
277
+ 'testament': 'OT',
278
+ 'verse_counts': [14, 17, 18, 6],
279
+ 'name': 'Malachi',
280
+ 'abbrs': ['mal', 'ml']
281
+ },
282
+ {
283
+ 'testament': 'NT',
284
+ 'verse_counts': [25, 23, 17, 25, 48, 34, 29, 34, 38, 42, 30, 50, 58, 36, 39, 28, 27, 35, 30, 34, 46, 46, 39, 51, 46, 75, 66, 20],
285
+ 'name': 'Matthew',
286
+ 'abbrs': ['mat', 'matt', 'mt']
287
+ },
288
+ {
289
+ 'testament': 'NT',
290
+ 'verse_counts': [45, 28, 35, 41, 43, 56, 37, 38, 50, 52, 33, 44, 37, 72, 47, 20],
291
+ 'name': 'Mark',
292
+ 'abbrs': ['mar', 'mk']},
293
+ {
294
+ 'testament': 'NT',
295
+ 'verse_counts': [80, 52, 38, 44, 39, 49, 50, 56, 62, 42, 54, 59, 35, 35, 32, 31, 37, 43, 48, 47, 38, 71, 56, 53],
296
+ 'name': 'Luke',
297
+ 'abbrs': ['lu', 'luk', 'lk']
298
+ },
299
+ {
300
+ 'testament': 'NT',
301
+ 'verse_counts': [51, 25, 36, 54, 47, 71, 53, 59, 41, 42, 57, 50, 38, 31, 27, 33, 26, 40, 42, 31, 25],
302
+ 'name': 'John',
303
+ 'abbrs': ['jo', 'joh', 'jn']
304
+ },
305
+ {
306
+ 'testament': 'NT',
307
+ 'verse_counts': [26, 47, 26, 37, 42, 15, 60, 40, 43, 48, 30, 25, 52, 28, 41, 40, 34, 28, 41, 38, 40, 30, 35, 27, 27, 32, 44, 31],
308
+ 'name': 'Acts',
309
+ 'abbrs': ['ac', 'act']},
310
+ {
311
+ 'testament': 'NT',
312
+ 'verse_counts': [32, 29, 31, 25, 21, 23, 25, 39, 33, 21, 36, 21, 14, 23, 33, 27],
313
+ 'name': 'Romans',
314
+ 'abbrs': ['rom', 'ro', 'rm']
315
+ },
316
+ {
317
+ 'testament': 'NT',
318
+ 'verse_counts': [31, 16, 23, 21, 13, 20, 40, 13, 27, 33, 34, 31, 13, 40, 58, 24],
319
+ 'name': '1 Corinthians',
320
+ 'abbrs': ['1corinthians', '1 cor', '1cor', '1 co', '1co', '1c']
321
+ },
322
+ {
323
+ 'testament': 'NT',
324
+ 'verse_counts': [24, 17, 18, 18, 21, 18, 16, 24, 15, 18, 33, 21, 14],
325
+ 'name': '2 Corinthians',
326
+ 'abbrs': ['2corinthians', '2 cor', '2cor', '2 co', '2co', '2c']
327
+ },
328
+ {
329
+ 'testament': 'NT',
330
+ 'verse_counts': [24, 21, 29, 31, 26, 18],
331
+ 'name': 'Galatians',
332
+ 'abbrs': ['gal', 'ga']
333
+ },
334
+ {
335
+ 'testament': 'NT',
336
+ 'verse_counts': [23, 22, 21, 32, 33, 24],
337
+ 'name': 'Ephesians',
338
+ 'abbrs': ['eph', 'ep']
339
+ },
340
+ {
341
+ 'testament': 'NT',
342
+ 'verse_counts': [30, 30, 21, 23],
343
+ 'name': 'Philippians',
344
+ 'abbrs': ['phil', 'php', 'phi']
345
+ },
346
+ {
347
+ 'testament': 'NT',
348
+ 'verse_counts': [29, 23, 25, 18],
349
+ 'name': 'Colossians',
350
+ 'abbrs': ['col', 'co']
351
+ },
352
+ {
353
+ 'testament': 'NT',
354
+ 'verse_counts': [10, 20, 13, 18, 28],
355
+ 'name': '1 Thessalonians',
356
+ 'abbrs': ['1thessalonians', '1 thess', '1thess', '1 thes', '1thes', '1th', '1 th']
357
+ },
358
+ {
359
+ 'testament': 'NT',
360
+ 'verse_counts': [12, 17, 18],
361
+ 'name': '2 Thessalonians',
362
+ 'abbrs': ['2thessalonians', '2 thess', '2thess', '2 thes', '2thes', '2th', '2 th']
363
+ },
364
+ {
365
+ 'testament': 'NT',
366
+ 'verse_counts': [20, 15, 16, 16, 25, 21],
367
+ 'name': '1 Timothy',
368
+ 'abbrs': ['1tim', '1tm', '1 tm', '1timothy', '1ti', '1 tim', '1 ti']
369
+ },
370
+ {
371
+ 'testament': 'NT',
372
+ 'verse_counts': [18, 26, 17, 22],
373
+ 'name': '2 Timothy',
374
+ 'abbrs': ['2tim', '2tm', '2 tm', '2timothy', '2ti', '2 tim', '2 ti']
375
+ },
376
+ {
377
+ 'testament': 'NT',
378
+ 'verse_counts': [16, 15, 15],
379
+ 'name': 'Titus',
380
+ 'abbrs': ['ti', 'tit']
381
+ },
382
+ {
383
+ 'testament': 'NT',
384
+ 'verse_counts': [25],
385
+ 'name': 'Philemon',
386
+ 'abbrs': ['philem', 'phm']
387
+ },
388
+ {
389
+ 'testament': 'NT',
390
+ 'verse_counts': [14, 18, 19, 16, 14, 20, 28, 13, 28, 39, 40, 29, 25],
391
+ 'name': 'Hebrews',
392
+ 'abbrs': ['heb', 'he']
393
+ },
394
+ {
395
+ 'testament': 'NT',
396
+ 'verse_counts': [27, 26, 18, 17, 20],
397
+ 'name': 'James',
398
+ 'abbrs': ['jam', 'ja', 'jas']
399
+ },
400
+ {
401
+ 'testament': 'NT',
402
+ 'verse_counts': [25, 25, 22, 19, 14],
403
+ 'name': '1 Peter',
404
+ 'abbrs': ['1pet', '1p', '1pe', '1 pe', '1pt', '1pe', '1 pet', '1 pt', '1 pe']
405
+ },
406
+ {
407
+ 'testament': 'NT',
408
+ 'verse_counts': [21, 22, 18],
409
+ 'name': '2 Peter',
410
+ 'abbrs': ['2pet', '2p', '2pe', '2 pe', '2pt', '2pe', '2 pet', '2 pt', '2 pe']
411
+ },
412
+ {
413
+ 'testament': 'NT',
414
+ 'verse_counts': [10, 29, 24, 21, 21],
415
+ 'name': '1 John',
416
+ 'abbrs': ['1john', '1j', '1jo', '1 jo', '1jn', '1 jn']
417
+ },
418
+ {
419
+ 'testament': 'NT',
420
+ 'verse_counts': [13],
421
+ 'name': '2 John',
422
+ 'abbrs': ['2john', '2j', '2jo', '2 jo', '2jn', '2 jn']
423
+ },
424
+ {
425
+ 'testament': 'NT',
426
+ 'verse_counts': [15],
427
+ 'name': '3 John',
428
+ 'abbrs': ['3john', '3j', '3jo', '3 jo', '3jn', '3 jn']
429
+ },
430
+ {
431
+ 'testament': 'NT',
432
+ 'verse_counts': [25],
433
+ 'name': 'Jude',
434
+ 'abbrs': ['ju', 'jud']
435
+ },
436
+ {
437
+ 'testament': 'NT',
438
+ 'verse_counts': [20, 29, 22, 11, 14, 17, 17, 13, 21, 11, 19, 17, 18, 20, 8, 21, 18, 24, 21, 15, 27, 21],
439
+ 'name': 'Revelation',
440
+ 'abbrs': ['rev', 're', 'rv', 'revel']
441
+ }
442
+ ]
443
+
444
+ roman_numerals = [
445
+ # 10
446
+ 'i', 'ii', 'iii', 'iv', 'v', 'vi', 'vii', 'viii', 'ix', 'x',
447
+ # 20
448
+ 'xi', 'xii', 'xiii', 'xiv', 'xv', 'xvi', 'xvii', 'xviii', 'xix', 'xx',
449
+ # 30
450
+ 'xxi', 'xxii', 'xxiii', 'xxiv', 'xxv', 'xxvi', 'xxvii', 'xxviii', 'xxix', 'xxx',
451
+ # 40
452
+ 'xxxi', 'xxxii', 'xxxiii', 'xxxiv', 'xxxv', 'xxxvi', 'xxxvii', 'xxxviii', 'xxxix', 'xl',
453
+ # 50
454
+ 'xli', 'xlii', 'xliii', 'xliv', 'xlv', 'xlvi', 'xlvii', 'xlviii', 'xlix', 'l',
455
+ # 60
456
+ 'li', 'lii', 'liii', 'liv', 'lv', 'lvi', 'lvii', 'lviii', 'lix', 'lx',
457
+ # 70
458
+ 'lxi', 'lxii', 'lxiii', 'lxiv', 'lxv', 'lxvi', 'lxvii', 'lxviii', 'lxix', 'lxx',
459
+ # 80
460
+ 'lxxi', 'lxxii', 'lxxiii', 'lxxiv', 'lxxv', 'lxxvi', 'lxxvii', 'lxxviii', 'lxxix', 'lxxx',
461
+ # 90
462
+ 'lxxxi', 'lxxxii', 'lxxxiii', 'lxxxiv', 'lxxxv', 'lxxxvi', 'lxxxvii', 'lxxxviii', 'lxxxix', 'xc',
463
+ # 100
464
+ 'xci', 'xcii', 'xciii', 'xciv', 'xcv', 'xcvi', 'xcvii', 'xcviii', 'xcix', 'c',
465
+ # 110
466
+ 'ci', 'cii', 'ciii', 'civ', 'cv', 'cvi', 'cvii', 'cviii', 'cix', 'cx',
467
+ # 120
468
+ 'cxi', 'cxii', 'cxiii', 'cxiv', 'cxv', 'cxvi', 'cxvii', 'cxviii', 'cxix', 'cxx',
469
+ # 130
470
+ 'cxxi', 'cxxii', 'cxxiii', 'cxxiv', 'cxxv', 'cxxvi', 'cxxvii', 'cxxviii', 'cxxix', 'cxxx',
471
+ # 140
472
+ 'cxxxi', 'cxxxii', 'cxxxiii', 'cxxxiv', 'cxxxv', 'cxxxvi', 'cxxxvii', 'cxxxviii', 'cxxxix', 'cxl',
473
+ # 150
474
+ 'cxli', 'cxlii', 'cxliii', 'cxliv', 'cxlv', 'cxlvi', 'cxlvii', 'cxlviii', 'cxlix', 'cl',
475
+ # 160
476
+ 'cli', 'clii', 'cliii', 'cliv', 'clv', 'clvi', 'clvii', 'clviii', 'clix', 'clx',
477
+ # 170
478
+ 'clxi', 'clxii', 'clxiii', 'clxiv', 'clxv', 'clxvi', 'clxvii', 'clxviii', 'clxix', 'clxx',
479
+ # 180
480
+ 'clxxi', 'clxxii', 'clxxiii', 'clxxiv', 'clxxv', 'clxxvi', 'clxxvii', 'clxxviii', 'clxxix', 'clxxx',
481
+ # 190
482
+ 'clxxxi', 'clxxxii', 'clxxxiii', 'clxxxiv', 'clxxxv', 'clxxxvi', 'clxxxvii', 'clxxxviii', 'clxxxix', 'cxc',
483
+ # 200
484
+ 'cxci', 'cxcii', 'cxciii', 'cxciv', 'cxcv', 'cxcvi', 'cxcvii', 'cxcviii', 'cxcix', 'cc'
485
+ ]
486
+
487
+ def get_verse_count(book: str, chapter: int) -> int:
488
+ """Get the number of verses in a given chapter of a book."""
489
+ for b in bible_structure:
490
+ if b['name'] == book:
491
+ if 1 <= chapter <= len(b['verse_counts']):
492
+ return b['verse_counts'][chapter-1]
493
+ return 0
494
+
495
+
496
+ ##################################################
497
+ # Load Bibles
498
+
499
+ def load_bible_to_dict(path: str) -> Dict[str, List[List[str]]]:
500
+ """Load bible verses from a file into a nested dictionary structure.
501
+
502
+ Args:
503
+ path: Path to the bible text file
504
+
505
+ Returns:
506
+ Dict with structure:
507
+ {
508
+ 'Genesis': [
509
+ ['In the beginning...', 'And the earth...'], # chapter 1
510
+ ['Thus the heavens...', 'And on the...'], # chapter 2
511
+ ]
512
+ }
513
+ """
514
+ bible_dict = {}
515
+ current_book = None
516
+ current_chapter = None
517
+
518
+ try:
519
+ with open(path, 'r', encoding='utf-8') as f:
520
+ for line in f:
521
+ line = line.strip()
522
+ if not line:
523
+ continue
524
+
525
+ # Parse the reference and verse
526
+ match = re.match(r'([\w\s]+)\s+(\d+):(\d+)\s+([A-Z]+)\s+(.+)', line)
527
+ if not match:
528
+ continue
529
+
530
+ book, chapter, verse, translation, text = match.groups()
531
+ chapter = int(chapter)
532
+ verse = int(verse)
533
+
534
+ # Initialize new book if needed
535
+ if book not in bible_dict:
536
+ bible_dict[book] = []
537
+
538
+ # Add chapters until we reach the current one
539
+ while len(bible_dict[book]) < chapter:
540
+ bible_dict[book].append([])
541
+
542
+ # Add verses until we reach the current one
543
+ while len(bible_dict[book][chapter-1]) < verse:
544
+ bible_dict[book][chapter-1].append('')
545
+
546
+ # Add the verse text
547
+ bible_dict[book][chapter-1][verse-1] = text
548
+
549
+ except FileNotFoundError:
550
+ print(f"Could not find Bible file at: {path}")
551
+ return {}
552
+
553
+ return bible_dict
554
+
555
+
556
+ # Load all bible translations to memory
557
+ bibles = {}
558
+ for translation, path in paths.items():
559
+ bibles[translation] = load_bible_to_dict(path)
560
+
561
+
562
+
563
+ ##################################################
564
+ # Parsers
565
+
566
+ # Optional whitespace
567
+ ws = regex(r'\s*')
568
+
569
+ # Required whitespace
570
+ required_ws = regex(r'\s+')
571
+
572
+ # Standard separators
573
+ colon = ws >> string(':') << ws
574
+ dash = ws >> string_from('-', '–') << ws
575
+ semicolon = ws >> string(';') << ws
576
+ comma = ws >> string(',') << ws
577
+ dot = string('.').optional()
578
+ ws_dot = ws >> string('.') << ws
579
+
580
+ @dataclass
581
+ class BookRef:
582
+ """Represents a standardized book reference.
583
+
584
+ >>> BookRef("Genesis")
585
+ BookRef('Genesis')
586
+ """
587
+ name: str
588
+ def __repr__(self):
589
+ return f"BookRef('{self.name}')"
590
+
591
+
592
+ def build_book_parser(allow_book_periods=True) -> Parser:
593
+ """Build a parser for Bible book names and abbreviations.
594
+
595
+ Uses the bible_structure data to create parsers for all valid book names
596
+ and abbreviations. Matching is case-insensitive.
597
+
598
+ Returns:
599
+ Parser that produces a BookRef object with standardized name
600
+
601
+ Examples:
602
+ >>> book_parser = build_book_parser()
603
+
604
+ # Full names - case variations
605
+ >>> book_parser.parse("Genesis")
606
+ BookRef('Genesis')
607
+ >>> book_parser.parse("GENESIS")
608
+ BookRef('Genesis')
609
+ >>> book_parser.parse("genesis")
610
+ BookRef('Genesis')
611
+ >>> book_parser.parse("GeNeSiS")
612
+ BookRef('Genesis')
613
+
614
+ # Error cases
615
+ >>> book_parser.parse("NotABook")
616
+ Traceback (most recent call last):
617
+ ...
618
+ parsy.ParseError: expected 'book name' at 0:0
619
+ >>> book_parser.parse("First Kings")
620
+ Traceback (most recent call last):
621
+ ...
622
+ parsy.ParseError: expected 'book name' at 0:0
623
+ """
624
+
625
+ # build sorted list of all names and abbreviations
626
+ forms = []
627
+ for book in bible_structure:
628
+ std_name = book['name']
629
+ # Full name doesn't get period
630
+ forms.append((std_name, std_name, False))
631
+ # Abbreviations can have optional period
632
+ forms.extend((abbr, std_name, True) for abbr in book['abbrs'])
633
+
634
+ # Sort by length (descending) then alphabetically to ensure longer matches take precedence
635
+ book_forms = sorted(forms, key=lambda x: (-len(x[0]), x[0].lower()))
636
+
637
+ # turn them into parsers
638
+ book_parsers = []
639
+ for form, std_name, allow_period in book_forms:
640
+ # Create case-insensitive parser for the book name/abbreviation
641
+ name_parser = string(form, transform=str.lower).result(std_name)
642
+ if allow_period and allow_book_periods:
643
+ # For abbreviations, allow optional period
644
+ parser = (name_parser << dot)
645
+ else:
646
+ # For full names, no period
647
+ parser = name_parser
648
+ book_parsers.append(parser)
649
+
650
+ # Combine all parsers with |
651
+ return (alt(*book_parsers)
652
+ .desc("book name")
653
+ .map(BookRef))
654
+
655
+ book_parser = build_book_parser()
656
+ book_parser_no_dot = build_book_parser(allow_book_periods=False)
657
+
658
+ # @@@@@@@@@@@@@@@@@@@@
659
+ # Test all books
660
+ for book in bible_structure:
661
+ std_name = book['name']
662
+ # Test standard name
663
+ result = book_parser.parse(std_name)
664
+ assert result == BookRef(std_name), f"Failed to parse {std_name}"
665
+ # Test lowercase
666
+ result = book_parser.parse(std_name.lower())
667
+ assert result == BookRef(std_name), f"Failed to parse {std_name.lower()}"
668
+ # Test uppercase
669
+ result = book_parser.parse(std_name.upper())
670
+ assert result == BookRef(std_name), f"Failed to parse {std_name.upper()}"
671
+ # Test all abbreviations
672
+ for abbr in book['abbrs']:
673
+ result = book_parser.parse(abbr)
674
+ assert result == BookRef(std_name), f"Failed to parse {abbr}"
675
+ # Test lowercase
676
+ result = book_parser.parse(abbr.lower())
677
+ assert result == BookRef(std_name), f"Failed to parse {abbr.lower()}"
678
+ # Test uppercase
679
+ result = book_parser.parse(abbr.upper())
680
+ assert result == BookRef(std_name), f"Failed to parse {abbr.upper()}"
681
+ # Test with period
682
+ result = book_parser.parse(abbr + '.')
683
+ assert result == BookRef(std_name), f"Failed to parse {abbr}."
684
+
685
+ # @@@@@@@@@@@@@@@@@@@@
686
+
687
+
688
+ ##################################################
689
+
690
+ ####################
691
+ # Verses
692
+
693
+ @dataclass
694
+ class VerseRef:
695
+ """Represents a verse number reference.
696
+
697
+ >>> VerseRef(1)
698
+ VerseRef(1)
699
+ """
700
+ number: int
701
+ def __repr__(self):
702
+ return f"VerseRef({self.number})"
703
+
704
+ def build_verse_parser() -> Parser:
705
+ """Build a parser for Bible verse numbers.
706
+
707
+ Handles Arabic numbers only (Roman numerals not used for verses).
708
+ Numbers must be positive.
709
+
710
+ Returns:
711
+ Parser that produces a VerseRef object
712
+
713
+ Examples:
714
+ >>> verse_parser = build_verse_parser()
715
+
716
+ # Basic numbers
717
+ >>> verse_parser.parse("1")
718
+ VerseRef(1)
719
+ >>> verse_parser.parse("176") # Longest verse (Ps 119:176)
720
+ VerseRef(176)
721
+
722
+ # Error cases
723
+ >>> verse_parser.parse("0") # No verse 0
724
+ Traceback (most recent call last):
725
+ ...
726
+ parsy.ParseError: expected 'verse number' at 0:0
727
+ >>> verse_parser.parse("1a")
728
+ Traceback (most recent call last):
729
+ ...
730
+ parsy.ParseError: expected 'EOF' at 0:1
731
+ """
732
+ return (regex(r'[1-9][0-9]*')
733
+ .map(int)
734
+ .map(VerseRef)
735
+ .desc("verse number"))
736
+
737
+ verse_parser = build_verse_parser()
738
+
739
+ @dataclass
740
+ class VerseRange:
741
+ """Represents a range of verses.
742
+
743
+ >>> VerseRange(VerseRef(1), VerseRef(3))
744
+ VerseRange(VerseRef(1), VerseRef(3))
745
+ """
746
+ start: VerseRef
747
+ end: VerseRef
748
+ def __repr__(self):
749
+ return f"VerseRange({self.start}, {self.end})"
750
+
751
+
752
+ def build_verse_range_parser() -> Parser:
753
+ """Build a parser for verse ranges like 1-3 or 1–3.
754
+
755
+ Examples:
756
+ >>> verse_range_parser = build_verse_range_parser()
757
+ >>> verse_range_parser.parse("1-3")
758
+ VerseRange(VerseRef(1), VerseRef(3))
759
+ >>> verse_range_parser.parse("1–3") # en-dash
760
+ VerseRange(VerseRef(1), VerseRef(3))
761
+ """
762
+ return seq(
763
+ start=verse_parser,
764
+ _dash=dash,
765
+ end=verse_parser
766
+ ).combine_dict(VerseRange)
767
+
768
+ verse_range_parser = build_verse_range_parser()
769
+
770
+
771
+ ####################
772
+ # Chapter
773
+
774
+ @dataclass
775
+ class ChapterRef:
776
+ """Represents a chapter reference that may be parsed from either Arabic or Roman numerals.
777
+
778
+ >>> ChapterRef(1)
779
+ ChapterRef(1)
780
+ """
781
+ number: int
782
+ def __repr__(self):
783
+ return f"ChapterRef({self.number})"
784
+
785
+ def build_chapter_parser(allow_dot=True) -> Parser:
786
+ """Build a parser for Bible chapter numbers.
787
+
788
+ Handles both Arabic numbers and Roman numerals. Roman numerals are matched
789
+ by length (longest first) then alphabetically to ensure correct parsing.
790
+
791
+ Returns:
792
+ Parser that produces a ChapterRef object
793
+
794
+ Examples:
795
+ >>> chapter_parser = build_chapter_parser()
796
+
797
+ # Arabic numbers
798
+ >>> chapter_parser.parse("1")
799
+ ChapterRef(1)
800
+ >>> chapter_parser.parse("119")
801
+ ChapterRef(119)
802
+
803
+ # Roman numerals - case variations
804
+ >>> chapter_parser.parse("i")
805
+ ChapterRef(1)
806
+ >>> chapter_parser.parse("I")
807
+ ChapterRef(1)
808
+ >>> chapter_parser.parse("iv")
809
+ ChapterRef(4)
810
+ >>> chapter_parser.parse("xl")
811
+ ChapterRef(40)
812
+
813
+ # Longer roman numerals
814
+ >>> chapter_parser.parse("xxxviii") # 38
815
+ ChapterRef(38)
816
+ >>> chapter_parser.parse("LXXXVIII") # 88
817
+ ChapterRef(88)
818
+ >>> chapter_parser.parse("CXIX") # 119
819
+ ChapterRef(119)
820
+
821
+ """
822
+
823
+ # Build sorted list of roman numerals with their values
824
+ roman_forms: List[Tuple[str, int]] = [
825
+ (numeral, idx + 1) for idx, numeral in enumerate(roman_numerals)
826
+ ]
827
+ # Sort by length (descending) and then alphabetically
828
+ roman_forms.sort(key=lambda x: (-len(x[0]), x[0]))
829
+
830
+ # Create individual parsers for each roman numeral
831
+ roman_parsers = []
832
+ for form, value in roman_forms:
833
+ # Create case-insensitive parser
834
+ if allow_dot:
835
+ parser = string(form, transform=str.lower).result(value) << dot
836
+ else:
837
+ parser = string(form, transform=str.lower).result(value)
838
+ roman_parsers.append(parser)
839
+
840
+ # Combine roman numeral parsers with reduce
841
+ roman = (alt(*roman_parsers)
842
+ .desc("roman numeral chapter"))
843
+
844
+ # Arabic numbers - must be 1 or greater
845
+ arabic = (regex(r'[1-9][0-9]*')
846
+ .map(int)
847
+ .desc("arabic chapter number"))
848
+
849
+ # Combine parsers and wrap result
850
+ return (roman | arabic).map(ChapterRef).desc("chapter number")
851
+
852
+
853
+
854
+ chapter_parser = build_chapter_parser()
855
+ chapter_parser_no_dot = build_chapter_parser(allow_dot=False)
856
+
857
+ # @@@@@@@@@@@@@@@@@@@@
858
+
859
+ # Test each roman numeral in the list
860
+ for idx, numeral in enumerate(roman_numerals):
861
+ expected = idx + 1 # Roman numerals are 1-based
862
+
863
+ # Test lowercase
864
+ result = chapter_parser.parse(numeral)
865
+ assert result == ChapterRef(expected), f"Failed to parse lowercase '{numeral}': expected {expected}, got {result}"
866
+
867
+ # Test uppercase
868
+ result = chapter_parser.parse(numeral.upper())
869
+ assert result == ChapterRef(expected), f"Failed to parse uppercase '{numeral.upper()}': expected {expected}, got {result}"
870
+
871
+ # Test mixed case (alternate upper/lower)
872
+ mixed = ''.join(c.upper() if i % 2 == 0 else c.lower()
873
+ for i, c in enumerate(numeral))
874
+ result = chapter_parser.parse(mixed)
875
+ assert result == ChapterRef(expected), f"Failed to parse mixed case '{mixed}': expected {expected}, got {result}"
876
+ # @@@@@@@@@@@@@@@@@@@@
877
+
878
+
879
+ @dataclass
880
+ class CrossChapterRange:
881
+ """Represents a range that spans chapters.
882
+
883
+ >>> CrossChapterRange(ChapterRef(1), VerseRef(31), ChapterRef(2), VerseRef(3))
884
+ CrossChapterRange(ChapterRef(1), VerseRef(31), ChapterRef(2), VerseRef(3))
885
+ """
886
+ start_chapter: ChapterRef
887
+ start_verse: VerseRef
888
+ end_chapter: ChapterRef
889
+ end_verse: VerseRef
890
+ def __repr__(self):
891
+ return f"CrossChapterRange({self.start_chapter}, {self.start_verse}, {self.end_chapter}, {self.end_verse})"
892
+
893
+ def build_cross_chapter_range_parser(chapter_parser: Parser, verse_parser: Parser) -> Parser:
894
+ """Build a parser for ranges that cross chapter boundaries.
895
+
896
+ Examples:
897
+ >>> chapter_parser = build_chapter_parser()
898
+ >>> verse_parser = build_verse_parser()
899
+ >>> range_parser = build_cross_chapter_range_parser(chapter_parser, verse_parser)
900
+ >>> range_parser.parse("1:31-2:3")
901
+ CrossChapterRange(ChapterRef(1), VerseRef(31), ChapterRef(2), VerseRef(3))
902
+ """
903
+ return seq(
904
+ start_chapter=chapter_parser << colon,
905
+ start_verse=verse_parser << dash,
906
+ end_chapter=chapter_parser << colon,
907
+ end_verse=verse_parser
908
+ ).combine_dict(CrossChapterRange)
909
+
910
+ cross_chapter_range = build_cross_chapter_range_parser(chapter_parser, verse_parser)
911
+
912
+ @dataclass
913
+ class ComplexChapter:
914
+ """ """
915
+ chapter: ChapterRef
916
+ verse_ref: List[Union[VerseRef, VerseRange]]
917
+ # verse_ref: Union[VerseRef, List[VerseRef], VerseRange, List[VerseRange]]
918
+ def __repr__(self):
919
+ return f"ComplexChapter({self.chapter}, {self.verse_ref})"
920
+
921
+ ComplexVerses = Union[ComplexChapter, CrossChapterRange]
922
+
923
+ ####################
924
+ # Whole References
925
+
926
+ @dataclass
927
+ class SingleReference:
928
+ """A single verse reference with book, chapter, and verse."""
929
+ book: BookRef
930
+ chapter: ChapterRef
931
+ verse: VerseRef
932
+ def __repr__(self):
933
+ return f"SingleReference({self.book}, {self.chapter}, {self.verse})"
934
+
935
+
936
+ @dataclass
937
+ class RangeReference:
938
+ """A verse range reference with book, chapter, and verse range. """
939
+ book: BookRef
940
+ chapter: ChapterRef
941
+ verse_range: VerseRange
942
+ def __repr__(self):
943
+ return f"RangeReference({self.book}, {self.chapter}, {self.verse_range})"
944
+
945
+
946
+ @dataclass
947
+ class CrossChapterReference:
948
+ """A cross-chapter range reference. """
949
+ book: BookRef
950
+ range: CrossChapterRange
951
+ def __repr__(self):
952
+ return f"CrossChapterReference({self.book}, {self.range})"
953
+
954
+
955
+ @dataclass
956
+ class ComplexReference:
957
+ """A reference containing multiple verses or ranges possibly across different chapters."""
958
+ book: BookRef
959
+ verse_refs: List[ComplexVerses]
960
+ def __repr__(self):
961
+ return f"ComplexReference({self.book}, {self.verse_refs})"
962
+
963
+
964
+ def build_complex_single_chapter_parser() -> Parser:
965
+ """
966
+ Ex: Gen 1: 1, 2-3
967
+
968
+ >>> parser = build_complex_single_chapter_parser()
969
+ >>> parser.parse("Gen 1:1,2")
970
+ ComplexReference(BookRef('Genesis'), [ComplexChapter(ChapterRef(1), [VerseRef(1), VerseRef(2)])])
971
+ >>> parser.parse("Gen 1:1-2,3-4")
972
+ ComplexReference(BookRef('Genesis'), [ComplexChapter(ChapterRef(1), [VerseRange(VerseRef(1), VerseRef(2)), VerseRange(VerseRef(3), VerseRef(4))])])
973
+ >>> parser.parse("Gen 1:1,2-3")
974
+ ComplexReference(BookRef('Genesis'), [ComplexChapter(ChapterRef(1), [VerseRef(1), VerseRange(VerseRef(2), VerseRef(3))])])
975
+ """
976
+ verses = seq(
977
+ chapter = chapter_parser << colon,
978
+ verse_ref = (verse_range_parser | verse_parser).sep_by(comma << ws, min=2)
979
+ ).combine_dict(ComplexChapter).map(lambda x: [x]) # wrap in list
980
+ return seq(
981
+ book=book_parser << required_ws,
982
+ verse_refs=verses
983
+ ).combine_dict(ComplexReference)
984
+
985
+
986
+ def build_complex_multi_chapter_parser() -> Parser:
987
+ """
988
+ Ex: Gen 1:1-2, 2:2-3
989
+
990
+ >>> parser = build_complex_multi_chapter_parser()
991
+ >>> parser.parse("Gen 1:1-2, 2:4-5")
992
+ ComplexReference(BookRef('Genesis'), [ComplexChapter(ChapterRef(1), [VerseRange(VerseRef(1), VerseRef(2))]), ComplexChapter(ChapterRef(2), [VerseRange(VerseRef(4), VerseRef(5))])])
993
+ >>> parser.parse('Gen 1:2, 2:3-4, 3:5-4:1')
994
+ ComplexReference(BookRef('Genesis'), [ComplexChapter(ChapterRef(1), [VerseRef(2)]), ComplexChapter(ChapterRef(2), [VerseRange(VerseRef(3), VerseRef(4))]), CrossChapterRange(ChapterRef(3), VerseRef(5), ChapterRef(4), VerseRef(1))])
995
+ """
996
+ single_chapter = seq(
997
+ chapter = chapter_parser << colon,
998
+ verse_ref = (verse_range_parser | verse_parser).map(lambda x: [x])
999
+ ).combine_dict(ComplexChapter)
1000
+
1001
+ p = (cross_chapter_range | single_chapter).sep_by(comma << ws, min=2)
1002
+
1003
+ return seq(
1004
+ book=book_parser << required_ws,
1005
+ verse_refs=p
1006
+ ).combine_dict(ComplexReference)
1007
+
1008
+
1009
+ def build_complex_reference_parser() -> Parser:
1010
+ """Build a parser for complex verse references with multiple verses or ranges across chapters.
1011
+
1012
+ Templates:
1013
+ - book chapter:1, 2, 3-4 # single chapter
1014
+ - book chapter:1, chapter:2-3, chapter:4 # multi chapter
1015
+ - book 1:30-2:2, 1:1 # multi chapter with cross chapter range
1016
+
1017
+ Examples:
1018
+ - Gen 1:1,3,5
1019
+ - Gen 1:31-2:3, 2:35
1020
+ - Ps. 119:1-3, 120:5-7, 121:4-122:2
1021
+
1022
+ Examples:
1023
+ >>> parser = build_complex_reference_parser()
1024
+ >>> parser.parse("Ps. 119:1-2, 120:5-6, 121:4-122:2")
1025
+ ComplexReference(BookRef('Psalms'), [ComplexChapter(ChapterRef(119), [VerseRange(VerseRef(1), VerseRef(2))]), ComplexChapter(ChapterRef(120), [VerseRange(VerseRef(5), VerseRef(6))]), CrossChapterRange(ChapterRef(121), VerseRef(4), ChapterRef(122), VerseRef(2))])
1026
+ """
1027
+ return (
1028
+ build_complex_multi_chapter_parser() |
1029
+ build_complex_single_chapter_parser()
1030
+ )
1031
+
1032
+
1033
+ ##################################################
1034
+
1035
+ @dataclass
1036
+ class ChapterOnlyReference:
1037
+ """A reference to a whole chapter without specific verses."""
1038
+ book: BookRef
1039
+ chapter: ChapterRef
1040
+ def __repr__(self):
1041
+ return f"ChapterOnlyReference({self.book}, {self.chapter})"
1042
+
1043
+ def build_chapter_only_parser() -> Parser:
1044
+ """Build a parser for whole chapter references.
1045
+
1046
+ Examples:
1047
+ >>> parser = build_chapter_only_parser()
1048
+ >>> parser.parse("Genesis 1")
1049
+ ChapterOnlyReference(BookRef('Genesis'), ChapterRef(1))
1050
+ >>> parser.parse("Gen. 1")
1051
+ ChapterOnlyReference(BookRef('Genesis'), ChapterRef(1))
1052
+ >>> parser.parse("Gen i")
1053
+ ChapterOnlyReference(BookRef('Genesis'), ChapterRef(1))
1054
+ """
1055
+ return (
1056
+ seq(book_parser << required_ws, chapter_parser).combine(ChapterOnlyReference) |
1057
+ seq(book_parser_no_dot << ws_dot, chapter_parser_no_dot).combine(ChapterOnlyReference)
1058
+ )
1059
+
1060
+
1061
+ ##################################################
1062
+
1063
+
1064
+ def build_reference_parser() -> Parser:
1065
+ """Build a parser for complete Bible references.
1066
+
1067
+ Examples:
1068
+ >>> parser = build_reference_parser()
1069
+
1070
+ # Single verse
1071
+ >>> parser.parse("Genesis 1:1")
1072
+ [SingleReference(BookRef('Genesis'), ChapterRef(1), VerseRef(1))]
1073
+
1074
+ # Verse range
1075
+ >>> parser.parse("Genesis 1:1-3")
1076
+ [RangeReference(BookRef('Genesis'), ChapterRef(1), VerseRange(VerseRef(1), VerseRef(3)))]
1077
+
1078
+ # Cross chapter range
1079
+ >>> parser.parse("Genesis 1:31-2:3")
1080
+ [CrossChapterReference(BookRef('Genesis'), CrossChapterRange(ChapterRef(1), VerseRef(31), ChapterRef(2), VerseRef(3)))]
1081
+
1082
+ # Book abbreviation
1083
+ >>> parser.parse("Gen 1:1")
1084
+ [SingleReference(BookRef('Genesis'), ChapterRef(1), VerseRef(1))]
1085
+
1086
+ # Roman numeral chapter
1087
+ >>> parser.parse("Genesis ii:1")
1088
+ [SingleReference(BookRef('Genesis'), ChapterRef(2), VerseRef(1))]
1089
+ """
1090
+
1091
+ # Single verse reference (eg "Genesis 1:1")
1092
+ single_ref = (
1093
+ seq(book_parser << required_ws, chapter_parser << colon, verse_parser).combine(SingleReference) | # Gen 1: 1
1094
+ seq(book_parser_no_dot << ws_dot, chapter_parser_no_dot << ws_dot, verse_parser).combine(SingleReference) | # Gen.1.1
1095
+ seq(book_parser_no_dot << ws, chapter_parser_no_dot << ws_dot, verse_parser).combine(SingleReference) # Gen i. 1
1096
+ )
1097
+
1098
+ # Verse range in same chapter (eg "Genesis 1:1-3")
1099
+ range_ref = (
1100
+ seq(book_parser << required_ws, chapter_parser << colon, verse_range_parser).combine(RangeReference) | # Gen 1:1-3
1101
+ seq(book_parser_no_dot << ws_dot, chapter_parser_no_dot << ws_dot, verse_range_parser).combine(RangeReference) # Gen. 1. 1-3
1102
+ )
1103
+
1104
+ # Cross-chapter range (eg "Genesis 1:31-2:3")
1105
+ cross_chapter_ref = seq(
1106
+ book=book_parser << required_ws,
1107
+ range=cross_chapter_range,
1108
+ ).combine_dict(CrossChapterReference)
1109
+
1110
+ # Complex (eg "Gen 1:3-4, 2:5-6")
1111
+ complex_ref = build_complex_reference_parser()
1112
+
1113
+ # Combine all parsers and allow multiple references separated by semicolons
1114
+ # Order matters - try more specific patterns first
1115
+ return (complex_ref |
1116
+ cross_chapter_ref |
1117
+ range_ref |
1118
+ single_ref |
1119
+ build_chapter_only_parser()
1120
+ ).sep_by(semicolon, min=1)
1121
+
1122
+
1123
+ # Reuse existing components from the base code
1124
+ book_parser = build_book_parser()
1125
+ chapter_parser = build_chapter_parser()
1126
+ verse_parser = build_verse_parser()
1127
+
1128
+
1129
+ ##################################################
1130
+ #
1131
+
1132
+
1133
+ ####################
1134
+ # Pipe Syntax Parser
1135
+
1136
+ def build_pipe_parser() -> Parser:
1137
+ """Build a parser for the pipe-delimited format.
1138
+
1139
+ Examples:
1140
+ >>> build_pipe_parser().parse("|Matt|5|6|0|0")
1141
+ SingleReference(BookRef('Matthew'), ChapterRef(5), VerseRef(6))
1142
+ >>> build_pipe_parser().parse("|John|10|11|10|13")
1143
+ RangeReference(BookRef('John'), ChapterRef(10), VerseRange(VerseRef(11), VerseRef(13)))
1144
+ """
1145
+ pipe = string("|")
1146
+ number = regex(r'[0-9]+').map(int)
1147
+
1148
+ @generate
1149
+ def pipe_reference():
1150
+ # Parse components
1151
+ yield pipe
1152
+ book = yield book_parser
1153
+ yield pipe
1154
+ chapter1 = yield number
1155
+ yield pipe
1156
+ verse1 = yield number
1157
+ yield pipe
1158
+ chapter2 = yield number
1159
+ yield pipe
1160
+ verse2 = yield number
1161
+
1162
+ # Convert numbers to proper reference types
1163
+ ch1 = ChapterRef(chapter1)
1164
+ v1 = VerseRef(verse1)
1165
+
1166
+ # Single verse reference
1167
+ if chapter2 == 0 and verse2 == 0:
1168
+ return SingleReference(book, ch1, v1)
1169
+
1170
+ # Range reference
1171
+ ch2 = ChapterRef(chapter2)
1172
+ v2 = VerseRef(verse2)
1173
+
1174
+ # Same chapter range
1175
+ if chapter1 == chapter2:
1176
+ return RangeReference(book, ch1, VerseRange(v1, v2))
1177
+
1178
+ # Cross chapter range
1179
+ return CrossChapterReference(
1180
+ book,
1181
+ CrossChapterRange(ch1, v1, ch2, v2)
1182
+ )
1183
+
1184
+ return pipe_reference
1185
+
1186
+
1187
+ ####################
1188
+ # OSIS Parser
1189
+
1190
+ def build_osis_parser() -> Parser:
1191
+ """Build a parser for OSIS format references.
1192
+
1193
+ Examples:
1194
+ >>> build_osis_parser().parse("Bible:Matt.5.6")
1195
+ [SingleReference(BookRef('Matthew'), ChapterRef(5), VerseRef(6))]
1196
+ >>> build_osis_parser().parse("Matt.5.6")
1197
+ [SingleReference(BookRef('Matthew'), ChapterRef(5), VerseRef(6))]
1198
+ >>> build_osis_parser().parse("Bible:John.10.11-John.10.13")
1199
+ [RangeReference(BookRef('John'), ChapterRef(10), VerseRange(VerseRef(11), VerseRef(13)))]
1200
+
1201
+ # whole chapter
1202
+ >>> build_osis_parser().parse("Bible:Matt.5")
1203
+ [ChapterOnlyReference(BookRef('Matthew'), ChapterRef(5))]
1204
+ >>> build_osis_parser().parse("Matt.5")
1205
+ [ChapterOnlyReference(BookRef('Matthew'), ChapterRef(5))]
1206
+ """
1207
+ bible_prefix = string("Bible:").optional()
1208
+ dot = string(".") << ws
1209
+
1210
+ # Chapter only reference (e.g., "Matt.5")
1211
+ chapter_only_ref = seq(
1212
+ _bible_prefix=bible_prefix,
1213
+ book=book_parser_no_dot,
1214
+ _d1=dot,
1215
+ chapter=chapter_parser
1216
+ ).combine_dict(ChapterOnlyReference)
1217
+
1218
+ # Single reference (e.g., "Matt.5.6")
1219
+ single_ref = seq(
1220
+ _bible_prefix=bible_prefix,
1221
+ book=book_parser_no_dot,
1222
+ _d1=dot,
1223
+ chapter=chapter_parser,
1224
+ _d2=dot,
1225
+ verse=verse_parser
1226
+ ).combine_dict(SingleReference)
1227
+
1228
+ # Verse range in same chapter (e.g., "Gen.1.1-Gen.1.3")
1229
+ @generate
1230
+ def range_ref():
1231
+ yield bible_prefix
1232
+ book1 = yield book_parser << ws << dot
1233
+ ch1 = yield chapter_parser << ws << dot
1234
+ v1 = yield verse_parser
1235
+ yield dash
1236
+ book2 = yield book_parser << ws << dot
1237
+ ch2 = yield chapter_parser << ws << dot
1238
+ v2 = yield verse_parser
1239
+ if book1 != book2:
1240
+ fail("OSIS format cannot handle cross-book references")
1241
+ return RangeReference(
1242
+ book1,
1243
+ ch1,
1244
+ VerseRange(v1, v2)
1245
+ )
1246
+
1247
+ return (range_ref | single_ref
1248
+ | chapter_only_ref
1249
+ ).sep_by(semicolon, min=1)
1250
+
1251
+
1252
+ ####################
1253
+
1254
+
1255
+ @dataclass
1256
+ class Verse:
1257
+ book: str
1258
+ chapter: int
1259
+ verse: int
1260
+ def __repr__(self):
1261
+ """Custom representation for doctests."""
1262
+ return f"Verse('{self.book}', {self.chapter}, {self.verse})"
1263
+
1264
+ def parse_verses(reference: str) -> List[Verse]:
1265
+ """Parse a scripture reference into individual verses.
1266
+
1267
+ This is the main entry point for parsing Bible references.
1268
+
1269
+ >>> parse_verses('Genesis 1:1')
1270
+ [Verse('Genesis', 1, 1)]
1271
+ >>> parse_verses('Gen 1:1-3')
1272
+ [Verse('Genesis', 1, 1), Verse('Genesis', 1, 2), Verse('Genesis', 1, 3)]
1273
+ >>> parse_verses('Gen 1:31-2:3')
1274
+ [Verse('Genesis', 1, 31), Verse('Genesis', 2, 1), Verse('Genesis', 2, 2), Verse('Genesis', 2, 3)]
1275
+ >>> parse_verses('Gen 1:1; Ex 2:3')
1276
+ [Verse('Genesis', 1, 1), Verse('Exodus', 2, 3)]
1277
+
1278
+ # Pipes
1279
+ >>> parse_verses("|Matt|5|6|0|0")
1280
+ [Verse('Matthew', 5, 6)]
1281
+ >>> parse_verses("|John|10|11|10|13")
1282
+ [Verse('John', 10, 11), Verse('John', 10, 12), Verse('John', 10, 13)]
1283
+
1284
+ # OSIS
1285
+ >>> parse_verses("Bible:Matt.5.6")
1286
+ [Verse('Matthew', 5, 6)]
1287
+ >>> parse_verses("Bible:John.10.11-John.10.13")
1288
+ [Verse('John', 10, 11), Verse('John', 10, 12), Verse('John', 10, 13)]
1289
+ """
1290
+ try:
1291
+ p = (
1292
+ build_reference_parser() |
1293
+ build_pipe_parser() |
1294
+ build_osis_parser()
1295
+ )
1296
+ refs = p.parse(reference)
1297
+ return convert_to_verses(refs)
1298
+ except:
1299
+ return []
1300
+
1301
+
1302
+ ##################################################
1303
+ # Fetching
1304
+
1305
+ def convert_cross_chapter_range_to_verses(x: CrossChapterRange, book):
1306
+ result = []
1307
+
1308
+ # Add verses from first chapter
1309
+ max_verse = get_verse_count(book, x.start_chapter.number)
1310
+ for v in range(x.start_verse.number, max_verse + 1):
1311
+ result.append(Verse(book, x.start_chapter.number, v))
1312
+
1313
+ # Add verses from intervening chapters
1314
+ for ch in range(x.start_chapter.number + 1, x.end_chapter.number):
1315
+ max_verse = get_verse_count(book, ch)
1316
+ for v in range(1, max_verse + 1):
1317
+ result.append(Verse(book, ch, v))
1318
+
1319
+ # Add verses from last chapter
1320
+ for v in range(1, x.end_verse.number + 1):
1321
+ result.append(Verse(book, x.end_chapter.number, v))
1322
+ return result
1323
+
1324
+
1325
+ def convert_cross_chapter_reference_to_verses(ref: CrossChapterReference) -> List[Verse]:
1326
+ return convert_cross_chapter_range_to_verses(ref.range, ref.book.name)
1327
+
1328
+ def f(book, chapter, verse_or_range):
1329
+ # VerseRef
1330
+ if isinstance(verse_or_range, VerseRef):
1331
+ return [Verse(book, chapter.number, verse_or_range.number)]
1332
+ # VerseRange
1333
+ elif isinstance(verse_or_range, VerseRange):
1334
+ result = []
1335
+ start = verse_or_range.start.number
1336
+ end = verse_or_range.end.number
1337
+ for v in range(start, end + 1):
1338
+ result.append(Verse(book, chapter.number, v))
1339
+ return result
1340
+
1341
+
1342
+ def convert_complex_chapter_to_verses(cc: ComplexChapter, book):
1343
+ assert isinstance(cc.verse_ref, list), f'ComplexChapter.verse_ref must be list, but found: {cc}'
1344
+ return list(reduce(lambda x, y: x + y,
1345
+ map(lambda v: f(book, cc.chapter, v), cc.verse_ref)))
1346
+
1347
+
1348
+ def convert_complex_verse_to_verses(x: ComplexVerses, book):
1349
+ if isinstance(x, ComplexChapter):
1350
+ return convert_complex_chapter_to_verses(x, book)
1351
+ elif isinstance(x, CrossChapterRange):
1352
+ return convert_cross_chapter_range_to_verses(x, book)
1353
+
1354
+
1355
+ def convert_complex_ref_to_verses(ref: ComplexReference) -> List[Verse]:
1356
+ return list(reduce(lambda x, y: x + y,
1357
+ map(lambda x: convert_complex_verse_to_verses(x, ref.book.name), ref.verse_refs)))
1358
+
1359
+
1360
+ def convert_chapter_only_reference_to_verses(ref: ChapterOnlyReference) -> List[Verse]:
1361
+ """Convert a chapter reference to a list of all verses in that chapter.
1362
+
1363
+ Examples:
1364
+ >>> ref = ChapterOnlyReference(BookRef('Genesis'), ChapterRef(1))
1365
+ >>> verses = convert_chapter_only_reference_to_verses(ref)
1366
+ >>> len(verses) # Genesis 1 has 31 verses
1367
+ 31
1368
+ >>> verses[0]
1369
+ Verse('Genesis', 1, 1)
1370
+ >>> verses[-1]
1371
+ Verse('Genesis', 1, 31)
1372
+ """
1373
+ result = []
1374
+ verse_count = get_verse_count(ref.book.name, ref.chapter.number)
1375
+ for verse_num in range(1, verse_count + 1):
1376
+ result.append(Verse(ref.book.name, ref.chapter.number, verse_num))
1377
+ return result
1378
+
1379
+ def convert_to_verses(refs) -> List[Verse]:
1380
+ """Convert parsed references into a list of Verse objects.
1381
+
1382
+ This handles all the different reference types and converts them into
1383
+ a flat list of individual verses. Invalid chapter or verse numbers are
1384
+ filtered out at the end.
1385
+
1386
+ Examples:
1387
+ >>> parser = build_reference_parser()
1388
+ >>> convert_to_verses(parser.parse("Gen 1:1-3"))
1389
+ [Verse('Genesis', 1, 1), Verse('Genesis', 1, 2), Verse('Genesis', 1, 3)]
1390
+ >>> convert_to_verses(parser.parse("Gen 1:31-2:3"))
1391
+ [Verse('Genesis', 1, 31), Verse('Genesis', 2, 1), Verse('Genesis', 2, 2), Verse('Genesis', 2, 3)]
1392
+ >>> convert_to_verses(parser.parse("Gen 51:1")) # chapter too high
1393
+ []
1394
+ >>> convert_to_verses(parser.parse("Gen 1:40")) # verse too high
1395
+ []
1396
+ >>> convert_to_verses(parser.parse("Gen 1:31-2:3, 2:4"))
1397
+ [Verse('Genesis', 1, 31), Verse('Genesis', 2, 1), Verse('Genesis', 2, 2), Verse('Genesis', 2, 3), Verse('Genesis', 2, 4)]
1398
+ >>> convert_to_verses(parser.parse("Gen 1:1, 2:4"))
1399
+ [Verse('Genesis', 1, 1), Verse('Genesis', 2, 4)]
1400
+ """
1401
+ result = []
1402
+
1403
+ # Handle single reference or list
1404
+ refs = [refs] if not isinstance(refs, list) else refs
1405
+
1406
+ for ref in refs:
1407
+ if isinstance(ref, SingleReference):
1408
+ result.append(Verse(ref.book.name, ref.chapter.number, ref.verse.number))
1409
+
1410
+ elif isinstance(ref, RangeReference):
1411
+ for v in range(ref.verse_range.start.number, ref.verse_range.end.number + 1):
1412
+ result.append(Verse(ref.book.name, ref.chapter.number, v))
1413
+
1414
+ elif isinstance(ref, CrossChapterReference):
1415
+ result += convert_cross_chapter_reference_to_verses(ref)
1416
+
1417
+ elif isinstance(ref, ComplexReference):
1418
+ result += convert_complex_ref_to_verses(ref)
1419
+
1420
+ elif isinstance(ref, ChapterOnlyReference):
1421
+ result += convert_chapter_only_reference_to_verses(ref)
1422
+
1423
+ # Filter out invalid verses at the end
1424
+ def is_valid_reference(verse: Verse) -> bool:
1425
+ """Check if a verse reference is valid."""
1426
+ for b in bible_structure:
1427
+ if b['name'] == verse.book:
1428
+ if 1 <= verse.chapter <= len(b['verse_counts']):
1429
+ return 1 <= verse.verse <= b['verse_counts'][verse.chapter-1]
1430
+ return False
1431
+
1432
+ return [verse for verse in result if is_valid_reference(verse)]
1433
+
1434
+
1435
+ def fetch_verses(verses: List[Verse], translation: str, with_reference: bool = False) -> List[str]:
1436
+ """Retrieve the text for a list of verses from the specified translation.
1437
+
1438
+ Args:
1439
+ verses: List of Verse objects to retrieve
1440
+ translation: Bible translation to use (e.g., 'KJV', 'ASV')
1441
+ with_reference: Whether to include the verse reference in the output
1442
+
1443
+ Returns:
1444
+ List of verse texts, optionally with references
1445
+ """
1446
+ if translation not in bibles:
1447
+ return []
1448
+
1449
+ bible = bibles[translation]
1450
+ results = []
1451
+
1452
+ for verse in verses:
1453
+ try:
1454
+ text = bible[verse.book][verse.chapter-1][verse.verse-1]
1455
+ if with_reference:
1456
+ results.append(f"{verse.book} {verse.chapter}:{verse.verse} {translation} {text}")
1457
+ else:
1458
+ results.append(text)
1459
+ except (KeyError, IndexError):
1460
+ # Skip verses that don't exist in this translation
1461
+ continue
1462
+
1463
+ return results
1464
+
1465
+ def fetch(ref_string:str, translation, with_reference: bool = True) -> List[str]:
1466
+ assert translation in {'CSB', 'KJV', 'ASV'}
1467
+ vs = parse_verses(ref_string)
1468
+ xs = fetch_verses(vs, translation, with_reference)
1469
+ return xs
1470
+
1471
+
1472
+ ##################################################
1473
+ # sandbox
1474
+
1475
+ if False:
1476
+
1477
+ # vs = parse_verses('Genesis 1:1-31')
1478
+ vs = parse_verses('1 Cor. ii. 14; Gen 1:2; Amos 1:9')
1479
+ # vs = parse_verses('|gen|1|2|2|4')
1480
+ xs = fetch_verses(vs, "CSB", with_reference=True)
1481
+ print('\n'.join(xs))
1482
+
1483
+
1484
+ ##################################################
1485
+
1486
+ def parse_verses_test(reference: str) -> List[Verse]:
1487
+ """Parse scripture references into individual verses.
1488
+
1489
+ TODO? Book only
1490
+
1491
+ TODO? Chapter only
1492
+
1493
+ TODO? Chapter range
1494
+
1495
+ Basic formats:
1496
+ >>> parse_verses('Genesis 1:1')
1497
+ [Verse('Genesis', 1, 1)]
1498
+ >>> parse_verses('Gen 1:1')
1499
+ [Verse('Genesis', 1, 1)]
1500
+ >>> parse_verses('Gen. 1:1')
1501
+ [Verse('Genesis', 1, 1)]
1502
+
1503
+ Single Chapter
1504
+ >>> parse_verses('Genesis 1')[0]
1505
+ Verse('Genesis', 1, 1)
1506
+ >>> parse_verses('Genesis 1')[-1]
1507
+ Verse('Genesis', 1, 31)
1508
+
1509
+ Verse ranges:
1510
+ >>> parse_verses('Genesis 1:1-3')
1511
+ [Verse('Genesis', 1, 1), Verse('Genesis', 1, 2), Verse('Genesis', 1, 3)]
1512
+ >>> parse_verses('Gen 1:31-2:1') # Cross-chapter
1513
+ [Verse('Genesis', 1, 31), Verse('Genesis', 2, 1)]
1514
+ >>> parse_verses('Exodus 39:32-40:2') # Cross-chapter with more verses
1515
+ [Verse('Exodus', 39, 32), Verse('Exodus', 39, 33), Verse('Exodus', 39, 34), Verse('Exodus', 39, 35), Verse('Exodus', 39, 36), Verse('Exodus', 39, 37), Verse('Exodus', 39, 38), Verse('Exodus', 39, 39), Verse('Exodus', 39, 40), Verse('Exodus', 39, 41), Verse('Exodus', 39, 42), Verse('Exodus', 39, 43), Verse('Exodus', 40, 1), Verse('Exodus', 40, 2)]
1516
+
1517
+ Roman numerals:
1518
+ >>> parse_verses('1 Cor. ii. 14')
1519
+ [Verse('1 Corinthians', 2, 14)]
1520
+ >>> parse_verses('Psalm CXLIX. 3') # Testing larger Roman numerals
1521
+ [Verse('Psalms', 149, 3)]
1522
+ >>> parse_verses('Matt. iv. 1-3') # Roman numerals with range
1523
+ [Verse('Matthew', 4, 1), Verse('Matthew', 4, 2), Verse('Matthew', 4, 3)]
1524
+
1525
+ Multiple references:
1526
+ >>> parse_verses('Gen 1:1; Ex 2:3')
1527
+ [Verse('Genesis', 1, 1), Verse('Exodus', 2, 3)]
1528
+ >>> parse_verses('Gen 1:1, 3, 5') # Same chapter, different verses
1529
+ [Verse('Genesis', 1, 1), Verse('Genesis', 1, 3), Verse('Genesis', 1, 5)]
1530
+ >>> parse_verses('Gen 1:1-3; Ex 2:3-5') # Multiple ranges
1531
+ [Verse('Genesis', 1, 1), Verse('Genesis', 1, 2), Verse('Genesis', 1, 3), Verse('Exodus', 2, 3), Verse('Exodus', 2, 4), Verse('Exodus', 2, 5)]
1532
+
1533
+ OSIS format:
1534
+ >>> parse_verses('Bible:Gen.1.1')
1535
+ [Verse('Genesis', 1, 1)]
1536
+ >>> parse_verses('Gen.1.1')
1537
+ [Verse('Genesis', 1, 1)]
1538
+ >>> parse_verses('1Cor.2.14')
1539
+ [Verse('1 Corinthians', 2, 14)]
1540
+ >>> parse_verses("Bible:John.10.11-John.10.13")
1541
+ [Verse('John', 10, 11), Verse('John', 10, 12), Verse('John', 10, 13)]
1542
+
1543
+ Book name variations:
1544
+ >>> parse_verses('1 Kings 1:1')
1545
+ [Verse('1 Kings', 1, 1)]
1546
+ >>> parse_verses('1Kgs 1:1')
1547
+ [Verse('1 Kings', 1, 1)]
1548
+ >>> parse_verses('1 Kg 1:1')
1549
+ [Verse('1 Kings', 1, 1)]
1550
+ >>> parse_verses('First Kings 1:1') # This should fail - we don't support spelled out numbers
1551
+ []
1552
+
1553
+ Special cases and edge cases:
1554
+ >>> parse_verses('Rev 22:21') # Last verse of the Bible
1555
+ [Verse('Revelation', 22, 21)]
1556
+ >>> parse_verses('Psa 119:176') # Longest chapter
1557
+ [Verse('Psalms', 119, 176)]
1558
+ >>> parse_verses('Ps. 119:1-3,5-7') # Complex range with gaps
1559
+ [Verse('Psalms', 119, 1), Verse('Psalms', 119, 2), Verse('Psalms', 119, 3), Verse('Psalms', 119, 5), Verse('Psalms', 119, 6), Verse('Psalms', 119, 7)]
1560
+ >>> parse_verses('Est 9:1–3') # Em dash instead of hyphen
1561
+ [Verse('Esther', 9, 1), Verse('Esther', 9, 2), Verse('Esther', 9, 3)]
1562
+
1563
+ Error cases:
1564
+ >>> parse_verses('Invalid 1:1')
1565
+ []
1566
+ >>> parse_verses('Gen 50:27') # Verse doesn't exist
1567
+ []
1568
+ >>> parse_verses('Gen 51:1') # Chapter doesn't exist
1569
+ []
1570
+ >>> parse_verses('') # Empty string
1571
+ []
1572
+ >>> parse_verses('Genesis 1:1:1') # Invalid format
1573
+ []
1574
+ >>> parse_verses('Gen 1:a') # Non-numeric verse
1575
+ []
1576
+ """
1577
+
1578
+ pass
1579
+
1580
+
1581
+
1582
+
1583
+ # @@@@@@@@@@@@@@@@@@@@
1584
+ #
1585
+
1586
+ if False:
1587
+ import doctest
1588
+ doctest.testmod()
1589
+ print('Parser doctests passed')
1590
+
1591
+ # @@@@@@@@@@@@@@@@@@@@