MujtabaAhmed commited on
Commit
227598c
·
verified ·
1 Parent(s): 218bf53

Update MCQ.py

Browse files
Files changed (1) hide show
  1. MCQ.py +148 -148
MCQ.py CHANGED
@@ -1,149 +1,149 @@
1
- import streamlit as st
2
- import openai
3
- import re
4
- from docx import Document
5
- from docx.enum.text import WD_ALIGN_PARAGRAPH
6
- from io import BytesIO
7
-
8
- # Set up OpenAI API
9
- openai.api_key = "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"
10
-
11
- # Function to get MCQ questions from OpenAI GPT-3.5
12
- def generate_mcq_questions(topic, difficulty, num_questions):
13
- prompt = f"""
14
- Generate a multiple-choice quiz with the following specifications:
15
- - Topic: "{topic}"
16
- - Difficulty level: "{difficulty}"
17
- - Number of questions: {num_questions}
18
- - Each question should have 4 options labeled a, b, c, and d.
19
- - Each option should be brief (2-3 words).
20
- - Clearly specify the correct answer for each question.
21
-
22
- Ensure the questions and options are:
23
- 1. Clear and concise.
24
- 2. Relevant to the specified topic.
25
- 3. Appropriately challenging based on the specified difficulty level.
26
- 4. Complete with all parts included.
27
-
28
- Do not include code-related questions.
29
-
30
- Example format:
31
- Q1: What is the capital of France?
32
- a. Berlin
33
- b. Madrid
34
- c. Paris
35
- d. Rome
36
- Answer: c
37
-
38
- Quiz:
39
- """
40
-
41
- response = openai.chat.completions.create(
42
- model="gpt-3.5-turbo",
43
- messages=[{"role": "system", "content": "You are a expert who helps in generating MCQs."},
44
- {"role": "user", "content": prompt}],
45
- max_tokens=1500,
46
- n=1,
47
- stop=None,
48
- temperature=0.4
49
- )
50
- return response.choices[0].message.content
51
-
52
- # Function to format the generated quiz to exclude answers and add selection options
53
- def format_quiz(quiz):
54
- lines = quiz.split("\n")
55
- formatted_quiz = []
56
- current_question = []
57
- for line in lines:
58
- if re.match(r"^Q\d+: ", line):
59
- if current_question:
60
- formatted_quiz.append(current_question)
61
- current_question = [line]
62
- elif re.match(r"^[a-d]\. ", line):
63
- current_question.append(line)
64
- elif re.match(r"^Answer: ", line):
65
- current_question.append(line)
66
- if current_question:
67
- formatted_quiz.append(current_question)
68
- return formatted_quiz
69
-
70
- # Function to generate a DOCX document
71
- def generate_docx(quiz, heading1, heading2):
72
- doc = Document()
73
-
74
- heading1_paragraph = doc.add_heading(heading1, level=0)
75
- heading1_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
76
-
77
- heading2_paragraph = doc.add_heading(heading2, level=2)
78
- heading2_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
79
-
80
- doc.add_paragraph("Name:")
81
- doc.add_paragraph("Roll number:")
82
- doc.add_paragraph("Class:")
83
- doc.add_paragraph("Section:")
84
- doc.add_paragraph("") # Add space after the fields
85
-
86
- for question in quiz:
87
- for line in question:
88
- if not re.match(r"^Answer: ", line):
89
- doc.add_paragraph(line)
90
- doc.add_paragraph("") # Add a line break between questions
91
-
92
- # Save document to BytesIO object
93
- doc_io = BytesIO()
94
- doc.save(doc_io)
95
- doc_io.seek(0)
96
-
97
- return doc_io
98
-
99
- # Streamlit app
100
- def MCQ():
101
- st.title("MCQ Quiz Generator")
102
-
103
- # Input fields for quiz parameters
104
- institute_name = st.text_input("Enter the Name of Institute:")
105
- quiz_title = st.text_input("Enter the quiz title:")
106
- topic = st.text_input("Enter the topic:")
107
- difficulty = st.selectbox("Select the difficulty level:", ["Beginner", "Intermediate", "Expert"])
108
- num_questions = st.number_input("Enter the number of questions:", min_value=1, max_value=20, value=5)
109
-
110
- # Generate quiz button
111
- if st.button("Generate Quiz"):
112
- if topic:
113
- with st.spinner("Generating questions..."):
114
- quiz = generate_mcq_questions(topic, difficulty, num_questions)
115
- formatted_quiz = format_quiz(quiz)
116
- st.subheader("Generated Quiz:")
117
- if institute_name:
118
- st.write(f"*{institute_name}*")
119
- if quiz_title:
120
- st.write(f"*{quiz_title}*")
121
-
122
- # Store the quiz in session state
123
- st.session_state['quiz'] = formatted_quiz
124
-
125
- # Generate DOCX and provide download button
126
- docx_content = generate_docx(formatted_quiz, institute_name, quiz_title)
127
- st.session_state['docx_content'] = docx_content
128
- else:
129
- st.error("Please enter a topic to generate the quiz.")
130
-
131
- # Display the quiz and allow users to view options
132
- if 'quiz' in st.session_state:
133
- for i, question in enumerate(st.session_state['quiz']):
134
- st.write(question[0])
135
- options = question[1:]
136
- for line in options:
137
- if "Answer: " in line:
138
- st.write(f"Correct answer: {line.split(': ')[1]}")
139
- else:
140
- st.write(line)
141
-
142
- # Download DOCX button
143
- if 'quiz' in st.session_state and 'docx_content' in st.session_state:
144
- st.download_button(
145
- label="Download Quiz as DOCX",
146
- data=st.session_state['docx_content'],
147
- file_name=f"{topic} quiz.docx",
148
- mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
149
  )
 
