Spaces:
Sleeping
Sleeping
import gradio as gr | |
import pandas as pd | |
from mcq_generator import ImprovedMCQGenerator, is_suitable_for_students | |
import io | |
import tempfile | |
import os | |
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 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)}" | |
demo.launch(share=True, server_name="0.0.0.0", server_port=7860) | |