File size: 6,023 Bytes
67f169b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import groq_gradio
import os
from PIL import Image, ImageDraw, ImageFont
from datetime import datetime
import json
import tempfile

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}
        
        Return the response in this JSON format:
        {{
            "questions": [
                {{
                    "question": "Question text",
                    "options": ["option1", "option2", "option3", "option4"],
                    "correct_answers": [0, 1]
                }}
            ]
        }}
        Only return the JSON, no other text."""
        
        # Use groq-gradio's built-in interface for LLM
        interface = gr.load(
            name='llama2-70b-4096',
            src=groq_gradio.registry,
        )
        
        response = interface.predict(prompt)
        questions = json.loads(response)
        self.current_questions = questions["questions"]
        return json.dumps(questions["questions"], indent=2)
    
    def calculate_score(self, answers):
        answers = json.loads(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
    
    def generate_certificate(self, name, score, course_name, company_logo=None, participant_photo=None):
        # Create certificate
        certificate = Image.new('RGB', (1200, 800), 'white')
        draw = ImageDraw.Draw(certificate)
        
        # Load a default font
        try:
            title_font = ImageFont.truetype("arial.ttf", 60)
            text_font = ImageFont.truetype("arial.ttf", 40)
        except:
            # Fallback to default font
            title_font = ImageFont.load_default()
            text_font = ImageFont.load_default()
        
        # Add certificate content
        draw.text((600, 100), "Certificate of Completion", font=title_font, fill='black', anchor="mm")
        draw.text((600, 300), f"This is to certify that", font=text_font, fill='black', anchor="mm")
        draw.text((600, 380), name, font=text_font, fill='black', anchor="mm")
        draw.text((600, 460), f"has successfully completed", font=text_font, fill='black', anchor="mm")
        draw.text((600, 540), course_name, font=text_font, fill='black', 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:
            logo = Image.open(company_logo)
            logo = logo.resize((150, 150))
            certificate.paste(logo, (50, 50))
        
        # Add photo if provided
        if participant_photo is not None:
            photo = Image.open(participant_photo)
            photo = photo.resize((150, 150))
            certificate.paste(photo, (1000, 50))
        
        # Save to temporary file
        temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
        certificate.save(temp_file.name)
        return temp_file.name

def create_quiz_app():
    quiz_app = QuizApp()
    
    with gr.Blocks(title="Interactive Quiz Generator") as demo:
        gr.Markdown("# Interactive Quiz Generator")
        
        # User Information Tab
        with gr.Tab("Step 1: User Information"):
            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="Content for Quiz", 
                                  placeholder="Enter the text content for generating questions",
                                  lines=10)
            num_questions = gr.Slider(minimum=1, maximum=10, value=5, step=1,
                                    label="Number of Questions")
            company_logo = gr.Image(label="Company Logo (Optional)", type="filepath")
            participant_photo = gr.Image(label="Participant Photo (Optional)", 
                                      type="filepath")
            generate_btn = gr.Button("Generate Quiz")
        
        # Quiz Tab
        with gr.Tab("Step 2: Take Quiz"):
            questions_display = gr.JSON(label="Questions")
            answers_input = gr.JSON(label="Your Answers (Enter indices of correct options)")
            submit_btn = gr.Button("Submit Answers")
            score_display = gr.Number(label="Your Score")
        
        # Certificate Tab
        with gr.Tab("Step 3: Get Certificate"):
            course_name = gr.Textbox(label="Course Name", 
                                   value="Interactive Quiz Course")
            certificate_display = gr.Image(label="Certificate")
        
        # Event handlers
        generate_btn.click(
            fn=quiz_app.generate_questions,
            inputs=[text_input, num_questions],
            outputs=questions_display
        )
        
        submit_btn.click(
            fn=quiz_app.calculate_score,
            inputs=[answers_input],
            outputs=score_display
        )
        
        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__":
    demo = create_quiz_app()
    demo.launch()