Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
from transformers import AutoModelForMultipleChoice, AutoTokenizer
|
| 4 |
+
|
| 5 |
+
# Load the model and tokenizer
|
| 6 |
+
model_id = "roberta-large-mnli"
|
| 7 |
+
model = AutoModelForMultipleChoice.from_pretrained(model_id)
|
| 8 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 9 |
+
|
| 10 |
+
# Define the preprocessing function
|
| 11 |
+
def preprocess(sample):
|
| 12 |
+
question = sample["question"]
|
| 13 |
+
choices = [sample[choice] for choice in "ABCDE"]
|
| 14 |
+
inputs = [f"{question} {choice}" for choice in choices]
|
| 15 |
+
tokenized = tokenizer(inputs, truncation=True, padding=True, return_tensors="pt")
|
| 16 |
+
return {
|
| 17 |
+
"input_ids": tokenized["input_ids"],
|
| 18 |
+
"attention_mask": tokenized["attention_mask"]
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
# Define the prediction function
|
| 22 |
+
def predict(data):
|
| 23 |
+
inputs = torch.stack(data["input_ids"])
|
| 24 |
+
masks = torch.stack(data["attention_mask"])
|
| 25 |
+
with torch.no_grad():
|
| 26 |
+
logits = model(inputs, attention_mask=masks).logits
|
| 27 |
+
predicted_indices = torch.argmax(logits, dim=1)
|
| 28 |
+
answers = [chr(ord('A') + idx) for idx in predicted_indices]
|
| 29 |
+
return answers
|
| 30 |
+
|
| 31 |
+
# Create the Gradio interface
|
| 32 |
+
iface = gr.Interface(
|
| 33 |
+
fn=predict,
|
| 34 |
+
inputs=gr.inputs.Input(type="json"),
|
| 35 |
+
outputs=gr.outputs.Label(num_top_classes=1, label="Predicted Answer"),
|
| 36 |
+
live=True,
|
| 37 |
+
examples=[
|
| 38 |
+
{"question": "What is the capital of France?", "A": "Paris", "B": "London", "C": "Berlin", "D": "Madrid", "E": "Rome"}
|
| 39 |
+
],
|
| 40 |
+
title="Multiple-Choice Question Answering",
|
| 41 |
+
description="Enter a question and answer choices (A to E) to get the predicted answer.",
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
# Run the interface
|
| 45 |
+
iface.launch()
|