Skip to content

API Reference

Translations

Bases: ABC

Base class for all Bible translations. Implementations should define async methods; sync wrappers are provided for convenience.

Source code in src/bible_translations/translations/base.py
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
class Translation(ABC):
    """
    Base class for all Bible translations.
    Implementations should define async methods; sync wrappers are provided for convenience.
    """

    name: str
    abbreviation: str
    copyright: str
    language: str = "English"
    url: str | None = None
    books: list[str] = list(DEFAULT_BOOK_CHAPTER_COUNTS.keys())
    book_chapter_counts: dict[str, int] = DEFAULT_BOOK_CHAPTER_COUNTS

    # ---------- Retrieval methods ----------

    @abstractmethod
    async def aget_books(self, on_book_complete=None) -> list[Book]:
        """
        Asynchronously return all books available in this translation.

        :param on_book_complete: Callback function to invoke after each book is loaded.
        :returns: list[Book]: A list of all `Book` objects for the translation.
        """
        raise NotImplementedError

    def get_books(self, on_book_complete=None) -> list[Book]:
        """
        Synchronously return all books available in this translation.

        :param on_book_complete: Callback function to invoke after each book is loaded.
        :returns: list[Book]: A list of all `Book` objects for the translation.
        """
        return _run_async(self.aget_books(on_book_complete=on_book_complete))

    @abstractmethod
    async def aget_book(self, name: str, *, on_chapter_complete=None) -> Book:
        """
        Asynchronously return a single book by name.

        :param name: The book name (e.g., "Genesis", "John").
        :param on_chapter_complete: Callback function to invoke after each chapter is loaded.
        :returns: Book: The corresponding `Book` object containing all chapters and verses.
        """
        raise NotImplementedError

    def get_book(self, name: str, *, on_chapter_complete=None) -> Book:
        """
        Synchronously return a single book by name.

        :param name: The book name (e.g., "Genesis", "John").
        :param on_chapter_complete: Callback function to invoke after each chapter is loaded.
        :returns: Book: The corresponding `Book` object containing all chapters and verses.
        """
        return _run_async(self.aget_book(name, on_chapter_complete=on_chapter_complete))

    @abstractmethod
    async def aget_chapter(self, book_name: str, chapter_number: int) -> Chapter:
        """
        Asynchronously return a single chapter by book name and chapter number.

        :param book_name: Name of the book (e.g., "John").
        :param chapter_number: Chapter number to retrieve.
        :returns: Chapter: The `Chapter` object, including its verses.
        """
        raise NotImplementedError

    def get_chapter(self, book_name: str, chapter_number: int) -> Chapter:
        """
        Synchronously return a single chapter by book name and chapter number.

        :param book_name: Name of the book (e.g., "John").
        :param chapter_number: Chapter number to retrieve.
        :returns: Chapter: The `Chapter` object, including its verses.
        """
        return _run_async(self.aget_chapter(book_name, chapter_number))

    @abstractmethod
    async def aget_verse(self, book_name: str, chapter_number: int, verse_number: int) -> Verse:
        """
        Asynchronously return a single verse by book, chapter, and verse number.

        :param book_name: Name of the book.
        :param chapter_number: Chapter number.
        :param verse_number: Verse number.
        :returns: Verse: The requested `Verse` object, linked to its chapter, book, and translation.
        """
        raise NotImplementedError

    def get_verse(self, book_name: str, chapter_number: int, verse_number: int) -> Verse:
        """
        Synchronously return a single verse by book, chapter, and verse number.

        :param book_name: Name of the book.
        :param chapter_number: Chapter number.
        :param verse_number: Verse number.
        :returns: Verse: The requested `Verse` object, linked to its chapter, book, and translation.
        """
        return _run_async(self.aget_verse(book_name, chapter_number, verse_number))

    # ---------- Selection retrieval ----------

    async def aget_selection(
        self,
        start_ref: str | None = None,
        end_ref: str | None = None,
        *,
        start_book: str | None = None,
        start_chapter: int | None = None,
        start_verse: int | None = None,
        end_book: str | None = None,
        end_chapter: int | None = None,
        end_verse: int | None = None,
    ) -> list[Book]:
        """
        Asynchronously return a continuous selection of verses between two points.

        Can be called with string references or explicit numeric arguments:

            await aget_selection("John 3:16", "John 5:1")

            await aget_selection(
                start_book="John", start_chapter=3, start_verse=16,
                end_book="John", end_chapter=5, end_verse=1)

        :param start_ref: Optional string reference for the start (e.g., "John 3:16").
        :param end_ref: Optional string reference for the end (e.g., "John 5:1").
        :param start_book: Start book name if using numeric mode.
        :param start_chapter: Start chapter number.
        :param start_verse: Start verse number.
        :param end_book: End book name if using numeric mode.
        :param end_chapter: End chapter number.
        :param end_verse: End verse number.
        :returns: list[Verse]: A list of `Verse` objects covering the inclusive range.
        """

        if self._is_selection_mode_ref(
            start_ref,
            end_ref,
            start_book=start_book,
            start_chapter=start_chapter,
            start_verse=start_verse,
            end_book=end_book,
            end_chapter=end_chapter,
            end_verse=end_verse,
        ):
            start_book, start_chapter, start_verse = self.parse_ref(start_ref)
            end_book, end_chapter, end_verse = self.parse_ref(end_ref)

        return await self._aget_selection_range(
            start_book, start_chapter, start_verse, end_book, end_chapter, end_verse
        )

    def get_selection(
        self,
        start_ref: str | None = None,
        end_ref: str | None = None,
        *,
        start_book: str | None = None,
        start_chapter: int | None = None,
        start_verse: int | None = None,
        end_book: str | None = None,
        end_chapter: int | None = None,
        end_verse: int | None = None,
    ) -> list[Book]:
        """
        Synchronously return a continuous selection of verses between two points.

        Can be called with string references or explicit numeric arguments:

            get_selection("John 3:16", "John 5:1")

            get_selection(
                start_book="John", start_chapter=3, start_verse=16,
                end_book="John", end_chapter=5, end_verse=1)

        :param start_ref: Optional string reference for the start (e.g., "John 3:16").
        :param end_ref: Optional string reference for the end (e.g., "John 5:1").
        :param start_book: Start book name if using numeric mode.
        :param start_chapter: Start chapter number.
        :param start_verse: Start verse number.
        :param end_book: End book name if using numeric mode.
        :param end_chapter: End chapter number.
        :param end_verse: End verse number.
        :returns: list[Verse]: A list of `Verse` objects covering the inclusive range.
        """

        if self._is_selection_mode_ref(
            start_ref,
            end_ref,
            start_book=start_book,
            start_chapter=start_chapter,
            start_verse=start_verse,
            end_book=end_book,
            end_chapter=end_chapter,
            end_verse=end_verse,
        ):
            start_book, start_chapter, start_verse = self.parse_ref(start_ref)
            end_book, end_chapter, end_verse = self.parse_ref(end_ref)

        return _run_async(
            self._aget_selection_range(start_book, start_chapter, start_verse, end_book, end_chapter, end_verse)
        )

    @abstractmethod
    async def _aget_selection_range(
        self,
        start_book: str,
        start_chapter: int,
        start_verse: int,
        end_book: str,
        end_chapter: int,
        end_verse: int,
    ) -> list[Book]:
        """
        Asynchronously retrieve a continuous list of verses between two reference points.

        This method must be implemented by subclasses to define
        how verses are loaded or generated internally.

        :param start_book: Name of the starting book.
        :param start_chapter: Starting chapter number.
        :param start_verse: Starting verse number.
        :param end_book: Name of the ending book.
        :param end_chapter: Ending chapter number.
        :param end_verse: Ending verse number.
        :returns: list[Verse]: Ordered list of all `Verse` objects in the range.
        """
        raise NotImplementedError

    @staticmethod
    def parse_ref(ref: str) -> tuple[str, int, int]:
        """
        Parse a string reference into components.

        Example:
            "John 3:16" → ("John", 3, 16)
            "1 John 3:16" → ("1 John", 3, 16)
            "2 Kings 5:10" → ("2 Kings", 5, 10)
            "Song of Solomon 2:1" → ("Song of Solomon", 2, 1)
            "Song of Songs 2:1" → ("Song of Solomon", 2, 1)
            "John 3" → ("John", 3, 1)
            "1 Kings 6" → ("1 Kings", 6, 1)
            "John" → ("John", 1, 1)
            "Mark" → ("Mark", 1, 1)
            "1 Kings" → ("1 Kings", 1, 1)

        :param ref: Reference string formatted as "Book Chapter:Verse", "Book Chapter", or "Book".

        :returns: tuple[str, int, int]: (book_name, chapter_number, verse_number)
        """
        parts = ref.split(" ")

        # Check if the first part is a number (e.g., "1", "2", "3")
        if parts[0].isdigit():
            # Multi-word book name like "1 John" or "2 Kings"
            book = f"{parts[0]} {parts[1].capitalize()}"
            rest = " ".join(parts[2:])
        elif len(parts) >= 3 and parts[0].lower() == "song" and parts[1].lower() == "of":
            # Handle "Song of Solomon" or "Song of Songs"
            if parts[2].lower() in ("solomon", "songs"):
                book = "Song Of Solomon"
                rest = " ".join(parts[3:])
            else:
                # Single-word book name like "Song"
                book = parts[0].capitalize()
                rest = " ".join(parts[1:])
        else:
            # Single-word book name like "John"
            book = parts[0].capitalize()
            rest = " ".join(parts[1:])

        if not rest:
            # Only book name provided, default to chapter 1, verse 1
            return book, 1, 1
        elif ":" in rest:
            chapter, verse = rest.split(":")
            return book, int(chapter), int(verse)
        else:
            # Only chapter provided, default verse to -1
            return book, int(rest), 1

    def getInfo(self):
        return Info(
            translation=self.name,
            abbreviation=self.abbreviation,
            language=self.language,
            copyright=self.copyright,
            url=self.url,
            fetch_date=datetime.now(tz=ZoneInfo("UTC")).isoformat(),
        )

    @staticmethod
    def _is_selection_mode_ref(
        start_ref: str | None = None,
        end_ref: str | None = None,
        *,
        start_book: str | None = None,
        start_chapter: int | None = None,
        start_verse: int | None = None,
        end_book: str | None = None,
        end_chapter: int | None = None,
        end_verse: int | None = None,
    ):
        mode_ref = start_ref is not None and end_ref is not None

        mode_parts = (
            start_book is not None
            and start_chapter is not None
            and start_verse is not None
            and end_book is not None
            and end_chapter is not None
            and end_verse is not None
        )

        if not (mode_ref or mode_parts):
            raise ValueError("Provide either start_ref and end_ref or all six granular fields.")

        if mode_ref and mode_parts:
            raise ValueError("Provide either reference mode or granular mode, not both.")

        logger.debug(f"Selection mode ref: {mode_ref}")
        return mode_ref

