udaypratap commited on
Commit
ded6bc1
·
verified ·
1 Parent(s): 9594ff7

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -0
app.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import torch.nn.functional as F
4
+ from transformers import AutoTokenizer, AutoModelForMultipleChoice
5
+
6
+ # 1. Load fine-tuned model and tokenizer from Hugging Face Hub
7
+ MODEL_ID = "udaypratap/smart-mcq-solver"
8
+
9
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
10
+ model = AutoModelForMultipleChoice.from_pretrained(MODEL_ID)
11
+ model.eval()
12
+
13
+ # 2. Define prediction function
14
+ def predict_mcq(prompt, option_a, option_b, option_c, option_d, option_e):
15
+ options = [option_a, option_b, option_c, option_d, option_e]
16
+ labels = ["A", "B", "C", "D", "E"]
17
+
18
+ # Format inputs for AutoModelForMultipleChoice
19
+ first_sentences = [prompt] * 5
20
+ second_sentences = options
21
+
22
+ inputs = tokenizer(
23
+ first_sentences,
24
+ second_sentences,
25
+ truncation=True,
26
+ padding=True,
27
+ max_length=256,
28
+ return_tensors="pt"
29
+ )
30
+
31
+ # Reshape input tensors for multiple choice model: (batch_size=1, num_choices=5, seq_len)
32
+ input_ids = inputs["input_ids"].unsqueeze(0)
33
+ attention_mask = inputs["attention_mask"].unsqueeze(0)
34
+
35
+ with torch.no_grad():
36
+ outputs = model(input_ids=input_ids, attention_mask=attention_mask)
37
+ logits = outputs.logits.squeeze(0)
38
+ probs = F.softmax(logits, dim=-1)
39
+
40
+ # Get top 3 predicted choices
41
+ top3_indices = torch.topk(probs, k=3).indices.tolist()
42
+ top3_choices = [f"{labels[idx]} ({probs[idx].item():.2%})" for idx in top3_indices]
43
+
44
+ return f"Top 3 Predicted Answers: {', '.join(top3_choices)}"
45
+
46
+ # 3. Create Gradio Interface
47
+ demo = gr.Interface(
48
+ fn=predict_mcq,
49
+ inputs=[
50
+ gr.Textbox(label="Question Prompt", placeholder="Enter your question here..."),
51
+ gr.Textbox(label="Option A"),
52
+ gr.Textbox(label="Option B"),
53
+ gr.Textbox(label="Option C"),
54
+ gr.Textbox(label="Option D"),
55
+ gr.Textbox(label="Option E")
56
+ ],
57
+ outputs=gr.Textbox(label="Predictions"),
58
+ title="Smart MCQ Solver",
59
+ description="Enter a question prompt along with 5 options to get the top predicted answers."
60
+ )
61
+
62
+ if __name__ == "__main__":
63
+ demo.launch()