Spaces:
Sleeping
Sleeping
File size: 7,736 Bytes
67f169b 4f91be2 67f169b 4f91be2 67f169b deff9b7 67f169b 0ef1d43 67f169b 0ef1d43 deff9b7 b1c910f deff9b7 0ef1d43 deff9b7 b1c910f deff9b7 67f169b 4f91be2 b1c910f 0ef1d43 8cd587a 0ef1d43 deff9b7 b1c910f 0ef1d43 deff9b7 0ef1d43 b1c910f deff9b7 67f169b ba67897 b1c910f ba67897 b1c910f ba67897 67f169b deff9b7 ba67897 deff9b7 ba67897 deff9b7 ba67897 deff9b7 ba67897 deff9b7 ba67897 deff9b7 ba67897 deff9b7 ba67897 deff9b7 ba67897 deff9b7 ba67897 deff9b7 ba67897 deff9b7 4f91be2 deff9b7 ba67897 b1c910f deff9b7 ba67897 deff9b7 ba67897 deff9b7 ba67897 4f91be2 b1c910f ba67897 b1c910f deff9b7 b1c910f 67f169b ba67897 67f169b ba67897 b1c910f ba67897 b1c910f 67f169b ba67897 b1c910f ba67897 b1c910f 67f169b 4f91be2 deff9b7 1f49f47 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 |
import gradio as gr
from groq import Groq
import os
from PIL import Image, ImageDraw, ImageFont
from datetime import datetime
import json
import tempfile
# Initialize Groq client
client = Groq(
api_key=os.getenv("GROQ_API_KEY")
)
class QuizApp:
def __init__(self):
self.current_questions = []
self.user_data = {}
def generate_questions(self, text, num_questions):
prompt = f"""Create {num_questions} multiple choice questions based on this text:
{text}
Each question should:
1. Have a clear, concise question text
2. Have exactly 4 options
3. Have only one correct answer
4. Be educational and test understanding
Return in this exact JSON format:
[
{{
"question": "What is the main topic discussed?",
"options": [
"Correct answer",
"Wrong answer 1",
"Wrong answer 2",
"Wrong answer 3"
],
"correct_answer": 0
}}
]"""
try:
response = client.chat.completions.create(
messages=[
{"role": "system", "content": "You are a quiz generator that creates clear, single-choice questions."},
{"role": "user", "content": prompt}
],
model="llama-3.2-3b-preview",
temperature=0.5,
max_tokens=2048
)
response_text = response.choices[0].message.content.strip()
response_text = response_text.replace("```json", "").replace("```", "").strip()
questions = json.loads(response_text)
self.current_questions = questions
return questions
except Exception as e:
print(f"Error generating questions: {e}")
return []
def calculate_score(self, answers):
try:
if not answers or not self.current_questions:
return 0
total = len(self.current_questions)
correct = sum(1 for q, a in zip(self.current_questions, answers)
if a is not None and q['correct_answer'] == a)
return (correct / total) * 100
except Exception as e:
print(f"Error calculating score: {e}")
return 0
# Certificate generation method remains the same
def create_quiz_interface():
quiz_app = QuizApp()
def create_question_blocks(questions):
blocks = []
if not questions:
return blocks
for i, q in enumerate(questions, 1):
with gr.Group(visible=True) as group:
gr.Markdown(f"### Question {i}")
gr.Markdown(q["question"])
radio = gr.Radio(
choices=q["options"],
label=f"Select your answer for Question {i}",
interactive=True
)
blocks.append(radio)
return blocks
def generate_and_display_questions(text, num_questions):
try:
questions = quiz_app.generate_questions(text, num_questions)
if not questions:
return [], gr.Markdown("Failed to generate questions. Please try again."), [], 0
blocks = create_question_blocks(questions)
return blocks, gr.Markdown(""), questions, 1
except Exception as e:
print(f"Error in generate_and_display_questions: {e}")
return [], gr.Markdown("An error occurred. Please try again."), [], 0
def submit_answers(answers, questions):
try:
score = quiz_app.calculate_score(answers)
return score, 2
except Exception as e:
print(f"Error in submit_answers: {e}")
return 0, 2
with gr.Blocks(title="CertifyMe AI", theme=gr.themes.Soft()) as demo:
# State management
current_tab = gr.State(0)
stored_questions = gr.State([])
# Header
gr.Markdown("""
# 🎓 CertifyMe AI
### Transform Your Knowledge into Recognized Achievements
""")
# Tabs
with gr.Tabs() as tabs:
# Step 1: Profile Setup
with gr.Tab("📋 Step 1: Profile Setup", id=0) as tab1:
with gr.Row():
name = gr.Textbox(label="Full Name", placeholder="Enter your full name")
email = gr.Textbox(label="Email", placeholder="Enter your email")
text_input = gr.Textbox(
label="Learning Content",
placeholder="Enter the text content you want to be assessed on",
lines=10
)
num_questions = gr.Slider(
minimum=1,
maximum=5,
value=3,
step=1,
label="Number of Questions"
)
with gr.Row():
company_logo = gr.Image(label="Company Logo (Optional)", type="filepath")
participant_photo = gr.Image(label="Your Photo (Optional)", type="filepath")
generate_btn = gr.Button("Generate Assessment", variant="primary", size="lg")
# Step 2: Take Assessment
with gr.Tab("📝 Step 2: Take Assessment", id=1) as tab2:
error_message = gr.Markdown("")
question_container = gr.Group()
with question_container:
question_blocks = []
submit_btn = gr.Button("Submit Assessment", variant="primary", size="lg")
# Step 3: Get Certified
with gr.Tab("🎓 Step 3: Get Certified", id=2) as tab3:
score_display = gr.Number(label="Your Score")
course_name = gr.Textbox(
label="Certification Title",
value="Professional Assessment Certification"
)
certificate_display = gr.Image(label="Your Certificate")
# Event handlers
generate_btn.click(
fn=generate_and_display_questions,
inputs=[text_input, num_questions],
outputs=[
question_container,
error_message,
stored_questions,
current_tab
]
).then(
fn=lambda tab: gr.update(selected=tab),
inputs=[current_tab],
outputs=[tabs]
)
submit_btn.click(
fn=submit_answers,
inputs=[question_container, stored_questions],
outputs=[score_display, current_tab]
).then(
fn=lambda tab: gr.update(selected=tab),
inputs=[current_tab],
outputs=[tabs]
)
score_display.change(
fn=lambda score, user_name, course, logo, photo: (
quiz_app.generate_certificate(user_name, score, course, logo, photo)
if score >= 80 else None
),
inputs=[score_display, name, course_name, company_logo, participant_photo],
outputs=certificate_display
)
return demo
if __name__ == "__main__":
if not os.getenv("GROQ_API_KEY"):
print("Please set your GROQ_API_KEY environment variable")
exit(1)
demo = create_quiz_interface()
demo.launch() |