aget_book(name, *, on_chapter_complete=None) abstractmethod async

Asynchronously return a single book by name.

Parameters:

Name Type Description Default
name str

The book name (e.g., "Genesis", "John").

required
on_chapter_complete

Callback function to invoke after each chapter is loaded.

None

Returns:

Type Description
Book

Book: The corresponding Book object containing all chapters and verses.

Source code in src/bible_translations/translations/base.py
64
65
66
67
68
69
70
71
72
73
@abstractmethod
async def aget_book(self, name: str, *, on_chapter_complete=None) -> Book:
    """
    Asynchronously return a single book by name.

    :param name: The book name (e.g., "Genesis", "John").
    :param on_chapter_complete: Callback function to invoke after each chapter is loaded.
    :returns: Book: The corresponding `Book` object containing all chapters and verses.
    """
    raise NotImplementedError

aget_books(on_book_complete=None) abstractmethod async

Asynchronously return all books available in this translation.

Parameters:

Name Type Description Default
on_book_complete

Callback function to invoke after each book is loaded.

None

Returns:

Type Description
list[Book]

list[Book]: A list of all Book objects for the translation.

Source code in src/bible_translations/translations/base.py
45
46
47
48
49
50
51
52
53
@abstractmethod
async def aget_books(self, on_book_complete=None) -> list[Book]:
    """
    Asynchronously return all books available in this translation.

    :param on_book_complete: Callback function to invoke after each book is loaded.
    :returns: list[Book]: A list of all `Book` objects for the translation.
    """
    raise NotImplementedError

