christian / src /bible.py
christopunk's picture
Upload src/bible.py with huggingface_hub
dcc9dae verified
'''
Parse scriptural references and fetch source texts.
TODO:
- [ ] separate out tests
- [ ] refactor and clean up
'''
from dataclasses import dataclass
from functools import reduce
from typing import Dict, List, Optional, Tuple, Union
import re
from parsy import (
Parser,
alt,
fail,
generate,
regex,
seq,
string,
string_from,
whitespace
)
# Verses are saved as one per line
paths = {
'KJV': 'curated/bible/kjv_king_james_version.txt',
'ASV': 'curated/bible/asv_american_standard_version.txt',
'CSB': 'curated/bible/csb_christian_standard_bible.txt',
}
# KJV
# Genesis 1:1 KJV In the beginning God created the heaven and the earth.
# 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.
# Genesis 1:3 KJV And God said, Let there be light: and there was light.
#
# ASV
# Genesis 1:1 ASV In the beginning God created the heavens and the earth.
# 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.
# Genesis 1:3 ASV And God said, Let there be light: and there was light.
#
# CSB
# Genesis 1:1 CSB In the beginning God created the heavens and the earth.
# 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.
# Genesis 1:3 CSB Then God said, Let there be light, and there was light.
bible_structure = [
{
'testament': 'OT',
'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],
'name': 'Genesis',
'abbrs': ['gen', 'ge', 'gn']
},
{
'testament': 'OT',
'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],
'name': 'Exodus',
'abbrs': ['exod', 'exo', 'ex']
},
{
'testament': 'OT',
'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],
'name': 'Leviticus',
'abbrs': ['lev', 'lv', 'le']
},
{
'testament': 'OT',
'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],
'name': 'Numbers',
'abbrs': ['num', 'nm', 'nu']
},
{
'testament': 'OT',
'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],
'name': 'Deuteronomy',
'abbrs': ['deut', 'deu', 'de', 'du', 'dt']
},
{
'testament': 'OT',
'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],
'name': 'Joshua',
'abbrs': ['josh', 'jos']
},
{
'testament': 'OT',
'verse_counts': [36, 23, 31, 24, 31, 40, 25, 35, 57, 18, 40, 15, 25, 20, 20, 31, 13, 31, 30, 48, 25],
'name': 'Judges',
'abbrs': ['judg', 'jgs', 'jdg']},
{
'testament': 'OT',
'verse_counts': [22, 23, 18, 22],
'name': 'Ruth',
'abbrs': ['rut', 'ru']
},
{
'testament': 'OT',
'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],
'name': '1 Samuel',
'abbrs': ['1samuel', '1sam', '1 sam', '1sm', '1 sm' , '1sa', '1 sa']
},
{
'testament': 'OT',
'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],
'name': '2 Samuel',
'abbrs': ['2samuel', '2sam', '2 sam', '2sm', '2 sm', '2sa', '2 sa']
},
{
'testament': 'OT',
'verse_counts': [53, 46, 28, 34, 18, 38, 51, 66, 28, 29, 43, 33, 34, 31, 34, 34, 24, 46, 21, 43, 29, 53],
'name': '1 Kings',
'abbrs': ['1kings', '1king', '1kgs', '1kg', '1 kg', '1 kgs', '1ki', '1 ki']
},
{
'testament': 'OT',
'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],
'name': '2 Kings',
'abbrs': ['2kings', '2king' '2kg 2', 'kg', '2ki', '2 ki']},
{
'testament': 'OT',
'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],
'name': '1 Chronicles',
'abbrs': ['1chronicles', '1chron', '1 chron', '1ch', '1 ch']
},
{
'testament': 'OT',
'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],
'name': '2 Chronicles',
'abbrs': ['2chronicles', '2chron', '2 chron', '2 ch', '2ch']
},
{
'testament': 'OT',
'verse_counts': [11, 70, 13, 24, 17, 22, 28, 36, 15, 44],
'name': 'Ezra',
'abbrs': ['ezr', 'ez']
},
{
'testament': 'OT',
'verse_counts': [11, 20, 32, 23, 19, 19, 73, 18, 38, 39, 36, 47, 31],
'name': 'Nehemiah',
'abbrs': ['nehem', 'neh', 'ne']
},
{
'testament': 'OT',
'verse_counts': [22, 23, 15, 17, 14, 14, 10, 17, 32, 3],
'name': 'Esther',
'abbrs': ['esth', 'est', 'es']
},
{
'testament': 'OT',
'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],
'name': 'Job',
'abbrs': ['jb']
},
{
'testament': 'OT',
'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],
'name': 'Psalms',
'abbrs': ['psalm', 'psa', 'pss', 'ps']
},
{
'testament': 'OT',
'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],
'name': 'Proverbs',
'abbrs': ['prov', 'prv', 'pv', 'pro']},
{
'testament': 'OT',
'verse_counts': [18, 26, 22, 16, 20, 12, 29, 17, 18, 20, 10, 14],
'name': 'Ecclesiastes',
'abbrs': ['eccles', 'ecc', 'ec']
},
{
'testament': 'OT',
'verse_counts': [17, 17, 11, 16, 16, 13, 13, 14],
'name': 'Song of Solomon',
'abbrs': [ 'song of sol', 'song', 'son', 'sos', 'ss', 'so', 'sg']
},
{
'testament': 'OT',
'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],
'name': 'Isaiah',
'abbrs': ['isa', 'is']
},
{
'testament': 'OT',
'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],
'name': 'Jeremiah',
'abbrs': ['jerem', 'jer', 'je']
},
{
'testament': 'OT',
'verse_counts': [22, 22, 66, 22, 22],
'name': 'Lamentations',
'abbrs': ['lamen', 'lam', 'la']
},
{
'testament': 'OT',
'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],
'name': 'Ezekiel',
'abbrs': ['ezek', 'eze', 'ezk']
},
{
'testament': 'OT',
'verse_counts': [21, 49, 30, 37, 31, 28, 28, 27, 27, 21, 45, 13],
'name': 'Daniel',
'abbrs': ['dan', 'da', 'dn']
},
{
'testament': 'OT',
'verse_counts': [11, 23, 5, 19, 15, 11, 16, 14, 17, 15, 12, 14, 16, 9],
'name': 'Hosea',
'abbrs': ['hos', 'ho']
},
{
'testament': 'OT',
'verse_counts': [20, 32, 21],
'name': 'Joel',
'abbrs': ['jl', 'joe']
},
{
'testament': 'OT',
'verse_counts': [15, 16, 15, 13, 27, 14, 17, 14, 15],
'name': 'Amos',
'abbrs': ['am', 'amo']
},
{
'testament': 'OT',
'verse_counts': [21],
'name': 'Obadiah',
'abbrs': ['obad', 'ob', 'oba']
},
{
'testament': 'OT',
'verse_counts': [17, 10, 10, 11],
'name': 'Jonah',
'abbrs': ['jon', 'jnh']
},
{
'testament': 'OT',
'verse_counts': [16, 13, 12, 13, 15, 16, 20],
'name': 'Micah',
'abbrs': ['mi', 'mic']
},
{
'testament': 'OT',
'verse_counts': [15, 13, 19],
'name': 'Nahum',
'abbrs': ['nah', 'na']
},
{
'testament': 'OT',
'verse_counts': [17, 20, 19],
'name': 'Habakkuk',
'abbrs': ['hab', 'hb']
},
{
'testament': 'OT',
'verse_counts': [18, 15, 20],
'name': 'Zephaniah',
'abbrs': ['zeph', 'zep']
},
{
'testament': 'OT',
'verse_counts': [15, 23],
'name': 'Haggai',
'abbrs': ['hag', 'hg']
},
{
'testament': 'OT',
'verse_counts': [21, 13, 10, 14, 11, 15, 14, 23, 17, 12, 17, 14, 9, 21],
'name': 'Zechariah',
'abbrs': ['zech', 'zec']
},
{
'testament': 'OT',
'verse_counts': [14, 17, 18, 6],
'name': 'Malachi',
'abbrs': ['mal', 'ml']
},
{
'testament': 'NT',
'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],
'name': 'Matthew',
'abbrs': ['mat', 'matt', 'mt']
},
{
'testament': 'NT',
'verse_counts': [45, 28, 35, 41, 43, 56, 37, 38, 50, 52, 33, 44, 37, 72, 47, 20],
'name': 'Mark',
'abbrs': ['mar', 'mk']},
{
'testament': 'NT',
'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],
'name': 'Luke',
'abbrs': ['lu', 'luk', 'lk']
},
{
'testament': 'NT',
'verse_counts': [51, 25, 36, 54, 47, 71, 53, 59, 41, 42, 57, 50, 38, 31, 27, 33, 26, 40, 42, 31, 25],
'name': 'John',
'abbrs': ['jo', 'joh', 'jn']
},
{
'testament': 'NT',
'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],
'name': 'Acts',
'abbrs': ['ac', 'act']},
{
'testament': 'NT',
'verse_counts': [32, 29, 31, 25, 21, 23, 25, 39, 33, 21, 36, 21, 14, 23, 33, 27],
'name': 'Romans',
'abbrs': ['rom', 'ro', 'rm']
},
{
'testament': 'NT',
'verse_counts': [31, 16, 23, 21, 13, 20, 40, 13, 27, 33, 34, 31, 13, 40, 58, 24],
'name': '1 Corinthians',
'abbrs': ['1corinthians', '1 cor', '1cor', '1 co', '1co', '1c']
},
{
'testament': 'NT',
'verse_counts': [24, 17, 18, 18, 21, 18, 16, 24, 15, 18, 33, 21, 14],
'name': '2 Corinthians',
'abbrs': ['2corinthians', '2 cor', '2cor', '2 co', '2co', '2c']
},
{
'testament': 'NT',
'verse_counts': [24, 21, 29, 31, 26, 18],
'name': 'Galatians',
'abbrs': ['gal', 'ga']
},
{
'testament': 'NT',
'verse_counts': [23, 22, 21, 32, 33, 24],
'name': 'Ephesians',
'abbrs': ['eph', 'ep']
},
{
'testament': 'NT',
'verse_counts': [30, 30, 21, 23],
'name': 'Philippians',
'abbrs': ['phil', 'php', 'phi']
},
{
'testament': 'NT',
'verse_counts': [29, 23, 25, 18],
'name': 'Colossians',
'abbrs': ['col', 'co']
},
{
'testament': 'NT',
'verse_counts': [10, 20, 13, 18, 28],
'name': '1 Thessalonians',
'abbrs': ['1thessalonians', '1 thess', '1thess', '1 thes', '1thes', '1th', '1 th']
},
{
'testament': 'NT',
'verse_counts': [12, 17, 18],
'name': '2 Thessalonians',
'abbrs': ['2thessalonians', '2 thess', '2thess', '2 thes', '2thes', '2th', '2 th']
},
{
'testament': 'NT',
'verse_counts': [20, 15, 16, 16, 25, 21],
'name': '1 Timothy',
'abbrs': ['1tim', '1tm', '1 tm', '1timothy', '1ti', '1 tim', '1 ti']
},
{
'testament': 'NT',
'verse_counts': [18, 26, 17, 22],
'name': '2 Timothy',
'abbrs': ['2tim', '2tm', '2 tm', '2timothy', '2ti', '2 tim', '2 ti']
},
{
'testament': 'NT',
'verse_counts': [16, 15, 15],
'name': 'Titus',
'abbrs': ['ti', 'tit']
},
{
'testament': 'NT',
'verse_counts': [25],
'name': 'Philemon',
'abbrs': ['philem', 'phm']
},
{
'testament': 'NT',
'verse_counts': [14, 18, 19, 16, 14, 20, 28, 13, 28, 39, 40, 29, 25],
'name': 'Hebrews',
'abbrs': ['heb', 'he']
},
{
'testament': 'NT',
'verse_counts': [27, 26, 18, 17, 20],
'name': 'James',
'abbrs': ['jam', 'ja', 'jas']
},
{
'testament': 'NT',
'verse_counts': [25, 25, 22, 19, 14],
'name': '1 Peter',
'abbrs': ['1pet', '1p', '1pe', '1 pe', '1pt', '1pe', '1 pet', '1 pt', '1 pe']
},
{
'testament': 'NT',
'verse_counts': [21, 22, 18],
'name': '2 Peter',
'abbrs': ['2pet', '2p', '2pe', '2 pe', '2pt', '2pe', '2 pet', '2 pt', '2 pe']
},
{
'testament': 'NT',
'verse_counts': [10, 29, 24, 21, 21],
'name': '1 John',
'abbrs': ['1john', '1j', '1jo', '1 jo', '1jn', '1 jn']
},
{
'testament': 'NT',
'verse_counts': [13],
'name': '2 John',
'abbrs': ['2john', '2j', '2jo', '2 jo', '2jn', '2 jn']
},
{
'testament': 'NT',
'verse_counts': [15],
'name': '3 John',
'abbrs': ['3john', '3j', '3jo', '3 jo', '3jn', '3 jn']
},
{
'testament': 'NT',
'verse_counts': [25],
'name': 'Jude',
'abbrs': ['ju', 'jud']
},
{
'testament': 'NT',
'verse_counts': [20, 29, 22, 11, 14, 17, 17, 13, 21, 11, 19, 17, 18, 20, 8, 21, 18, 24, 21, 15, 27, 21],
'name': 'Revelation',
'abbrs': ['rev', 're', 'rv', 'revel']
}
]
roman_numerals = [
# 10
'i', 'ii', 'iii', 'iv', 'v', 'vi', 'vii', 'viii', 'ix', 'x',
# 20
'xi', 'xii', 'xiii', 'xiv', 'xv', 'xvi', 'xvii', 'xviii', 'xix', 'xx',
# 30
'xxi', 'xxii', 'xxiii', 'xxiv', 'xxv', 'xxvi', 'xxvii', 'xxviii', 'xxix', 'xxx',
# 40
'xxxi', 'xxxii', 'xxxiii', 'xxxiv', 'xxxv', 'xxxvi', 'xxxvii', 'xxxviii', 'xxxix', 'xl',
# 50
'xli', 'xlii', 'xliii', 'xliv', 'xlv', 'xlvi', 'xlvii', 'xlviii', 'xlix', 'l',
# 60
'li', 'lii', 'liii', 'liv', 'lv', 'lvi', 'lvii', 'lviii', 'lix', 'lx',
# 70
'lxi', 'lxii', 'lxiii', 'lxiv', 'lxv', 'lxvi', 'lxvii', 'lxviii', 'lxix', 'lxx',
# 80
'lxxi', 'lxxii', 'lxxiii', 'lxxiv', 'lxxv', 'lxxvi', 'lxxvii', 'lxxviii', 'lxxix', 'lxxx',
# 90
'lxxxi', 'lxxxii', 'lxxxiii', 'lxxxiv', 'lxxxv', 'lxxxvi', 'lxxxvii', 'lxxxviii', 'lxxxix', 'xc',
# 100
'xci', 'xcii', 'xciii', 'xciv', 'xcv', 'xcvi', 'xcvii', 'xcviii', 'xcix', 'c',
# 110
'ci', 'cii', 'ciii', 'civ', 'cv', 'cvi', 'cvii', 'cviii', 'cix', 'cx',
# 120
'cxi', 'cxii', 'cxiii', 'cxiv', 'cxv', 'cxvi', 'cxvii', 'cxviii', 'cxix', 'cxx',
# 130
'cxxi', 'cxxii', 'cxxiii', 'cxxiv', 'cxxv', 'cxxvi', 'cxxvii', 'cxxviii', 'cxxix', 'cxxx',
# 140
'cxxxi', 'cxxxii', 'cxxxiii', 'cxxxiv', 'cxxxv', 'cxxxvi', 'cxxxvii', 'cxxxviii', 'cxxxix', 'cxl',
# 150
'cxli', 'cxlii', 'cxliii', 'cxliv', 'cxlv', 'cxlvi', 'cxlvii', 'cxlviii', 'cxlix', 'cl',
# 160
'cli', 'clii', 'cliii', 'cliv', 'clv', 'clvi', 'clvii', 'clviii', 'clix', 'clx',
# 170
'clxi', 'clxii', 'clxiii', 'clxiv', 'clxv', 'clxvi', 'clxvii', 'clxviii', 'clxix', 'clxx',
# 180
'clxxi', 'clxxii', 'clxxiii', 'clxxiv', 'clxxv', 'clxxvi', 'clxxvii', 'clxxviii', 'clxxix', 'clxxx',
# 190
'clxxxi', 'clxxxii', 'clxxxiii', 'clxxxiv', 'clxxxv', 'clxxxvi', 'clxxxvii', 'clxxxviii', 'clxxxix', 'cxc',
# 200
'cxci', 'cxcii', 'cxciii', 'cxciv', 'cxcv', 'cxcvi', 'cxcvii', 'cxcviii', 'cxcix', 'cc'
]
def get_verse_count(book: str, chapter: int) -> int:
"""Get the number of verses in a given chapter of a book."""
for b in bible_structure:
if b['name'] == book:
if 1 <= chapter <= len(b['verse_counts']):
return b['verse_counts'][chapter-1]
return 0
##################################################
# Load Bibles
def load_bible_to_dict(path: str) -> Dict[str, List[List[str]]]:
"""Load bible verses from a file into a nested dictionary structure.
Args:
path: Path to the bible text file
Returns:
Dict with structure:
{
'Genesis': [
['In the beginning...', 'And the earth...'], # chapter 1
['Thus the heavens...', 'And on the...'], # chapter 2
]
}
"""
bible_dict = {}
current_book = None
current_chapter = None
try:
with open(path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if not line:
continue
# Parse the reference and verse
match = re.match(r'([\w\s]+)\s+(\d+):(\d+)\s+([A-Z]+)\s+(.+)', line)
if not match:
continue
book, chapter, verse, translation, text = match.groups()
chapter = int(chapter)
verse = int(verse)
# Initialize new book if needed
if book not in bible_dict:
bible_dict[book] = []
# Add chapters until we reach the current one
while len(bible_dict[book]) < chapter:
bible_dict[book].append([])
# Add verses until we reach the current one
while len(bible_dict[book][chapter-1]) < verse:
bible_dict[book][chapter-1].append('')
# Add the verse text
bible_dict[book][chapter-1][verse-1] = text
except FileNotFoundError:
print(f"Could not find Bible file at: {path}")
return {}
return bible_dict
# Load all bible translations to memory
bibles = {}
for translation, path in paths.items():
bibles[translation] = load_bible_to_dict(path)
##################################################
# Parsers
# Optional whitespace
ws = regex(r'\s*')
# Required whitespace
required_ws = regex(r'\s+')
# Standard separators
colon = ws >> string(':') << ws
dash = ws >> string_from('-', '–') << ws
semicolon = ws >> string(';') << ws
comma = ws >> string(',') << ws
dot = string('.').optional()
ws_dot = ws >> string('.') << ws
@dataclass
class BookRef:
"""Represents a standardized book reference.
>>> BookRef("Genesis")
BookRef('Genesis')
"""
name: str
def __repr__(self):
return f"BookRef('{self.name}')"
def build_book_parser(allow_book_periods=True) -> Parser:
"""Build a parser for Bible book names and abbreviations.
Uses the bible_structure data to create parsers for all valid book names
and abbreviations. Matching is case-insensitive.
Returns:
Parser that produces a BookRef object with standardized name
Examples:
>>> book_parser = build_book_parser()
# Full names - case variations
>>> book_parser.parse("Genesis")
BookRef('Genesis')
>>> book_parser.parse("GENESIS")
BookRef('Genesis')
>>> book_parser.parse("genesis")
BookRef('Genesis')
>>> book_parser.parse("GeNeSiS")
BookRef('Genesis')
# Error cases
>>> book_parser.parse("NotABook")
Traceback (most recent call last):
...
parsy.ParseError: expected 'book name' at 0:0
>>> book_parser.parse("First Kings")
Traceback (most recent call last):
...
parsy.ParseError: expected 'book name' at 0:0
"""
# build sorted list of all names and abbreviations
forms = []
for book in bible_structure:
std_name = book['name']
# Full name doesn't get period
forms.append((std_name, std_name, False))
# Abbreviations can have optional period
forms.extend((abbr, std_name, True) for abbr in book['abbrs'])
# Sort by length (descending) then alphabetically to ensure longer matches take precedence
book_forms = sorted(forms, key=lambda x: (-len(x[0]), x[0].lower()))
# turn them into parsers
book_parsers = []
for form, std_name, allow_period in book_forms:
# Create case-insensitive parser for the book name/abbreviation
name_parser = string(form, transform=str.lower).result(std_name)
if allow_period and allow_book_periods:
# For abbreviations, allow optional period
parser = (name_parser << dot)
else:
# For full names, no period
parser = name_parser
book_parsers.append(parser)
# Combine all parsers with |
return (alt(*book_parsers)
.desc("book name")
.map(BookRef))
book_parser = build_book_parser()
book_parser_no_dot = build_book_parser(allow_book_periods=False)
# @@@@@@@@@@@@@@@@@@@@
# Test all books
for book in bible_structure:
std_name = book['name']
# Test standard name
result = book_parser.parse(std_name)
assert result == BookRef(std_name), f"Failed to parse {std_name}"
# Test lowercase
result = book_parser.parse(std_name.lower())
assert result == BookRef(std_name), f"Failed to parse {std_name.lower()}"
# Test uppercase
result = book_parser.parse(std_name.upper())
assert result == BookRef(std_name), f"Failed to parse {std_name.upper()}"
# Test all abbreviations
for abbr in book['abbrs']:
result = book_parser.parse(abbr)
assert result == BookRef(std_name), f"Failed to parse {abbr}"
# Test lowercase
result = book_parser.parse(abbr.lower())
assert result == BookRef(std_name), f"Failed to parse {abbr.lower()}"
# Test uppercase
result = book_parser.parse(abbr.upper())
assert result == BookRef(std_name), f"Failed to parse {abbr.upper()}"
# Test with period
result = book_parser.parse(abbr + '.')
assert result == BookRef(std_name), f"Failed to parse {abbr}."
# @@@@@@@@@@@@@@@@@@@@
##################################################
####################
# Verses
@dataclass
class VerseRef:
"""Represents a verse number reference.
>>> VerseRef(1)
VerseRef(1)
"""
number: int
def __repr__(self):
return f"VerseRef({self.number})"
def build_verse_parser() -> Parser:
"""Build a parser for Bible verse numbers.
Handles Arabic numbers only (Roman numerals not used for verses).
Numbers must be positive.
Returns:
Parser that produces a VerseRef object
Examples:
>>> verse_parser = build_verse_parser()
# Basic numbers
>>> verse_parser.parse("1")
VerseRef(1)
>>> verse_parser.parse("176") # Longest verse (Ps 119:176)
VerseRef(176)
# Error cases
>>> verse_parser.parse("0") # No verse 0
Traceback (most recent call last):
...
parsy.ParseError: expected 'verse number' at 0:0
>>> verse_parser.parse("1a")
Traceback (most recent call last):
...
parsy.ParseError: expected 'EOF' at 0:1
"""
return (regex(r'[1-9][0-9]*')
.map(int)
.map(VerseRef)
.desc("verse number"))
verse_parser = build_verse_parser()
@dataclass
class VerseRange:
"""Represents a range of verses.
>>> VerseRange(VerseRef(1), VerseRef(3))
VerseRange(VerseRef(1), VerseRef(3))
"""
start: VerseRef
end: VerseRef
def __repr__(self):
return f"VerseRange({self.start}, {self.end})"
def build_verse_range_parser() -> Parser:
"""Build a parser for verse ranges like 1-3 or 1–3.
Examples:
>>> verse_range_parser = build_verse_range_parser()
>>> verse_range_parser.parse("1-3")
VerseRange(VerseRef(1), VerseRef(3))
>>> verse_range_parser.parse("1–3") # en-dash
VerseRange(VerseRef(1), VerseRef(3))
"""
return seq(
start=verse_parser,
_dash=dash,
end=verse_parser
).combine_dict(VerseRange)
verse_range_parser = build_verse_range_parser()
####################
# Chapter
@dataclass
class ChapterRef:
"""Represents a chapter reference that may be parsed from either Arabic or Roman numerals.
>>> ChapterRef(1)
ChapterRef(1)
"""
number: int
def __repr__(self):
return f"ChapterRef({self.number})"
def build_chapter_parser(allow_dot=True) -> Parser:
"""Build a parser for Bible chapter numbers.
Handles both Arabic numbers and Roman numerals. Roman numerals are matched
by length (longest first) then alphabetically to ensure correct parsing.
Returns:
Parser that produces a ChapterRef object
Examples:
>>> chapter_parser = build_chapter_parser()
# Arabic numbers
>>> chapter_parser.parse("1")
ChapterRef(1)
>>> chapter_parser.parse("119")
ChapterRef(119)
# Roman numerals - case variations
>>> chapter_parser.parse("i")
ChapterRef(1)
>>> chapter_parser.parse("I")
ChapterRef(1)
>>> chapter_parser.parse("iv")
ChapterRef(4)
>>> chapter_parser.parse("xl")
ChapterRef(40)
# Longer roman numerals
>>> chapter_parser.parse("xxxviii") # 38
ChapterRef(38)
>>> chapter_parser.parse("LXXXVIII") # 88
ChapterRef(88)
>>> chapter_parser.parse("CXIX") # 119
ChapterRef(119)
"""
# Build sorted list of roman numerals with their values
roman_forms: List[Tuple[str, int]] = [
(numeral, idx + 1) for idx, numeral in enumerate(roman_numerals)
]
# Sort by length (descending) and then alphabetically
roman_forms.sort(key=lambda x: (-len(x[0]), x[0]))
# Create individual parsers for each roman numeral
roman_parsers = []
for form, value in roman_forms:
# Create case-insensitive parser
if allow_dot:
parser = string(form, transform=str.lower).result(value) << dot
else:
parser = string(form, transform=str.lower).result(value)
roman_parsers.append(parser)
# Combine roman numeral parsers with reduce
roman = (alt(*roman_parsers)
.desc("roman numeral chapter"))
# Arabic numbers - must be 1 or greater
arabic = (regex(r'[1-9][0-9]*')
.map(int)
.desc("arabic chapter number"))
# Combine parsers and wrap result
return (roman | arabic).map(ChapterRef).desc("chapter number")
chapter_parser = build_chapter_parser()
chapter_parser_no_dot = build_chapter_parser(allow_dot=False)
# @@@@@@@@@@@@@@@@@@@@
# Test each roman numeral in the list
for idx, numeral in enumerate(roman_numerals):
expected = idx + 1 # Roman numerals are 1-based
# Test lowercase
result = chapter_parser.parse(numeral)
assert result == ChapterRef(expected), f"Failed to parse lowercase '{numeral}': expected {expected}, got {result}"
# Test uppercase
result = chapter_parser.parse(numeral.upper())
assert result == ChapterRef(expected), f"Failed to parse uppercase '{numeral.upper()}': expected {expected}, got {result}"
# Test mixed case (alternate upper/lower)
mixed = ''.join(c.upper() if i % 2 == 0 else c.lower()
for i, c in enumerate(numeral))
result = chapter_parser.parse(mixed)
assert result == ChapterRef(expected), f"Failed to parse mixed case '{mixed}': expected {expected}, got {result}"
# @@@@@@@@@@@@@@@@@@@@
@dataclass
class CrossChapterRange:
"""Represents a range that spans chapters.
>>> CrossChapterRange(ChapterRef(1), VerseRef(31), ChapterRef(2), VerseRef(3))
CrossChapterRange(ChapterRef(1), VerseRef(31), ChapterRef(2), VerseRef(3))
"""
start_chapter: ChapterRef
start_verse: VerseRef
end_chapter: ChapterRef
end_verse: VerseRef
def __repr__(self):
return f"CrossChapterRange({self.start_chapter}, {self.start_verse}, {self.end_chapter}, {self.end_verse})"
def build_cross_chapter_range_parser(chapter_parser: Parser, verse_parser: Parser) -> Parser:
"""Build a parser for ranges that cross chapter boundaries.
Examples:
>>> chapter_parser = build_chapter_parser()
>>> verse_parser = build_verse_parser()
>>> range_parser = build_cross_chapter_range_parser(chapter_parser, verse_parser)
>>> range_parser.parse("1:31-2:3")
CrossChapterRange(ChapterRef(1), VerseRef(31), ChapterRef(2), VerseRef(3))
"""
return seq(
start_chapter=chapter_parser << colon,
start_verse=verse_parser << dash,
end_chapter=chapter_parser << colon,
end_verse=verse_parser
).combine_dict(CrossChapterRange)
cross_chapter_range = build_cross_chapter_range_parser(chapter_parser, verse_parser)
@dataclass
class ComplexChapter:
""" """
chapter: ChapterRef
verse_ref: List[Union[VerseRef, VerseRange]]
# verse_ref: Union[VerseRef, List[VerseRef], VerseRange, List[VerseRange]]
def __repr__(self):
return f"ComplexChapter({self.chapter}, {self.verse_ref})"
ComplexVerses = Union[ComplexChapter, CrossChapterRange]
####################
# Whole References
@dataclass
class SingleReference:
"""A single verse reference with book, chapter, and verse."""
book: BookRef
chapter: ChapterRef
verse: VerseRef
def __repr__(self):
return f"SingleReference({self.book}, {self.chapter}, {self.verse})"
@dataclass
class RangeReference:
"""A verse range reference with book, chapter, and verse range. """
book: BookRef
chapter: ChapterRef
verse_range: VerseRange
def __repr__(self):
return f"RangeReference({self.book}, {self.chapter}, {self.verse_range})"
@dataclass
class CrossChapterReference:
"""A cross-chapter range reference. """
book: BookRef
range: CrossChapterRange
def __repr__(self):
return f"CrossChapterReference({self.book}, {self.range})"
@dataclass
class ComplexReference:
"""A reference containing multiple verses or ranges possibly across different chapters."""
book: BookRef
verse_refs: List[ComplexVerses]
def __repr__(self):
return f"ComplexReference({self.book}, {self.verse_refs})"
def build_complex_single_chapter_parser() -> Parser:
"""
Ex: Gen 1: 1, 2-3
>>> parser = build_complex_single_chapter_parser()
>>> parser.parse("Gen 1:1,2")
ComplexReference(BookRef('Genesis'), [ComplexChapter(ChapterRef(1), [VerseRef(1), VerseRef(2)])])
>>> parser.parse("Gen 1:1-2,3-4")
ComplexReference(BookRef('Genesis'), [ComplexChapter(ChapterRef(1), [VerseRange(VerseRef(1), VerseRef(2)), VerseRange(VerseRef(3), VerseRef(4))])])
>>> parser.parse("Gen 1:1,2-3")
ComplexReference(BookRef('Genesis'), [ComplexChapter(ChapterRef(1), [VerseRef(1), VerseRange(VerseRef(2), VerseRef(3))])])
"""
verses = seq(
chapter = chapter_parser << colon,
verse_ref = (verse_range_parser | verse_parser).sep_by(comma << ws, min=2)
).combine_dict(ComplexChapter).map(lambda x: [x]) # wrap in list
return seq(
book=book_parser << required_ws,
verse_refs=verses
).combine_dict(ComplexReference)
def build_complex_multi_chapter_parser() -> Parser:
"""
Ex: Gen 1:1-2, 2:2-3
>>> parser = build_complex_multi_chapter_parser()
>>> parser.parse("Gen 1:1-2, 2:4-5")
ComplexReference(BookRef('Genesis'), [ComplexChapter(ChapterRef(1), [VerseRange(VerseRef(1), VerseRef(2))]), ComplexChapter(ChapterRef(2), [VerseRange(VerseRef(4), VerseRef(5))])])
>>> parser.parse('Gen 1:2, 2:3-4, 3:5-4:1')
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))])
"""
single_chapter = seq(
chapter = chapter_parser << colon,
verse_ref = (verse_range_parser | verse_parser).map(lambda x: [x])
).combine_dict(ComplexChapter)
p = (cross_chapter_range | single_chapter).sep_by(comma << ws, min=2)
return seq(
book=book_parser << required_ws,
verse_refs=p
).combine_dict(ComplexReference)
def build_complex_reference_parser() -> Parser:
"""Build a parser for complex verse references with multiple verses or ranges across chapters.
Templates:
- book chapter:1, 2, 3-4 # single chapter
- book chapter:1, chapter:2-3, chapter:4 # multi chapter
- book 1:30-2:2, 1:1 # multi chapter with cross chapter range
Examples:
- Gen 1:1,3,5
- Gen 1:31-2:3, 2:35
- Ps. 119:1-3, 120:5-7, 121:4-122:2
Examples:
>>> parser = build_complex_reference_parser()
>>> parser.parse("Ps. 119:1-2, 120:5-6, 121:4-122:2")
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))])
"""
return (
build_complex_multi_chapter_parser() |
build_complex_single_chapter_parser()
)
##################################################
@dataclass
class ChapterOnlyReference:
"""A reference to a whole chapter without specific verses."""
book: BookRef
chapter: ChapterRef
def __repr__(self):
return f"ChapterOnlyReference({self.book}, {self.chapter})"
def build_chapter_only_parser() -> Parser:
"""Build a parser for whole chapter references.
Examples:
>>> parser = build_chapter_only_parser()
>>> parser.parse("Genesis 1")
ChapterOnlyReference(BookRef('Genesis'), ChapterRef(1))
>>> parser.parse("Gen. 1")
ChapterOnlyReference(BookRef('Genesis'), ChapterRef(1))
>>> parser.parse("Gen i")
ChapterOnlyReference(BookRef('Genesis'), ChapterRef(1))
"""
return (
seq(book_parser << required_ws, chapter_parser).combine(ChapterOnlyReference) |
seq(book_parser_no_dot << ws_dot, chapter_parser_no_dot).combine(ChapterOnlyReference)
)
##################################################
def build_reference_parser() -> Parser:
"""Build a parser for complete Bible references.
Examples:
>>> parser = build_reference_parser()
# Single verse
>>> parser.parse("Genesis 1:1")
[SingleReference(BookRef('Genesis'), ChapterRef(1), VerseRef(1))]
# Verse range
>>> parser.parse("Genesis 1:1-3")
[RangeReference(BookRef('Genesis'), ChapterRef(1), VerseRange(VerseRef(1), VerseRef(3)))]
# Cross chapter range
>>> parser.parse("Genesis 1:31-2:3")
[CrossChapterReference(BookRef('Genesis'), CrossChapterRange(ChapterRef(1), VerseRef(31), ChapterRef(2), VerseRef(3)))]
# Book abbreviation
>>> parser.parse("Gen 1:1")
[SingleReference(BookRef('Genesis'), ChapterRef(1), VerseRef(1))]
# Roman numeral chapter
>>> parser.parse("Genesis ii:1")
[SingleReference(BookRef('Genesis'), ChapterRef(2), VerseRef(1))]
"""
# Single verse reference (eg "Genesis 1:1")
single_ref = (
seq(book_parser << required_ws, chapter_parser << colon, verse_parser).combine(SingleReference) | # Gen 1: 1
seq(book_parser_no_dot << ws_dot, chapter_parser_no_dot << ws_dot, verse_parser).combine(SingleReference) | # Gen.1.1
seq(book_parser_no_dot << ws, chapter_parser_no_dot << ws_dot, verse_parser).combine(SingleReference) # Gen i. 1
)
# Verse range in same chapter (eg "Genesis 1:1-3")
range_ref = (
seq(book_parser << required_ws, chapter_parser << colon, verse_range_parser).combine(RangeReference) | # Gen 1:1-3
seq(book_parser_no_dot << ws_dot, chapter_parser_no_dot << ws_dot, verse_range_parser).combine(RangeReference) # Gen. 1. 1-3
)
# Cross-chapter range (eg "Genesis 1:31-2:3")
cross_chapter_ref = seq(
book=book_parser << required_ws,
range=cross_chapter_range,
).combine_dict(CrossChapterReference)
# Complex (eg "Gen 1:3-4, 2:5-6")
complex_ref = build_complex_reference_parser()
# Combine all parsers and allow multiple references separated by semicolons
# Order matters - try more specific patterns first
return (complex_ref |
cross_chapter_ref |
range_ref |
single_ref |
build_chapter_only_parser()
).sep_by(semicolon, min=1)
# Reuse existing components from the base code
book_parser = build_book_parser()
chapter_parser = build_chapter_parser()
verse_parser = build_verse_parser()
##################################################
#
####################
# Pipe Syntax Parser
def build_pipe_parser() -> Parser:
"""Build a parser for the pipe-delimited format.
Examples:
>>> build_pipe_parser().parse("|Matt|5|6|0|0")
SingleReference(BookRef('Matthew'), ChapterRef(5), VerseRef(6))
>>> build_pipe_parser().parse("|John|10|11|10|13")
RangeReference(BookRef('John'), ChapterRef(10), VerseRange(VerseRef(11), VerseRef(13)))
"""
pipe = string("|")
number = regex(r'[0-9]+').map(int)
@generate
def pipe_reference():
# Parse components
yield pipe
book = yield book_parser
yield pipe
chapter1 = yield number
yield pipe
verse1 = yield number
yield pipe
chapter2 = yield number
yield pipe
verse2 = yield number
# Convert numbers to proper reference types
ch1 = ChapterRef(chapter1)
v1 = VerseRef(verse1)
# Single verse reference
if chapter2 == 0 and verse2 == 0:
return SingleReference(book, ch1, v1)
# Range reference
ch2 = ChapterRef(chapter2)
v2 = VerseRef(verse2)
# Same chapter range
if chapter1 == chapter2:
return RangeReference(book, ch1, VerseRange(v1, v2))
# Cross chapter range
return CrossChapterReference(
book,
CrossChapterRange(ch1, v1, ch2, v2)
)
return pipe_reference
####################
# OSIS Parser
def build_osis_parser() -> Parser:
"""Build a parser for OSIS format references.
Examples:
>>> build_osis_parser().parse("Bible:Matt.5.6")
[SingleReference(BookRef('Matthew'), ChapterRef(5), VerseRef(6))]
>>> build_osis_parser().parse("Matt.5.6")
[SingleReference(BookRef('Matthew'), ChapterRef(5), VerseRef(6))]
>>> build_osis_parser().parse("Bible:John.10.11-John.10.13")
[RangeReference(BookRef('John'), ChapterRef(10), VerseRange(VerseRef(11), VerseRef(13)))]
# whole chapter
>>> build_osis_parser().parse("Bible:Matt.5")
[ChapterOnlyReference(BookRef('Matthew'), ChapterRef(5))]
>>> build_osis_parser().parse("Matt.5")
[ChapterOnlyReference(BookRef('Matthew'), ChapterRef(5))]
"""
bible_prefix = string("Bible:").optional()
dot = string(".") << ws
# Chapter only reference (e.g., "Matt.5")
chapter_only_ref = seq(
_bible_prefix=bible_prefix,
book=book_parser_no_dot,
_d1=dot,
chapter=chapter_parser
).combine_dict(ChapterOnlyReference)
# Single reference (e.g., "Matt.5.6")
single_ref = seq(
_bible_prefix=bible_prefix,
book=book_parser_no_dot,
_d1=dot,
chapter=chapter_parser,
_d2=dot,
verse=verse_parser
).combine_dict(SingleReference)
# Verse range in same chapter (e.g., "Gen.1.1-Gen.1.3")
@generate
def range_ref():
yield bible_prefix
book1 = yield book_parser << ws << dot
ch1 = yield chapter_parser << ws << dot
v1 = yield verse_parser
yield dash
book2 = yield book_parser << ws << dot
ch2 = yield chapter_parser << ws << dot
v2 = yield verse_parser
if book1 != book2:
fail("OSIS format cannot handle cross-book references")
return RangeReference(
book1,
ch1,
VerseRange(v1, v2)
)
return (range_ref | single_ref
| chapter_only_ref
).sep_by(semicolon, min=1)
####################
@dataclass
class Verse:
book: str
chapter: int
verse: int
def __repr__(self):
"""Custom representation for doctests."""
return f"Verse('{self.book}', {self.chapter}, {self.verse})"
def parse_verses(reference: str) -> List[Verse]:
"""Parse a scripture reference into individual verses.
This is the main entry point for parsing Bible references.
>>> parse_verses('Genesis 1:1')
[Verse('Genesis', 1, 1)]
>>> parse_verses('Gen 1:1-3')
[Verse('Genesis', 1, 1), Verse('Genesis', 1, 2), Verse('Genesis', 1, 3)]
>>> parse_verses('Gen 1:31-2:3')
[Verse('Genesis', 1, 31), Verse('Genesis', 2, 1), Verse('Genesis', 2, 2), Verse('Genesis', 2, 3)]
>>> parse_verses('Gen 1:1; Ex 2:3')
[Verse('Genesis', 1, 1), Verse('Exodus', 2, 3)]
# Pipes
>>> parse_verses("|Matt|5|6|0|0")
[Verse('Matthew', 5, 6)]
>>> parse_verses("|John|10|11|10|13")
[Verse('John', 10, 11), Verse('John', 10, 12), Verse('John', 10, 13)]
# OSIS
>>> parse_verses("Bible:Matt.5.6")
[Verse('Matthew', 5, 6)]
>>> parse_verses("Bible:John.10.11-John.10.13")
[Verse('John', 10, 11), Verse('John', 10, 12), Verse('John', 10, 13)]
"""
try:
p = (
build_reference_parser() |
build_pipe_parser() |
build_osis_parser()
)
refs = p.parse(reference)
return convert_to_verses(refs)
except:
return []
##################################################
# Fetching
def convert_cross_chapter_range_to_verses(x: CrossChapterRange, book):
result = []
# Add verses from first chapter
max_verse = get_verse_count(book, x.start_chapter.number)
for v in range(x.start_verse.number, max_verse + 1):
result.append(Verse(book, x.start_chapter.number, v))
# Add verses from intervening chapters
for ch in range(x.start_chapter.number + 1, x.end_chapter.number):
max_verse = get_verse_count(book, ch)
for v in range(1, max_verse + 1):
result.append(Verse(book, ch, v))
# Add verses from last chapter
for v in range(1, x.end_verse.number + 1):
result.append(Verse(book, x.end_chapter.number, v))
return result
def convert_cross_chapter_reference_to_verses(ref: CrossChapterReference) -> List[Verse]:
return convert_cross_chapter_range_to_verses(ref.range, ref.book.name)
def f(book, chapter, verse_or_range):
# VerseRef
if isinstance(verse_or_range, VerseRef):
return [Verse(book, chapter.number, verse_or_range.number)]
# VerseRange
elif isinstance(verse_or_range, VerseRange):
result = []
start = verse_or_range.start.number
end = verse_or_range.end.number
for v in range(start, end + 1):
result.append(Verse(book, chapter.number, v))
return result
def convert_complex_chapter_to_verses(cc: ComplexChapter, book):
assert isinstance(cc.verse_ref, list), f'ComplexChapter.verse_ref must be list, but found: {cc}'
return list(reduce(lambda x, y: x + y,
map(lambda v: f(book, cc.chapter, v), cc.verse_ref)))
def convert_complex_verse_to_verses(x: ComplexVerses, book):
if isinstance(x, ComplexChapter):
return convert_complex_chapter_to_verses(x, book)
elif isinstance(x, CrossChapterRange):
return convert_cross_chapter_range_to_verses(x, book)
def convert_complex_ref_to_verses(ref: ComplexReference) -> List[Verse]:
return list(reduce(lambda x, y: x + y,
map(lambda x: convert_complex_verse_to_verses(x, ref.book.name), ref.verse_refs)))
def convert_chapter_only_reference_to_verses(ref: ChapterOnlyReference) -> List[Verse]:
"""Convert a chapter reference to a list of all verses in that chapter.
Examples:
>>> ref = ChapterOnlyReference(BookRef('Genesis'), ChapterRef(1))
>>> verses = convert_chapter_only_reference_to_verses(ref)
>>> len(verses) # Genesis 1 has 31 verses
31
>>> verses[0]
Verse('Genesis', 1, 1)
>>> verses[-1]
Verse('Genesis', 1, 31)
"""
result = []
verse_count = get_verse_count(ref.book.name, ref.chapter.number)
for verse_num in range(1, verse_count + 1):
result.append(Verse(ref.book.name, ref.chapter.number, verse_num))
return result
def convert_to_verses(refs) -> List[Verse]:
"""Convert parsed references into a list of Verse objects.
This handles all the different reference types and converts them into
a flat list of individual verses. Invalid chapter or verse numbers are
filtered out at the end.
Examples:
>>> parser = build_reference_parser()
>>> convert_to_verses(parser.parse("Gen 1:1-3"))
[Verse('Genesis', 1, 1), Verse('Genesis', 1, 2), Verse('Genesis', 1, 3)]
>>> convert_to_verses(parser.parse("Gen 1:31-2:3"))
[Verse('Genesis', 1, 31), Verse('Genesis', 2, 1), Verse('Genesis', 2, 2), Verse('Genesis', 2, 3)]
>>> convert_to_verses(parser.parse("Gen 51:1")) # chapter too high
[]
>>> convert_to_verses(parser.parse("Gen 1:40")) # verse too high
[]
>>> convert_to_verses(parser.parse("Gen 1:31-2:3, 2:4"))
[Verse('Genesis', 1, 31), Verse('Genesis', 2, 1), Verse('Genesis', 2, 2), Verse('Genesis', 2, 3), Verse('Genesis', 2, 4)]
>>> convert_to_verses(parser.parse("Gen 1:1, 2:4"))
[Verse('Genesis', 1, 1), Verse('Genesis', 2, 4)]
"""
result = []
# Handle single reference or list
refs = [refs] if not isinstance(refs, list) else refs
for ref in refs:
if isinstance(ref, SingleReference):
result.append(Verse(ref.book.name, ref.chapter.number, ref.verse.number))
elif isinstance(ref, RangeReference):
for v in range(ref.verse_range.start.number, ref.verse_range.end.number + 1):
result.append(Verse(ref.book.name, ref.chapter.number, v))
elif isinstance(ref, CrossChapterReference):
result += convert_cross_chapter_reference_to_verses(ref)
elif isinstance(ref, ComplexReference):
result += convert_complex_ref_to_verses(ref)
elif isinstance(ref, ChapterOnlyReference):
result += convert_chapter_only_reference_to_verses(ref)
# Filter out invalid verses at the end
def is_valid_reference(verse: Verse) -> bool:
"""Check if a verse reference is valid."""
for b in bible_structure:
if b['name'] == verse.book:
if 1 <= verse.chapter <= len(b['verse_counts']):
return 1 <= verse.verse <= b['verse_counts'][verse.chapter-1]
return False
return [verse for verse in result if is_valid_reference(verse)]
def fetch_verses(verses: List[Verse], translation: str, with_reference: bool = False) -> List[str]:
"""Retrieve the text for a list of verses from the specified translation.
Args:
verses: List of Verse objects to retrieve
translation: Bible translation to use (e.g., 'KJV', 'ASV')
with_reference: Whether to include the verse reference in the output
Returns:
List of verse texts, optionally with references
"""
if translation not in bibles:
return []
bible = bibles[translation]
results = []
for verse in verses:
try:
text = bible[verse.book][verse.chapter-1][verse.verse-1]
if with_reference:
results.append(f"{verse.book} {verse.chapter}:{verse.verse} {translation} {text}")
else:
results.append(text)
except (KeyError, IndexError):
# Skip verses that don't exist in this translation
continue
return results
def fetch(ref_string:str, translation, with_reference: bool = True) -> List[str]:
assert translation in {'CSB', 'KJV', 'ASV'}
vs = parse_verses(ref_string)
xs = fetch_verses(vs, translation, with_reference)
return xs
##################################################
# sandbox
if False:
# vs = parse_verses('Genesis 1:1-31')
vs = parse_verses('1 Cor. ii. 14; Gen 1:2; Amos 1:9')
# vs = parse_verses('|gen|1|2|2|4')
xs = fetch_verses(vs, "CSB", with_reference=True)
print('\n'.join(xs))
##################################################
def parse_verses_test(reference: str) -> List[Verse]:
"""Parse scripture references into individual verses.
TODO? Book only
TODO? Chapter only
TODO? Chapter range
Basic formats:
>>> parse_verses('Genesis 1:1')
[Verse('Genesis', 1, 1)]
>>> parse_verses('Gen 1:1')
[Verse('Genesis', 1, 1)]
>>> parse_verses('Gen. 1:1')
[Verse('Genesis', 1, 1)]
Single Chapter
>>> parse_verses('Genesis 1')[0]
Verse('Genesis', 1, 1)
>>> parse_verses('Genesis 1')[-1]
Verse('Genesis', 1, 31)
Verse ranges:
>>> parse_verses('Genesis 1:1-3')
[Verse('Genesis', 1, 1), Verse('Genesis', 1, 2), Verse('Genesis', 1, 3)]
>>> parse_verses('Gen 1:31-2:1') # Cross-chapter
[Verse('Genesis', 1, 31), Verse('Genesis', 2, 1)]
>>> parse_verses('Exodus 39:32-40:2') # Cross-chapter with more verses
[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)]
Roman numerals:
>>> parse_verses('1 Cor. ii. 14')
[Verse('1 Corinthians', 2, 14)]
>>> parse_verses('Psalm CXLIX. 3') # Testing larger Roman numerals
[Verse('Psalms', 149, 3)]
>>> parse_verses('Matt. iv. 1-3') # Roman numerals with range
[Verse('Matthew', 4, 1), Verse('Matthew', 4, 2), Verse('Matthew', 4, 3)]
Multiple references:
>>> parse_verses('Gen 1:1; Ex 2:3')
[Verse('Genesis', 1, 1), Verse('Exodus', 2, 3)]
>>> parse_verses('Gen 1:1, 3, 5') # Same chapter, different verses
[Verse('Genesis', 1, 1), Verse('Genesis', 1, 3), Verse('Genesis', 1, 5)]
>>> parse_verses('Gen 1:1-3; Ex 2:3-5') # Multiple ranges
[Verse('Genesis', 1, 1), Verse('Genesis', 1, 2), Verse('Genesis', 1, 3), Verse('Exodus', 2, 3), Verse('Exodus', 2, 4), Verse('Exodus', 2, 5)]
OSIS format:
>>> parse_verses('Bible:Gen.1.1')
[Verse('Genesis', 1, 1)]
>>> parse_verses('Gen.1.1')
[Verse('Genesis', 1, 1)]
>>> parse_verses('1Cor.2.14')
[Verse('1 Corinthians', 2, 14)]
>>> parse_verses("Bible:John.10.11-John.10.13")
[Verse('John', 10, 11), Verse('John', 10, 12), Verse('John', 10, 13)]
Book name variations:
>>> parse_verses('1 Kings 1:1')
[Verse('1 Kings', 1, 1)]
>>> parse_verses('1Kgs 1:1')
[Verse('1 Kings', 1, 1)]
>>> parse_verses('1 Kg 1:1')
[Verse('1 Kings', 1, 1)]
>>> parse_verses('First Kings 1:1') # This should fail - we don't support spelled out numbers
[]
Special cases and edge cases:
>>> parse_verses('Rev 22:21') # Last verse of the Bible
[Verse('Revelation', 22, 21)]
>>> parse_verses('Psa 119:176') # Longest chapter
[Verse('Psalms', 119, 176)]
>>> parse_verses('Ps. 119:1-3,5-7') # Complex range with gaps
[Verse('Psalms', 119, 1), Verse('Psalms', 119, 2), Verse('Psalms', 119, 3), Verse('Psalms', 119, 5), Verse('Psalms', 119, 6), Verse('Psalms', 119, 7)]
>>> parse_verses('Est 9:1–3') # Em dash instead of hyphen
[Verse('Esther', 9, 1), Verse('Esther', 9, 2), Verse('Esther', 9, 3)]
Error cases:
>>> parse_verses('Invalid 1:1')
[]
>>> parse_verses('Gen 50:27') # Verse doesn't exist
[]
>>> parse_verses('Gen 51:1') # Chapter doesn't exist
[]
>>> parse_verses('') # Empty string
[]
>>> parse_verses('Genesis 1:1:1') # Invalid format
[]
>>> parse_verses('Gen 1:a') # Non-numeric verse
[]
"""
pass
# @@@@@@@@@@@@@@@@@@@@
#
if False:
import doctest
doctest.testmod()
print('Parser doctests passed')
# @@@@@@@@@@@@@@@@@@@@