#!/usr/bin/env python3 """ Exhaustive miracle scan of the whole Bible (OT, Deuterocanon, NT). Walks every chapter in overlapping verse windows, asks the model to list each miracle event as a verse range, and tags every verse in the range through the existing tag tables on 10.0.1.50 (bible_verse_tags / bible_verse_tag_links), so the website's tag search finds them. Nothing new is created in the database. Tags written (prompt_version "miracles-v1"): miracle every verse in a narrated miracle (category topic) miracle_recalled a miracle a later text looks back on (category topic) miracle_ the kind of miracle, see TYPES (category miracle_type) Every event is also appended to podcast/miracle_scan/events.jsonl (book, chapter, verse range, type, mode, summary) so --report can count events per book, which is what the "densest concentration of miracles" claim in the podcast needs. Usage (Mac, like run_verse_tagging.py): python3 tag_miracles.py --dry-run --book-id 12 --chapters 1-8 # look only python3 tag_miracles.py --workers 6 # whole Bible, resumable python3 tag_miracles.py --report # counts per book """ import argparse import json import os import re import sys import threading from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Dict, List, Optional, Tuple import psycopg2 import psycopg2.extras _here = os.path.dirname(os.path.abspath(__file__)) if _here not in sys.path: sys.path.insert(0, _here) from queue_client import queue_generate # noqa: E402 SOURCE_DSN = os.environ.get("SOURCE_DSN", "host=10.0.1.50 dbname=source_service user=mctrivia") BIBLE_DSN = os.environ.get("BIBLE_DSN", "dbname=source_service user=mc") PROMPT_VERSION = "miracles-v1" MODEL_NAME = "gemma4-nvfp4" PRIORITY = 5 # same as run_verse_tagging.py PROJECT = "bible-verse-tagger" # existing queue project name, not renamed WINDOW = 40 # verses per prompt STEP = 32 # overlap of 8 so a story cut at a boundary is seen whole OUT_DIR = os.path.normpath(os.path.join(_here, "..", "..", "podcast", "miracle_scan")) EVENTS = os.path.join(OUT_DIR, "events.jsonl") DONE = os.path.join(OUT_DIR, "done.txt") TYPES = { "healing": "sickness, disability or disease cured", "raising_the_dead": "a dead person brought back to life", "exorcism": "a demon or unclean spirit driven out", "provision": "food, water, oil or money supplied or multiplied beyond natural means", "nature": "sea, river, sun, weather, earth, fire or animals acting beyond natural means", "judgment": "plague, fire, earthquake, sudden death or affliction sent as punishment", "deliverance": "rescue, protection or victory by supernatural means (angel, fire, walls falling, prison opened)", "birth": "conception or birth that is miraculous (barren or virgin)", "transformation": "a person, object or substance changed (staff to snake, water to wine, Lot's wife)", "translation": "taken up alive, ascension, or resurrection of Jesus", "relic": "healing or power through the remains, clothing or shadow of a holy person (bones, cloak, handkerchief, shadow)", "sign": "a sign or wonder not covered above (speaking in tongues, speaking animal, handwriting on the wall, answer by fire)", } SYSTEM = """\ You are a careful, denomination-neutral Bible scholar cataloguing miracles. You are given a run of consecutive verses. List every miracle in them as a verse range. A miracle here is an event the text presents as really happening through God or a divine agent, beyond ordinary natural or human causation: healings, raisings of the dead, exorcisms, supernatural provision, wonders of nature, plagues and judgments sent by God, supernatural rescue, miraculous conception or birth, bodily translation or resurrection, signs and wonders. NOT a miracle: ordinary providence or answered prayer with no wonder described; dreams, visions or God speaking, by themselves; poetry or metaphor; laws, genealogies, teaching, ethics; natural events with no divine action stated; wonders that are only predicted for the future (use mode "predicted"); the passing mention of a miracle in a list. For each miracle give: start, end: verse numbers inside the verses shown (the whole story, not just one verse) type: one of {types} mode: "narrated" (the text tells it as happening), "recalled" (the text looks back on a miracle told elsewhere, e.g. a psalm or speech reviewing the Exodus), or "predicted" (promised for the future) confidence: 0.0 to 1.0 summary: at most 15 words Return ONLY JSON, no commentary: {{"events":[{{"start":1,"end":5,"type":"healing","mode":"narrated","confidence":0.9,"summary":"..."}}]}} If there are none, return {{"events":[]}}. """.format(types=", ".join(TYPES)) _lock = threading.Lock() _tag_cache: Dict[str, int] = {} def norm(name: str) -> str: return re.sub(r"[^a-z0-9]+", "_", name.lower()).strip("_")[:128] def tag_id(conn, name: str, category: str, description: str = "") -> int: n = norm(name) with _lock: if n in _tag_cache: return _tag_cache[n] with conn.cursor() as cur: cur.execute( """ INSERT INTO bible_verse_tags (name, normalized_name, category, description, created_at, updated_at) VALUES (%s, %s, %s, NULLIF(%s, ''), NOW(), NOW()) ON CONFLICT (normalized_name) DO UPDATE SET updated_at = NOW() RETURNING id """, (n.replace("_", " "), n, category, description), ) tid = cur.fetchone()[0] conn.commit() with _lock: _tag_cache[n] = tid return tid def load_books(src) -> Dict[int, Tuple[str, str]]: with src.cursor() as cur: cur.execute("SELECT id, name, testament FROM bible_books ORDER BY id") return {r[0]: (r[1], r[2]) for r in cur.fetchall()} def chapters(bib, book_id: int) -> Dict[int, List[Tuple[int, int, str]]]: """chapter -> [(verse_id, verse_number, text)] using public-domain text first.""" out: Dict[int, List[Tuple[int, int, str]]] = {} with bib.cursor() as cur: cur.execute( """SELECT id, chapter, verse, COALESCE(NULLIF(text_web, ''), NULLIF(text_other, ''), NULLIF(text_net, ''), NULLIF(text_nrsvue, '')) FROM bible_verses WHERE book_id = %s ORDER BY chapter, verse""", (book_id,), ) for vid, ch, v, text in cur.fetchall(): if text: out.setdefault(ch, []).append((vid, v, text)) return out def windows(verses: List[Tuple[int, int, str]]): if len(verses) <= WINDOW: yield verses return i = 0 while True: yield verses[i:i + WINDOW] if i + WINDOW >= len(verses): return i += STEP def ask(book: str, chapter: int, win: List[Tuple[int, int, str]]) -> List[dict]: body = "\n".join("%d %s" % (v, t) for _, v, t in win) user = "%s chapter %d, verses %d-%d:\n\n%s\n\nList the miracles." % (book, chapter, win[0][1], win[-1][1], body) last = None for _ in range(3): try: raw = queue_generate( messages=[{"role": "system", "content": SYSTEM}, {"role": "user", "content": user}], priority=PRIORITY, temperature=0.1, max_tokens=1500, project_name=PROJECT) s, e = raw.find("{"), raw.rfind("}") data = json.loads(raw[s:e + 1]) return [x for x in data.get("events", []) if isinstance(x, dict)] except Exception as exc: # retry, then surface last = exc raise RuntimeError("model failed for %s %d: %s" % (book, chapter, last)) def clean(events: List[dict], win) -> List[dict]: lo, hi = win[0][1], win[-1][1] out = [] for e in events: try: s, t = int(e["start"]), int(e["end"]) except Exception: continue s, t = max(s, lo), min(t, hi) typ = norm(str(e.get("type", ""))) mode = str(e.get("mode", "")).lower() if s > t or typ not in TYPES or mode not in ("narrated", "recalled", "predicted"): continue try: conf = max(0.0, min(1.0, float(e.get("confidence", 0.7)))) except Exception: conf = 0.7 out.append({"start": s, "end": t, "type": typ, "mode": mode, "confidence": conf, "summary": str(e.get("summary", ""))[:160]}) return out def merge(events: List[dict]) -> List[dict]: """Overlapping windows can report the same story twice; keep one per overlapping same-type range.""" events = sorted(events, key=lambda e: (e["type"], e["mode"], e["start"], -e["end"])) out: List[dict] = [] for e in events: if out and out[-1]["type"] == e["type"] and out[-1]["mode"] == e["mode"] and e["start"] <= out[-1]["end"]: out[-1]["end"] = max(out[-1]["end"], e["end"]) out[-1]["confidence"] = max(out[-1]["confidence"], e["confidence"]) else: out.append(dict(e)) return sorted(out, key=lambda e: e["start"]) def store(src, rows: List[Tuple[int, int, float]]) -> None: if not rows: return best: Dict[Tuple[int, int], float] = {} for v, t, c in rows: best[(v, t)] = max(c, best.get((v, t), 0.0)) with src.cursor() as cur: psycopg2.extras.execute_values( cur, """INSERT INTO bible_verse_tag_links (verse_id, tag_id, confidence, source, model, prompt_version, created_at) VALUES %s ON CONFLICT (verse_id, tag_id) DO UPDATE SET confidence = GREATEST(bible_verse_tag_links.confidence, EXCLUDED.confidence)""", [(v, t, c, "ai", MODEL_NAME, PROMPT_VERSION) for (v, t), c in best.items()], template="(%s,%s,%s,%s,%s,%s,NOW())") src.commit() def do_chapter(book_id: int, book: str, ch: int, verses, dry: bool) -> Tuple[str, int, List[dict]]: events: List[dict] = [] for win in windows(verses): events += clean(ask(book, ch, win), win) events = merge(events) if dry: return book, ch, events src = psycopg2.connect(SOURCE_DSN) try: ids = {v: vid for vid, v, _ in verses} rows = [] for e in events: if e["mode"] == "predicted": continue main = tag_id(src, "miracle" if e["mode"] == "narrated" else "miracle_recalled", "topic", "A miracle told as happening in the text" if e["mode"] == "narrated" else "A miracle the text looks back on") kind = tag_id(src, "miracle_" + e["type"], "miracle_type", TYPES[e["type"]]) for v in range(e["start"], e["end"] + 1): if v in ids: rows.append((ids[v], main, e["confidence"])) rows.append((ids[v], kind, e["confidence"])) store(src, rows) finally: src.close() with _lock: with open(EVENTS, "a") as f: for e in events: f.write(json.dumps(dict(e, book_id=book_id, book=book, chapter=ch), ensure_ascii=False) + "\n") with open(DONE, "a") as f: f.write("%d:%d\n" % (book_id, ch)) return book, ch, events def report() -> None: per: Dict[str, Dict[str, int]] = {} order: List[str] = [] with open(EVENTS) as f: for line in f: e = json.loads(line) if e["mode"] != "narrated": continue b = e["book"] if b not in per: per[b] = {"events": 0, "verses": 0} order.append(b) per[b]["events"] += 1 per[b]["verses"] += e["end"] - e["start"] + 1 print("%-22s %7s %7s" % ("book", "events", "verses")) for b in sorted(order, key=lambda b: -per[b]["events"]): print("%-22s %7d %7d" % (b, per[b]["events"], per[b]["verses"])) def parse_range(s: str) -> List[int]: a, _, b = s.partition("-") return list(range(int(a), int(b or a) + 1)) def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--workers", type=int, default=6) ap.add_argument("--book-id", type=int) ap.add_argument("--chapters", help="e.g. 1-8 (with --book-id)") ap.add_argument("--testament", help="OT, NT, Deuterocanonical, NonCanonical (default: all but NonCanonical)") ap.add_argument("--dry-run", action="store_true", help="print events, write nothing") ap.add_argument("--redo", action="store_true", help="ignore done.txt") ap.add_argument("--report", action="store_true") a = ap.parse_args() if a.report: report() return os.makedirs(OUT_DIR, exist_ok=True) done = set() if os.path.exists(DONE) and not a.redo: done = set(l.strip() for l in open(DONE)) src = psycopg2.connect(SOURCE_DSN) bib = psycopg2.connect(BIBLE_DSN) books = load_books(src) with src.cursor() as cur: cur.execute("SELECT normalized_name, id FROM bible_verse_tags") _tag_cache.update(dict(cur.fetchall())) src.close() jobs = [] for bid, (name, test) in books.items(): if a.book_id and bid != a.book_id: continue if a.testament and test != a.testament: continue if not a.testament and not a.book_id and test == "NonCanonical": continue chs = chapters(bib, bid) want = parse_range(a.chapters) if a.chapters else sorted(chs) for ch in want: if ch in chs and "%d:%d" % (bid, ch) not in done: jobs.append((bid, name, ch, chs[ch])) print("%d chapters to scan" % len(jobs), flush=True) failed = 0 with ThreadPoolExecutor(max_workers=a.workers) as ex: futs = {ex.submit(do_chapter, b, n, c, v, a.dry_run): (n, c) for b, n, c, v in jobs} for i, f in enumerate(as_completed(futs), 1): try: book, ch, events = f.result() except Exception as exc: failed += 1 print("FAILED %s %s: %s" % (futs[f][0], futs[f][1], exc), flush=True) continue if a.dry_run: for e in events: print("%s %d:%d-%d %-16s %-9s %.2f %s" % (book, ch, e["start"], e["end"], e["type"], e["mode"], e["confidence"], e["summary"])) elif i % 50 == 0: print("%d/%d chapters" % (i, len(jobs)), flush=True) print("done, %d chapters failed (rerun to retry them)" % failed) if __name__ == "__main__": main()