aget_chapter(book_name, chapter_number) abstractmethod async

Asynchronously return a single chapter by book name and chapter number.

Parameters:

Name Type Description Default
book_name str

Name of the book (e.g., "John").

required
chapter_number int

Chapter number to retrieve.

required

Returns:

Type Description
Chapter

Chapter: The Chapter object, including its verses.

Source code in src/bible_translations/translations/base.py
85
86
87
88
89
90
91
92
93
94
@abstractmethod
async def aget_chapter(self, book_name: str, chapter_number: int) -> Chapter:
    """
    Asynchronously return a single chapter by book name and chapter number.

    :param book_name: Name of the book (e.g., "John").
    :param chapter_number: Chapter number to retrieve.
    :returns: Chapter: The `Chapter` object, including its verses.
    """
    raise NotImplementedError

aget_selection(start_ref=None, end_ref=None, *, start_book=None, start_chapter=None, start_verse=None, end_book=None, end_chapter=None, end_verse=None) async

Asynchronously return a continuous selection of verses between two points.

Can be called with string references or explicit numeric arguments:

await aget_selection("John 3:16", "John 5:1")

await aget_selection(
    start_book="John", start_chapter=3, start_verse=16,
    end_book="John", end_chapter=5, end_verse=1)

Parameters:

Name Type Description Default
start_ref str | None

Optional string reference for the start (e.g., "John 3:16").

None
end_ref str | None

Optional string reference for the end (e.g., "John 5:1").

None
start_book str | None

Start book name if using numeric mode.

None
start_chapter int | None

Start chapter number.

None
start_verse int | None

Start verse number.

None
end_book str | None

End book name if using numeric mode.

None
end_chapter int | None

End chapter number.

None
end_verse int | None

End verse number.

None

Returns:

Type Description
list[Book]

list[Verse]: A list of Verse objects covering the inclusive range.

