Spaces:
Sleeping
Sleeping
```python | |
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.current_answers = [] | |
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): | |
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 q['correct_answer'] == a) | |
return (correct / total) * 100 | |
def generate_certificate(self, name, score, course_name, company_logo=None, participant_photo=None): | |
try: | |
certificate = Image.new('RGB', (1200, 800), '#F0F8FF') | |
draw = ImageDraw.Draw(certificate) | |
try: | |
title_font = ImageFont.truetype("arial.ttf", 60) | |
text_font = ImageFont.truetype("arial.ttf", 40) | |
subtitle_font = ImageFont.truetype("arial.ttf", 30) | |
except: | |
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 or "Participant", 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 or "Assessment", 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") | |
current_date = datetime.now().strftime("%B %d, %Y") | |
draw.text((600, 700), current_date, font=text_font, fill='black', anchor="mm") | |
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}") | |
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}") | |
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_interface(): | |
quiz_app = QuizApp() | |
def generate_question_blocks(questions): | |
blocks = [] | |
for i, q in enumerate(questions): | |
with gr.Group(): | |
gr.Markdown(f"### Question {i+1}") | |
gr.Markdown(q["question"]) | |
radio = gr.Radio( | |
choices=q["options"], | |
type="index", | |
label="Select your answer" | |
) | |
blocks.append(radio) | |
return blocks | |
def update_quiz(text, num_questions): | |
questions = quiz_app.generate_questions(text, num_questions) | |
if not questions: | |
return [gr.Group(visible=False)], 1, [] | |
quiz_blocks = generate_question_blocks(questions) | |
return quiz_blocks, 1, questions | |
def calculate_final_score(answers, questions): | |
score = quiz_app.calculate_score(answers) | |
return score, 2 | |
with gr.Blocks(title="CertifyMe AI") as demo: | |
current_tab = gr.State(0) | |
current_questions = gr.State([]) | |
gr.Markdown(""" | |
# 🎓 CertifyMe AI | |
### Transform Your Knowledge into Recognized Achievements | |
""") | |
with gr.Tabs() as tabs: | |
# Step 1: Profile Setup | |
with gr.Tab("📋 Step 1: Profile Setup") 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=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") | |
# Step 2: Take Assessment | |
with gr.Tab("📝 Step 2: Take Assessment") as tab2: | |
quiz_container = gr.Group() | |
with quiz_container: | |
question_blocks = [] | |
submit_btn = gr.Button("Submit Assessment", variant="primary") | |
gr.Markdown("### Answer all questions and click Submit to get your score") | |
# Step 3: Get Certified | |
with gr.Tab("🎓 Step 3: Get Certified") as tab3: | |
score_display = gr.Number(label="Your Score", value=0) | |
course_name = gr.Textbox( | |
label="Certification Title", | |
value="Professional Assessment Certification" | |
) | |
certificate_display = gr.Image(label="Your Certificate") | |
# Event handlers | |
generate_btn.click( | |
fn=update_quiz, | |
inputs=[text_input, num_questions], | |
outputs=[quiz_container, current_tab, current_questions] | |
).then( | |
fn=lambda tab: gr.Tabs(selected=tab), | |
inputs=[current_tab], | |
outputs=[tabs] | |
) | |
submit_btn.click( | |
fn=calculate_final_score, | |
inputs=[quiz_container, current_questions], | |
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_interface() | |
demo.launch() | |
``` |