rameshmoorthy commited on
Commit
f936c1d
·
verified ·
1 Parent(s): f35100d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +247 -20
app.py CHANGED
@@ -106,36 +106,66 @@ def collect_answers_and_calculate(*all_inputs):
106
  print(f"Received radio_values: {radio_values}") # Debug print
107
  print(f"Received quiz_data: {quiz_data}") # Debug print
108
 
109
- # Filter out None values but keep track of positions
110
- user_answer_list = list(radio_values)
111
- correct_answers = [item.correct_answer for item in quiz_data.items[:10]]
112
-
113
- print(f"User answers: {user_answer_list}") # Debug print
114
- print(f"Correct answers: {correct_answers}") # Debug print
115
-
116
- # Calculate score - only count answered questions
117
  score = 0
118
  answered_questions = 0
119
- for u, c in zip(user_answer_list, correct_answers):
120
- if u is not None: # Only count if user answered
 
121
  answered_questions += 1
122
- if u == c:
 
 
 
 
 
 
 
123
  score += 1
124
 
125
  print(f"Calculated score: {score}/{answered_questions}") # Debug print
126
 
 
127
  if answered_questions == 0:
128
- message = "### Please answer at least one question!"
 
 
 
 
129
  elif score == answered_questions:
130
- message = f"### Perfect! You got {score} out of {answered_questions} correct!"
 
 
 
 
 
 
131
  elif score > answered_questions * 0.7:
132
- message = f"### Excellent! You got {score} out of {answered_questions} correct!"
 
 
 
 
 
 
133
  elif score > answered_questions * 0.5:
134
- message = f"### Good! You got {score} out of {answered_questions} correct!"
 
 
 
 
 
 
135
  else:
136
- message = f"### You got {score} out of {answered_questions} correct! Don't worry. You can prepare well and try better next time!"
 
 
 
 
 
 
137
 
138
- return message
139
 
140
  # Define a colorful theme
141
  colorful_theme = gr.themes.Default(primary_hue="cyan", secondary_hue="yellow", neutral_hue="purple")
@@ -166,8 +196,10 @@ with gr.Blocks(title="Quiz Maker", theme=colorful_theme) as QUIZBOT:
166
  # Pre-defined radio buttons for 10 questions
167
  question_radios = [gr.Radio(visible=False, label="", choices=[""], value=None) for _ in range(10)]
168
  quiz_data_state = gr.State(value=None)
169
- check_score_btn = gr.Button("Check Score")
170
- score_output = gr.Markdown(visible=False)
 
 
171
 
172
  # Register the click event for Generate Quiz without @ decorator
173
  generate_quiz_btn.click(
@@ -186,10 +218,205 @@ with gr.Blocks(title="Quiz Maker", theme=colorful_theme) as QUIZBOT:
186
  inputs=question_radios + [quiz_data_state], # This creates a list of 11 inputs
187
  outputs=[score_output],
188
  api_name="check_score"
 
 
 
 
189
  )
190
 
191
  if __name__ == "__main__":
192
- QUIZBOT.queue().launch(server_name="0.0.0.0", server_port=7860)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
  # from pathlib import Path
194
  # from sentence_transformers import CrossEncoder
195
  # import numpy as np
 
106
  print(f"Received radio_values: {radio_values}") # Debug print
107
  print(f"Received quiz_data: {quiz_data}") # Debug print
108
 
109
+ # Calculate score by comparing user answers with correct answers
 
 
 
 
 
 
 
110
  score = 0
111
  answered_questions = 0
112
+
113
+ for i, (user_answer, quiz_item) in enumerate(zip(radio_values, quiz_data.items[:10])):
114
+ if user_answer is not None: # Only count if user answered
115
  answered_questions += 1
116
+
117
+ # Convert correct answer code (e.g., 'C3') to actual choice text
118
+ correct_answer_index = int(quiz_item.correct_answer[1]) - 1 # 'C3' -> index 2
119
+ correct_answer_text = quiz_item.choices[correct_answer_index]
120
+
121
+ print(f"Q{i+1}: User='{user_answer}' vs Correct='{correct_answer_text}'") # Debug
122
+
123
+ if user_answer == correct_answer_text:
124
  score += 1
125
 
126
  print(f"Calculated score: {score}/{answered_questions}") # Debug print
127
 
128
+ # Create colorful HTML message
129
  if answered_questions == 0:
130
+ html_message = """
131
+ <div style="text-align: center; padding: 20px; border-radius: 10px; background: linear-gradient(135deg, #ff6b6b, #ee5a24);">
132
+ <h2 style="color: white; margin: 0;">⚠️ Please answer at least one question!</h2>
133
+ </div>
134
+ """
135
  elif score == answered_questions:
