capradeepgujaran commited on
Commit
deff9b7
1 Parent(s): 76ec966

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +101 -145
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import gradio as gr
2
  from groq import Groq
3
  import os
@@ -14,8 +15,9 @@ client = Groq(
14
  class QuizApp:
15
  def __init__(self):
16
  self.current_questions = []
 
17
  self.user_data = {}
18
-
19
  def generate_questions(self, text, num_questions):
20
  prompt = f"""Create {num_questions} multiple choice questions based on this text:
21
  {text}
@@ -26,20 +28,19 @@ class QuizApp:
26
  3. Have only one correct answer
27
  4. Be educational and test understanding
28
 
29
- Return the questions in this JSON format:
30
  [
31
  {{
32
- "question": "Question text?",
33
  "options": [
34
  "Correct answer",
35
  "Wrong answer 1",
36
  "Wrong answer 2",
37
  "Wrong answer 3"
38
  ],
39
- "correct_answers": [0]
40
  }}
41
- ]
42
- Only return the JSON array, no other text."""
43
 
44
  try:
45
  response = client.chat.completions.create(
@@ -49,65 +50,39 @@ class QuizApp:
49
  ],
50
  model="llama-3.2-3b-preview",
51
  temperature=0.5,
52
- max_tokens=2048,
53
- top_p=0.9
54
  )
55
 
56
  response_text = response.choices[0].message.content.strip()
57
- # Remove any markdown formatting
58
  response_text = response_text.replace("```json", "").replace("```", "").strip()
59
 
60
  questions = json.loads(response_text)
61
- if isinstance(questions, list):
62
- self.current_questions = questions
63
- else:
64
- self.current_questions = questions.get("questions", [])
65
-
66
- # Validate question format
67
- for q in self.current_questions:
68
- if not all(key in q for key in ["question", "options", "correct_answers"]):
69
- raise ValueError("Invalid question format")
70
- if len(q["options"]) != 4:
71
- raise ValueError("Each question must have exactly 4 options")
72
-
73
- return json.dumps(self.current_questions, indent=2)
74
 
75
  except Exception as e:
76
  print(f"Error generating questions: {e}")
77
- return json.dumps([{
78
- "question": "Error generating questions. Please try again.",
79
- "options": ["Error", "Error", "Error", "Error"],
80
- "correct_answers": [0]
81
- }])
82
-
83
  def calculate_score(self, answers):
84
- try:
85
- answers = json.loads(answers) if isinstance(answers, str) else answers
86
- total = len(self.current_questions)
87
- correct = 0
88
-
89
- for q, a in zip(self.current_questions, answers):
90
- if set(a) == set(q["correct_answers"]):
91
- correct += 1
92
-
93
- return (correct / total) * 100
94
- except Exception as e:
95
- print(f"Error calculating score: {e}")
96
  return 0
97
-
 
 
 
 
 
98
  def generate_certificate(self, name, score, course_name, company_logo=None, participant_photo=None):
99
  try:
100
- # Create certificate with a light blue background
101
  certificate = Image.new('RGB', (1200, 800), '#F0F8FF')
102
  draw = ImageDraw.Draw(certificate)
103
 
104
- # Load fonts
105
  try:
106
  title_font = ImageFont.truetype("arial.ttf", 60)
107
  text_font = ImageFont.truetype("arial.ttf", 40)
108
  subtitle_font = ImageFont.truetype("arial.ttf", 30)
109
  except:
110
- print("Using default font as Arial not found")
111
  title_font = ImageFont.load_default()
112
  text_font = ImageFont.load_default()
113
  subtitle_font = ImageFont.load_default()
@@ -119,16 +94,14 @@ class QuizApp:
119
  draw.text((600, 100), "CertifyMe AI", font=title_font, fill='#4682B4', anchor="mm")
120
  draw.text((600, 160), "Certificate of Achievement", font=subtitle_font, fill='#4682B4', anchor="mm")
121
  draw.text((600, 300), "This is to certify that", font=text_font, fill='black', anchor="mm")
122
- draw.text((600, 380), name, font=text_font, fill='#4682B4', anchor="mm")
123
  draw.text((600, 460), "has successfully completed", font=text_font, fill='black', anchor="mm")
124
- draw.text((600, 540), course_name, font=text_font, fill='#4682B4', anchor="mm")
125
  draw.text((600, 620), f"with a score of {score:.1f}%", font=text_font, fill='black', anchor="mm")
126
 
127
- # Add date
128
  current_date = datetime.now().strftime("%B %d, %Y")
129
  draw.text((600, 700), current_date, font=text_font, fill='black', anchor="mm")
130
 
131
- # Add logo if provided
132
  if company_logo is not None:
133
  try:
