Spaces:
Sleeping
Sleeping
Create question_answering.py
Browse files- question_answering.py +27 -0
question_answering.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from transformers import BertTokenizer, BertForQuestionAnswering
|
| 3 |
+
|
| 4 |
+
# Load the pre-trained model and tokenizer
|
| 5 |
+
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
|
| 6 |
+
model = BertForQuestionAnswering.from_pretrained("bert-base-uncased")
|
| 7 |
+
|
| 8 |
+
def answer_query(question, context):
|
| 9 |
+
# Preprocess the question and context using the tokenizer
|
| 10 |
+
inputs = tokenizer(question, context, return_tensors="pt")
|
| 11 |
+
|
| 12 |
+
# Use the model for question answering
|
| 13 |
+
with torch.no_grad():
|
| 14 |
+
outputs = model(**inputs)
|
| 15 |
+
|
| 16 |
+
# Get start and end logits directly from model outputs
|
| 17 |
+
start_logits = outputs.start_logits
|
| 18 |
+
end_logits = outputs.end_logits
|
| 19 |
+
|
| 20 |
+
# Find the most likely answer span
|
| 21 |
+
answer_start = torch.argmax(start_logits)
|
| 22 |
+
answer_end = torch.argmax(end_logits) + 1
|
| 23 |
+
|
| 24 |
+
# Extract the answer from the context
|
| 25 |
+
answer = tokenizer.convert_tokens_to_string(context)[answer_start:answer_end]
|
| 26 |
+
|
| 27 |
+
return answer
|