File size: 13,623 Bytes
67f169b
4f91be2
67f169b
 
 
 
 
058bca9
 
67f169b
058bca9
 
 
 
 
4f91be2
058bca9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deff9b7
058bca9
 
67f169b
 
7f84089
 
 
 
 
 
a4b4349
b1c910f
 
a4b4349
0ef1d43
7f84089
 
 
 
4be5ff1
 
b1c910f
4be5ff1
a3b6a5f
4be5ff1
058bca9
 
 
 
 
67f169b
058bca9
 
a3b6a5f
058bca9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4be5ff1
058bca9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4b4349
 
058bca9
7f84089
058bca9
 
e130fe4
058bca9
e130fe4
a3b6a5f
058bca9
51fcc77
058bca9
 
 
 
 
7f84089
058bca9
 
 
 
 
 
 
 
 
 
 
a3b6a5f
058bca9
 
7f84089
deff9b7
058bca9
 
 
 
deff9b7
ba67897
058bca9
a3b6a5f
 
058bca9
deff9b7
 
 
 
 
 
058bca9
 
deff9b7
 
 
4f91be2
deff9b7
058bca9
deff9b7
 
 
 
ba67897
058bca9
ba67897
 
 
 
 
b1c910f
deff9b7
 
 
 
ba67897
deff9b7
058bca9
 
a3b6a5f
418545a
058bca9
 
 
 
51fcc77
4f91be2
058bca9
 
ba67897
a3b6a5f
b1c910f
deff9b7
b1c910f
 
 
418545a
67f169b
 
058bca9
67f169b
51fcc77
418545a
a3b6a5f
418545a
a3b6a5f
 
51fcc77
67f169b
 
 
058bca9
a3b6a5f
51fcc77
a3b6a5f
 
51fcc77
a3b6a5f
 
51fcc77
67f169b
 
 
058bca9
67f169b
56b1a6d
67f169b
058bca9
67f169b
 
 
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
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import gradio as gr
from groq import Groq
import os
from PIL import Image, ImageDraw, ImageFont
from datetime import datetime
import json
import tempfile
from typing import List, Dict, Tuple, Optional
from dataclasses import dataclass

@dataclass
class Question:
    question: str
    options: List[str]
    correct_answer: int

@dataclass
class QuizFeedback:
    is_correct: bool
    selected: Optional[str]
    correct_answer: str

class QuizGenerator:
    def __init__(self, api_key: str):
        self.client = Groq(api_key=api_key)
    
    def generate_questions(self, text: str, num_questions: int) -> List[Question]:
        prompt = self._create_prompt(text, num_questions)
        
        try:
            response = self.client.chat.completions.create(
                messages=[
                    {
                        "role": "system",
                        "content": "You are a quiz generator. Create clear questions with concise answer options."
                    },
                    {
                        "role": "user",
                        "content": prompt
                    }
                ],
                model="llama-3.2-3b-preview",
                temperature=0.3,
                max_tokens=2048
            )
            
            questions = self._parse_response(response.choices[0].message.content)
            return self._validate_questions(questions, num_questions)
            
        except Exception as e:
            raise QuizGenerationError(f"Failed to generate questions: {str(e)}")
    
    def _create_prompt(self, text: str, num_questions: int) -> str:
        return f"""Create exactly {num_questions} multiple choice questions based on this text:
        {text}
        
        For each question:
        1. Create a clear, concise question
        2. Provide exactly 4 options
        3. Mark the correct answer with the index (0-3)
        4. Ensure options are concise and clear
        
        Return ONLY a JSON array with this EXACT format - no other text:
        [
            {{
                "question": "Question text here?",
                "options": [
                    "Brief option 1",
                    "Brief option 2",
                    "Brief option 3",
                    "Brief option 4"
                ],
                "correct_answer": 0
            }}
        ]
        Keep all options concise (10 words or less each).
        """
    
    def _parse_response(self, response_text: str) -> List[Dict]:
        response_text = response_text.replace("```json", "").replace("```", "").strip()
        start_idx = response_text.find("[")
        end_idx = response_text.rfind("]")
        
        if start_idx == -1 or end_idx == -1:
            raise ValueError("No valid JSON array found in response")
            
        response_text = response_text[start_idx:end_idx + 1]
        return json.loads(response_text)
    
    def _validate_questions(self, questions: List[Dict], num_questions: int) -> List[Question]:
        validated = []
        for q in questions:
            if not self._is_valid_question(q):
                continue
            validated.append(Question(
                question=q["question"].strip(),
                options=[opt.strip()[:100] for opt in q["options"]],
                correct_answer=int(q["correct_answer"]) % 4
            ))
        
        if not validated:
            raise ValueError("No valid questions after validation")
            
        return validated[:num_questions]
    
    def _is_valid_question(self, question: Dict) -> bool:
        return (
            all(key in question for key in ["question", "options", "correct_answer"]) and
            isinstance(question["options"], list) and
            len(question["options"]) == 4 and
            all(isinstance(opt, str) for opt in question["options"])
        )