Source code in src/bible_translations/translations/base.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
async def aget_selection(
    self,
    start_ref: str | None = None,
    end_ref: str | None = None,
    *,
    start_book: str | None = None,
    start_chapter: int | None = None,
    start_verse: int | None = None,
    end_book: str | None = None,
    end_chapter: int | None = None,
    end_verse: int | None = None,
) -> list[Book]:
    """
    Asynchronously return a continuous selection of verses between two points.

    Can be called with string references or explicit numeric arguments:

        await aget_selection("John 3:16", "John 5:1")

        await aget_selection(
            start_book="John", start_chapter=3, start_verse=16,
            end_book="John", end_chapter=5, end_verse=1)

    :param start_ref: Optional string reference for the start (e.g., "John 3:16").
    :param end_ref: Optional string reference for the end (e.g., "John 5:1").
    :param start_book: Start book name if using numeric mode.
    :param start_chapter: Start chapter number.
    :param start_verse: Start verse number.
    :param end_book: End book name if using numeric mode.
    :param end_chapter: End chapter number.
    :param end_verse: End verse number.
    :returns: list[Verse]: A list of `Verse` objects covering the inclusive range.
    """

    if self._is_selection_mode_ref(
        start_ref,
        end_ref,
        start_book=start_book,
        start_chapter=start_chapter,
        start_verse=start_verse,
        end_book=end_book,
        end_chapter=end_chapter,
        end_verse=end_verse,
    ):
        start_book, start_chapter, start_verse = self.parse_ref(start_ref)
        end_book, end_chapter, end_verse = self.parse_ref(end_ref)

    return await self._aget_selection_range(
        start_book, start_chapter, start_verse, end_book, end_chapter, end_verse
    )

aget_verse(book_name, chapter_number, verse_number) abstractmethod async

Asynchronously return a single verse by book, chapter, and verse number.

Parameters:

Name Type Description Default
book_name str

Name of the book.

required
chapter_number int

Chapter number.

required
verse_number int

Verse number.

required

Returns:

Type Description
Verse

Verse: The requested Verse object, linked to its chapter, book, and translation.

Source code in src/bible_translations/translations/base.py
106
107
108
109
110
111
112
113
114
115
116
@abstractmethod
async def aget_verse(self, book_name: str, chapter_number: int, verse_number: int) -> Verse:
    """
    Asynchronously return a single verse by book, chapter, and verse number.

    :param book_name: Name of the book.
    :param chapter_number: Chapter number.
    :param verse_number: Verse number.
    :returns: Verse: The requested `Verse` object, linked to its chapter, book, and translation.
    """
    raise NotImplementedError

get_book(name, *, on_chapter_complete=None)

Synchronously return a single book by name.

Parameters:

Name Type Description Default
name str

The book name (e.g., "Genesis", "John").

required
on_chapter_complete

Callback function to invoke after each chapter is loaded.

None

Returns:

Type Description
Book

Book: The corresponding Book object containing all chapters and verses.

Source code in src/bible_translations/translations/base.py
75
76
77
78
79
80
81
82
83
def get_book(self, name: str, *, on_chapter_complete=None) -> Book:
    """
    Synchronously return a single book by name.

    :param name: The book name (e.g., "Genesis", "John").
    :param on_chapter_complete: Callback function to invoke after each chapter is loaded.
    :returns: Book: The corresponding `Book` object containing all chapters and verses.
    """
    return _run_async(self.aget_book(name, on_chapter_complete=on_chapter_complete))

get_books(on_book_complete=None)

Synchronously return all books available in this translation.

Parameters:

Name Type Description Default
on_book_complete

Callback function to invoke after each book is loaded.

None

Returns:

Type Description
list[Book]

list[Book]: A list of all Book objects for the translation.

Source code in src/bible_translations/translations/base.py
55
56
57
58
59
60
61
62
def get_books(self, on_book_complete=None) -> list[Book]:
    """
    Synchronously return all books available in this translation.

    :param on_book_complete: Callback function to invoke after each book is loaded.
    :returns: list[Book]: A list of all `Book` objects for the translation.
    """
    return _run_async(self.aget_books(on_book_complete=on_book_complete))

get_chapter(book_name, chapter_number)

Synchronously return a single chapter by book name and chapter number.

Parameters:

Name Type Description Default
book_name str

Name of the book (e.g., "John").

required
chapter_number int

Chapter number to retrieve.

required

Returns:

Type Description
Chapter

Chapter: The Chapter object, including its verses.

Source code in src/bible_translations/translations/base.py
 96
 97
 98
 99
100
101
102
103
104
def get_chapter(self, book_name: str, chapter_number: int) -> Chapter:
    """
    Synchronously return a single chapter by book name and chapter number.

    :param book_name: Name of the book (e.g., "John").
    :param chapter_number: Chapter number to retrieve.
    :returns: Chapter: The `Chapter` object, including its verses.
    """
    return _run_async(self.aget_chapter(book_name, chapter_number))

get_selection(start_ref=None, end_ref=None, *, start_book=None, start_chapter=None, start_verse=None, end_book=None, end_chapter=None, end_verse=None)

Synchronously return a continuous selection of verses between two points.

Can be called with string references or explicit numeric arguments:

get_selection("John 3:16", "John 5:1")

get_selection(
    start_book="John", start_chapter=3, start_verse=16,
    end_book="John", end_chapter=5, end_verse=1)

Parameters:

Name Type Description Default
start_ref str | None

