Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from transformers import AutoModelForQuestionAnswering, AutoTokenizer
|
3 |
+
|
4 |
+
# Load the pre-trained model and tokenizer
|
5 |
+
model_name = "facebook/bart-base-squad2"
|
6 |
+
model = AutoModelForQuestionAnswering.from_pretrained(model_name)
|
7 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
8 |
+
|
9 |
+
def answer_query(question, context):
|
10 |
+
# Preprocess the question and context using the tokenizer
|
11 |
+
inputs = tokenizer(question, context, return_tensors="pt")
|
12 |
+
|
13 |
+
# Use the model to get the answer
|
14 |
+
with torch.no_grad():
|
15 |
+
outputs = model(**inputs)
|
16 |
+
start_scores, end_scores = outputs.start_logits, outputs.end_scores
|
17 |
+
|
18 |
+
# Find the most likely answer span
|
19 |
+
answer_start = torch.argmax(start_scores)
|
20 |
+
answer_end = torch.argmax(end_scores) + 1
|
21 |
+
|
22 |
+
# Extract the answer from the context
|
23 |
+
answer = tokenizer.convert_tokens_to_string(context)[answer_start:answer_end]
|
24 |
+
|
25 |
+
return answer
|
26 |
+
|
27 |
+
# Streamlit app
|
28 |
+
st.title("Question Answering App")
|
29 |
+
|
30 |
+
# Textbox for user query
|
31 |
+
user_query = st.text_input("Enter your question:")
|
32 |
+
|
33 |
+
# File uploader for context
|
34 |
+
uploaded_file = st.file_uploader("Upload a context file (txt):")
|
35 |
+
|
36 |
+
if uploaded_file is not None:
|
37 |
+
# Read the uploaded file content
|
38 |
+
context = uploaded_file.read().decode("utf-8")
|
39 |
+
else:
|
40 |
+
# Use default context if no file uploaded
|
41 |
+
context = "This is a sample context for demonstration purposes. You can upload your own text file for context."
|
42 |
+
|
43 |
+
# Answer the query if a question is provided
|
44 |
+
if user_query:
|
45 |
+
answer = answer_query(user_query, context)
|
46 |
+
st.write(f"Answer: {answer}")
|
47 |
+
else:
|
48 |
+
st.write("Please enter a question.")
|