1
+ import streamlit as st
2
+ import openai
3
+ import re
4
+ from docx import Document
5
+ from docx.enum.text import WD_ALIGN_PARAGRAPH
6
+ from io import BytesIO
7
+ import os
8
+ # Set up OpenAI API
9
+ openai.api_key = os.environ["key"]
10
+
11
+ # Function to get MCQ questions from OpenAI GPT-3.5
12
+ def generate_mcq_questions(topic, difficulty, num_questions):
13
+ prompt = f"""
14
+ Generate a multiple-choice quiz with the following specifications:
15
+ - Topic: "{topic}"
16
+ - Difficulty level: "{difficulty}"
17
+ - Number of questions: {num_questions}
18
+ - Each question should have 4 options labeled a, b, c, and d.
19
+ - Each option should be brief (2-3 words).
20
+ - Clearly specify the correct answer for each question.
21
+
22
+ Ensure the questions and options are:
23
+ 1. Clear and concise.
24
+ 2. Relevant to the specified topic.
25
+ 3. Appropriately challenging based on the specified difficulty level.
26
+ 4. Complete with all parts included.
27
+
28
+ Do not include code-related questions.
29
+
30
+ Example format:
31
+ Q1: What is the capital of France?
32
+ a. Berlin
33
+ b. Madrid
34
+ c. Paris
35
+ d. Rome
36
+ Answer: c
37
+
38
+ Quiz:
39
+ """
40
+
41
+ response = openai.chat.completions.create(
42
+ model="gpt-3.5-turbo",
43
+ messages=[{"role": "system", "content": "You are a expert who helps in generating MCQs."},
44
+ {"role": "user", "content": prompt}],
45
+ max_tokens=1500,
46
+ n=1,
47
+ stop=None,
48
+ temperature=0.4
49
+ )
50
+ return response.choices[0].message.content
51
+
52
+ # Function to format the generated quiz to exclude answers and add selection options
53
+ def format_quiz(quiz):
54
+ lines = quiz.split("\n")
55
+ formatted_quiz = []
56
+ current_question = []
57
+ for line in lines:
58
+ if re.match(r"^Q\d+: ", line):
59
+ if current_question:
60
+ formatted_quiz.append(current_question)
61
+ current_question = [line]
62
+ elif re.match(r"^[a-d]\. ", line):
63
+ current_question.append(line)
64
+ elif re.match(r"^Answer: ", line):
65
+ current_question.append(line)
66
+ if current_question:
67
+ formatted_quiz.append(current_question)
68
+ return formatted_quiz
69
+
70
+ # Function to generate a DOCX document
71
+ def generate_docx(quiz, heading1, heading2):
72
+ doc = Document()
73
+
74
+ heading1_paragraph = doc.add_heading(heading1, level=0)
75
+ heading1_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
76
+
77
+ heading2_paragraph = doc.add_heading(heading2, level=2)
78
+ heading2_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
79
+
80
+ doc.add_paragraph("Name:")
81
+ doc.add_paragraph("Roll number:")
82
+ doc.add_paragraph("Class:")
83
+ doc.add_paragraph("Section:")
84
+ doc.add_paragraph("") # Add space after the fields
85
+
86
+ for question in quiz:
87
+ for line in question:
88
+ if not re.match(r"^Answer: ", line):
89
+ doc.add_paragraph(line)
90
+ doc.add_paragraph("") # Add a line break between questions
91
+
92
+ # Save document to BytesIO object
93
+ doc_io = BytesIO()
94
+ doc.save(doc_io)
95
+ doc_io.seek(0)
96
+
97
+ return doc_io
98
+
99
+ # Streamlit app
100
+ def MCQ():
101
+ st.title("MCQ Quiz Generator")
102
+
103
+ # Input fields for quiz parameters
104
+ institute_name = st.text_input("Enter the Name of Institute:")
105
+ quiz_title = st.text_input("Enter the quiz title:")
106
+ topic = st.text_input("Enter the topic:")
107
+ difficulty = st.selectbox("Select the difficulty level:", ["Beginner", "Intermediate", "Expert"])
108
+ num_questions = st.number_input("Enter the number of questions:", min_value=1, max_value=20, value=5)
109
+
110
+ # Generate quiz button
111
+ if st.button("Generate Quiz"):
112
+ if topic:
113
+ with st.spinner("Generating questions..."):
114
+ quiz = generate_mcq_questions(topic, difficulty, num_questions)
115
+ formatted_quiz = format_quiz(quiz)
116
+ st.subheader("Generated Quiz:")
117
+ if institute_name:
118
+ st.write(f"*{institute_name}*")
119
+ if quiz_title:
120
+ st.write(f"*{quiz_title}*")
121
+
122
+ # Store the quiz in session state
123
+ st.session_state['quiz'] = formatted_quiz
124
+
125
+ # Generate DOCX and provide download button
126
+ docx_content = generate_docx(formatted_quiz, institute_name, quiz_title)
127
+ st.session_state['docx_content'] = docx_content
128
+ else:
129
+ st.error("Please enter a topic to generate the quiz.")
130
+
131
+ # Display the quiz and allow users to view options
132
+ if 'quiz' in st.session_state:
133
+ for i, question in enumerate(st.session_state['quiz']):
134
+ st.write(question[0])
135
+ options = question[1:]
136
+ for line in options:
137
+ if "Answer: " in line:
138
+ st.write(f"Correct answer: {line.split(': ')[1]}")
139
+ else:
140
+ st.write(line)
141
+
142
+ # Download DOCX button
143
+ if 'quiz' in st.session_state and 'docx_content' in st.session_state:
144
+ st.download_button(
145
+ label="Download Quiz as DOCX",
146
+ data=st.session_state['docx_content'],
147
+ file_name=f"{topic} quiz.docx",
148
+ mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
149
  )