Optional string reference for the start (e.g., "John 3:16").

None
end_ref str | None

Optional string reference for the end (e.g., "John 5:1").

None
start_book str | None

Start book name if using numeric mode.

None
start_chapter int | None

Start chapter number.

None
start_verse int | None

Start verse number.

None
end_book str | None

End book name if using numeric mode.

None
end_chapter int | None

End chapter number.

None
end_verse int | None

End verse number.

None

Returns:

Type Description
list[Book]

list[Verse]: A list of Verse objects covering the inclusive range.

Source code in src/bible_translations/translations/base.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
def get_selection(
    self,
    start_ref: str | None = None,
    end_ref: str | None = None,
    *,
    start_book: str | None = None,
    start_chapter: int | None = None,
    start_verse: int | None = None,
    end_book: str | None = None,
    end_chapter: int | None = None,
    end_verse: int | None = None,
) -> list[Book]:
    """
    Synchronously return a continuous selection of verses between two points.

    Can be called with string references or explicit numeric arguments:

        get_selection("John 3:16", "John 5:1")

        get_selection(
            start_book="John", start_chapter=3, start_verse=16,
            end_book="John", end_chapter=5, end_verse=1)

    :param start_ref: Optional string reference for the start (e.g., "John 3:16").
    :param end_ref: Optional string reference for the end (e.g., "John 5:1").
    :param start_book: Start book name if using numeric mode.
    :param start_chapter: Start chapter number.
    :param start_verse: Start verse number.
    :param end_book: End book name if using numeric mode.
    :param end_chapter: End chapter number.
    :param end_verse: End verse number.
    :returns: list[Verse]: A list of `Verse` objects covering the inclusive range.
    """

    if self._is_selection_mode_ref(
        start_ref,
        end_ref,
        start_book=start_book,
        start_chapter=start_chapter,
        start_verse=start_verse,
        end_book=end_book,
        end_chapter=end_chapter,
        end_verse=end_verse,
    ):
        start_book, start_chapter, start_verse = self.parse_ref(start_ref)
        end_book, end_chapter, end_verse = self.parse_ref(end_ref)

    return _run_async(
        self._aget_selection_range(start_book, start_chapter, start_verse, end_book, end_chapter, end_verse)
    )

get_verse(book_name, chapter_number, verse_number)

Synchronously return a single verse by book, chapter, and verse number.

Parameters:

Name Type Description Default
book_name str

Name of the book.

required
chapter_number int

Chapter number.

required
verse_number int

Verse number.

required

Returns:

Type Description
Verse

Verse: The requested Verse object, linked to its chapter, book, and translation.

Source code in src/bible_translations/translations/base.py
118
119
120
121
122
123
124
125
126
127
def get_verse(self, book_name: str, chapter_number: int, verse_number: int) -> Verse:
    """
    Synchronously return a single verse by book, chapter, and verse number.

    :param book_name: Name of the book.
    :param chapter_number: Chapter number.
    :param verse_number: Verse number.
    :returns: Verse: The requested `Verse` object, linked to its chapter, book, and translation.
    """
    return _run_async(self.aget_verse(book_name, chapter_number, verse_number))

parse_ref(ref) staticmethod

Parse a string reference into components.

Example: "John 3:16" → ("John", 3, 16) "1 John 3:16" → ("1 John", 3, 16) "2 Kings 5:10" → ("2 Kings", 5, 10) "Song of Solomon 2:1" → ("Song of Solomon", 2, 1) "Song of Songs 2:1" → ("Song of Solomon", 2, 1) "John 3" → ("John", 3, 1) "1 Kings 6" → ("1 Kings", 6, 1) "John" → ("John", 1, 1) "Mark" → ("Mark", 1, 1) "1 Kings" → ("1 Kings", 1, 1)

Parameters:

Name Type Description Default
ref str

Reference string formatted as "Book Chapter:Verse", "Book Chapter", or "Book".

required

Returns:

Type Description
tuple[str, int, int]

tuple[str, int, int]: (book_name, chapter_number, verse_number)

