File size: 3,874 Bytes
18fc9c1
 
 
 
 
1279145
 
18fc9c1
bec29d2
 
 
 
 
 
 
 
1279145
bec29d2
 
 
 
 
 
 
 
 
 
 
 
 
 
01cbd3a
bec29d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01cbd3a
 
 
 
 
 
 
 
 
bec29d2
01cbd3a
 
 
c1f6444
01cbd3a
bec29d2
 
 
eced281
 
1279145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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)