Spaces:
Sleeping
Sleeping
File size: 2,709 Bytes
18fc9c1 bec29d2 01cbd3a bec29d2 01cbd3a bec29d2 01cbd3a c1f6444 01cbd3a bec29d2 eced281 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
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)
|