class CertificateGenerator:
    def __init__(self):
        self.certificate_size = (1200, 800)
        self.border_color = '#4682B4'
        self.background_color = '#F0F8FF'
        
    def generate(
        self,
        name: str,
        score: float,
        course_name: str,
        company_logo: Optional[str] = None,
        participant_photo: Optional[str] = None
    ) -> str:
        certificate = self._create_base_certificate()
        draw = ImageDraw.Draw(certificate)
        
        fonts = self._load_fonts()
        self._add_borders(draw)
        self._add_content(draw, fonts, name, score, course_name)
        self._add_images(certificate, company_logo, participant_photo)
        
        return self._save_certificate(certificate)
    
    def _create_base_certificate(self) -> Image.Image:
        return Image.new('RGB', self.certificate_size, self.background_color)
    
    def _load_fonts(self) -> Dict[str, ImageFont.FreeTypeFont]:
        try:
            return {
                'title': ImageFont.truetype("arial.ttf", 60),
                'text': ImageFont.truetype("arial.ttf", 40),
                'subtitle': ImageFont.truetype("arial.ttf", 30)
            }
        except Exception as e:
            print(f"Font loading error: {e}. Using default font.")
            default = ImageFont.load_default()
            return {'title': default, 'text': default, 'subtitle': default}
    
    def _add_borders(self, draw: ImageDraw.Draw):
        # Main borders
        draw.rectangle([20, 20, 1180, 780], outline=self.border_color, width=3)
        draw.rectangle([40, 40, 1160, 760], outline=self.border_color, width=1)
        
        # Decorative corners
        self._add_decorative_corners(draw)
    
    def _add_decorative_corners(self, draw: ImageDraw.Draw):
        corner_size = 20
        corners = [
            # Top-left
            [(20, 40), (20 + corner_size, 40)],
            [(40, 20), (40, 20 + corner_size)],
            # Top-right
            [(1180 - corner_size, 40), (1180, 40)],
            [(1160, 20), (1160, 20 + corner_size)],
            # Bottom-left
            [(20, 760), (20 + corner_size, 760)],
            [(40, 780 - corner_size), (40, 780)],
            # Bottom-right
            [(1180 - corner_size, 760), (1180, 760)],
            [(1160, 780 - corner_size), (1160, 780)]
        ]
        
        for corner in corners:
            draw.line(corner, fill=self.border_color, width=2)
    
    def _add_content(
        self,
        draw: ImageDraw.Draw,
        fonts: Dict[str, ImageFont.FreeTypeFont],
        name: str,
        score: float,
        course_name: str
    ):
        # Title and headers
        draw.text((600, 100), "CertifyMe AI", font=fonts['title'], fill=self.border_color, anchor="mm")
        draw.text((600, 160), "Certificate of Achievement", font=fonts['subtitle'], fill=self.border_color, anchor="mm")
        
        # Main content
        content = [
            (300, "This is to certify that", 'black'),
            (380, name.strip() or "Participant", self.border_color),
            (460, "has successfully completed", 'black'),
            (540, course_name.strip() or "Assessment", self.border_color),
            (620, f"with a score of {score:.1f}%", 'black'),
            (700, datetime.now().strftime("%B %d, %Y"), 'black')
        ]
        
        for y, text, color in content:
            draw.text((600, y), text, font=fonts['text'], fill=color, anchor="mm")
    
    def _add_images(
        self,
        certificate: Image.Image,
        company_logo: Optional[str],
        participant_photo: Optional[str]
    ):
        if company_logo:
            self._add_image(certificate, company_logo, (50, 50))
        if participant_photo:
            self._add_image(certificate, participant_photo, (1000, 50))
    
    def _add_image(self, certificate: Image.Image, image_path: str, position: Tuple[int, int]):
        try:
            img = Image.open(image_path)
            img.thumbnail((150, 150))
            certificate.paste(img, position)
        except Exception as e:
            print(f"Error adding image: {e}")
    
    def _save_certificate(self, certificate: Image.Image) -> str:
        temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
        certificate.save(temp_file.name, 'PNG', quality=95)
        return temp_file.name

