-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbolls.py
More file actions
1790 lines (1547 loc) · 60 KB
/
bolls.py
File metadata and controls
1790 lines (1547 loc) · 60 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# bolls.py - Python client for bolls.life API
import hashlib
import json
import os
import re
import sys
import tempfile
import time
from io import BytesIO
try:
import pycurl
except Exception as exc:
print(f"Error: pycurl is required: {exc}", file=sys.stderr)
sys.exit(2)
try:
import jq as jqmod
except Exception:
jqmod = None
BASE_URL = "https://bolls.life"
PARALLEL_CHAPTER_MAX_VERSE = 300
OUTPUT_LINE_THRESHOLD = 1000
OUTPUT_FILE_PREFIX = "bolls_output"
LOCAL_TRANSLATIONS_DIR = "bible-translations"
SOFT_LINK_PROBE_CHAPTER = 1
SOFT_LINK_PROBE_VERSE = 1
_MAX_VERSE_CACHE: dict[tuple[str, int, int], int] = {}
_SOFT_LINK_CACHE: dict[tuple[str, str], int] = {}
_LANGUAGE_MAP: dict[str, str] | None = None
_LANGUAGE_TRANSLATIONS: dict[str, set[str]] | None = None
_LOCAL_TRANSLATION_INDEX_CACHE: dict[str, dict[int, dict[int, list[dict]]]] = {}
JQ_PRETTY_FILTER = r"""
def indent($n): " " * ($n * 4);
def strip_html:
if type == "string" then
gsub("(?is)<s[^>]*>.*?</s>"; "")
| gsub("<(br|p) */?>"; "\n")
| gsub("<[^>]*>"; "")
else . end;
def scalar:
if . == null then "null"
elif (type == "string") then (strip_html)
else tostring
end;
def is_scalar: (type == "string" or type == "number" or type == "boolean" or type == "null");
def keyfmt: gsub("_"; " ");
def fmt($v; $n):
if ($v|type) == "object" then
$v|to_entries|map(
if (.value|type) == "object" or (.value|type) == "array" then
"\(indent($n))\(.key|keyfmt):\n\(fmt(.value; $n+1))"
else
"\(indent($n))\(.key|keyfmt): \(.value|scalar)"
end
)|join("\n")
elif ($v|type) == "array" then
if ($v|length) == 0 then ""
else
($v|map(fmt(.;$n))) as $lines
| if ($v|all(is_scalar)) then ($lines|join("\n")) else ($lines|join("\n\n")) end
end
else
"\(indent($n))\($v|scalar)"
end;
fmt(.;0)
""".strip()
JQ_TEXT_COMMENT = r"""
def keep_text_comment:
if type == "array" then map(keep_text_comment) | map(select(. != null and . != ""))
elif type == "object" then
if (has("comment") and .comment != null) then
[ .text, {comment} ]
else
.text
end
else .
end;
keep_text_comment
""".strip()
JQ_TEXT_ONLY = r"""
def keep_text_only:
if type == "array" then map(keep_text_only) | map(select(. != null and . != ""))
elif type == "object" then
.text
else .
end;
keep_text_only
""".strip()
def _print_help() -> None:
print("""
Command flags (choose one):
-h / --help
Show this help page
-d / --dictionaries
List all available Hebrew/Greek dictionaries
-D / --define <dictionary> <Hebrew/Greek word>
Get definitions for a Hebrew or Greek word
-t / --translations
List all available Bible translations
-b / --books <translation>
List all books of a chosen translation
-v / --verses <translation(s)> <book> [chapter(s) [:verse(s)] ]
Get text from the Bible
-r / --random <translation>
Get a single random verse
-s / --search <translation> [options] <search term>
Search text in verses
Search options (choose any amount or none when using -s):
-c / --match-case
Make search case-sensitive
-w / --match-whole
Only search exact phrase matches (requires multiple words)
-B / --book <book/ot/nt>
Search in a specific book, or in just the Old or New Testament
-p / --page <#>
Go to a specific page of search results (each page has up to 128 results by default)
-l / --page-limit <#>
Limits the number of search results displayed per page
Notes:
<translation> must be the abbreviation, not the full name. Multiple translations are separated by commas.
<book> can be a number, full name, or short name (e.g. "1th" instead of "1 Thessalonians").
[verse(s)] and [chapter(s)] can be a single number, multiple numbers separated by commas (e.g. 1,5,9), or a range (e.g. 13-17).
When using -v, omit verses to get a full chapter, and omit chapters to get the full book.
Use slashes to use multiple -v commands at once (see examples).
Modifier flags (choose one or none):
-j / --raw-json
Disable formatting
-a / --include-all
Include everything (verse id, translation, book number, etc.) in -v
-C / --include-comments
Include commentary (currently not working without -n)
-f / --file
Save output to a .txt or .json file in current working directory
-n / --no-api
Use local translation files for -v (downloads if missing)
-u / --url
Print the URL (and POST body) that would have been called from the API
Examples:
bolls --dictionaries
Lists all the available dictionaries.
bolls -D BDBT אֹ֑ור
Translates אֹ֑ור to English using Brown-Driver-Briggs' Hebrew Definitions / Thayer's Greek Definitions.
bolls --translations
Lists all the available Bible translations.
bolls -b AMP
Lists the books in the Amplified translation.
bolls --verses ESV genesis 1 --no-api --include-comments
bolls -v esv 1 1 -n -C
Shows the text of Genesis 1 from a downloaded copy of the English Standard Version, including commentary.
bolls --verses nlt,nkjv exodus 2:1,5,7 -a
Shows Exodus 2:1, 2:5, and 2:7 from both the New Living Translation and the New King James Version, with all the descriptive information.
bolls -v niv jon 1:1-3 / esv luk 2 / ylt,nkjv deu 6:5
Shows John 1:1-3 from the New International Version, Luke 2 from the English Standard Version, and Deuteronomy 6:5 from Young's Literal Translation and the New King James Version.
bolls --verses niv 1 Corinthians
Shows the entirety of 1 Corinthians from the New international Version.
bolls -r MSG -j -f
Shows a random verse from the Message translation in raw JSON format, and saves it to a file.
bolls --random nlt -u
Shows the URL that would have been used to get a random verse from the New Living Translation.
bolls -s ylt -c -w -l 3 Jesus said
bolls --search YLT --match-case --match-whole --page-limit 3 Jesus said
Searches Young's Literal Translation for "Jesus said", case-sensitive and matching the entire phrase, with a limit of 3 results.
""".strip()
)
def _curl_get(url: str) -> str:
buf = BytesIO()
curl = pycurl.Curl()
try:
curl.setopt(pycurl.URL, url)
curl.setopt(pycurl.WRITEDATA, buf)
curl.setopt(pycurl.FAILONERROR, True)
curl.setopt(pycurl.NOSIGNAL, True)
curl.perform()
except pycurl.error as exc:
errno, msg = exc.args
print(f"Error: HTTP request failed ({errno}): {msg}", file=sys.stderr)
raise
finally:
curl.close()
return buf.getvalue().decode("utf-8", errors="replace")
def _curl_post(url: str, body: str) -> str:
buf = BytesIO()
curl = pycurl.Curl()
try:
curl.setopt(pycurl.URL, url)
curl.setopt(pycurl.WRITEDATA, buf)
curl.setopt(pycurl.FAILONERROR, True)
curl.setopt(pycurl.NOSIGNAL, True)
curl.setopt(pycurl.HTTPHEADER, ["Content-Type: application/json"])
curl.setopt(pycurl.POSTFIELDS, body.encode("utf-8"))
curl.perform()
except pycurl.error as exc:
errno, msg = exc.args
print(f"Error: HTTP request failed ({errno}): {msg}", file=sys.stderr)
raise
finally:
curl.close()
return buf.getvalue().decode("utf-8", errors="replace")
def _jq_pretty(raw: str, jq_prefix: str | None) -> str:
program = JQ_PRETTY_FILTER
if jq_prefix:
program = f"{jq_prefix}\n| {JQ_PRETTY_FILTER}"
compiled = jqmod.compile(program)
out = compiled.input_text(raw).first()
if out is None:
return ""
if isinstance(out, (dict, list)):
return json.dumps(out, indent=2, ensure_ascii=False)
return str(out)
def _drop_translation_only_entries(value: object) -> object:
if isinstance(value, list):
out = []
for item in value:
cleaned = _drop_translation_only_entries(item)
if cleaned is None:
continue
out.append(cleaned)
return out
if isinstance(value, dict):
# Drop objects that only contain a translation and no text/meaningful fields
if "translation" in value and "text" not in value:
if all(k == "translation" for k in value.keys()):
return None
if "translation" in value and (value.get("text") is None or value.get("text") == ""):
has_meaningful = False
for k, v in value.items():
if k in ("translation", "text"):
continue
if v not in (None, "", [], {}):
has_meaningful = True
break
if not has_meaningful:
return None
cleaned = {}
for k, v in value.items():
cleaned_v = _drop_translation_only_entries(v)
if cleaned_v is None:
continue
cleaned[k] = cleaned_v
return cleaned
return value
def _strip_s_tags(text: str) -> str:
return re.sub(r"<s[^>]*>.*?</s>", "", text, flags=re.IGNORECASE | re.DOTALL)
def _strip_s_tags_in_data(value: object) -> object:
if isinstance(value, str):
return _strip_s_tags(value)
if isinstance(value, list):
return [_strip_s_tags_in_data(v) for v in value]
if isinstance(value, dict):
return {k: _strip_s_tags_in_data(v) for k, v in value.items()}
return value
def _strip_html(text: str) -> str:
text = re.sub(r"(?is)<s[^>]*>.*?</s>", "", text)
text = re.sub(r"(?i)<(br|p)\s*/?>", "\n", text)
text = re.sub(r"<[^>]*>", "", text)
return text
def _value_to_int(value: object) -> int | None:
if isinstance(value, bool):
return None
if isinstance(value, int):
return value
if isinstance(value, str) and value.isdigit():
return int(value)
return None
def _get_chapter_value(item: dict) -> int | None:
return _value_to_int(item.get("chapter"))
def _get_verse_value(item: dict) -> int | None:
return _value_to_int(item.get("verse"))
def _get_book_value(item: dict) -> int | None:
return _value_to_int(item.get("book"))
def _flatten_verse_items(data: object) -> list[dict]:
out: list[dict] = []
if isinstance(data, dict):
out.append(data)
return out
if isinstance(data, list):
for item in data:
if isinstance(item, list):
out.extend(_flatten_verse_items(item))
elif isinstance(item, dict):
out.append(item)
return out
return out
def _format_verses(raw: str, include_comments: bool) -> str | None:
def render_items(items: list[dict]) -> str:
parts: list[str] = []
last_chapter: int | None = None
for item in items:
if not isinstance(item, dict):
continue
comment_val = item.get("comment") if include_comments else None
text_val = item.get("text")
if text_val is None:
if include_comments and comment_val not in (None, ""):
text_val = ""
else:
continue
if not isinstance(text_val, str):
text_val = str(text_val)
text_val = _strip_html(text_val)
verse_val = _get_verse_value(item)
verse_prefix = f"[{verse_val}] " if verse_val is not None else ""
if include_comments and comment_val not in (None, ""):
if not isinstance(comment_val, str):
comment_val = str(comment_val)
block = f"{verse_prefix}{text_val} [{comment_val}]\n\n"
else:
block = f"{verse_prefix}{text_val}"
chapter_val = _get_chapter_value(item)
if parts:
if chapter_val is not None and last_chapter is not None and chapter_val != last_chapter:
parts.append("\n\n{name} {chapter_val}\n")
else:
parts.append(" ")
parts.append(block)
if chapter_val is not None:
last_chapter = chapter_val
return "".join(parts)
try:
data = json.loads(raw)
except Exception:
return None
blocks: list[str] = []
if isinstance(data, list):
has_nested = any(isinstance(item, list) for item in data)
if has_nested:
for group in data:
if isinstance(group, list):
rendered = render_items(_flatten_verse_items(group))
elif isinstance(group, dict):
rendered = render_items([group])
else:
rendered = ""
if rendered:
blocks.append(rendered)
else:
rendered = render_items(_flatten_verse_items(data))
if rendered:
blocks.append(rendered)
else:
rendered = render_items(_flatten_verse_items(data))
if rendered:
blocks.append(rendered)
if not blocks:
return None
out = "\n\n".join(blocks)
if out and not out.endswith("\n"):
out += "\n"
return out
def _format_json(
raw: str,
raw_json: bool,
jq_prefix: str | None = None,
drop_translation_only: bool = False,
) -> str:
if drop_translation_only:
try:
data = json.loads(raw)
except Exception:
data = None
if data is not None:
data = _drop_translation_only_entries(data)
raw = json.dumps(data, ensure_ascii=False)
if raw_json:
return raw
if jqmod is not None:
try:
rendered = _jq_pretty(raw, jq_prefix)
if rendered and not rendered.endswith("\n"):
rendered += "\n"
return rendered
except Exception:
pass
try:
data = json.loads(raw)
except Exception:
return raw
data = _strip_s_tags_in_data(data)
return json.dumps(data, indent=2, ensure_ascii=False) + "\n"
def _print_json(
raw: str,
raw_json: bool,
jq_prefix: str | None = None,
drop_translation_only: bool = False,
) -> None:
sys.stdout.write(_format_json(raw, raw_json, jq_prefix, drop_translation_only))
def _line_count(text: str) -> int:
if not text:
return 0
return len(text.splitlines())
def _next_output_path(ext: str) -> str:
ts = time.strftime("%Y%m%d_%H%M%S")
base = f"{OUTPUT_FILE_PREFIX}_{ts}"
directory = os.getcwd()
path = os.path.join(directory, f"{base}.{ext}")
if not os.path.exists(path):
return path
for i in range(1, 1000):
alt = os.path.join(directory, f"{base}_{i}.{ext}")
if not os.path.exists(alt):
return alt
return os.path.join(directory, f"{base}_{int(time.time())}.{ext}")
def _save_output(text: str, raw_json: bool) -> str:
ext = "json" if raw_json else "txt"
path = _next_output_path(ext)
with open(path, "w", encoding="utf-8") as f:
f.write(text)
return path
def _write_output(text: str, raw_json: bool, force_file: bool) -> None:
sys.stdout.write(text)
line_count = _line_count(text)
if force_file or line_count > OUTPUT_LINE_THRESHOLD:
path = _save_output(text, raw_json)
print(f"Saved output to {path}", file=sys.stderr)
def _format_url(method: str, url: str, body: str | None = None) -> str:
method_up = method.upper()
if method_up == "POST" and body is not None:
body_out = body.rstrip("\n")
return f"{method_up} {url}\n{body_out}\n"
return f"{method_up} {url}\n"
def _split_slash_groups(args: list[str]) -> list[list[str]]:
groups = []
current = []
for token in args:
if token == "/":
if current:
groups.append(current)
current = []
continue
if "/" not in token or token.startswith("/") or token.startswith("./") or token.startswith("../"):
current.append(token)
continue
parts = token.split("/")
for i, part in enumerate(parts):
part = part.strip()
if part:
current.append(part)
if i < len(parts) - 1:
if current:
groups.append(current)
current = []
if current:
groups.append(current)
return groups
def _is_single_chapter_book_for_translation(translation: str, book: str) -> bool:
try:
book_id = _book_to_id(
translation,
book,
allow_language_fallback=True,
)
except Exception:
return False
try:
data = _load_books_data()
except Exception:
return False
keys = {k.lower(): k for k in data.keys()}
tkey = translation.lower()
if tkey not in keys:
return False
entry = None
for item in data[keys[tkey]]:
if isinstance(item, dict) and item.get("bookid") == book_id:
entry = item
break
chapters = _chapters_from_entry(entry)
return bool(chapters and len(chapters) == 1)
def _group_translation_info(group: list[str]) -> tuple[set[str], bool]:
if not group:
return set(), False
if len(group) < 2:
return set(), False
translations = set(_parse_translations_arg(group[0]))
ref_args = group[1:]
if not ref_args:
return translations, False
mode, book, chapters, _ = _parse_v_reference(ref_args)
if mode == "book":
is_multi_chapter = any(
not _is_single_chapter_book_for_translation(translation, book)
for translation in translations
)
return translations, is_multi_chapter
if mode == "chapters":
return translations, bool(chapters and len(chapters) > 1)
return translations, False
def _is_local_translation_cached(translation: str) -> bool:
cache_path = _local_translation_cache_path(translation)
return os.path.isfile(cache_path) and os.path.getsize(cache_path) > 0
def _should_default_no_api_for_group(group: list[str]) -> bool:
translations, is_multi_chapter = _group_translation_info(group)
return is_multi_chapter and len(translations) == 1
def _enforce_no_api_download_limit(groups: list[list[str]], no_api_requested: bool) -> None:
no_api_translations: set[str] = set()
for group in groups:
translations, _ = _group_translation_info(group)
effective_no_api = no_api_requested or _should_default_no_api_for_group(group)
if effective_no_api:
no_api_translations.update(t.upper() for t in translations)
if len(no_api_translations) <= 1:
return
uncached = sorted(t for t in no_api_translations if not _is_local_translation_cached(t))
if len(uncached) > 1:
missing = ", ".join(uncached)
raise ValueError(
"Refusing request: this would require downloading multiple uncached translations "
f"({missing}). Download those translations manually, or use separate commands for this request."
)
def _local_translation_cache_dir() -> str:
return os.path.join(os.getcwd(), LOCAL_TRANSLATIONS_DIR)
def _local_translation_cache_path(translation: str) -> str:
return os.path.join(_local_translation_cache_dir(), f"{translation.upper()}.json")
def _local_sections_cache_dir(translation: str) -> str:
return os.path.join(_local_translation_cache_dir(), "sections", translation.upper())
def _ensure_local_translation_cache(translation: str) -> str:
translation_up = translation.upper()
cache_dir = _local_translation_cache_dir()
os.makedirs(cache_dir, exist_ok=True)
cache_path = _local_translation_cache_path(translation_up)
if os.path.isfile(cache_path) and os.path.getsize(cache_path) > 0:
return cache_path
url = f"{BASE_URL}/static/translations/{translation_up}.json"
raw = _curl_get(url)
_validate_json(raw)
with open(cache_path, "w", encoding="utf-8") as f:
f.write(raw)
return cache_path
def _collect_translation_verse_items(data: object, translation: str) -> list[dict]:
out: list[dict] = []
def walk(node: object) -> None:
if isinstance(node, list):
for child in node:
walk(child)
return
if not isinstance(node, dict):
return
book_val = _get_book_value(node)
chapter_val = _get_chapter_value(node)
text_val = node.get("text")
comment_val = node.get("comment")
has_content = text_val not in (None, "") or comment_val not in (None, "")
if book_val is not None and chapter_val is not None and has_content:
verse_obj = dict(node)
if not isinstance(verse_obj.get("translation"), str):
verse_obj["translation"] = translation.upper()
out.append(verse_obj)
return
for child in node.values():
if isinstance(child, (list, dict)):
walk(child)
walk(data)
return out
def _translation_chapter_index(translation: str) -> dict[int, dict[int, list[dict]]]:
translation_up = translation.upper()
cached = _LOCAL_TRANSLATION_INDEX_CACHE.get(translation_up)
if cached is not None:
return cached
cache_path = _ensure_local_translation_cache(translation_up)
with open(cache_path, "r", encoding="utf-8") as f:
data = json.load(f)
verses = _collect_translation_verse_items(data, translation_up)
index: dict[int, dict[int, list[dict]]] = {}
for item in verses:
book_val = _get_book_value(item)
chapter_val = _get_chapter_value(item)
if book_val is None or chapter_val is None:
continue
index.setdefault(book_val, {}).setdefault(chapter_val, []).append(item)
for chapters in index.values():
for chapter_num, chapter_items in list(chapters.items()):
chapters[chapter_num] = sorted(
chapter_items,
key=lambda v: (_get_verse_value(v) is None, _get_verse_value(v) or 0),
)
_LOCAL_TRANSLATION_INDEX_CACHE[translation_up] = index
return index
def _local_chapters_for_book(translation: str, book_id: int) -> list[int]:
index = _translation_chapter_index(translation)
chapters = index.get(int(book_id), {})
return sorted(chapters.keys())
def _local_verses_for_chapter(translation: str, book_id: int, chapter: int) -> list[int]:
index = _translation_chapter_index(translation)
chapter_items = index.get(int(book_id), {}).get(int(chapter), [])
out: list[int] = []
seen: set[int] = set()
for item in chapter_items:
verse_num = _get_verse_value(item)
if verse_num is None or verse_num in seen:
continue
seen.add(verse_num)
out.append(verse_num)
return out
def _section_cache_path(translation: str, request: dict) -> str:
section_dir = _local_sections_cache_dir(translation)
os.makedirs(section_dir, exist_ok=True)
key = json.dumps(request, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
digest = hashlib.sha1(key.encode("utf-8")).hexdigest()
return os.path.join(section_dir, f"{digest}.json")
def _build_local_section(translation: str, request: dict) -> list[dict]:
index = _translation_chapter_index(translation)
book_val = _value_to_int(request.get("book"))
if book_val is None:
return []
chapters = index.get(book_val, {})
if not chapters:
return []
chapter_raw = request.get("chapter")
chapter_val = _value_to_int(chapter_raw)
if chapter_raw is None:
chapter_numbers = sorted(chapters.keys())
elif chapter_val is None:
return []
elif chapter_val not in chapters:
return []
else:
chapter_numbers = [chapter_val]
verses_req = request.get("verses")
verse_list: list[int] | None
if verses_req is None:
verse_list = None
elif isinstance(verses_req, list):
verse_list = []
for value in verses_req:
parsed = _value_to_int(value)
if parsed is not None:
verse_list.append(parsed)
else:
parsed = _value_to_int(verses_req)
verse_list = [parsed] if parsed is not None else []
out: list[dict] = []
for chapter_number in chapter_numbers:
chapter_items = chapters.get(chapter_number, [])
if verse_list is None:
selected = chapter_items
else:
by_verse: dict[int, list[dict]] = {}
for item in chapter_items:
verse_num = _get_verse_value(item)
if verse_num is None:
continue
by_verse.setdefault(verse_num, []).append(item)
selected = []
for verse_num in verse_list:
selected.extend(by_verse.get(verse_num, []))
for item in selected:
out_item = dict(item)
if not isinstance(out_item.get("translation"), str):
out_item["translation"] = translation.upper()
out.append(out_item)
return out
def _load_local_section(translation: str, request: dict) -> list[dict]:
cache_path = _section_cache_path(translation, request)
if os.path.isfile(cache_path) and os.path.getsize(cache_path) > 0:
try:
with open(cache_path, "r", encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, list):
return data
except Exception:
pass
section = _build_local_section(translation, request)
with open(cache_path, "w", encoding="utf-8") as f:
json.dump(section, f, ensure_ascii=False)
return section
def _fetch_verses_from_local_cache(requests_obj: list[dict]) -> str:
out: list[list[dict]] = []
for req in requests_obj:
if not isinstance(req, dict):
out.append([])
continue
translation = req.get("translation")
if not isinstance(translation, str) or not translation.strip():
raise ValueError("get-verses items must include translation")
translation = translation.upper()
req_local = dict(req)
req_local["translation"] = translation
_ensure_local_translation_cache(translation)
section = _load_local_section(translation, req_local)
out.append(section)
return json.dumps(out, ensure_ascii=False)
def _body_with_materialized_verses(requests_obj: list[dict]) -> str:
body_obj_list: list[dict] = []
for req in requests_obj:
req_copy = dict(req)
verses = req_copy.get("verses")
if verses is None:
translation = str(req_copy.get("translation", "")).upper()
book_val = _value_to_int(req_copy.get("book"))
chapter_val = _value_to_int(req_copy.get("chapter"))
if translation and book_val is not None and chapter_val is not None:
req_copy["verses"] = _local_verses_for_chapter(translation, book_val, chapter_val)
else:
req_copy["verses"] = []
body_obj_list.append(req_copy)
return json.dumps(body_obj_list)
def _build_verses_body_objects(rest: list[str], no_api: bool) -> list[dict]:
if not rest:
raise ValueError(
"Error: Incorrect --verses syntax.\nUsage: bolls --verses <translation(s)> <book> [chapter(s) [:verse(s)] ]"
)
if len(rest) == 1:
body = _normalize_get_verses_json(rest[0])
obj = json.loads(body)
if not isinstance(obj, list):
raise ValueError("get-verses JSON must be an array")
return obj
translations_list = _parse_translations_arg(rest[0])
ref_args = rest[1:]
if not ref_args:
raise ValueError(
"Error: Incorrect --verses syntax.\nUsage: bolls --verses <translation(s)> <book> [chapter(s) [:verse(s)] ]"
)
mode, book, chapters, verses_list = _parse_v_reference(ref_args)
body_obj_list: list[dict] = []
for translation in translations_list:
book_id = _book_to_id(
translation,
book,
allow_language_fallback=True,
)
if mode == "book":
if no_api:
chapters_list = _local_chapters_for_book(translation, int(book_id))
else:
chapters_list = _chapters_for_book(translation, book_id)
if not chapters_list:
raise ValueError(
f"Could not determine chapters for book '{book}' in translation '{translation}'."
)
else:
chapters_list = chapters or []
for chapter_val in chapters_list:
if mode == "verses":
verses = verses_list
elif no_api:
verses = None
else:
max_verse = _max_verse_for_chapter(translation, book_id, chapter_val)
verses = list(range(1, max_verse + 1))
body_obj_list.append(
{
"translation": translation,
"book": book_id,
"chapter": chapter_val,
"verses": verses,
}
)
return body_obj_list
def _run_verses(
rest: list[str],
include_all: bool,
add_comments: bool,
raw_json: bool,
url_only: bool = False,
no_api: bool = False,
) -> str:
jq_prefix = _choose_jq_prefix(include_all, add_comments)
body_obj_list = _build_verses_body_objects(rest, no_api)
if url_only:
body_for_url = json.dumps(body_obj_list) if not no_api else _body_with_materialized_verses(body_obj_list)
return _format_url("POST", f"{BASE_URL}/get-verses/", body_for_url)
if no_api:
raw = _fetch_verses_from_local_cache(body_obj_list)
else:
body = json.dumps(body_obj_list)
raw = _curl_post(f"{BASE_URL}/get-verses/", body)
if not raw_json and jq_prefix in (JQ_TEXT_ONLY, JQ_TEXT_COMMENT):
formatted = _format_verses(raw, add_comments)
if formatted is not None:
return formatted
return _format_json(raw, raw_json, jq_prefix, drop_translation_only=(include_all or raw_json))
def _norm_translation(s: str) -> str:
return s.upper()
def _urlencode(s: str) -> str:
from urllib.parse import quote
return quote(s)
def _urlencode_path_segment(s: str) -> str:
from urllib.parse import quote
return quote(s, safe="")
def _soft_link_book_id(translation: str, book: str) -> int | None:
if not isinstance(book, str):
return None
book = book.strip()
if not book:
return None
t = translation.upper()
key = (t, book.lower())
cached = _SOFT_LINK_CACHE.get(key)
if cached is not None:
return cached
book_enc = _urlencode_path_segment(book)
url = (
f"{BASE_URL}/get-verse/{t}/{book_enc}/"
f"{SOFT_LINK_PROBE_CHAPTER}/{SOFT_LINK_PROBE_VERSE}/"
)
try:
raw = _curl_get(url)
except pycurl.error:
return None
try:
data = json.loads(raw)
except Exception:
return None
book_val = None
if isinstance(data, dict):
book_val = data.get("book")
elif isinstance(data, list) and data:
first = data[0]
if isinstance(first, dict):
book_val = first.get("book")
if isinstance(book_val, str) and book_val.isdigit():
book_val = int(book_val)
if isinstance(book_val, int):
_SOFT_LINK_CACHE[key] = book_val
return book_val
return None
def _choose_jq_prefix(include_all: bool, add_comments: bool) -> str | None:
if include_all:
return None
if add_comments == False:
return JQ_TEXT_ONLY
return JQ_TEXT_COMMENT