garrnizon commited on
Commit
93dcaf5
·
verified ·
1 Parent(s): 02ffce8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -0
app.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from datasets import load_dataset
3
+
4
+ # from transformers import T5Tokenizer, T5ForConditionalGeneration
5
+ from transformers import AutoTokenizer, AutoModelForQuestionAnswering, pipeline, AutoModelForQuestionAnswering
6
+ import torch
7
+ # model_path = "./kaggle-3/working/bert_qa"
8
+ model_path = "./flan_t5_qa_60"
9
+
10
+ tokenizer_new = AutoTokenizer.from_pretrained(model_path)
11
+ model_new = AutoModelForQuestionAnswering.from_pretrained(model_path)
12
+
13
+ def ask(question: str, context: str) -> str:
14
+ inputs = tokenizer_new(question, context, max_length=384,
15
+ truncation="only_second", padding="max_length", return_tensors="pt")
16
+ with torch.no_grad():
17
+ outputs = model_new(**inputs)
18
+
19
+ answer_start_index = outputs.start_logits.argmax()
20
+ answer_end_index = outputs.end_logits.argmax()
21
+
22
+ predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]
23
+ answer = tokenizer_new.decode(predict_answer_tokens)
24
+ return answer
25
+ return f"Question: '{question}'\nAnswer: {answer}"
26
+
27
+ # print(ask('What God created at first', 'Genesis 1:1 In the beginning God created the heaven and the earth.'))
28
+ # Streamlit App
29
+ st.set_page_config(page_title="Bible Q&A Bot", page_icon="📖", layout="centered")
30
+
31
+ st.title("📖 Bible Q&A Bot")
32
+ st.markdown("## Ask any question about the Bible and get scripturally grounded answers.")
33
+ st.write("‼️Only english🇺🇸 language provided‼️")
34
+
35
+
36
+ # User input
37
+ query = st.text_input("Enter your question:")
38
+
39
+ clear_button = st.button("Clear")
40
+ if clear_button:
41
+ for key in st.session_state.keys():
42
+ del st.session_state[key]
43
+
44
+ st.markdown('### Choose option to provide context')
45
+ option = st.radio("Choose how to provide context:", ("Manually", "Select Bible Verse"), label_visibility="collapsed")
46
+
47
+ def print_answer(question, context, answer):
48
+ if context.isascii() and question.isascii():
49
+ st.markdown("### ❓Question❓")
50
+ st.write(question)
51
+ st.markdown("### 📖Context📖")
52
+ st.write(context)
53
+ st.markdown("### ✅Answer✅")
54
+ st.write(answer)
55
+ else:
56
+ st.error("Please ensure both the question and context are in English.")
57
+
58
+
59
+ import pandas as pd
60
+
61
+ # bible = pd.read_json("bible-dpo.json")
62
+
63
+ bible = pd.read_json("hf://datasets/nbeerbower/bible-dpo/bible-dpo.json")
64
+
65
+ books = list(bible['book'].unique())
66
+ v_by_b_c = bible.groupby(by=['book', 'chapter']).size().to_dict()
67
+
68
+ if option == "Manually":
69
+ context = st.text_area("Enter the context (optional):")
70
+ submit_button = st.button("Get Answer")
71
+
72
+ if submit_button and query:
73
+ with st.spinner("Searching Scripture..."):
74
+ answer = ask(query, context)
75
+
76
+ print_answer(query, context, answer)
77
+
78
+
79
+ elif option == "Select Bible Verse":
80
+
81
+
82
+ book_name = st.selectbox("Select the book name:", [""] + books)
83
+
84
+ if book_name:
85
+ max_chapter = len(bible[bible["book"] == book_name].groupby('chapter'))
86
+ chapter = st.selectbox("Select the chapter:", [""] + list(range(1, max_chapter + 1)))
87
+ else:
88
+ chapter = st.selectbox("Select the chapter:", [""])
89
+
90
+ if chapter:
91
+ max_verse = v_by_b_c.get((book_name, int(chapter)), 0)
92
+ verse = st.selectbox("Enter the verse:", [""] + list(range(1, max_verse + 1)))
93
+ else:
94
+ verse = st.selectbox("Enter the verse:", [""])
95
+
96
+ fetch_context_button = st.button("Fetch Verse")
97
+
98
+ if query and fetch_context_button and book_name and chapter and verse:
99
+ context = bible[
100
+ (bible["book"] == book_name) &
101
+ (bible['chapter'] == chapter) &
102
+ (bible['verse'] == verse)
103
+ ]['text'].values[0]
104
+ with st.spinner("Searching Scripture..."):
105
+ answer = ask(query, context)
106
+
107
+ print_answer(query, context, answer)