capradeepgujaran commited on
Commit
4f91be2
1 Parent(s): 58f709a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -41
app.py CHANGED
@@ -1,11 +1,16 @@
1
  import gradio as gr
2
- import groq_gradio
3
  import os
4
  from PIL import Image, ImageDraw, ImageFont
5
  from datetime import datetime
6
  import json
7
  import tempfile
8
 
 
 
 
 
 
9
  class QuizApp:
10
  def __init__(self):
11
  self.current_questions = []
@@ -27,27 +32,34 @@ class QuizApp:
27
  }}
28
  Only return the JSON, no other text."""
29
 
30
- # Use groq-gradio's built-in interface for LLM
31
- interface = gr.load(
32
- name='llama2-70b-4096',
33
- src=groq_gradio.registry,
 
 
34
  )
35
 
36
- response = interface.predict(prompt)
37
- questions = json.loads(response)
38
- self.current_questions = questions["questions"]
39
- return json.dumps(questions["questions"], indent=2)
 
 
40
 
41
  def calculate_score(self, answers):
42
- answers = json.loads(answers)
43
- total = len(self.current_questions)
44
- correct = 0
45
-
46
- for q, a in zip(self.current_questions, answers):
47
- if set(a) == set(q["correct_answers"]):
48
- correct += 1
49
-
50
- return (correct / total) * 100
 
 
 
51
 
52
  def generate_certificate(self, name, score, course_name, company_logo=None, participant_photo=None):
53
  # Create certificate
@@ -77,15 +89,21 @@ class QuizApp:
77
 
78
  # Add logo if provided
79
  if company_logo is not None:
80
- logo = Image.open(company_logo)
81
- logo = logo.resize((150, 150))
82
- certificate.paste(logo, (50, 50))
 
 
 
83
 
84
  # Add photo if provided
85
  if participant_photo is not None:
86
- photo = Image.open(participant_photo)
87
- photo = photo.resize((150, 150))
88
- certificate.paste(photo, (1000, 50))
 
 
 
89
 
90
  # Save to temporary file
91
  temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
@@ -95,34 +113,59 @@ class QuizApp:
95
  def create_quiz_app():
96
  quiz_app = QuizApp()
97
 
98
- with gr.Blocks(title="Interactive Quiz Generator") as demo:
99
- gr.Markdown("# Interactive Quiz Generator")
 
100
 
101
  # User Information Tab
102
  with gr.Tab("Step 1: User Information"):
103
- name = gr.Textbox(label="Full Name", placeholder="Enter your full name")
104
- email = gr.Textbox(label="Email", placeholder="Enter your email")
105
- text_input = gr.Textbox(label="Content for Quiz",
106
- placeholder="Enter the text content for generating questions",
107
- lines=10)
108
- num_questions = gr.Slider(minimum=1, maximum=10, value=5, step=1,
109
- label="Number of Questions")
110
- company_logo = gr.Image(label="Company Logo (Optional)", type="filepath")
111
- participant_photo = gr.Image(label="Participant Photo (Optional)",
112
- type="filepath")
113
- generate_btn = gr.Button("Generate Quiz")
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
115
  # Quiz Tab
116
  with gr.Tab("Step 2: Take Quiz"):
 
 
 
 
 
 
 
 
117
  questions_display = gr.JSON(label="Questions")
118
  answers_input = gr.JSON(label="Your Answers (Enter indices of correct options)")
119
- submit_btn = gr.Button("Submit Answers")
120
  score_display = gr.Number(label="Your Score")
121
 
122
  # Certificate Tab
123
  with gr.Tab("Step 3: Get Certificate"):
124
- course_name = gr.Textbox(label="Course Name",
125
- value="Interactive Quiz Course")
 
 
 
126
  certificate_display = gr.Image(label="Certificate")
127
 
128
  # Event handlers
@@ -150,5 +193,9 @@ def create_quiz_app():
150
  return demo
151
 
152
  if __name__ == "__main__":
 
 
 
 
153
  demo = create_quiz_app()
154
- demo.launch()
 
1
  import gradio as gr
2
+ from groq import Groq
3
  import os
4
  from PIL import Image, ImageDraw, ImageFont
5
  from datetime import datetime
6
  import json
7
  import tempfile
8
 
9
+ # Initialize Groq client
10
+ client = Groq(
11
+ api_key=os.getenv("GROQ_API_KEY")
12
+ )
13
+
14
  class QuizApp:
15
  def __init__(self):
16
  self.current_questions = []
 
32
  }}
33
  Only return the JSON, no other text."""
34
 
