-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
601 lines (481 loc) · 21.9 KB
/
app.py
File metadata and controls
601 lines (481 loc) · 21.9 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
from anthropic import Anthropic
import streamlit as st
import requests
from datetime import datetime
from zoneinfo import ZoneInfo
import os
import base64
from supabase import create_client
from streamlit_js_eval import streamlit_js_eval
# COLOUR SCHEME
# AF9164 - olive brown
# F7F3E3 - offwhite
# B3B6B7 - light gray
# 6F1A07 - red
# 2B2118 - dark brown
SUPABASE_URL = os.getenv("SUPABASE_URL") or st.secrets.get("SUPABASE_URL")
SUPABASE_KEY = os.getenv("SUPABASE_KEY") or st.secrets.get("SUPABASE_KEY")
supabase = create_client(SUPABASE_URL, SUPABASE_KEY)
# Semantic search backend URL (local dev or deployed)
def get_semantic_search_url():
if os.getenv("SEMANTIC_SEARCH_URL"):
return os.getenv("SEMANTIC_SEARCH_URL")
try:
return st.secrets.get("SEMANTIC_SEARCH_URL", "https://ssbackend-production-f786.up.railway.app")
except:
return "https://ssbackend-production-f786.up.railway.app"
SEMANTIC_SEARCH_URL = get_semantic_search_url()
st.set_page_config(page_title="First Loved Bible", page_icon="flower.png", layout="centered", initial_sidebar_state="expanded")
# login authentication featurss
def init_auth_state():
"""Initialize authentication session state"""
if "user" not in st.session_state:
st.session_state.user = None
if "auth_mode" not in st.session_state:
st.session_state.auth_mode = "login" # state
@st.dialog(" ")
def auth_modal():
tab1, tab2 = st.tabs(["Sign in ⊹", "I'm new here"])
with tab1:
# 1. LOGIN
login_email = st.text_input("Email", key="login_email")
login_password = st.text_input("Password", type="password", key="login_password")
if st.button("Sign In", key="login_btn"):
if login_email and login_password:
try:
# sign in part
response = supabase.auth.sign_in_with_password({
"email": login_email,
"password": login_password
})
# store user info and session inside session state
st.session_state.user = response.user
st.session_state.access_token = response.session.access_token
st.session_state.refresh_token = response.session.refresh_token
# set the session (in supa base client)
supabase.postgrest.auth(response.session.access_token)
st.rerun()
except Exception as e:
st.error({str(e)})
else:
st.error("Please enter both email and password")
with tab2:
# 2. SIGN UP
st.write("Don't have an account? Create one today ☻")
signup_email = st.text_input("Email", key="signup_email")
signup_password = st.text_input("Password (min 6 characters)", type="password", key="signup_password")
signup_password_confirm = st.text_input("Confirm Password", type="password", key="signup_password_confirm")
if st.button("Create account", key="signup_btn"):
if signup_email and signup_password and signup_password_confirm:
if signup_password != signup_password_confirm:
st.error("Passwords don't match!")
elif len(signup_password) < 6:
st.error("Password must be at least 6 characters")
else:
try:
# supabase sign up
response = supabase.auth.sign_up({
"email": signup_email,
"password": signup_password
})
if response.user:
st.session_state.user = response.user
if response.session:
st.session_state.access_token = response.session.access_token
st.session_state.refresh_token = response.session.refresh_token
supabase.postgrest.auth(response.session.access_token)
st.rerun()
else:
st.error("Sign up failed. Please try again.")
except Exception as e:
st.error(f"Sign up failed: {str(e)}")
else:
st.error("Please fill in all fields")
def logout():
try:
supabase.auth.sign_out()
st.session_state.user = None
st.session_state.access_token = None
st.session_state.refresh_token = None
st.rerun()
except Exception as e:
st.error(f"Logout failed: {str(e)}")
def save_verse_reference(reference, translation, notes=""):
if not st.session_state.user:
st.error("Please sign in to save verses")
return False
try:
# avoid duplicates
existing = supabase.table("saved_verses").select("id").eq("user_id", st.session_state.user.id).eq("reference", reference).execute()
if existing.data:
st.warning(f"{reference} is already saved.")
return False
supabase.table("saved_verses").insert({
"user_id": st.session_state.user.id,
"reference": reference,
"verse_text": "",
"translation": translation,
"notes": notes
}).execute()
return True
except Exception as e:
st.error(f"Failed to save verse: {str(e)}")
return False
def get_saved_verses():
if not st.session_state.user:
return []
try:
response = supabase.table("saved_verses").select("*").eq("user_id", st.session_state.user.id).order("created_at", desc=True).execute()
return response.data
except Exception as e:
st.error(f"Failed to load saved verses: {str(e)}")
return []
def group_verses_by_book(verses):
from collections import defaultdict
grouped = defaultdict(list)
for verse in verses:
book, _ = parse_reference(verse['reference'])
if book:
grouped[book].append(verse)
else:
grouped["Other"].append(verse)
return dict(grouped)
def delete_saved_verse(verse_id):
try:
supabase.table("saved_verses").delete().eq("id", verse_id).execute()
return True
except Exception as e:
st.error(f"Failed to delete verse: {str(e)}")
return False
def parse_reference(reference):
parts = reference.split()
if len(parts) >= 2:
if parts[0].isdigit() and len(parts) >= 3:
book = f"{parts[0]} {parts[1]}"
verse = parts[2]
else:
book = parts[0]
verse = parts[1]
return book, verse
return None, None
@st.dialog("Saving bookmark for...")
def save_verse_modal(reference, translation):
st.write(f"**{reference}** in {translation}")
notes_input = st.text_area("Add notes", key="modal_verse_notes", placeholder="", height=67)
if st.button("Save", key="confirm_save_btn", use_container_width=True):
if save_verse_reference(reference, translation, notes_input):
st.rerun()
@st.dialog("View bookmark")
def verse_detail_modal(verse):
st.subheader(f"{verse['reference']} in {verse['translation']}")
# get notes
if verse.get('notes') and verse['notes'].strip():
st.markdown(f'{verse["notes"]}')
else:
# maybe make a way you can add notes / edit
st.caption("No notes written.")
col1, col2 = st.columns(2)
# actions in the modal
with col1:
if st.button("Load", key=f"load_detail_{verse['id']}", use_container_width=True):
book, verse_ref = parse_reference(verse['reference'])
if book and verse_ref:
result = get_verse(book, verse_ref, verse['translation'])
if result:
st.session_state.verse_results = result
st.session_state.current_translation = verse['translation']
st.rerun()
with col2:
if st.button("Delete", key=f"delete_detail_{verse['id']}", type="secondary", use_container_width=True):
if delete_saved_verse(verse['id']):
st.rerun()
# setup claude wrapper prompt
SYSTEM_PROMPT = {
"role": "system",
"content": """You are a scholarly educator on the Bible.
Rules:
- Do not provide spiritual guidance
- Provide context, clarification and insight into bible verses
- Always cite specific Bible verses (Book Chapter:Verse) when relevant
- Provide historical and cultural context when helpful
- Be respectful of all Christian denominations as well as other religions
- Keep responses clear and accessible
- If unsure, say so rather than making things up
Tone: Warm, thoughtful, and encouraging."""
}
# load custom styling
def load_css(file_path):
with open(file_path) as f:
st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)
load_css("style.css")
# init
init_auth_state()
if "access_token" in st.session_state and st.session_state.access_token:
supabase.postgrest.auth(st.session_state.access_token)
if "verse_results" not in st.session_state:
st.session_state.verse_results = None
if "semantic_results" not in st.session_state:
st.session_state.semantic_results = None
if "user_tz" not in st.session_state:
st.session_state.user_tz = None
tz_string = streamlit_js_eval(js_expressions="Intl.DateTimeFormat().resolvedOptions().timeZone", key="tz")
if tz_string:
st.session_state.user_tz = tz_string
# title and header of page
st.html("<p class='nanum-myeongjo-regular' style='text-align: center;'>1 John 4:19 ꣑ৎ We love because he first loved us.</p>")
# encode letter image to base64 for inline display
def get_base64_image(image_path):
with open(image_path, "rb") as img_file:
return base64.b64encode(img_file.read()).decode()
emoji_img_base64 = get_base64_image("reading.png")
st.html(f"<h1 class='nanum-pen-script-regular front-title' style='text-align: center;'>You are firstloved, let's <img src='data:image/png;base64,{emoji_img_base64}' width='30'> read</h1>")
st.markdown("---")
# sidebar!
with st.sidebar:
st.html("<h2 class='nanum-pen-script-regular'>Search Instructions</h2>")
st.html("""
<p><b>By Reference:</b></p>
<p>✱ Search an entire chapter like <span style='color: var(--red);'>Philippians 4</p>
<p>✱ Search a single verse like <span style='color: var(--red);'>Jeremiah 29:11</p>
<p>✱ Search a range of verses like <span style='color: var(--red);'>Matthew 6:25-34</p>
<p><b>By Meaning:</b></p>
<p>✱ Search topics like <span style='color: var(--red);'>finding peace</span> or <span style='color: var(--red);'>feeling anxious</span></p>
""")
#login button
if st.session_state.user: # logged in
if st.button("Log Out ⊹₊˚", key="logout_btn"):
logout()
st.markdown("---")
# show saved verses/bookmarks
st.subheader("Bookmarks")
saved_verses = get_saved_verses()
if not saved_verses:
st.caption("None yet.")
else:
grouped_verses = group_verses_by_book(saved_verses)
for book, verses in grouped_verses.items():
with st.expander(f"{book}", expanded=True):
for verse in verses:
if st.button(f"✱ {verse['reference']}", key=f"verse_{verse['id']}"):
verse_detail_modal(verse)
else: # if user is not logged in, don't show
if st.button("Log in ⊹", key="open_auth_modal"):
auth_modal()
st.markdown("---")
# full date and time
try:
user_tz = ZoneInfo(st.session_state.user_tz) if st.session_state.user_tz else ZoneInfo("America/Los_Angeles")
except:
user_tz = ZoneInfo("America/Los_Angeles")
now = datetime.now(user_tz)
st.html(f"<p>It's {now.strftime('%I:%M%p').lstrip('0')} on a {now.strftime('%A')}.</p>")
# mini feedback bar for funsies
with st.form(key="feedback_form", clear_on_submit=True):
name = st.text_input(label="Send me feedback!", placeholder="Your name")
message = st.text_input(label="", placeholder="Your message here", label_visibility="collapsed")
submitted = st.form_submit_button("Send ⊹")
if submitted and name and message:
supabase.table("feedback").insert({"name":name, "message":message}).execute()
st.success(f"Thanks for the feedback, {name}!")
# footer
st.markdown("---")
st.html("""
<div class='sidebar-footer'>
<small>Made with ♡ by <a class='sidebar-footer' href="https://github.com/wrufay/first-loved" target="_blank">Fay Wu</a></small>
</div>""")
# front page columns (search tool) - using empty columns to center
# initialize search mode
if "search_mode" not in st.session_state:
st.session_state.search_mode = "reference"
search_tab1, search_tab2 = st.tabs(["By Reference", "By Meaning"])
with search_tab1:
_, col1, col2, col3, _ = st.columns([0.5, 1, 1, 1, 0.5])
with col1:
TRANSLATIONS = {
"kjv": "King James Version",
"web": "World English Bible",
"bbe": "Bible in Basic English",
"asv": "American Standard Version",
}
translation = st.selectbox(
"Select Translation",
options=TRANSLATIONS.keys(),
format_func=lambda x: TRANSLATIONS[x]
)
with col2:
book = st.text_input("Book Name", placeholder="1 John")
with col3:
verse = st.text_input("Chapter + Verse", placeholder="4:19")
st.write("")
_, btn_col1, btn_col2, _ = st.columns([0.5, 1, 1, 0.5])
with btn_col1:
if "show_ai_chat" not in st.session_state:
st.session_state.show_ai_chat = False
if st.button("Ask Claude" if not st.session_state.show_ai_chat else "Hide chat", use_container_width=True, key="claude_btn_ref"):
st.session_state.show_ai_chat = not st.session_state.show_ai_chat
st.rerun()
with btn_col2:
search_button = st.button("Search passage", use_container_width=True)
with search_tab2:
st.caption("Search by topic, feeling, or question — find verses by meaning")
_, sem_col, _ = st.columns([0.5, 2, 0.5])
with sem_col:
semantic_query = st.text_input("What are you looking for?", placeholder="e.g. feeling anxious, finding peace, God's love", key="semantic_query")
num_results = st.slider("Number of results", min_value=3, max_value=20, value=5, key="num_results")
_, sem_btn_col, _ = st.columns([0.5, 2, 0.5])
with sem_btn_col:
semantic_search_button = st.button("Search by meaning", use_container_width=True)
# semantic search using the ML backend
def semantic_search(query: str, top_k: int = 10):
"""Search for verses by meaning using the semantic search backend."""
try:
response = requests.post(
f"{SEMANTIC_SEARCH_URL}/search",
json={"query": query, "top_k": top_k},
timeout=10
)
if response.status_code == 200:
return response.json()
else:
st.error(f"Search failed (Status: {response.status_code})")
return None
except requests.exceptions.ConnectionError:
st.error("Semantic search backend not available. Make sure it's running.")
return None
except Exception as e:
st.error(f"Search error: {str(e)}")
return None
# get the verse with bible api
def get_verse(book, verse, translation):
url = f'https://bible-api.com/{book}+{verse}?translation={translation}'
try:
response = requests.get(url)
if response.status_code == 404:
st.error("Invalid input. Please try again with a valid book and chapter.")
return None
elif response.status_code == 200: # if successful
return response.json()
else:
# catch errors
st.warning(f"Unexpected error. (Status code: {response.status_code})")
return None
except Exception as e:
st.error(f"An error occurred: {str(e)}")
return None
# logic to show the bible verse
def display_verse(bible_content, translation="kjv"):
if bible_content:
st.markdown("---")
st.badge(f"{bible_content['reference']}", color="gray")
reference = bible_content['reference']
base_ref = reference.split(':')[0] if ':' in reference else reference
enduring_word_path = ""
# check if the split is 3 or 2
str_split = base_ref.split(" ") # split into list of 2 or 3 strings
cur_len = len(str_split)
ch = ""
ve = ""
pr = ""
if cur_len == 2:
ch=str_split[0]
ve=str_split[1]
elif cur_len == 3:
pr = f"{str_split[0]}-"
ch=str_split[1]
ve=str_split[2]
# note bug: in enduring word they call it "psalm" without the s.
if ch == "Psalms":
ch = "Psalm"
enduring_word_path = f'https://enduringword.com/bible-commentary/{pr}{ch}-{ve}/'
for v in bible_content["verses"]:
st.html(f'<p class="bible-text"><span class="verse-num">{v["verse"]}</span> {v["text"]}</p>')
st.markdown("---")
# show save verse button only if logged in
if st.session_state.user:
if st.button(f"✱ Make a bookmark for {reference}"):
save_verse_modal(reference, translation.upper())
# link to enduring word bible commentary
st.page_link(label=f'Read commentary from :red[**Enduring Word**]', page=enduring_word_path)
st.markdown("---")
# trigger with the search btn (reference search)
if search_button:
if book and verse:
with st.spinner("..."):
result = get_verse(book, verse, translation)
if result:
st.session_state.verse_results = result
st.session_state.current_translation = translation
st.session_state.semantic_results = None # clear semantic results
# trigger semantic search
if semantic_search_button:
if semantic_query:
with st.spinner("Searching by meaning..."):
result = semantic_search(semantic_query, num_results)
if result:
st.session_state.semantic_results = result
st.session_state.verse_results = None # clear reference results
current_translation = st.session_state.get("current_translation", "kjv")
display_verse(st.session_state.verse_results, current_translation)
# display semantic search results
if st.session_state.get("semantic_results"):
semantic_data = st.session_state.semantic_results
st.markdown("---")
st.caption(f"Results for: **{semantic_data['query']}**")
for i, result in enumerate(semantic_data["results"]):
score_pct = int(result["score"] * 100)
with st.container():
st.markdown(f"**{result['reference']}**")
st.progress(result["score"], text=f"{score_pct}% match")
st.html(f'<p class="bible-text">{result["text"]}</p>')
# option to load full chapter context
col_load, col_save = st.columns(2)
with col_load:
if st.button(f"Load in KJV", key=f"load_sem_{i}"):
book_name = result["book"]
ch_verse = f"{result['chapter']}:{result['verse']}"
full_result = get_verse(book_name, ch_verse, "kjv")
if full_result:
st.session_state.verse_results = full_result
st.session_state.current_translation = "kjv"
st.session_state.semantic_results = None
st.rerun()
with col_save:
if st.session_state.user:
if st.button(f"Bookmark", key=f"save_sem_{i}"):
save_verse_modal(result["reference"], "KJV")
st.markdown("---")
# implement large language model
if st.session_state.get("show_ai_chat", False):
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY") or st.secrets.get("ANTHROPIC_API_KEY")
client = Anthropic(api_key=ANTHROPIC_API_KEY)
if "anthropic_model" not in st.session_state:
st.session_state["anthropic_model"] = "claude-sonnet-4-5"
if "messages" not in st.session_state:
st.session_state.messages = []
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
if prompt := st.chat_input("need context, definitions or clarification?"):
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
with st.chat_message("assistant"):
try:
# making sure to provide current verse or chapter for context if available
system_message = SYSTEM_PROMPT["content"]
if st.session_state.verse_results:
verse_text = "\n".join(
f'{v["verse"]}. {v["text"]}' for v in st.session_state.verse_results["verses"]
)
system_message += f"\n\nThe user is currently viewing {st.session_state.verse_results['reference']}:\n{verse_text}"
with client.messages.stream(
model=st.session_state["anthropic_model"],
max_tokens=1024,
system=system_message,
messages=st.session_state.messages,
) as stream:
response = st.write_stream(stream.text_stream)
st.session_state.messages.append({"role": "assistant", "content": response})
except Exception as e:
st.error(f"Error: {str(e)}")
# Don't append failed message to history