Source code in src/bible_translations/translations/base.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
@staticmethod
def parse_ref(ref: str) -> tuple[str, int, int]:
    """
    Parse a string reference into components.

    Example:
        "John 3:16" → ("John", 3, 16)
        "1 John 3:16" → ("1 John", 3, 16)
        "2 Kings 5:10" → ("2 Kings", 5, 10)
        "Song of Solomon 2:1" → ("Song of Solomon", 2, 1)
        "Song of Songs 2:1" → ("Song of Solomon", 2, 1)
        "John 3" → ("John", 3, 1)
        "1 Kings 6" → ("1 Kings", 6, 1)
        "John" → ("John", 1, 1)
        "Mark" → ("Mark", 1, 1)
        "1 Kings" → ("1 Kings", 1, 1)

    :param ref: Reference string formatted as "Book Chapter:Verse", "Book Chapter", or "Book".

    :returns: tuple[str, int, int]: (book_name, chapter_number, verse_number)
    """
    parts = ref.split(" ")

    # Check if the first part is a number (e.g., "1", "2", "3")
    if parts[0].isdigit():
        # Multi-word book name like "1 John" or "2 Kings"
        book = f"{parts[0]} {parts[1].capitalize()}"
        rest = " ".join(parts[2:])
    elif len(parts) >= 3 and parts[0].lower() == "song" and parts[1].lower() == "of":
        # Handle "Song of Solomon" or "Song of Songs"
        if parts[2].lower() in ("solomon", "songs"):
            book = "Song Of Solomon"
            rest = " ".join(parts[3:])
        else:
            # Single-word book name like "Song"
            book = parts[0].capitalize()
            rest = " ".join(parts[1:])
    else:
        # Single-word book name like "John"
        book = parts[0].capitalize()
        rest = " ".join(parts[1:])

    if not rest:
        # Only book name provided, default to chapter 1, verse 1
        return book, 1, 1
    elif ":" in rest:
        chapter, verse = rest.split(":")
        return book, int(chapter), int(verse)
    else:
        # Only chapter provided, default verse to -1
        return book, int(rest), 1

Get a translation class by its abbreviation.

Parameters:

Name Type Description Default
abbreviation str

The translation abbreviation (e.g., "KJV").

required

Returns:

Type Description

The translation class.

Raises:

Type Description
ValueError

If the translation is not found.

Source code in src/bible_translations/translations/__init__.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
def get_translation(abbreviation: str):
    """
    Get a translation class by its abbreviation.

    :param abbreviation: The translation abbreviation (e.g., "KJV").
    :return: The translation class.
    :raises ValueError: If the translation is not found.
    """
    translation_class = TRANSLATIONS.get(abbreviation.upper())
    if not translation_class:
        raise ValueError(
            f"Translation not found: {abbreviation}. Available translations: {', '.join(TRANSLATIONS.keys())}"
        )
    return translation_class()

Models

Source code in src/bible_translations/models/book.py
 7
 8
 9
10
11
@dataclass
class Book:
    name: str
    chapters: list[Chapter]
    info: Info | None = None
Source code in src/bible_translations/models/chapter.py
6
7
8
9
@dataclass
class Chapter:
    number: int
    verses: list[Verse]
Source code in src/bible_translations/models/verse.py
 4
 5
 6
 7
 8
 9
10
@dataclass
class Verse:
    number: int
    text: str
    heading: str | None = None
    superscription: str | None = None
    footnotes: list[str] | None = None
Source code in src/bible_translations/models/info.py
 4
 5
 6
 7
 8
 9
10
11
@dataclass
class Info:
    translation: str
    abbreviation: str
    language: str
    copyright: str | None = None
    url: str | None = None
    fetch_date: str | None = None

Flattening

Flatten a list of Book objects into a flat list of per-verse records.

Parameters:

Name Type Description Default
books list[Book]

List of Book objects to flatten.

required

Returns:

Type Description
list[FlatVerse]

list[FlatVerse]: One record per verse, in book/chapter/verse order.

Source code in src/bible_translations/utils/flatten.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def flatten_books(books: list[Book]) -> list[FlatVerse]:
    """
    Flatten a list of Book objects into a flat list of per-verse records.

    :param books: List of Book objects to flatten.
    :returns: list[FlatVerse]: One record per verse, in book/chapter/verse order.
    """
    flat: list[FlatVerse] = []
    for book in books:
        info = book.info
        translation = info.translation if info else ""
        abbreviation = info.abbreviation if info else ""
        for chapter in book.chapters:
            for verse in chapter.verses:
                flat.append(
                    FlatVerse(
                        translation=translation,
                        abbreviation=abbreviation,
                        book=book.name,
                        chapter=chapter.number,
                        verse=verse.number,
                        text=verse.text,
                        heading=verse.heading,
                        superscription=verse.superscription,
                        footnotes=verse.footnotes,
                    )
                )
    return flat

A single verse flattened out of the nested Book/Chapter/Verse structure.

Source code in src/bible_translations/utils/flatten.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
@dataclass
class FlatVerse:
    """A single verse flattened out of the nested Book/Chapter/Verse structure."""

    translation: str
    abbreviation: str
    book: str
    chapter: int
    verse: int
    text: str
    heading: str | None = None
    superscription: str | None = None
    footnotes: list[str] | None = None

Exporting

Export Bible translations to various formats.