35
+ # Use Groq API directly
36
+ response = client.chat.completions.create(
37
+ messages=[{"role": "user", "content": prompt}],
38
+ model="llama2-70b-4096",
39
+ temperature=0.7,
40
+ max_tokens=1024
41
  )
42
 
43
+ try:
44
+ questions = json.loads(response.choices[0].message.content)
45
+ self.current_questions = questions["questions"]
46
+ return json.dumps(questions["questions"], indent=2)
47
+ except json.JSONDecodeError:
48
+ return json.dumps({"error": "Failed to generate valid questions. Please try again."})
49
 
50
  def calculate_score(self, answers):
51
+ try:
52
+ answers = json.loads(answers)
53
+ total = len(self.current_questions)
54
+ correct = 0
55
+
56
+ for q, a in zip(self.current_questions, answers):
57
+ if set(a) == set(q["correct_answers"]):
58
+ correct += 1
59
+
60
+ return (correct / total) * 100
61
+ except:
62
+ return 0
63
 
64
  def generate_certificate(self, name, score, course_name, company_logo=None, participant_photo=None):
65
  # Create certificate
 
89
 
90
  # Add logo if provided
91
  if company_logo is not None:
92
+ try:
93
+ logo = Image.open(company_logo)
94
+ logo = logo.resize((150, 150))
95
+ certificate.paste(logo, (50, 50))
96
+ except Exception as e:
97
+ print(f"Error adding logo: {e}")
98
 
99
  # Add photo if provided
100
  if participant_photo is not None:
101
+ try:
102
+ photo = Image.open(participant_photo)
103
+ photo = photo.resize((150, 150))
104
+ certificate.paste(photo, (1000, 50))
105
+ except Exception as e:
106
+ print(f"Error adding photo: {e}")
107
 
108
  # Save to temporary file
109
  temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
 
113
  def create_quiz_app():
114
  quiz_app = QuizApp()
115
 
116
+ with gr.Blocks(title="QuizForge AI") as demo:
117
+ gr.Markdown("# QuizForge AI")
118
+ gr.Markdown("### Generate personalized quizzes and earn certificates powered by AI")
119
 
120
  # User Information Tab
121
  with gr.Tab("Step 1: User Information"):
122
+ with gr.Row():
123
+ name = gr.Textbox(label="Full Name", placeholder="Enter your full name")
124
+ email = gr.Textbox(label="Email", placeholder="Enter your email")
125
+
126
+ text_input = gr.Textbox(
127
+ label="Content for Quiz",
128
+ placeholder="Enter the text content for generating questions",
129
+ lines=10
130
+ )
131
+
132
+ with gr.Row():
133
+ num_questions = gr.Slider(
134
+ minimum=1,
135
+ maximum=10,
136
+ value=5,
137
+ step=1,
138
+ label="Number of Questions"
139
+ )
140
+
141
+ with gr.Row():
142
+ company_logo = gr.Image(label="Company Logo (Optional)", type="filepath")
143
+ participant_photo = gr.Image(label="Participant Photo (Optional)", type="filepath")
144
+
145
+ generate_btn = gr.Button("Generate Quiz", variant="primary")
146
 
147
  # Quiz Tab
148
  with gr.Tab("Step 2: Take Quiz"):
149
+ gr.Markdown("""
150
+ ### Instructions:
151
+ 1. Questions will appear in JSON format below
152
+ 2. Each question has multiple options
153
+ 3. Enter answers as array indices (e.g., [0, 2] for first and third options)
154
+ 4. Submit when ready to get your score
155
+ """)
156
+
157
  questions_display = gr.JSON(label="Questions")
158
  answers_input = gr.JSON(label="Your Answers (Enter indices of correct options)")
159
+ submit_btn = gr.Button("Submit Answers", variant="primary")
160
  score_display = gr.Number(label="Your Score")
161
 
162
  # Certificate Tab
163
  with gr.Tab("Step 3: Get Certificate"):
164
+ gr.Markdown("### Your certificate will be generated automatically if you score 80% or above")
165
+ course_name = gr.Textbox(
166
+ label="Course Name",
167
+ value="QuizForge AI Certification"
168
+ )
169
  certificate_display = gr.Image(label="Certificate")
170
 
171
  # Event handlers
 
193
  return demo
194
 
195
  if __name__ == "__main__":
196
+ if not os.getenv("GROQ_API_KEY"):
197
+ print("Please set your GROQ_API_KEY environment variable")
198
+ exit(1)
199
+
200
  demo = create_quiz_app()
201
+ demo.launch(share=True)