mcq-generator / app.py
ManthaBhuvana's picture
Update app.py
1279145 verified
raw
history blame
3.87 kB
import gradio as gr
import pandas as pd
from mcq_generator import ImprovedMCQGenerator, is_suitable_for_students
import io
# Initialize MCQ Generator
mcq_generator = ImprovedMCQGenerator()
def generate_mcqs_ui(paragraph, num_questions):
if not paragraph.strip():
return None, None, "⚠️ Please enter a valid paragraph."
if not is_suitable_for_students(paragraph):
return None, None, "❌ The paragraph is not suitable for MCQ generation (due to bias/toxicity/short length)."
try:
# Generate MCQs using the generator
mcqs = mcq_generator.generate_mcqs(paragraph, num_questions)
# Create pretty formatted MCQ list
pretty_mcqs = []
for idx, mcq in enumerate(mcqs):
options = ""
for opt_idx, option in enumerate(mcq['options']):
options += f"<b>{chr(65+opt_idx)}.</b> {option}<br>"
question_html = f"<div style='margin-bottom:20px; padding:10px; border:1px solid #ccc; border-radius:10px; background:#f9f9f9;'>"
question_html += f"<b>Q{idx+1}:</b> {mcq['question']}<br><br>{options}"
question_html += f"<i><b>Answer:</b> {chr(65+mcq['answer_index'])}</i>"
question_html += "</div>"
pretty_mcqs.append(question_html)
# Prepare text output and CSV data
txt_output = ""
csv_data = []
for idx, mcq in enumerate(mcqs):
txt_output += f"Q{idx+1}: {mcq['question']}\n"
for opt_idx, option in enumerate(mcq['options']):
txt_output += f" {chr(65+opt_idx)}. {option}\n"
txt_output += f"Answer: {chr(65+mcq['answer_index'])}\n\n"
csv_data.append({
'Question': mcq['question'],
'Option A': mcq['options'][0],
'Option B': mcq['options'][1],
'Option C': mcq['options'][2],
'Option D': mcq['options'][3],
'Answer': chr(65+mcq['answer_index'])
})
# Create in-memory text file
txt_buffer = io.StringIO()
txt_buffer.write(txt_output)
txt_buffer.seek(0)
# Create in-memory CSV file
csv_buffer = io.StringIO()
pd.DataFrame(csv_data).to_csv(csv_buffer, index=False)
csv_buffer.seek(0)
# Return Gradio-compatible downloadable files
txt_file = gr.File(value=txt_buffer, file_name="mcqs.txt", file_type="text/plain")
csv_file = gr.File(value=csv_buffer, file_name="mcqs.csv", file_type="text/csv")
return pretty_mcqs, [txt_file, csv_file], "βœ… MCQs generated successfully!"
except Exception as e:
return None, None, f"❌ Error generating MCQs: {str(e)}"
# Define Gradio interface
with gr.Blocks() as demo:
gr.Markdown("<h1 style='text-align:center;'>πŸ“š Smart MCQ Generator</h1>")
# Input for the paragraph and number of questions
with gr.Row():
paragraph_input = gr.Textbox(lines=8, label="Enter Paragraph for MCQs", placeholder="Paste your study material here...")
with gr.Row():
num_questions_slider = gr.Slider(1, 10, step=1, value=5, label="Number of Questions")
# Generate Button
with gr.Row():
generate_btn = gr.Button("πŸš€ Generate MCQs")
# Status box to show the message (success/error)
status = gr.Textbox(label="Status", interactive=False)
# MCQ output and download links
with gr.Row():
mcq_output = gr.HTML()
with gr.Row():
download_output = gr.File(label="Download MCQs (TXT/CSV)")
# Set up the button to trigger MCQ generation
generate_btn.click(
fn=generate_mcqs_ui,
inputs=[paragraph_input, num_questions_slider],
outputs=[mcq_output, download_output, status]
)
# Launch the app
demo.launch(share=True, server_name="0.0.0.0", server_port=7860)