Source code in src/bible_translations/utils/exporter.py
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
class Exporter:
    """Export Bible translations to various formats."""

    def __init__(self, output_dir: str | Path = "exports"):
        """
        Initialize the exporter.

        :param output_dir: Directory to save exported files
        """
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)

    def export(
        self,
        books: List[Book],
        file_format: str = "json",
        compression: Literal[".tar.gz", ".tgz", ".zip"] = ".zip",
        folder_name: str | None = None,
        flat: bool = False,
    ) -> Path:
        """
        Export books to the specified format.

        :param folder_name: Name of the exported folder
        :param compression: Type of compression to use (tar.gz, tgz, zip)
        :param books: List of Book objects to export
        :param file_format: Export format (json, txt, csv, xml)
        :param flat: If True, export a single flat list of verse records instead of the
            nested book/chapter/verse structure.
        :return: Path to the exported file
        """

        # If the list is empty, return an error
        if not books or len(books) == 0:
            raise ValueError("No books to export")

        # first book info is always used
        book_info = books[0].info
        if book_info is None:
            raise ValueError("Book.info is required for export")

        # Create a temp directory and do all the work in there
        with tempfile.TemporaryDirectory() as tempdir:
            logger.debug("Created temporary directory: %s", tempdir)
            # Grab today's date and time
            date = datetime.now().strftime("%Y%m%d_%H%M%S")
            logger.debug("Date: %s", date)
            # Create the assembly folder inside the temp directory
            if not folder_name:
                abbreviation = book_info.abbreviation.lower() if book_info.abbreviation else "bt"
                abbreviation += "_"
                assembly_folder = Path(tempdir) / f"{abbreviation}{file_format}_export_{date}"
            else:
                assembly_folder = Path(tempdir) / folder_name

            assembly_folder.mkdir(parents=True, exist_ok=True)
            parent_folder = str(assembly_folder)

            # Create all the export files depending on parameters
            if file_format == "json":
                if flat:
                    self._export_json_flat(books, parent_folder, book_info)
                else:
                    self._export_json(books, parent_folder, book_info)
            elif file_format == "sql":
                raise NotImplementedError("SQL export not implemented yet")
            else:
                raise ValueError(f"Unsupported file format: {file_format}")

            # compress and zip to finale location
            if compression in [".tar.gz", ".tgz"]:
                output_path = str(self.output_dir / f"{Path(parent_folder).name}.tar.gz")
                with tarfile.open(output_path, "w:gz") as tar:
                    tar.add(parent_folder, arcname=Path(parent_folder).name)
                return Path(output_path)
            else:  # .zip
                output_path = str(self.output_dir / f"{Path(parent_folder).name}.zip")
                with zipfile.ZipFile(output_path, "w", zipfile.ZIP_DEFLATED) as zip_file:
                    for file in Path(parent_folder).rglob("*"):
                        zip_file.write(file, file.relative_to(Path(parent_folder)))
                return Path(output_path)

    @staticmethod
    def _write_info_json(output_dir: str, info: Info) -> dict:
        info_data = {
            "translation": info.translation or "",
            "abbreviation": info.abbreviation or "",
            "language": info.language or "",
            "copyright": info.copyright or "",
            "url": info.url or "",
            "fetch_date": info.fetch_date or "",
        }
        with open(output_dir + "/" + info.abbreviation.lower() + "_info.json", "w") as json_file:
            json.dump(info_data, json_file, indent=4)
        return info_data

    @staticmethod
    def _export_json_flat(books: List[Book], output_dir: str, info: Info):
        logger.debug("Exporting flat JSON...")
        Exporter._write_info_json(output_dir, info)
        records = [asdict(record) for record in flatten_books(books)]
        file_path = Path(output_dir, info.abbreviation.lower() + "_flat.json")
        with open(file_path, "w", encoding="utf-8") as json_file:
            json.dump(records, json_file, indent=4, ensure_ascii=False)
        logger.debug("Flat JSON export completed for %d verse records", len(records))

    @staticmethod
    def _export_json(books: List[Book], output_dir: str, info: Info):
        logger.debug("Exporting JSON files...")
        info_data = Exporter._write_info_json(output_dir, info)

        # Export each book as a separate JSON file
        for book in books:
            logger.debug("Exporting book: %s", book.name)

            # Create a book data structure
            book_data = {"name": book.name, "chapters": []}

            # Add chapters and verses
            for chapter in book.chapters:
                chapter_data = {"number": chapter.number, "verses": []}

                # Add verses to a chapter
                for verse in chapter.verses:
                    verse_data = {"number": verse.number, "text": verse.text}
                    chapter_data["verses"].append(verse_data)

                book_data["chapters"].append(chapter_data)

            # Create filename (sanitize book name for filesystem)
            safe_book_name = "".join(c for c in book.name if c.isalnum() or c in (" ", "-", "_")).rstrip()
            safe_book_name = safe_book_name.replace(" ", "_").lower()
            filename = f"{safe_book_name}.json"
            books_dir = Path(output_dir) / "books"
            if not exists(books_dir):
                mkdir(books_dir)

            # Write book data to JSON file
            file_path = Path(books_dir, filename)
            with open(file_path, "w", encoding="utf-8") as json_file:
                json.dump(book_data, json_file, indent=4, ensure_ascii=False)

        full_data = {
            "info": info_data,
            "books": [
                {
                    "name": book.name,
                    "chapters": [
                        {
                            "number": chapter.number,
                            "verses": [{"number": verse.number, "text": verse.text} for verse in chapter.verses],
                        }
                        for chapter in book.chapters
                    ],
                }
                for book in books
            ],
        }

        full_file_path = Path(output_dir, info.abbreviation.lower() + ".json")
        with open(full_file_path, "w", encoding="utf-8") as json_file:
            json.dump(full_data, json_file, indent=4, ensure_ascii=False)

        logger.debug("JSON export completed for %d books", len(books))

