"""Download the World English Bible and write data/web_bible.json.
The WEB (World English Bible) is in the public domain, released by Michael Paul
Johnson / ebible.org. This script pulls the USFX XML mirror at seven1m/open-bibles
(derived from ebible.org) and flattens it to {book, chapter, verse, text} records.
"""
import json
import re
import sys
import xml.etree.ElementTree as ET
from pathlib import Path
import requests
ROOT = Path(__file__).resolve().parent.parent
DATA_DIR = ROOT / "data"
OUT_PATH = DATA_DIR / "web_bible.json"
SOURCE_URL = "https://raw.githubusercontent.com/seven1m/open-bibles/master/eng-web.usfx.xml"
USFX_TO_NAME = {
"GEN": "Genesis", "EXO": "Exodus", "LEV": "Leviticus", "NUM": "Numbers", "DEU": "Deuteronomy",
"JOS": "Joshua", "JDG": "Judges", "RUT": "Ruth", "1SA": "1 Samuel", "2SA": "2 Samuel",
"1KI": "1 Kings", "2KI": "2 Kings", "1CH": "1 Chronicles", "2CH": "2 Chronicles",
"EZR": "Ezra", "NEH": "Nehemiah", "EST": "Esther", "JOB": "Job", "PSA": "Psalms",
"PRO": "Proverbs", "ECC": "Ecclesiastes", "SNG": "Song of Solomon", "ISA": "Isaiah",
"JER": "Jeremiah", "LAM": "Lamentations", "EZK": "Ezekiel", "DAN": "Daniel",
"HOS": "Hosea", "JOL": "Joel", "AMO": "Amos", "OBA": "Obadiah", "JON": "Jonah",
"MIC": "Micah", "NAM": "Nahum", "HAB": "Habakkuk", "ZEP": "Zephaniah",
"HAG": "Haggai", "ZEC": "Zechariah", "MAL": "Malachi",
"MAT": "Matthew", "MRK": "Mark", "LUK": "Luke", "JHN": "John", "ACT": "Acts",
"ROM": "Romans", "1CO": "1 Corinthians", "2CO": "2 Corinthians", "GAL": "Galatians",
"EPH": "Ephesians", "PHP": "Philippians", "COL": "Colossians",
"1TH": "1 Thessalonians", "2TH": "2 Thessalonians",
"1TI": "1 Timothy", "2TI": "2 Timothy", "TIT": "Titus", "PHM": "Philemon",
"HEB": "Hebrews", "JAS": "James", "1PE": "1 Peter", "2PE": "2 Peter",
"1JN": "1 John", "2JN": "2 John", "3JN": "3 John", "JUD": "Jude", "REV": "Revelation",
}
# Tags whose content is metadata (titles, footnotes, cross-refs, figures) — drop entirely.
DROP_CONTAINERS = (
"id", "h", "toc", "f", "x", "fig", "rq", "ide",
"ms", "mt", "s", "e", "ref", "v1s", "ca", "va", "vp", "xt",
)
_MARKER_RE = re.compile(r"@@@(CHAP|VERSE|VEND):?([^@]*)@@@")
def extract_verses(book_elem, book_name: str) -> list[dict]:
xml_str = ET.tostring(book_elem, encoding="unicode")
# Replace chapter/verse boundary tags with unique sentinels so we can
# split the flat string back into verse-sized chunks after stripping XML.
xml_str = re.sub(r'', r"@@@CHAP:\1@@@", xml_str)
xml_str = re.sub(r'', r"@@@VERSE:\1@@@", xml_str)
xml_str = re.sub(r"", r"@@@VEND@@@", xml_str)
# Drop container tags whose content is metadata, not scripture.
for tag in DROP_CONTAINERS:
xml_str = re.sub(rf"<{tag}\b[^>]*>.*?{tag}>", " ", xml_str, flags=re.DOTALL)
xml_str = re.sub(rf"<{tag}\b[^/]*/>", " ", xml_str)
text = re.sub(r"<[^>]+>", " ", xml_str)
for ent, ch in (("&", "&"), ("<", "<"), (">", ">"), (""", '"'), ("'", "'")):
text = text.replace(ent, ch)
verses: list[dict] = []
chapter: int | None = None
last_verse: int | None = None
chunks: list[str] = []
def flush():
nonlocal last_verse, chunks
if last_verse is not None and chapter is not None:
t = " ".join("".join(chunks).split()).strip()
if t:
verses.append(
{"book": book_name, "chapter": chapter, "verse": last_verse, "text": t}
)
last_verse = None
chunks = []
pos = 0
for m in _MARKER_RE.finditer(text):
chunks.append(text[pos:m.start()])
kind = m.group(1)
arg = m.group(2)
if kind == "CHAP":
flush()
try:
chapter = int(arg)
except ValueError:
chapter = None
elif kind == "VERSE":
flush()
try:
last_verse = int(arg.split("-")[0].split(",")[0])
except ValueError:
last_verse = None
elif kind == "VEND":
flush()
pos = m.end()
chunks.append(text[pos:])
flush()
return verses
def main() -> int:
DATA_DIR.mkdir(parents=True, exist_ok=True)
print(f"Downloading WEB from {SOURCE_URL} ...")
try:
r = requests.get(SOURCE_URL, timeout=90)
r.raise_for_status()
except Exception as e:
print(f"ERROR: download failed: {e}", file=sys.stderr)
return 1
root = ET.fromstring(r.content)
all_verses: list[dict] = []
for book in root.iter("book"):
bid = book.get("id")
if bid not in USFX_TO_NAME:
continue
all_verses.extend(extract_verses(book, USFX_TO_NAME[bid]))
if len(all_verses) < 30000:
print(
f"ERROR: parsed only {len(all_verses)} verses (expected ~31,100).",
file=sys.stderr,
)
return 2
by_ref = {(v["book"], v["chapter"], v["verse"]): v["text"] for v in all_verses}
gen_1_1 = by_ref.get(("Genesis", 1, 1), "")
john_3_16 = by_ref.get(("John", 3, 16), "")
if "beginning" not in gen_1_1.lower() or "world" not in john_3_16.lower():
print("WARNING: spot-check failed for Gen 1:1 / John 3:16.", file=sys.stderr)
OUT_PATH.write_text(json.dumps(all_verses, ensure_ascii=False), encoding="utf-8")
print(f"Wrote {len(all_verses)} verses to {OUT_PATH}")
return 0
if __name__ == "__main__":
raise SystemExit(main())