Spaces:
Sleeping
Sleeping
import gradio as gr | |
import pandas as pd | |
from mcq_generator import ImprovedMCQGenerator, is_suitable_for_students | |
import io | |
# Load MCQ generator once | |
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: | |
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 download files | |
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 file objects | |
txt_file = io.BytesIO(txt_output.encode('utf-8')) | |
csv_file = io.BytesIO() | |
pd.DataFrame(csv_data).to_csv(csv_file, index=False) | |
csv_file.seek(0) | |
return pretty_mcqs, [("mcqs.txt", txt_file), ("mcqs.csv", csv_file)], "β MCQs generated successfully!" | |
except Exception as e: | |
return None, None, f"β Error generating MCQs: {str(e)}" | |
# Gradio Interface | |
with gr.Blocks(theme=gr.themes.Default()) as demo: | |
gr.Markdown("<h1 style='text-align:center;'>π Smart MCQ Generator</h1>") | |
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") | |
with gr.Row(): | |
generate_btn = gr.Button("π Generate MCQs") | |
status = gr.Textbox(label="Status", interactive=False) | |
with gr.Row(): | |
mcq_output = gr.HTML() | |
with gr.Row(): | |
download_output = gr.File(label="Download MCQs (TXT/CSV)") | |
generate_btn.click( | |
fn=generate_mcqs_ui, | |
inputs=[paragraph_input, num_questions_slider], | |
outputs=[mcq_output, download_output, status] | |
) | |
demo.launch() | |