__init__(output_dir='exports')

Initialize the exporter.

Parameters:

Name Type Description Default
output_dir str | Path

Directory to save exported files

'exports'
Source code in src/bible_translations/utils/exporter.py
21
22
23
24
25
26
27
28
def __init__(self, output_dir: str | Path = "exports"):
    """
    Initialize the exporter.

    :param output_dir: Directory to save exported files
    """
    self.output_dir = Path(output_dir)
    self.output_dir.mkdir(parents=True, exist_ok=True)

export(books, file_format='json', compression='.zip', folder_name=None, flat=False)

Export books to the specified format.

Parameters:

Name Type Description Default
folder_name str | None

Name of the exported folder

None
compression Literal['.tar.gz', '.tgz', '.zip']

Type of compression to use (tar.gz, tgz, zip)

'.zip'
books List[Book]

List of Book objects to export

required
file_format str

Export format (json, txt, csv, xml)

'json'
flat bool

If True, export a single flat list of verse records instead of the nested book/chapter/verse structure.

False

Returns:

Type Description
Path

Path to the exported file

Source code in src/bible_translations/utils/exporter.py
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def export(
    self,
    books: List[Book],
    file_format: str = "json",
    compression: Literal[".tar.gz", ".tgz", ".zip"] = ".zip",
    folder_name: str | None = None,
    flat: bool = False,
) -> Path:
    """
    Export books to the specified format.

    :param folder_name: Name of the exported folder
    :param compression: Type of compression to use (tar.gz, tgz, zip)
    :param books: List of Book objects to export
    :param file_format: Export format (json, txt, csv, xml)
    :param flat: If True, export a single flat list of verse records instead of the
        nested book/chapter/verse structure.
    :return: Path to the exported file
    """

    # If the list is empty, return an error
    if not books or len(books) == 0:
        raise ValueError("No books to export")

    # first book info is always used
    book_info = books[0].info
    if book_info is None:
        raise ValueError("Book.info is required for export")

    # Create a temp directory and do all the work in there
    with tempfile.TemporaryDirectory() as tempdir:
        logger.debug("Created temporary directory: %s", tempdir)
        # Grab today's date and time
        date = datetime.now().strftime("%Y%m%d_%H%M%S")
        logger.debug("Date: %s", date)
        # Create the assembly folder inside the temp directory
        if not folder_name:
            abbreviation = book_info.abbreviation.lower() if book_info.abbreviation else "bt"
            abbreviation += "_"
            assembly_folder = Path(tempdir) / f"{abbreviation}{file_format}_export_{date}"
        else:
            assembly_folder = Path(tempdir) / folder_name

        assembly_folder.mkdir(parents=True, exist_ok=True)
        parent_folder = str(assembly_folder)

        # Create all the export files depending on parameters
        if file_format == "json":
            if flat:
                self._export_json_flat(books, parent_folder, book_info)
            else:
                self._export_json(books, parent_folder, book_info)
        elif file_format == "sql":
            raise NotImplementedError("SQL export not implemented yet")
        else:
            raise ValueError(f"Unsupported file format: {file_format}")

        # compress and zip to finale location
        if compression in [".tar.gz", ".tgz"]:
            output_path = str(self.output_dir / f"{Path(parent_folder).name}.tar.gz")
            with tarfile.open(output_path, "w:gz") as tar:
                tar.add(parent_folder, arcname=Path(parent_folder).name)
            return Path(output_path)
        else:  # .zip
            output_path = str(self.output_dir / f"{Path(parent_folder).name}.zip")
            with zipfile.ZipFile(output_path, "w", zipfile.ZIP_DEFLATED) as zip_file:
                for file in Path(parent_folder).rglob("*"):
                    zip_file.write(file, file.relative_to(Path(parent_folder)))
            return Path(output_path)

Exceptions

Bases: Exception

Raised when a requested book cannot be found.

Source code in src/bible_translations/exceptions.py
 7
 8
 9
10
class BookNotFoundError(Exception):
    """Raised when a requested book cannot be found."""

    pass

Bases: Exception

Raised when a requested chapter cannot be found.

Source code in src/bible_translations/exceptions.py
13
14
15
16
class ChapterNotFoundError(Exception):
    """Raised when a requested chapter cannot be found."""

    pass

Bases: Exception

Raised when a requested verse cannot be found.

Source code in src/bible_translations/exceptions.py
1
2
3
4
class VerseNotFoundError(Exception):
    """Raised when a requested verse cannot be found."""

    pass

Bases: Exception

Raised when a selection is invalid.

Source code in src/bible_translations/exceptions.py
19
20
21
22
class SelectionInvalidError(Exception):
    """Raised when a selection is invalid."""

    pass