YashJD commited on
Commit
0eb15ce
·
verified ·
1 Parent(s): b53affd

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -121
app.py DELETED
@@ -1,121 +0,0 @@
1
- import streamlit as st
2
- import google.generativeai as genai
3
- import random
4
- import re
5
-
6
- # Configure the Gemini API with your API key
7
- genai.configure(api_key='AIzaSyAjDT14MAn93D1xJMsBtHeaNThaFIYeLbs')
8
-
9
- # Initialize the generative model
10
- model = genai.GenerativeModel('gemini-pro')
11
-
12
- def generate_mcqs(context):
13
- prompt = f"""
14
- Based on the following context, generate 10 multiple-choice questions (MCQs).
15
- You can use data without the context too if needed, but all the topics within the context should be included.
16
- Generate valid MCQs too.
17
- Each MCQ should have 4 options with only one correct answer.
18
- Format each question exactly as follows:
19
-
20
- **Question X:** [Question text]
21
- A) [Option A]
22
- B) [Option B]
23
- C) [Option C]
24
- D) [Option D]
25
- Correct Answer: [A/B/C/D]
26
-
27
- Context:
28
- {context}
29
- """
30
-
31
- try:
32
- response = model.generate_content(prompt)
33
- raw_text = response.text
34
-
35
- # Debug: Print raw response
36
- st.text("Raw API Response:")
37
- st.text(raw_text)
38
-
39
- # Parse the raw text into a structured format
40
- questions = re.split(r'\*\*Question \d+:\*\*', raw_text)[1:] # Split by question number
41
- mcqs = []
42
-
43
- for q in questions:
44
- try:
45
- # Extract question text
46
- question_text = q.split('A)')[0].strip()
47
-
48
- # Extract options
49
- options = re.findall(r'([A-D]\).*?)(?=[A-D]\)|Correct Answer:)', q, re.DOTALL)
50
- options = [opt.strip() for opt in options]
51
-
52
- # Extract correct answer
53
- correct_answer = re.search(r'Correct Answer:\s*([A-D])', q).group(1)
54
-
55
- if len(options) == 4 and correct_answer in ['A', 'B', 'C', 'D']:
56
- mcqs.append({
57
- "question": question_text,
58
- "options": options,
59
- "correct_answer": correct_answer
60
- })
61
- else:
62
- st.warning(f"Skipped question due to incorrect format: {q}")
63
- except Exception as e:
64
- st.warning(f"Skipped a malformed question: {str(e)}\nQuestion: {q}")
65
-
66
- if not mcqs:
67
- raise ValueError("No valid MCQs were generated")
68
-
69
- return mcqs
70
- except Exception as e:
71
- st.error(f"An error occurred while generating MCQs: {str(e)}")
72
- return None
73
-
74
- def main():
75
- st.title("MCQ Generator and Exam")
76
-
77
- # Input section
78
- st.header("Generate MCQs")
79
- context = st.text_area("Enter the context or data for generating MCQs:")
80
- if st.button("Generate MCQs"):
81
- if context:
82
- with st.spinner("Generating MCQs..."):
83
- mcqs = generate_mcqs(context)
84
- if mcqs:
85
- st.session_state.mcqs = mcqs
86
- st.success(f"Generated {len(mcqs)} MCQs successfully!")
87
- else:
88
- st.error("Failed to generate valid MCQs. Please try again with a different or more detailed context.")
89
- else:
90
- st.warning("Please enter some context to generate MCQs.")
91
-
92
- # Exam section
93
- st.header("Take Exam")
94
- if 'mcqs' in st.session_state and st.session_state.mcqs:
95
- user_answers = []
96
- for i, question in enumerate(st.session_state.mcqs):
97
- st.subheader(f"Question {i + 1}")
98
- st.write(question['question'])
99
- user_answer = st.radio("Select your answer:", question['options'], key=f"q{i}")
100
- user_answers.append(user_answer)
101
-
102
- if st.button("Submit Exam"):
103
- score = sum(1 for q, a in zip(st.session_state.mcqs, user_answers)
104
- if a == q['options'][ord(q['correct_answer']) - ord('A')])
105
- st.subheader("Exam Completed!")
106
- st.write(f"Your score: {score}/{len(st.session_state.mcqs)}")
107
-
108
- # Display correct answers
109
- st.subheader("Correct Answers:")
110
- for i, (question, user_answer) in enumerate(zip(st.session_state.mcqs, user_answers)):
111
- st.write(f"Q{i+1}: {question['question']}")
112
- st.write(f"Your answer: {user_answer}")
113
- correct_answer = question['options'][ord(question['correct_answer']) - ord('A')]
114
- st.write(f"Correct answer: {correct_answer}")
115
- st.write("---")
116
-
117
- else:
118
- st.info("Generate MCQs first to take the exam.")
119
-
120
- if __name__ == "__main__":
121
- main()