Spaces:
Sleeping
Sleeping
File size: 11,134 Bytes
67f169b 4f91be2 67f169b 4f91be2 67f169b b1c910f 67f169b 4f91be2 b1c910f 4f91be2 b1c910f 4f91be2 67f169b 4f91be2 12a21f4 4f91be2 b1c910f 4f91be2 67f169b b1c910f 4f91be2 b1c910f 67f169b b1c910f 67f169b b1c910f 4f91be2 b1c910f 4f91be2 b1c910f 12a21f4 b1c910f 12a21f4 b1c910f 4f91be2 b1c910f 67f169b b1c910f 67f169b b1c910f 67f169b b1c910f 67f169b b1c910f 67f169b b1c910f 67f169b 4f91be2 67f169b b1c910f |
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 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 |
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"""Generate {num_questions} multiple choice questions based on this text:
{text}
Format your response as a list of questions, where each question is a JSON object with the following structure:
[
{{
"question": "Question text",
"options": ["option1", "option2", "option3", "option4"],
"correct_answers": [0, 1]
}}
]
Only return the JSON array, no other text."""
try:
response = client.chat.completions.create(
messages=[{"role": "user", "content": prompt}],
model="llama2-70b-4096",
temperature=0.7,
max_tokens=1024
)
# Parse the response directly as a list
questions = json.loads(response.choices[0].message.content)
if isinstance(questions, list):
self.current_questions = questions
else:
# If we get an object with a questions key, extract the list
self.current_questions = questions.get("questions", [])
return json.dumps(self.current_questions, indent=2)
except Exception as e:
print(f"Error generating questions: {e}")
return json.dumps({"error": "Failed to generate valid questions. Please try again."})
def calculate_score(self, answers):
try:
answers = json.loads(answers) if isinstance(answers, str) else answers
total = len(self.current_questions)
correct = 0
for q, a in zip(self.current_questions, answers):
if set(a) == set(q["correct_answers"]):
correct += 1
return (correct / total) * 100
except Exception as e:
print(f"Error calculating score: {e}")
return 0
def generate_certificate(self, name, score, course_name, company_logo=None, participant_photo=None):
try:
# Create certificate with a light blue background
certificate = Image.new('RGB', (1200, 800), '#F0F8FF')
draw = ImageDraw.Draw(certificate)
# Load fonts
try:
title_font = ImageFont.truetype("arial.ttf", 60)
text_font = ImageFont.truetype("arial.ttf", 40)
subtitle_font = ImageFont.truetype("arial.ttf", 30)
except:
print("Using default font as Arial not found")
title_font = ImageFont.load_default()
text_font = ImageFont.load_default()
subtitle_font = ImageFont.load_default()
# Add decorative border
draw.rectangle([20, 20, 1180, 780], outline='#4682B4', width=3)
# Draw certificate content
draw.text((600, 100), "CertifyMe AI", font=title_font, fill='#4682B4', anchor="mm")
draw.text((600, 160), "Certificate of Achievement", font=subtitle_font, fill='#4682B4', anchor="mm")
draw.text((600, 300), "This is to certify that", font=text_font, fill='black', anchor="mm")
draw.text((600, 380), name, font=text_font, fill='#4682B4', anchor="mm")
draw.text((600, 460), "has successfully completed", font=text_font, fill='black', anchor="mm")
draw.text((600, 540), course_name, font=text_font, fill='#4682B4', anchor="mm")
draw.text((600, 620), f"with a score of {score:.1f}%", font=text_font, fill='black', anchor="mm")
# Add date
current_date = datetime.now().strftime("%B %d, %Y")
draw.text((600, 700), current_date, font=text_font, fill='black', anchor="mm")
# Add logo if provided
if company_logo is not None:
try:
logo = Image.open(company_logo)
logo = logo.resize((150, 150))
certificate.paste(logo, (50, 50))
except Exception as e:
print(f"Error adding logo: {e}")
# Add photo if provided
if participant_photo is not None:
try:
photo = Image.open(participant_photo)
photo = photo.resize((150, 150))
certificate.paste(photo, (1000, 50))
except Exception as e:
print(f"Error adding photo: {e}")
# Save certificate
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
certificate.save(temp_file.name)
return temp_file.name
except Exception as e:
print(f"Error generating certificate: {e}")
return None
def create_quiz_app():
quiz_app = QuizApp()
with gr.Blocks(title="CertifyMe AI") as demo:
# Store current tab state
current_tab = gr.State(0)
gr.Markdown("""
# CertifyMe AI
### Transform Your Knowledge into Recognized Achievements
Get AI-powered assessments and professional certificates for any learning content.
""")
# Create 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
)
with gr.Row():
num_questions = gr.Slider(
minimum=1,
maximum=10,
value=5,
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")
# Instructions for Step 1
gr.Markdown("""
### Instructions:
1. Enter your full name and email
2. Paste or type the learning content you want to be assessed on
3. Select the number of questions for your assessment
4. Optionally upload a company logo and your photo for the certificate
5. Click 'Generate Assessment' to proceed
""")
# Step 2: Take Assessment
with gr.Tab("📝 Step 2: Take Assessment", id=1) as tab2:
gr.Markdown("""
### Assessment Instructions:
1. Review each question carefully
2. For each question, you may select one or more correct options
3. Enter your answers in the following format:
```
[
[0], // First question: selected first option
[1, 2], // Second question: selected second and third options
[3] // Third question: selected fourth option
]
```
4. Click 'Submit Assessment' when you're ready
5. You need 80% or higher to earn your certificate
""")
questions_display = gr.JSON(label="Assessment Questions")
answers_input = gr.JSON(label="Your Answers")
submit_btn = gr.Button("Submit Assessment", variant="primary")
score_display = gr.Number(label="Your Score")
# Step 3: Get Certified
with gr.Tab("🎓 Step 3: Get Certified", id=2) as tab3:
gr.Markdown("""
### Certification
- Your certificate will be generated automatically if you score 80% or above
- The certificate includes your name, score, and completion date
- Company logo and photo will be included if provided
- You can download your certificate once it's generated
""")
course_name = gr.Textbox(
label="Certification Title",
value="Professional Assessment Certification"
)
certificate_display = gr.Image(label="Your Certificate")
# Helper functions for tab navigation
def generate_and_switch_tab(text, num_questions):
questions = quiz_app.generate_questions(text, num_questions)
return questions, 1
def submit_and_switch_tab(answers):
score = quiz_app.calculate_score(answers)
return score, 2
# Event handlers
generate_btn.click(
fn=generate_and_switch_tab,
inputs=[text_input, num_questions],
outputs=[questions_display, current_tab]
).then(
fn=lambda tab: gr.Tabs(selected=tab),
inputs=[current_tab],
outputs=[tabs]
)
submit_btn.click(
fn=submit_and_switch_tab,
inputs=[answers_input],
outputs=[score_display, current_tab]
).then(
fn=lambda tab: gr.Tabs(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_app()
demo.launch() |