File size: 6,070 Bytes
0165bb9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# --- Certificate Generator ---
def generate_certificate(name, score, total, instructor="Instructor"):
    unique_id = str(uuid.uuid4())
    filename = f"cert_{unique_id}.pdf"
    filepath = os.path.join(tempfile.gettempdir(), filename)

    c = canvas.Canvas(filepath, pagesize=landscape(A5))
    width, height = landscape(A5)

    c.setFillColor(HexColor("#fffdf6"))
    c.rect(0, 0, width, height, stroke=0, fill=1)

    c.setStrokeColor(HexColor("#001858"))
    c.setLineWidth(3)
    margin = 10 * mm
    c.rect(margin, margin, width - 2 * margin, height - 2 * margin)

    c.setFillColor(HexColor("#001858"))
    c.setFont("Helvetica-Bold", 24)
    c.drawCentredString(width / 2, height - 60, "Certificate of Completion")

    c.setFont("Helvetica", 14)
    c.drawCentredString(width / 2, height - 100, "This is awarded to")

    c.setFont("Helvetica-Bold", 18)
    c.drawCentredString(width / 2, height - 130, name)

    c.setFont("Helvetica", 14)
    c.drawCentredString(width / 2, height - 160, "For successfully completing the quiz")

    c.setFont("Helvetica", 12)
    c.drawCentredString(width / 2, height - 185, f"Score: {score} / {total}")

    c.setFont("Helvetica-Oblique", 10)
    c.drawString(margin + 10, margin + 20, f"Instructor: {instructor}")

    date_str = datetime.now().strftime("%d %B %Y")
    c.setFont("Helvetica", 10)
    c.drawRightString(width - margin - 10, margin + 20, f"Issued on: {date_str}")

    c.save()
    return filepath


# --- Main Quiz Code Generator ---
def generate_python_code(title, instructor, quiz_type, questions_text):
    # Parse questions and hash answers
    parsed_questions = []
    for line in questions_text.strip().split("\n"):
        if not line.strip():
            continue
        parts = [p.strip() for p in line.split(",")]
        
        if quiz_type == "Multiple Choice":
            q_text = parts[0]
            options = parts[1:-1]  # all except question and last (answer)
            answer = parts[-1]
            parsed_questions.append({
                "question": q_text,
                "options": options,
                "answer_hash": hashlib.sha256(answer.lower().encode()).hexdigest()
            })
        else:
            q_text = parts[0]
            answer = parts[1]
            parsed_questions.append({
                "question": q_text,
                "answer_hash": hashlib.sha256(answer.lower().encode()).hexdigest()
            })

    # Generate code for the student quiz
    python_code = f'''
import gradio as gr
import uuid, os, tempfile, hashlib
from reportlab.lib.pagesizes import A5, landscape
from reportlab.pdfgen import canvas
from reportlab.lib.units import mm
from reportlab.lib.colors import HexColor
from datetime import datetime

def generate_certificate(name, score, total, instructor="{instructor}"):
    unique_id = str(uuid.uuid4())
    filename = f"cert_{{unique_id}}.pdf"
    filepath = os.path.join(tempfile.gettempdir(), filename)
    c = canvas.Canvas(filepath, pagesize=landscape(A5))
    width, height = landscape(A5)
    c.setFillColor(HexColor("#fffdf6"))
    c.rect(0, 0, width, height, stroke=0, fill=1)
    c.setStrokeColor(HexColor("#001858"))
    c.setLineWidth(3)
    margin = 10 * mm
    c.rect(margin, margin, width - 2 * margin, height - 2 * margin)
    c.setFillColor(HexColor("#001858"))
    c.setFont("Helvetica-Bold", 24)
    c.drawCentredString(width / 2, height - 60, "Certificate of Completion")
    c.setFont("Helvetica", 14)
    c.drawCentredString(width / 2, height - 100, "This is awarded to")
    c.setFont("Helvetica-Bold", 18)
    c.drawCentredString(width / 2, height - 130, name)
    c.setFont("Helvetica", 14)
    c.drawCentredString(width / 2, height - 160, "For successfully completing the quiz")
    c.setFont("Helvetica", 12)
    c.drawCentredString(width / 2, height - 185, f"Score: {{score}} / {{total}}")
    c.setFont("Helvetica-Oblique", 10)
    c.drawString(margin + 10, margin + 20, f"Instructor: {{instructor}}")
    date_str = datetime.now().strftime("%d %B %Y")
    c.setFont("Helvetica", 10)
    c.drawRightString(width - margin - 10, margin + 20, f"Issued on: {{date_str}}")
    c.save()
    return filepath

quiz_type = "{quiz_type}"
questions = {parsed_questions}

def eval_quiz(name, *answers):
    score = 0
    for i, ans in enumerate(answers):
        if hashlib.sha256(ans.lower().strip().encode()).hexdigest() == questions[i]["answer_hash"]:
            score += 1
    cert_path = generate_certificate(name, score, len(questions), instructor="{instructor}")
    return f"Score: {{score}} / {{len(questions)}}", cert_path

with gr.Blocks() as app:
    gr.Markdown("## {title}")
    name = gr.Textbox(label="Your Name")
    answer_inputs = []
    for q in questions:
        gr.Markdown(q["question"])
        if quiz_type == "Multiple Choice":
            answer_inputs.append(gr.Radio(choices=q["options"], label="Select Answer"))
        else:
            answer_inputs.append(gr.Textbox(label="Your Answer"))
    submit = gr.Button("Submit")
    result = gr.Textbox(label="Result")
    cert = gr.File(label="Download Certificate")
    submit.click(fn=eval_quiz, inputs=[name] + answer_inputs, outputs=[result, cert])

app.launch()
'''
    return python_code


# --- Instructor Interface ---
with gr.Blocks() as interface:
    gr.Markdown("## Instructor Quiz Generator")

    title = gr.Textbox(label="Quiz Title", placeholder="e.g. Python Basics Quiz")
    instructor = gr.Textbox(label="Instructor Name", placeholder="e.g. Dr. Smith")
    quiz_type = gr.Dropdown(choices=["Multiple Choice", "Text Answer"], label="Quiz Type", value="Multiple Choice")
    questions = gr.Textbox(lines=10, label="Questions and Answers",
        placeholder="For MCQ: Question, Option1, Option2, Option3, Correct Option\nFor Text: Question, Correct Answer")

    generate_btn = gr.Button("Generate Python Quiz Code")
    output = gr.Code(label="Generated Python Code")

    generate_btn.click(fn=generate_python_code, inputs=[title, instructor, quiz_type, questions], outputs=output)

interface.launch()