136
+ html_message = f"""
137
+ <div style="text-align: center; padding: 20px; border-radius: 10px; background: linear-gradient(135deg, #00d2d3, #54a0ff); box-shadow: 0 4px 15px rgba(0,0,0,0.2);">
138
+ <h1 style="color: white; margin: 0; text-shadow: 2px 2px 4px rgba(0,0,0,0.3);">🏆 PERFECT SCORE! 🏆</h1>
139
+ <h2 style="color: #fff3cd; margin: 10px 0;">You got {score} out of {answered_questions} correct!</h2>
140
+ <p style="color: white; font-size: 18px; margin: 0;">Outstanding performance! 🌟</p>
141
+ </div>
142
+ """
143
  elif score > answered_questions * 0.7:
144
+ html_message = f"""
145
+ <div style="text-align: center; padding: 20px; border-radius: 10px; background: linear-gradient(135deg, #2ed573, #7bed9f); box-shadow: 0 4px 15px rgba(0,0,0,0.2);">
146
+ <h1 style="color: white; margin: 0; text-shadow: 2px 2px 4px rgba(0,0,0,0.3);">🎉 EXCELLENT! 🎉</h1>
147
+ <h2 style="color: #fff3cd; margin: 10px 0;">You got {score} out of {answered_questions} correct!</h2>
148
+ <p style="color: white; font-size: 18px; margin: 0;">Great job! Keep it up! 💪</p>
149
+ </div>
150
+ """
151
  elif score > answered_questions * 0.5:
152
+ html_message = f"""
153
+ <div style="text-align: center; padding: 20px; border-radius: 10px; background: linear-gradient(135deg, #ffa726, #ffcc02); box-shadow: 0 4px 15px rgba(0,0,0,0.2);">
154
+ <h1 style="color: white; margin: 0; text-shadow: 2px 2px 4px rgba(0,0,0,0.3);">👍 GOOD JOB! 👍</h1>
155
+ <h2 style="color: #fff3cd; margin: 10px 0;">You got {score} out of {answered_questions} correct!</h2>
156
+ <p style="color: white; font-size: 18px; margin: 0;">Well done! Room for improvement! 📚</p>
157
+ </div>
158
+ """
159
  else:
160
+ html_message = f"""
161
+ <div style="text-align: center; padding: 20px; border-radius: 10px; background: linear-gradient(135deg, #ff7675, #fd79a8); box-shadow: 0 4px 15px rgba(0,0,0,0.2);">
162
+ <h1 style="color: white; margin: 0; text-shadow: 2px 2px 4px rgba(0,0,0,0.3);">💪 KEEP TRYING! 💪</h1>
163
+ <h2 style="color: #fff3cd; margin: 10px 0;">You got {score} out of {answered_questions} correct!</h2>
164
+ <p style="color: white; font-size: 18px; margin: 0;">Don't worry! Practice makes perfect! 📖✨</p>
165
+ </div>
166
+ """
167
 
168
+ return html_message
169
 
170
  # Define a colorful theme
171
  colorful_theme = gr.themes.Default(primary_hue="cyan", secondary_hue="yellow", neutral_hue="purple")
 
196
  # Pre-defined radio buttons for 10 questions
197
  question_radios = [gr.Radio(visible=False, label="", choices=[""], value=None) for _ in range(10)]
198
  quiz_data_state = gr.State(value=None)
199
+ check_score_btn = gr.Button("Check Score", variant="primary", size="lg")
200
+
201
+ # HTML output for colorful score display at bottom
202
+ score_output = gr.HTML(visible=False, label="Your Results")
203
 
204
  # Register the click event for Generate Quiz without @ decorator
205
  generate_quiz_btn.click(
 
218
  inputs=question_radios + [quiz_data_state], # This creates a list of 11 inputs
219
  outputs=[score_output],
220
  api_name="check_score"
221
+ ).then(
222
+ fn=lambda: gr.update(visible=True), # Make score output visible after calculation
223
+ inputs=[],
224
+ outputs=[score_output]
225
  )
226
 
227
  if __name__ == "__main__":
