"""Gradio entrypoint — Encounter God.
Custom-rendered chat column (per-message reaction/reference/save controls),
a Bible side panel that opens beside the chat without overlaying, paced-reveal
streaming, and HF-Dataset persistence for reactions and saves.
"""
from __future__ import annotations
import os
import traceback
from pathlib import Path
from typing import Generator
import gradio as gr
from huggingface_hub import CommitScheduler
from trinity import bible
from trinity.chat import PERSONAS, respond, trinity_turn
from trinity.prompts import PERSONA_TITLES
from trinity.reactions import REACTIONS, log_reaction
from trinity.saves import list_saves, save_response
# ─── Persistence setup ─────────────────────────────────────────────────────
for p in (Path("data/reactions"), Path("data/saves")):
p.mkdir(parents=True, exist_ok=True)
scheduler: CommitScheduler | None = None
if os.environ.get("HF_TOKEN") and os.environ.get("REACTIONS_REPO"):
try:
scheduler = CommitScheduler(
repo_id=os.environ["REACTIONS_REPO"],
repo_type="dataset",
folder_path="data",
path_in_repo="",
allow_patterns=["reactions/*.jsonl", "saves/*.jsonl"],
every=5,
)
except Exception as e:
print(f"[encounter-god] CommitScheduler disabled: {type(e).__name__}: {e}")
scheduler = None
# ─── Theme & CSS ───────────────────────────────────────────────────────────
THEME = gr.themes.Base(
font=[gr.themes.GoogleFont("EB Garamond"), "Georgia", "serif"],
font_mono=[gr.themes.GoogleFont("IBM Plex Mono"), "Consolas", "monospace"],
).set(
body_background_fill="#F3EAD3",
body_background_fill_dark="#F3EAD3",
body_text_color="#2C2E4A",
body_text_color_dark="#2C2E4A",
background_fill_primary="#F3EAD3",
background_fill_primary_dark="#F3EAD3",
background_fill_secondary="#E8DDBF",
background_fill_secondary_dark="#E8DDBF",
border_color_primary="#C8B98C",
block_background_fill="#FAF4E1",
block_background_fill_dark="#FAF4E1",
block_border_color="#C8B98C",
block_title_text_color="#2C2E4A",
block_label_background_fill="#E8DDBF",
button_primary_background_fill="#A8842C",
button_primary_background_fill_hover="#8C6D23",
button_primary_text_color="#FAF4E1",
button_secondary_background_fill="#E8DDBF",
button_secondary_background_fill_hover="#DCCBA5",
button_secondary_text_color="#2C2E4A",
link_text_color="#6A5719",
input_background_fill="#FAF4E1",
input_background_fill_focus="#FFFDF3",
input_border_color="#C8B98C",
input_border_color_focus="#A8842C",
body_text_size="16px",
)
CSS = """
html, body, #root, gradio-app { height: 100vh; overflow: hidden; }
.gradio-container { max-width: 1200px !important; height: 100vh; padding-top: 0 !important; }
.gradio-container > .main { height: 100vh; }
h1, h2, h3, h4 { font-family: 'EB Garamond', Georgia, serif; letter-spacing: 0.01em; }
h1 { font-size: 2.0rem; font-weight: 600; margin: 0.4rem 0 0.2rem; color: #2C2E4A; }
.persona-label {
font-variant: small-caps;
letter-spacing: 0.08em;
font-size: 0.82rem;
color: #6A5719;
margin-bottom: 0.1rem;
}
.msg-bubble {
padding: 0.4rem 0.7rem;
border-radius: 8px;
background: #FAF4E1;
margin-bottom: 0.2rem;
line-height: 1.55;
}
.msg-bubble-user {
padding: 0.3rem 0.7rem;
border-radius: 8px;
background: #E8DDBF;
margin-bottom: 0.35rem;
color: #2C2E4A;
font-style: italic;
}
.msg-controls button {
font-size: 1.0rem !important;
padding: 2px 10px !important;
min-width: auto !important;
background: transparent !important;
border: 1px solid #C8B98C !important;
color: #6A5719 !important;
}
.msg-controls button:hover {
background: #FFFDF3 !important;
border-color: #A8842C !important;
}
.chat-scroll {
overflow-y: auto !important;
max-height: calc(100vh - 220px);
padding-right: 6px;
}
.bible-panel {
border-left: 1px solid #C8B98C;
padding-left: 10px;
transition: all 240ms ease-out;
}
.chapter-text p { line-height: 1.7; margin: 0.3em 0; }
footer, .footer { display: none !important; }
"""
# ─── Helpers ───────────────────────────────────────────────────────────────
PERSONA_ORDER = ("son", "spirit", "father", "trinity")
TAB_LABELS = {
"son": "Jesus Christ",
"spirit": "The Holy Spirit",
"father": "God the Father",
"trinity": "Trinity",
}
def _empty_histories() -> dict:
return {k: [] for k in PERSONA_ORDER}
def _preceding_user(msgs: list[dict], i: int) -> str:
for j in range(i - 1, -1, -1):
if msgs[j].get("role") == "user":
return str(msgs[j].get("content", ""))
return ""
def _refs_markdown(retrieved: list[dict]) -> str:
if not retrieved:
return "_No passages retrieved for this response._"
lines = []
for p in retrieved:
ref = f"{p['book']} {p['chapter']}:{p['verse']}"
text = (p.get("text") or "").strip()
link = bible.bible_com_link(p["book"], p["chapter"], p["verse"])
linked_ref = f"[**{ref}**]({link})" if link else f"**{ref}**"
lines.append(f"- {linked_ref} — {text}")
return "\n".join(lines)
def _saves_markdown(persona: str | None) -> str:
entries = list_saves(persona=persona, limit=10)
if not entries:
return "_You haven't saved anything in this session yet._"
lines = []
for e in entries:
pname = PERSONA_TITLES.get(e.get("persona"), "")
first_line = (e.get("message") or "").splitlines()[0][:200]
lines.append(f"- *{pname}* — {first_line}…")
return "\n".join(lines)
# ─── Handlers ──────────────────────────────────────────────────────────────
def on_tab_change(select_data: gr.SelectData) -> str:
idx = int(select_data.index) if select_data.index is not None else 0
if 0 <= idx < len(PERSONA_ORDER):
return PERSONA_ORDER[idx]
return "son"
def toggle_bible(is_open: bool):
new_open = not bool(is_open)
return new_open, gr.update(visible=new_open), ("Close Bible" if new_open else "📖 Bible")
def on_book_change(book: str):
n = bible.chapter_count(book) or 1
return gr.update(choices=[str(c) for c in range(1, n + 1)], value="1")
def render_chapter(book: str, chapter: str) -> str:
try:
ch = int(chapter)
except (ValueError, TypeError):
return ""
verses = bible.chapter_text(book, ch)
if not verses:
return "_No verses found for this chapter._"
lines = [f"## {book} {ch}"]
for v in verses:
lines.append(f"**{v['verse']}** {v['text']}")
link = bible.bible_com_link(book, ch)
if link:
lines.append(f"\n[Open on Bible.com ↗]({link})")
return "\n\n".join(lines)
def append_user_message(query: str, active: str, histories: dict):
if not (query or "").strip():
return histories, query
hs = {k: list(v) for k, v in histories.items()}
hs.setdefault(active, [])
hs[active].append({"role": "user", "content": query.strip()})
return hs, ""
def append_bible_explain(passage: str, active: str, histories: dict):
if not (passage or "").strip():
return histories, passage
query = f"Please explain this passage in Holy Scripture:\n\n{passage.strip()}"
hs, _ = append_user_message(query, active, histories)
return hs, ""
def stream_response(active: str, histories: dict) -> Generator[dict, None, None]:
hs = {k: list(v) for k, v in histories.items()}
active_history = hs.get(active, [])
if not active_history or active_history[-1].get("role") != "user":
yield hs
return
query = str(active_history[-1]["content"])
if active == "trinity":
gen = trinity_turn(active_history[:-1], query)
else:
gen = respond(active, active_history[:-1], query)
current_persona: str | None = None
try:
for state in gen:
p = state.get("persona")
if p != current_persona:
hs[active].append({
"role": "assistant",
"persona": p,
"content": state.get("text", ""),
"refs": state.get("refs", ""),
"retrieved": state.get("retrieved", []),
})
current_persona = p
else:
hs[active][-1]["content"] = state.get("text", "")
if state.get("final"):
hs[active][-1]["refs"] = state.get("refs", "")
hs[active][-1]["retrieved"] = state.get("retrieved", [])
yield hs
except Exception as e:
hs[active].append({
"role": "assistant",
"persona": "son" if active == "trinity" else active,
"content": (
f"**Error generating a response.**\n\n"
f"`{type(e).__name__}: {e}`\n\n"
f"Traceback
\n\n```\n"
f"{traceback.format_exc()}\n```\n