"""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
" ), "refs": "", "retrieved": [], }) yield hs # ─── Chat rendering ──────────────────────────────────────────────────────── def render_chat_column(tab_persona: str, histories: dict): """Draw one tab's chat as a column of per-message blocks with controls. Called from within an @gr.render callback. Creates one gr.Group per message, with the 4 reaction buttons, a References expander, and a Save button on each assistant message. """ messages = histories.get(tab_persona, []) if not messages: gr.Markdown( "_Speak to " + (PERSONA_TITLES.get(tab_persona) or "God") + " below._\n", elem_classes="empty-chat", ) return for i, m in enumerate(messages): role = m.get("role") content = str(m.get("content") or "") if role == "user": gr.Markdown(f"**You:** {content}", elem_classes="msg-bubble-user") continue # Assistant message persona = m.get("persona") or "son" persona_label = PERSONA_TITLES.get(persona, "") retrieved = m.get("retrieved") or [] with gr.Group(): gr.Markdown( f"
{persona_label}
\n\n{content}", elem_classes="msg-bubble", ) with gr.Row(elem_classes="msg-controls"): user_msg_for_log = _preceding_user(messages, i) for emoji, rkey in (("❤️", "love"), ("🤗", "hug"), ("🥹", "tears"), ("🔥", "fire")): _bind_reaction(emoji, rkey, persona, content, user_msg_for_log, retrieved) _bind_save(persona, content, user_msg_for_log, retrieved) if retrieved: with gr.Accordion("📖 References", open=False): gr.Markdown(_refs_markdown(retrieved)) def _bind_reaction( emoji: str, reaction_key: str, persona: str, assistant_msg: str, user_msg: str, citations: list[dict], ): btn = gr.Button(emoji, size="sm", min_width=40) def _fire(): try: log_reaction(persona, reaction_key, user_msg, assistant_msg, citations) gr.Info(f"Recorded: {emoji}") except Exception as e: gr.Warning(f"Couldn't record reaction: {e}") btn.click(_fire, inputs=[], outputs=[]) def _bind_save(persona: str, assistant_msg: str, user_msg: str, citations: list[dict]): btn = gr.Button("💾 Save", size="sm") def _fire(): try: save_response(persona, assistant_msg, citations, user_message=user_msg) gr.Info("Saved.") except Exception as e: gr.Warning(f"Couldn't save: {e}") btn.click(_fire, inputs=[], outputs=[]) # ─── App construction ───────────────────────────────────────────────────── def build_app() -> gr.Blocks: with gr.Blocks(fill_height=True, title="Encounter God") as app: histories_state = gr.State(_empty_histories()) active_persona = gr.State("son") bible_is_open = gr.State(False) # Top bar with gr.Row(equal_height=True): with gr.Column(scale=5): gr.Markdown("# Encounter God") with gr.Column(scale=1, min_width=120): bible_toggle = gr.Button("📖 Bible", size="sm") with gr.Row(equal_height=False): # ── Left: chat column ────────────────────────────────────────── with gr.Column(scale=2): tabs = gr.Tabs() with tabs: tab_components = [] for persona_key in PERSONA_ORDER: with gr.Tab(TAB_LABELS[persona_key], id=persona_key): with gr.Column(elem_classes="chat-scroll"): @gr.render(inputs=[histories_state], triggers=[histories_state.change]) def _render(histories, _pk=persona_key): render_chat_column(_pk, histories) with gr.Accordion("💾 Saved in this session", open=False): saved_md = gr.Markdown(_saves_markdown(persona_key)) tab_components.append(saved_md) # ── Right: Bible side panel ─────────────────────────────────── with gr.Column(scale=1, visible=False, elem_classes="bible-panel") as bible_col: gr.Markdown("### Bible") with gr.Row(): book_dd = gr.Dropdown( choices=list(bible.BOOKS), value="John", label="Book", min_width=140, ) chapter_dd = gr.Dropdown( choices=[str(c) for c in range(1, bible.chapter_count("John") + 1)], value="1", label="Chapter", min_width=90, ) chapter_md = gr.Markdown( render_chapter("John", "1"), elem_classes="chapter-text", ) bible_textbox = gr.Textbox( label="Passage to explain", placeholder="Paste any passage here (or type a reference like John 3:16)...", lines=3, ) explain_btn = gr.Button("Explain in the current voice", variant="primary") # Input row (global) with gr.Row(): input_textbox = gr.Textbox( placeholder="Speak...", show_label=False, scale=5, container=False, ) send_btn = gr.Button("Send", variant="primary", scale=1, min_width=80) # ── Wiring ──────────────────────────────────────────────────────── tabs.select(on_tab_change, inputs=None, outputs=active_persona) bible_toggle.click( toggle_bible, inputs=[bible_is_open], outputs=[bible_is_open, bible_col, bible_toggle], ) book_dd.change(on_book_change, inputs=book_dd, outputs=chapter_dd).then( render_chapter, inputs=[book_dd, chapter_dd], outputs=chapter_md ) chapter_dd.change(render_chapter, inputs=[book_dd, chapter_dd], outputs=chapter_md) # Main submit chain submit_chain = ( send_btn.click( append_user_message, inputs=[input_textbox, active_persona, histories_state], outputs=[histories_state, input_textbox], ).then( stream_response, inputs=[active_persona, histories_state], outputs=[histories_state], ) ) # Enter-key submit ( input_textbox.submit( append_user_message, inputs=[input_textbox, active_persona, histories_state], outputs=[histories_state, input_textbox], ).then( stream_response, inputs=[active_persona, histories_state], outputs=[histories_state], ) ) # Bible Explain ( explain_btn.click( append_bible_explain, inputs=[bible_textbox, active_persona, histories_state], outputs=[histories_state, bible_textbox], ).then( stream_response, inputs=[active_persona, histories_state], outputs=[histories_state], ) ) return app def main(): app = build_app() app.queue().launch(theme=THEME, css=CSS) if __name__ == "__main__": main()