class QuizApp:
    def __init__(self, api_key: str):
        self.quiz_generator = QuizGenerator(api_key)
        self.certificate_generator = CertificateGenerator()
        self.current_questions: List[Question] = []
    
    def generate_questions(self, text: str, num_questions: int) -> Tuple[bool, List[Question]]:
        try:
            self.current_questions = self.quiz_generator.generate_questions(text, num_questions)
            return True, self.current_questions
        except Exception as e:
            print(f"Error generating questions: {e}")
            return False, []
    
    def calculate_score(self, answers: List[Optional[str]]) -> Tuple[float, bool, List[QuizFeedback]]:
        if not answers or not self.current_questions:
            return 0, False, []
        
        feedback = []
        correct = 0
        
        for question, answer in zip(self.current_questions, answers):
            if answer is None:
                feedback.append(QuizFeedback(False, None, question.options[question.correct_answer]))
                continue
                
            try:
                selected_index = question.options.index(answer)
                is_correct = selected_index == question.correct_answer
                if is_correct:
                    correct += 1
                feedback.append(QuizFeedback(
                    is_correct,
                    answer,
                    question.options[question.correct_answer]
                ))
            except ValueError:
                feedback.append(QuizFeedback(False, answer, question.options[question.correct_answer]))
        
        score = (correct / len(self.current_questions)) * 100
        return score, score >= 80, feedback

def create_quiz_interface():
    if not os.getenv("GROQ_API_KEY"):
        raise EnvironmentError("Please set your GROQ_API_KEY environment variable")
        
    quiz_app = QuizApp(os.getenv("GROQ_API_KEY"))
    
    with gr.Blocks(title="CertifyMe AI", theme=gr.themes.Soft()) as demo:
        # State management
        current_questions = gr.State([])
        
        # UI Components layout
        gr.Markdown("""
        # 🎓 CertifyMe AI
        ### Transform Your Knowledge into Recognized Achievements
        """)
        
        with gr.Tabs() as tabs:
            # Profile Setup Tab
            with gr.Tab("📋 Step 1: Profile Setup"):
                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")
            
            # Assessment Tab
            with gr.Tab("📝 Step 2: Take Assessment"):
                feedback_box = gr.Markdown("")
                question_box = gr.Markdown("")
                answers = [
                    gr.Radio(choices=[], label=f"Question {i+1}", visible=False)
                    for i in range(5)
                ]
                submit_btn = gr.Button("Submit Assessment", variant="primary", size="lg")
            
            # Certification Tab
            with gr.Tab("🎓 Step 3: Get Certified"):
                score_display = gr.Number(label="Your Score")
                result_message = gr.Markdown("")
                course_name = gr.Textbox(
                    label="Certification Title",
                    value="Professional Assessment Certification"
                )
                certificate_display = gr.Image(label="Your Certificate")
        
        # Event handlers
        generate_btn.click(
            fn=quiz_app.update_questions,
            inputs=[text_input, num_questions],
            outputs=[
                question_box,
                feedback_box,
                *answers,
                current_questions,
                tabs
            ]
        )
        
        submit_btn.click(
            fn=quiz_app.submit_quiz,
            inputs=[*answers, current_questions],
            outputs=[
                feedback_box,
                *answers,
                score_display,
                result_message,
                tabs
            ]
        )
        
        score_display.change(
            fn=quiz_app.certificate_generator.generate,
            inputs=[score_display, name, course_name, company_logo, participant_photo],
            outputs=certificate_display
        )
    
    return demo

if __name__ == "__main__":
    demo = create_quiz_interface()
    demo.launch()