134
  logo = Image.open(company_logo)
@@ -137,7 +110,6 @@ class QuizApp:
137
  except Exception as e:
138
  print(f"Error adding logo: {e}")
139
 
140
- # Add photo if provided
141
  if participant_photo is not None:
142
  try:
143
  photo = Image.open(participant_photo)
@@ -146,7 +118,6 @@ class QuizApp:
146
  except Exception as e:
147
  print(f"Error adding photo: {e}")
148
 
149
- # Save certificate
150
  temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
151
  certificate.save(temp_file.name)
152
  return temp_file.name
@@ -154,108 +125,94 @@ class QuizApp:
154
  print(f"Error generating certificate: {e}")
155
  return None
156
 
157
- def create_quiz_app():
158
- quiz_app = QuizApp()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
 
160
- with gr.Blocks(title="CertifyMe AI", theme=gr.themes.Soft()) as demo:
161
- current_tab = gr.State(0)
162
- current_questions = gr.State([])
163
- user_answers = gr.State([])
164
-
165
- gr.Markdown("""
166
- # 🎓 CertifyMe AI
167
- ### Transform Your Knowledge into Recognized Achievements
168
- """)
169
-
170
- with gr.Tabs() as tabs:
171
- # Step 1: Profile Setup (remains largely the same)
172
- with gr.Tab("📋 Step 1: Profile Setup", id=0) as tab1:
173
- # ... (previous profile setup code remains the same)
 
 
 
 
 
 
 
 
174
 
175
- # Step 2: Take Assessment (completely revised)
176
- with gr.Tab("📝 Step 2: Take Assessment", id=1) as tab2:
177
- def format_questions(questions_json):
178
- try:
179
- questions = json.loads(questions_json) if isinstance(questions_json, str) else questions_json
180
- return questions
181
- except:
182
- return []
183
-
184
- def display_questions(questions):
185
- with gr.Group() as quiz_container:
186
- answers = []
187
- for i, q in enumerate(questions):
188
- gr.Markdown(f"### Question {i+1}")
189
- gr.Markdown(q["question"])
190
- radio = gr.Radio(
191
- choices=q["options"],
192
- label="Select your answer",
193
- value=None,
194
- visible=True
195
- )
196
- answers.append(radio)
197
- return quiz_container
198
-
199
- def process_answers(answers):
200
- processed = []
201
- for i, ans in enumerate(answers):
202
- if ans is not None:
203
- processed.append([i])
204
- return processed
205
-
206
- questions_display = gr.JSON(visible=False) # Hidden JSON storage
207
- quiz_area = gr.Group(visible=False) # Container for dynamic quiz content
208
-
209
- submit_btn = gr.Button("Submit Assessment", variant="primary", visible=False)
210
- score_display = gr.Number(label="Your Score", visible=False)
211
-
212
- # Update the question display when questions are generated
213
- questions_display.change(
214
- fn=lambda q: (
215
- gr.Group(visible=True),
216
- gr.Button(visible=True),
217
- format_questions(q)
218
- ),
219
- inputs=[questions_display],
220
- outputs=[quiz_area, submit_btn, current_questions]
221
  )
222
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
 
224
  # Step 3: Get Certified
225
- with gr.Tab("🎓 Step 3: Get Certified", id=2) as tab3:
226
- gr.Markdown("""
227
- ### Certification
228
- - Your certificate will be generated automatically if you score 80% or above
229
- - The certificate includes your name, score, and completion date
230
- - Company logo and photo will be included if provided
231
- - You can download your certificate once it's generated
232
- """)
233
-
234
  course_name = gr.Textbox(
235
- label="Certification Title",
236
  value="Professional Assessment Certification"
237
  )
238
  certificate_display = gr.Image(label="Your Certificate")
239
 
240
- # Helper functions for tab navigation
241
- def generate_and_switch_tab(text, num_questions):
242
- questions = quiz_app.generate_questions(text, num_questions)
243
- return questions, 1, gr.Markdown(visible=True), gr.Button(visible=True)
244
-
245
- def calculate_score(selected_answers, questions):
246
- correct = 0
247
- total = len(questions)
248
- for q, ans in zip(questions, selected_answers):
249
- if set(ans) == set(q["correct_answers"]):
250
- correct += 1
251
- score = (correct / total) * 100 if total > 0 else 0
252
- return score, 2
253
-
254
  # Event handlers
255
  generate_btn.click(
256
- fn=generate_and_switch_tab,
257
  inputs=[text_input, num_questions],
258
- outputs=[questions_display, current_tab, quiz_area, submit_btn]
259
  ).then(
260
  fn=lambda tab: gr.Tabs(selected=tab),
261
  inputs=[current_tab],
@@ -263,8 +220,8 @@ class QuizApp:
263
  )
