bible-ref-tagger 0.2.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ from . import books
2
+ from . import config
3
+ from . import engines
4
+ from . import refparser
5
+ from . import providers
6
+ from . import reference
7
+ from . import utils
8
+ from . import tagger
@@ -0,0 +1,127 @@
1
+ import re
2
+ from typing import Dict, Optional
3
+
4
+ CANON = {
5
+ "genesis": ["gen", "ge", "gn"],
6
+ "exodus": ["exod", "exo", "ex"],
7
+ "leviticus": ["lev"],
8
+ "numbers": ["num", "nu", "nm"],
9
+ "deuteronomy": ["deut", "dt"],
10
+ "joshua": ["josh"],
11
+ "judges": ["judg", "jdg"],
12
+ "ruth": ["ruth", "rth"],
13
+ "1 samuel": ["1 sam", "1sam", "1sa"],
14
+ "2 samuel": ["2 sam", "2sam", "2sa"],
15
+ "1 kings": ["1 kgs", "1kgs", "1ki"],
16
+ "2 kings": ["2 kgs", "2kgs", "2ki"],
17
+ "1 chronicles": ["1 chr", "1 chron", "1chron", "1ch"],
18
+ "2 chronicles": ["2 chr", "2 chron", "2chron", "2ch"],
19
+ "ezra": ["ezra"],
20
+ "nehemiah": ["neh"],
21
+ "esther": ["est"],
22
+ "job": ["job"],
23
+ "psalms": ["ps", "psalm", "psa", "pss"],
24
+ "proverbs": ["prov", "prv"],
25
+ "ecclesiastes": ["eccl", "ecc"],
26
+ "song of solomon": ["song", "song of songs", "sos"],
27
+ "isaiah": ["isa"],
28
+ "jeremiah": ["jer"],
29
+ "lamentations": ["lam"],
30
+ "ezekiel": ["ezek", "eze"],
31
+ "daniel": ["dan"],
32
+ "hosea": ["hos"],
33
+ "joel": ["joel"],
34
+ "amos": ["amos"],
35
+ "obadiah": ["obad"],
36
+ "jonah": ["jon"],
37
+ "micah": ["mic"],
38
+ "nahum": ["nah"],
39
+ "habakkuk": ["hab"],
40
+ "zephaniah": ["zeph"],
41
+ "haggai": ["hag"],
42
+ "zechariah": ["zech"],
43
+ "malachi": ["mal"],
44
+ "matthew": ["matt", "mt"],
45
+ "mark": ["mark", "mk"],
46
+ "luke": ["luke", "lk"],
47
+ "john": ["john", "jn"],
48
+ "acts": ["acts"],
49
+ "romans": ["rom"],
50
+ "1 corinthians": ["1 cor", "1cor", "1co"],
51
+ "2 corinthians": ["2 cor", "2cor", "2co"],
52
+ "galatians": ["gal"],
53
+ "ephesians": ["eph"],
54
+ "philippians": ["phil", "php"],
55
+ "colossians": ["col"],
56
+ "1 thessalonians": ["1 thess", "1thess", "1th"],
57
+ "2 thessalonians": ["2 thess", "2thess", "2th"],
58
+ "1 timothy": ["1 tim", "1tim", "1ti"],
59
+ "2 timothy": ["2 tim", "2tim", "2ti"],
60
+ "titus": ["tit"],
61
+ "philemon": ["phlm"],
62
+ "hebrews": ["heb"],
63
+ "james": ["jas"],
64
+ "1 peter": ["1 pet", "1pet", "1pe"],
65
+ "2 peter": ["2 pet", "2pet", "2pe"],
66
+ "1 john": ["1 john", "1john", "1 jn", "1jn", "1jo", "1 jo"],
67
+ "2 john": ["2 john", "2john", "2 jn", "2jn", "2jo", "2 jo"],
68
+ "3 john": ["3 john", "3john", "3 jn", "3jn", "3jo", "3 jo"],
69
+ "jude": ["jude", "jud"],
70
+ "revelation": ["rev", "apoc"]
71
+ }
72
+
73
+ BOOK_LOOKUP: Dict[str, str] = {}
74
+ for canon, abbrs in CANON.items():
75
+ BOOK_LOOKUP[canon] = canon
76
+ for a in abbrs:
77
+ BOOK_LOOKUP[a] = canon
78
+
79
+ def levenshtein(a: str, b: str) -> int:
80
+ if len(a) < len(b):
81
+ return levenshtein(b, a)
82
+ if len(b) == 0:
83
+ return len(a)
84
+ prev = list(range(len(b) + 1))
85
+ for i, ca in enumerate(a):
86
+ curr = [i + 1]
87
+ for j, cb in enumerate(b):
88
+ ins = prev[j + 1] + 1
89
+ dele = curr[j] + 1
90
+ sub = prev[j] + (ca != cb)
91
+ curr.append(min(ins, dele, sub))
92
+ prev = curr
93
+ return prev[-1]
94
+
95
+
96
+ def fuzzy_book(token: str) -> Optional[str]:
97
+ token = token.lower()
98
+ if token in BOOK_LOOKUP:
99
+ return BOOK_LOOKUP[token]
100
+ best = None
101
+ best_dist = 3
102
+ for k in BOOK_LOOKUP:
103
+ d = levenshtein(token, k)
104
+ if d < best_dist:
105
+ best = BOOK_LOOKUP[k]
106
+ best_dist = d
107
+ return best
108
+
109
+
110
+ def normalize_book_name(book: str) -> Optional[str]:
111
+ book = book.strip().lower()
112
+
113
+ roman_numbers = {
114
+ "i": "1",
115
+ "ii": "2",
116
+ "iii": "3"
117
+ }
118
+
119
+ match = re.match(r"^(i{1,3})\.?\s+(.+)$", book)
120
+ if match:
121
+ numeral, name = match.groups()
122
+ book = f"{roman_numbers[numeral]} {name}"
123
+
124
+ if book in BOOK_LOOKUP:
125
+ return BOOK_LOOKUP[book]
126
+
127
+ return fuzzy_book(book)
@@ -0,0 +1,16 @@
1
+ import os
2
+ from pathlib import Path
3
+
4
+ APP_NAME = "bible-ref-tagger"
5
+ LEB_JSON_URL = "https://raw.githubusercontent.com/scrollmapper/bible_databases/refs/heads/master/sources/en/LEB/LEB.json"
6
+
7
+
8
+ def get_state_dir() -> Path:
9
+ base = os.environ.get("XDG_STATE_HOME")
10
+ if base:
11
+ return Path(base) / APP_NAME
12
+ return Path.home() / ".local" / "state" / APP_NAME
13
+
14
+
15
+ STATE_DIR = get_state_dir()
16
+ CACHE_PATH = STATE_DIR / "bible_leb.json"
@@ -0,0 +1,12 @@
1
+ class BibleEngine:
2
+ def __init__(self, name, fn):
3
+ self.name = name
4
+ self.build = fn
5
+
6
+
7
+ ENGINES = {
8
+ "esv": BibleEngine("ESV", lambda r: f"https://www.esv.org/{r.replace(' ', '+')}/"),
9
+ "biblegateway": BibleEngine("BibleGateway", lambda r: f"https://www.biblegateway.com/passage/?search={r.replace(' ', '+')}"),
10
+ "youversion": BibleEngine("YouVersion", lambda r: f"https://www.bible.com/search/bible?q={r.replace(' ', '%20')}"),
11
+ "logos": BibleEngine("Logos", lambda r: f"https://ref.ly/{r.replace(' ', '')}")
12
+ }
@@ -0,0 +1,90 @@
1
+ import json
2
+ from typing import List, Tuple
3
+
4
+ import requests
5
+
6
+ from .reference import Reference
7
+ from .config import LEB_JSON_URL, CACHE_PATH
8
+ from .books import normalize_book_name
9
+
10
+
11
+ class VerseProvider:
12
+ def _load(self, url: str):
13
+ raise NotImplementedError
14
+
15
+ def get(self, ref: Reference) -> str:
16
+ raise NotImplementedError
17
+
18
+ def get_passage(self, ref: "Ref") -> List[Tuple[int, int, str]]:
19
+ raise NotImplementedError
20
+
21
+
22
+ class JSONVerseProvider(VerseProvider):
23
+ def __init__(self, url=LEB_JSON_URL, cache_path=CACHE_PATH):
24
+ self.cache_path = cache_path
25
+ self.data = self._load(url)
26
+
27
+ def _load(self, url: str):
28
+ self.cache_path.parent.mkdir(parents=True, exist_ok=True)
29
+
30
+ if self.cache_path.exists():
31
+ with open(self.cache_path, "r", encoding="utf-8") as f:
32
+ raw = json.load(f)
33
+ else:
34
+ r = requests.get(url)
35
+ r.raise_for_status()
36
+ raw = r.json()
37
+ with open(self.cache_path, "w", encoding="utf-8") as f:
38
+ json.dump(raw, f, ensure_ascii=False, indent=2)
39
+
40
+ bible = {}
41
+ for book in raw.get("books", []):
42
+ canon = normalize_book_name(book["name"])
43
+ if not canon:
44
+ continue
45
+ canon = canon.lower()
46
+ bible[canon] = {}
47
+ for ch in book.get("chapters", []):
48
+ ch_num = ch["chapter"]
49
+ bible[canon][ch_num] = {v["verse"]: v["text"] for v in ch.get("verses", [])}
50
+ return bible
51
+
52
+ def get(self, ref: Reference) -> str:
53
+ verses = self.get_passage(ref)
54
+ if not verses:
55
+ return "[Verse not found]"
56
+ return verses[0][2]
57
+
58
+ def get_passage(self, ref: Reference) -> List[Tuple[int, int, str]]:
59
+ book_name = ref.book.lower()
60
+ book = self.data.get(book_name, {})
61
+ if not book:
62
+ return []
63
+
64
+ start_ch, start_vs = ref.start_ch, ref.start_vs or 1
65
+ end_ch, end_vs = ref.end_ch or start_ch, ref.end_vs
66
+
67
+ result = []
68
+ for ch_num in range(start_ch, end_ch + 1):
69
+ verses = book.get(ch_num, {})
70
+ if not verses:
71
+ continue
72
+
73
+ if ch_num == start_ch and ch_num == end_ch:
74
+ first_vs = start_vs
75
+ last_vs = end_vs if end_vs is not None else start_vs
76
+ elif ch_num == start_ch:
77
+ first_vs = start_vs
78
+ last_vs = max(verses.keys())
79
+ elif ch_num == end_ch:
80
+ first_vs = 1
81
+ last_vs = end_vs if end_vs is not None else max(verses.keys())
82
+ else:
83
+ first_vs = 1
84
+ last_vs = max(verses.keys())
85
+
86
+ for vs_num in sorted(verses.keys()):
87
+ if first_vs <= vs_num <= last_vs:
88
+ result.append((ch_num, vs_num, verses[vs_num]))
89
+
90
+ return result
@@ -0,0 +1,28 @@
1
+ from dataclasses import dataclass
2
+ from typing import Optional
3
+
4
+
5
+ @dataclass
6
+ class Reference:
7
+ book: str
8
+ start_ch: int
9
+ start_vs: Optional[int] = None
10
+ end_ch: Optional[int] = None
11
+ end_vs: Optional[int] = None
12
+ display: Optional[str] = None
13
+
14
+ def canonical(self):
15
+ s = f"{self.book.title()} {self.start_ch}"
16
+
17
+ if self.start_vs is not None:
18
+ s += f":{self.start_vs}"
19
+
20
+ if self.end_vs is not None:
21
+ if self.end_ch is not None and self.end_ch != self.start_ch:
22
+ s += f"–{self.end_ch}:{self.end_vs}"
23
+ else:
24
+ s += f"–{self.end_vs}"
25
+ elif self.end_ch is not None:
26
+ s += f"–{self.end_ch}"
27
+
28
+ return s
@@ -0,0 +1,87 @@
1
+ import re
2
+ from typing import Tuple, Optional, List
3
+
4
+ from .reference import Reference
5
+ from .books import BOOK_LOOKUP
6
+
7
+ RANGE = re.compile(r"[–-]")
8
+ LIST = re.compile(r"(?<!e\.g\.)(?<!i\.e\.)([;,])(?=\s*(?:\d|cf\.|e\.g\.|i\.e\.))", re.IGNORECASE)
9
+ QUALIFIER_PATTERN = r"(?:cf\.|e\.g\.|i\.e\.)(?:,)?"
10
+ QUALIFIER = re.compile(rf"^{QUALIFIER_PATTERN}\s+", re.IGNORECASE)
11
+ BOOK_PATTERN = r"|".join(sorted(map(re.escape, BOOK_LOOKUP.keys()), key=len, reverse=True))
12
+ REF = r"\d+(?::\d+)?(?:[–-]\d+(?::\d+)?)?(?:ff|f)?"
13
+ TAIL = rf"\s+({REF}(?:\s*[,;]\s*(?:{QUALIFIER_PATTERN}\s+)?{REF})*)"
14
+ MAIN = re.compile(rf"\b({BOOK_PATTERN})\b({TAIL})", re.IGNORECASE | re.VERBOSE)
15
+
16
+
17
+ def parse_range(a: str, b: str, current_ch: int) -> Tuple[int, Optional[int], int, Optional[int]]:
18
+ if ":" in a:
19
+ ch1, vs1 = map(int, a.split(":"))
20
+ else:
21
+ ch1, vs1 = current_ch, int(a)
22
+
23
+ if ":" in b:
24
+ ch2, vs2 = map(int, b.split(":"))
25
+ else:
26
+ ch2, vs2 = ch1, int(b)
27
+ return ch1, vs1, ch2, vs2
28
+
29
+
30
+ def parse_part(p, current_ch):
31
+ suffix = ""
32
+ if p.lower().endswith("ff"):
33
+ suffix = "ff"
34
+ p = p[:-2].strip()
35
+ elif p.lower().endswith("f"):
36
+ suffix = "f"
37
+ p = p[:-1].strip()
38
+ if ":" in p:
39
+ ch, vs = map(int, p.split(":"))
40
+ else:
41
+ ch, vs = current_ch, int(p)
42
+ return ch, vs, suffix
43
+
44
+
45
+ def parse_tail(book: str, tail: str) -> List[tuple[Reference, str, str, str]]:
46
+ parts = LIST.split(tail)
47
+ refs = []
48
+ ctx_ch = None
49
+ separator = ""
50
+ for part in parts:
51
+ part = part.strip()
52
+ if not part:
53
+ continue
54
+ if part in ",;":
55
+ separator = part
56
+ continue
57
+ qualifier = ""
58
+ match = QUALIFIER.match(part)
59
+ if match:
60
+ qualifier = match.group(0)
61
+ part = part[match.end():].strip()
62
+ display = part
63
+ if RANGE.search(part):
64
+ a, b = RANGE.split(part, 1)
65
+ ch1, vs1, follows1 = parse_part(a.strip(), ctx_ch or 1)
66
+ ch2, vs2, follows2 = parse_part(b.strip(), ch1)
67
+ end_ch = ch2
68
+ end_vs = vs2 + 1 if follows2 else vs2
69
+ refs.append((Reference(book, ch1, vs1, end_ch, end_vs), display, separator, qualifier))
70
+ ctx_ch = end_ch
71
+ elif ":" in part:
72
+ ch, vs, suffix = parse_part(part, ctx_ch or 1)
73
+ if suffix == "f":
74
+ refs.append((Reference(book, ch, vs, ch, vs + 1), display, separator, qualifier))
75
+ else:
76
+ refs.append((Reference(book, ch, vs), display, separator, qualifier))
77
+ ctx_ch = ch
78
+ else:
79
+ if ctx_ch is None:
80
+ raise ValueError(f"Cannot parse verse without chapter context: {part}")
81
+ ch, vs, suffix = parse_part(part, ctx_ch)
82
+ if suffix == "f":
83
+ refs.append((Reference(book, ch, vs, ch, vs + 1), display, separator, qualifier))
84
+ else:
85
+ refs.append((Reference(book, ch, vs), display, separator, qualifier))
86
+ separator = ""
87
+ return refs
@@ -0,0 +1,44 @@
1
+ from typing import Optional
2
+
3
+ from bible_ref_tagger.refparser import parse_tail, MAIN
4
+ from bible_ref_tagger.books import fuzzy_book
5
+ from bible_ref_tagger.engines import ENGINES
6
+ from bible_ref_tagger.providers import VerseProvider
7
+ from bible_ref_tagger.utils import sbl_format, build_tooltip, build_ref_html
8
+
9
+
10
+ class BibleRefTagger:
11
+ def __init__(self, bible_translation="esv", engine: str = "biblegateway", provider: Optional[VerseProvider] = None):
12
+ self.translation = bible_translation
13
+ self.engine = engine
14
+ self.engine_obj = ENGINES.get(engine, ENGINES["biblegateway"])
15
+ self.provider = provider
16
+
17
+ def tag(self, html_txt: str) -> str:
18
+ def repl(m):
19
+ raw_book = m.group(1).lower()
20
+ book = fuzzy_book(raw_book)
21
+ if not book:
22
+ return m.group(0)
23
+ parsed_refs = parse_tail(book, m.group(2))
24
+ rendered = []
25
+ for i, (r, display_text, separator, qualifier) in enumerate(parsed_refs):
26
+ canon = r.canonical()
27
+ url = self.engine_obj.build(canon)
28
+ sbl = sbl_format(r)
29
+ tooltip_txt = ""
30
+ if self.provider:
31
+ try:
32
+ verses = self.provider.get_passage(r)
33
+ if verses:
34
+ text = " ".join(t for _, _, t in verses)
35
+ tooltip_txt = build_tooltip(text, sbl, url)
36
+ except Exception:
37
+ tooltip_txt = "[Unable to load passage]"
38
+ if i == 0:
39
+ display_text = f"{m.group(1)} {display_text}"
40
+ ref_html = build_ref_html(canon, sbl, tooltip_txt, display_text)
41
+ rendered.append((separator, qualifier, ref_html))
42
+ return "".join(f"{separator} {qualifier}{ref}" for separator, qualifier, ref in rendered)
43
+
44
+ return MAIN.sub(repl, html_txt)
@@ -0,0 +1,47 @@
1
+ import html as html_lib
2
+ import urllib.parse
3
+
4
+ from .reference import Reference
5
+
6
+
7
+ def build_tooltip(text: str, sbl: str, url: str) -> str:
8
+ return (
9
+ f'<div class="bibleref-tooltip-content">'
10
+ f'<div class="bibleref-tooltip-passage">{html_lib.escape(text)}</div>'
11
+ f'<div class="bibleref-tooltip-links">'
12
+ f'<a class="bibleref-bible-link" data-bible="bible://{urllib.parse.quote(sbl)}">'
13
+ f"{html_lib.escape(sbl)}</a>"
14
+ f'<span class="bibleref-link-separator">&nbsp;or&nbsp;</span>'
15
+ f'<a class="bibleref-web-link" href="{html_lib.escape(url)}">Read on the web…</a>'
16
+ f"</div>"
17
+ f"</div>"
18
+ )
19
+
20
+
21
+ def build_ref_html(canon: str, sbl: str, tooltip: str, display_text: str) -> str:
22
+ return (
23
+ f'<div class="bibleref">'
24
+ f'<span class="bibleref-trigger" data-ref="{html_lib.escape(canon)}" role="button" tabindex="0">'
25
+ f'{html_lib.escape(display_text)}'
26
+ f'</span>'
27
+ f'<div class="bibleref-tooltip" data-sbl="{html_lib.escape(sbl)}">{tooltip}</div>'
28
+ f"</div>"
29
+ )
30
+
31
+
32
+ def sbl_format(ref: Reference) -> str:
33
+ b = ref.book.title()
34
+ s = f"{b} {ref.start_ch}"
35
+
36
+ if ref.start_vs is not None:
37
+ s += f":{ref.start_vs}"
38
+
39
+ if ref.end_vs is not None:
40
+ if ref.end_ch is not None and ref.end_ch != ref.start_ch:
41
+ s += f"–{ref.end_ch}:{ref.end_vs}"
42
+ else:
43
+ s += f"–{ref.end_vs}"
44
+ elif ref.end_ch is not None:
45
+ s += f"–{ref.end_ch}"
46
+
47
+ return s