228
+ QUIZBOT.queue().launch(server_name="0.0.0.0", server_port=7860)# import gradio as gr
229
+ # from pathlib import Path
230
+ # from sentence_transformers import CrossEncoder
231
+ # import numpy as np
232
+ # from time import perf_counter
233
+ # from pydantic import BaseModel, Field
234
+ # from phi.agent import Agent
235
+ # from phi.model.groq import Groq
236
+ # import os
237
+ # import logging
238
+
239
+ # # Set up logging
240
+ # logging.basicConfig(level=logging.INFO)
241
+ # logger = logging.getLogger(__name__)
242
+
243
+ # # API Key setup
244
+ # api_key = os.getenv("GROQ_API_KEY")
245
+ # if not api_key:
246
+ # gr.Warning("GROQ_API_KEY not found. Set it in 'Repository secrets'.")
247
+ # logger.error("GROQ_API_KEY not found.")
248
+ # else:
249
+ # os.environ["GROQ_API_KEY"] = api_key
250
+
251
+ # # Pydantic Model for Quiz Structure
252
+ # class QuizItem(BaseModel):
253
+ # question: str = Field(..., description="The quiz question")
254
+ # choices: list[str] = Field(..., description="List of 4 multiple-choice options")
255
+ # correct_answer: str = Field(..., description="The correct choice (e.g., 'C1')")
256
+
257
+ # class QuizOutput(BaseModel):
258
+ # items: list[QuizItem] = Field(..., description="List of 10 quiz items")
259
+
260
+ # # Initialize Agents
261
+ # groq_agent = Agent(model=Groq(model="llama3-70b-8192", api_key=api_key), markdown=True)
262
+
263
+ # quiz_generator = Agent(
264
+ # name="Quiz Generator",
265
+ # role="Generates structured quiz questions and answers",
266
+ # instructions=[
267
+ # "Create 10 questions with 4 choices each based on the provided topic and documents.",
268
+ # "Use the specified difficulty level (easy, average, hard) to adjust question complexity.",
269
+ # "Ensure questions are derived only from the provided documents.",
270
+ # "Return the output in a structured format using the QuizOutput Pydantic model.",
271
+ # "Each question should have a unique correct answer from the choices (labeled C1, C2, C3, C4)."
272
+ # ],
273
+ # model=Groq(id="llama3-70b-8192", api_key=api_key),
274
+ # response_model=QuizOutput,
275
+ # markdown=True
276
+ # )
277
+
278
+ # VECTOR_COLUMN_NAME = "vector"
279
+ # TEXT_COLUMN_NAME = "text"
280
+ # proj_dir = Path.cwd()
281
+
282
+ # # Calling functions from backend (assuming they exist)
283
+ # from backend.semantic_search import table, retriever
284
+
285
+ # def generate_quiz_data(question_difficulty, topic, documents_str):
286
+ # prompt = f"""Generate a quiz with {question_difficulty} difficulty on topic '{topic}' using only the following documents:\n{documents_str}"""
287
+ # try:
288
+ # response = quiz_generator.run(prompt)
289
+ # return response.content
290
+ # except Exception as e:
291
+ # logger.error(f"Failed to generate quiz: {e}")
292
+ # return None
293
+
294
+ # def retrieve_and_generate_quiz(question_difficulty, topic):
295
+ # gr.Warning('Generating quiz may take 1-2 minutes. Please wait.', duration=60)
296
+ # top_k_rank = 10
297
+ # documents = []
298
+
299
+ # document_start = perf_counter()
300
+ # query_vec = retriever.encode(topic)
301
+ # documents = [doc[TEXT_COLUMN_NAME] for doc in table.search(query_vec, vector_column_name=VECTOR_COLUMN_NAME).limit(top_k_rank).to_list()]
302
+
303
+ # # Apply BGE reranker
304
+ # cross_encoder = CrossEncoder('BAAI/bge-reranker-base')
305
+ # query_doc_pair = [[topic, doc] for doc in documents]
306
+ # cross_scores = cross_encoder.predict(query_doc_pair)
307
+ # sim_scores_argsort = list(reversed(np.argsort(cross_scores)))
308
+ # documents = [documents[idx] for idx in sim_scores_argsort[:top_k_rank]]
309
+
310
+ # documents_str = '\n'.join(documents)
311
+ # quiz_data = generate_quiz_data(question_difficulty, topic, documents_str)
312
+ # return quiz_data
313
+
314
+ # def update_quiz_components(quiz_data):
315
+ # if not quiz_data or not quiz_data.items:
316
+ # return [gr.update(visible=False) for _ in range(10)] + [gr.update(value="Error: Failed to generate quiz.", visible=True)]
317
+
318
+ # radio_updates = []
319
+ # for i, item in enumerate(quiz_data.items[:10]):
320
+ # choices = item.choices
321
+ # radio_update = gr.update(visible=True, choices=choices, label=item.question, value=None)
322
+ # radio_updates.append(radio_update)
323
+ # return radio_updates + [gr.update(value="Please select answers and click 'Check Score'.", visible=True)]
324
+
325
+ # # FIXED FUNCTION: Changed parameter signature to accept all arguments positionally
326
+ # def collect_answers_and_calculate(*all_inputs):
327
+ # print(f"Total inputs received: {len(all_inputs)}") # Debug print
328
+
329
+ # # The last input is quiz_data, the first 10 are radio values
330
+ # radio_values = all_inputs[:10] # First 10 inputs are radio button values
331
+ # quiz_data = all_inputs[10] # Last input is quiz_data
332
+
333
+ # print(f"Received radio_values: {radio_values}") # Debug print
334
+ # print(f"Received quiz_data: {quiz_data}") # Debug print
335
+
336
+ # # Filter out None values but keep track of positions
337
+ # user_answer_list = list(radio_values)
338
+ # correct_answers = [item.correct_answer for item in quiz_data.items[:10]]
339
+
340
+ # print(f"User answers: {user_answer_list}") # Debug print
341
+ # print(f"Correct answers: {correct_answers}") # Debug print
342
+
343
+ # # Calculate score - only count answered questions
344
+ # score = 0
345
+ # answered_questions = 0
346
+ # for u, c in zip(user_answer_list, correct_answers):
347
+ # if u is not None: # Only count if user answered
348
+ # answered_questions += 1
349
+ # if u == c:
350
+ # score += 1
351
+
352
+ # print(f"Calculated score: {score}/{answered_questions}") # Debug print
353
+
354
+ # if answered_questions == 0:
355
+ # message = "### Please answer at least one question!"
356
+ # elif score == answered_questions:
357
+ # message = f"### Perfect! You got {score} out of {answered_questions} correct!"
358
+ # elif score > answered_questions * 0.7:
359
+ # message = f"### Excellent! You got {score} out of {answered_questions} correct!"
360
+ # elif score > answered_questions * 0.5:
361
+ # message = f"### Good! You got {score} out of {answered_questions} correct!"
362
+ # else:
363
+ # message = f"### You got {score} out of {answered_questions} correct! Don't worry. You can prepare well and try better next time!"
364
+
365
+ # return message
366
+
367
+ # # Define a colorful theme
368
+ # colorful_theme = gr.themes.Default(primary_hue="cyan", secondary_hue="yellow", neutral_hue="purple")
369
+
370
+ # with gr.Blocks(title="Quiz Maker", theme=colorful_theme) as QUIZBOT:
371
+ # # Create a single row for the HTML and Image
372
+ # with gr.Row():
373
+ # with gr.Column(scale=2):
374
+ # gr.Image(value='logo.png', height=200, width=200)
375
+ # with gr.Column(scale=6):
376
+ # gr.HTML("""
377
+ # <center>
378
+ # <h1><span style="color: purple;">GOVERNMENT HIGH SCHOOL,SUTHUKENY</span> STUDENTS QUIZBOT </h1>
379
+ # <h2>Generative AI-powered Capacity building for STUDENTS</h2>
380
+ # <i>⚠️ Students can create quiz from any topic from 10th Science and evaluate themselves! ⚠️</i>
381
+ # </center>
382
+ # """)
383
+
384
+ # topic = gr.Textbox(label="Enter the Topic for Quiz", placeholder="Write any CHAPTER NAME")
385
+
386
+ # with gr.Row():
387
+ # difficulty_radio = gr.Radio(["easy", "average", "hard"], label="How difficult should the quiz be?")
388
+ # model_radio = gr.Radio(choices=['(ACCURATE) BGE reranker'], value='(ACCURATE) BGE reranker', label="Embeddings")
389
+
390
+ # generate_quiz_btn = gr.Button("Generate Quiz!🚀")
391
+ # quiz_msg = gr.Textbox(label="Status", interactive=False)
392
+
393
+ # # Pre-defined radio buttons for 10 questions
394
+ # question_radios = [gr.Radio(visible=False, label="", choices=[""], value=None) for _ in range(10)]
395
+ # quiz_data_state = gr.State(value=None)
396
+ # check_score_btn = gr.Button("Check Score")
397
+ # score_output = gr.Markdown(visible=False)
398
+
399
+ # # Register the click event for Generate Quiz without @ decorator
400
+ # generate_quiz_btn.click(
401
+ # fn=retrieve_and_generate_quiz,
402
+ # inputs=[difficulty_radio, topic],
403
+ # outputs=[quiz_data_state]
404
+ # ).then(
405
+ # fn=update_quiz_components,
406
+ # inputs=[quiz_data_state],
407
+ # outputs=question_radios + [quiz_msg]
408
+ # )
409
+
410
+ # # FIXED: Register the click event for Check Score with correct input handling
411
+ # check_score_btn.click(
412
+ # fn=collect_answers_and_calculate,
413
+ # inputs=question_radios + [quiz_data_state], # This creates a list of 11 inputs
414
+ # outputs=[score_output],
415
+ # api_name="check_score"
416
+ # )
417
+
418
+ # if __name__ == "__main__":
419
+ # QUIZBOT.queue().launch(server_name="0.0.0.0", server_port=7860)
420
  # from pathlib import Path
421
  # from sentence_transformers import CrossEncoder
422
  # import numpy as np