264
 
265
  submit_btn.click(
266
- fn=calculate_score,
267
- inputs=[user_answers, current_questions],
268
  outputs=[score_display, current_tab]
269
  ).then(
270
  fn=lambda tab: gr.Tabs(selected=tab),
@@ -272,7 +229,6 @@ class QuizApp:
272
  outputs=[tabs]
273
  )
274
 
275
- # Certificate generation remains the same
276
  score_display.change(
277
  fn=lambda score, user_name, course, logo, photo: (
278
  quiz_app.generate_certificate(user_name, score, course, logo, photo)
@@ -284,11 +240,11 @@ class QuizApp:
284
 
285
  return demo
286
 
287
- # Main execution remains the same
288
  if __name__ == "__main__":
289
  if not os.getenv("GROQ_API_KEY"):
290
  print("Please set your GROQ_API_KEY environment variable")
291
  exit(1)
292
-
293
- demo = create_quiz_app()
294
- demo.launch()
 
 
1
+ ```python
2
  import gradio as gr
3
  from groq import Groq
4
  import os
 
15
  class QuizApp:
16
  def __init__(self):
17
  self.current_questions = []
18
+ self.current_answers = []
19
  self.user_data = {}
20
+
21
  def generate_questions(self, text, num_questions):
22
  prompt = f"""Create {num_questions} multiple choice questions based on this text:
23
  {text}
 
28
  3. Have only one correct answer
29
  4. Be educational and test understanding
30
 
31
+ Return in this exact JSON format:
32
  [
33
  {{
34
+ "question": "What is the main topic discussed?",
35
  "options": [
36
  "Correct answer",
37
  "Wrong answer 1",
38
  "Wrong answer 2",
39
  "Wrong answer 3"
40
  ],
41
+ "correct_answer": 0
42
  }}
43
+ ]"""
 
44
 
45
  try:
46
  response = client.chat.completions.create(
 
50
  ],
51
  model="llama-3.2-3b-preview",
52
  temperature=0.5,
53
+ max_tokens=2048
 
54
  )
55
 
56
  response_text = response.choices[0].message.content.strip()
 
57
  response_text = response_text.replace("```json", "").replace("```", "").strip()
58
 
59
  questions = json.loads(response_text)
60
+ self.current_questions = questions
61
+ return questions
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  except Exception as e:
64
  print(f"Error generating questions: {e}")
65
+ return []
66
+
 
 
 
 
67
  def calculate_score(self, answers):
68
+ if not answers or not self.current_questions:
 
 
 
 
 
 
 
 
 
 
 
69
  return 0
70
+
71
+ total = len(self.current_questions)
72
+ correct = sum(1 for q, a in zip(self.current_questions, answers)
73
+ if q['correct_answer'] == a)
74
+ return (correct / total) * 100
75
+
76
  def generate_certificate(self, name, score, course_name, company_logo=None, participant_photo=None):
77
  try:
 
78
  certificate = Image.new('RGB', (1200, 800), '#F0F8FF')
79
  draw = ImageDraw.Draw(certificate)
80
 
 
81
  try:
82
  title_font = ImageFont.truetype("arial.ttf", 60)
83
  text_font = ImageFont.truetype("arial.ttf", 40)
84
  subtitle_font = ImageFont.truetype("arial.ttf", 30)
85
  except:
 
86
  title_font = ImageFont.load_default()
87
  text_font = ImageFont.load_default()
88
  subtitle_font = ImageFont.load_default()
 
94
  draw.text((600, 100), "CertifyMe AI", font=title_font, fill='#4682B4', anchor="mm")
95
  draw.text((600, 160), "Certificate of Achievement", font=subtitle_font, fill='#4682B4', anchor="mm")
96
  draw.text((600, 300), "This is to certify that", font=text_font, fill='black', anchor="mm")
97
+ draw.text((600, 380), name or "Participant", font=text_font, fill='#4682B4', anchor="mm")
98
  draw.text((600, 460), "has successfully completed", font=text_font, fill='black', anchor="mm")
99
+ draw.text((600, 540), course_name or "Assessment", font=text_font, fill='#4682B4', anchor="mm")
100
  draw.text((600, 620), f"with a score of {score:.1f}%", font=text_font, fill='black', anchor="mm")
101
 
 
102
  current_date = datetime.now().strftime("%B %d, %Y")
103
  draw.text((600, 700), current_date, font=text_font, fill='black', anchor="mm")
104
 
 
105
  if company_logo is not None:
106
  try:
107
  logo = Image.open(company_logo)
 
110
  except Exception as e:
111
  print(f"Error adding logo: {e}")
112
 
 
113
  if participant_photo is not None:
114
  try:
115
  photo = Image.open(participant_photo)
 
118
  except Exception as e:
119
  print(f"Error adding photo: {e}")
120
 
 
121
  temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
122
  certificate.save(temp_file.name)
123
  return temp_file.name
 
125
  print(f"Error generating certificate: {e}")
126
  return None
127
 
128
+ def create_quiz_interface():
129
+ quiz_app = QuizApp()
130
+
131
+ def generate_question_blocks(questions):
132
+ blocks = []
133
+ for i, q in enumerate(questions):
134
+ with gr.Group():
135
+ gr.Markdown(f"### Question {i+1}")
136
+ gr.Markdown(q["question"])
137
+ radio = gr.Radio(
138
+ choices=q["options"],
139
+ type="index",
140
+ label="Select your answer"
141
+ )
142
+ blocks.append(radio)
143
+ return blocks
144
+
145
+ def update_quiz(text, num_questions):
146
+ questions = quiz_app.generate_questions(text, num_questions)
147
+ if not questions:
148
+ return [gr.Group(visible=False)], 1, []
149
 
150
+ quiz_blocks = generate_question_blocks(questions)
151
+ return quiz_blocks, 1, questions
152
+
153
+ def calculate_final_score(answers, questions):
154
+ score = quiz_app.calculate_score(answers)
155
+ return score, 2
156
+
157
+ with gr.Blocks(title="CertifyMe AI") as demo:
158
+ current_tab = gr.State(0)
159
+ current_questions = gr.State([])
160
+
161
+ gr.Markdown("""
162
+ # 🎓 CertifyMe AI
163
+ ### Transform Your Knowledge into Recognized Achievements
164
+ """)
165
+
166
+ with gr.Tabs() as tabs:
167
+ # Step 1: Profile Setup
168
+ with gr.Tab("📋 Step 1: Profile Setup") as tab1:
169
+ with gr.Row():
170
+ name = gr.Textbox(label="Full Name", placeholder="Enter your full name")
171
+ email = gr.Textbox(label="Email", placeholder="Enter your email")
172
 
173
+ text_input = gr.Textbox(
174
+ label="Learning Content",
175
+ placeholder="Enter the text content you want to be assessed on",
176
+ lines=10
177
+ )
178
+
179
+ with gr.Row():
180
+ num_questions = gr.Slider(
181
+ minimum=1,
182
+ maximum=5,
183
+ value=3,
184
+ step=1,
185
+ label="Number of Questions"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  )
187
 
188
+ with gr.Row():
189
+ company_logo = gr.Image(label="Company Logo (Optional)", type="filepath")
190
+ participant_photo = gr.Image(label="Your Photo (Optional)", type="filepath")
191
+
192
+ generate_btn = gr.Button("Generate Assessment", variant="primary")
193
+
194
+ # Step 2: Take Assessment
195
+ with gr.Tab("📝 Step 2: Take Assessment") as tab2:
196
+ quiz_container = gr.Group()
197
+ with quiz_container:
198
+ question_blocks = []
199
+ submit_btn = gr.Button("Submit Assessment", variant="primary")
200
+ gr.Markdown("### Answer all questions and click Submit to get your score")
201
 
202
  # Step 3: Get Certified
203
+ with gr.Tab("🎓 Step 3: Get Certified") as tab3:
204
+ score_display = gr.Number(label="Your Score", value=0)
 
 
 
 
 
 
 
205
  course_name = gr.Textbox(
206
+ label="Certification Title",
207
  value="Professional Assessment Certification"
208
  )
209
  certificate_display = gr.Image(label="Your Certificate")
210
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
  # Event handlers
212
  generate_btn.click(
213
+ fn=update_quiz,
214
  inputs=[text_input, num_questions],
215
+ outputs=[quiz_container, current_tab, current_questions]
216
  ).then(
217
  fn=lambda tab: gr.Tabs(selected=tab),
218
  inputs=[current_tab],
 
220
  )
221
 
222
  submit_btn.click(
223
+ fn=calculate_final_score,
224
+ inputs=[quiz_container, current_questions],
225
  outputs=[score_display, current_tab]
226
  ).then(
227
  fn=lambda tab: gr.Tabs(selected=tab),
 
229
  outputs=[tabs]
230
  )
231
 
 
232
  score_display.change(
233
  fn=lambda score, user_name, course, logo, photo: (
234
  quiz_app.generate_certificate(user_name, score, course, logo, photo)
 
240
 
241
  return demo
242
 
 
243
  if __name__ == "__main__":
244
  if not os.getenv("GROQ_API_KEY"):
245
  print("Please set your GROQ_API_KEY environment variable")
246
  exit(1)
247
+
248
+ demo = create_quiz_interface()
249
+ demo.launch()
250
+ ```