Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -9,8 +9,14 @@ from reportlab.lib.units import mm
|
|
9 |
from reportlab.lib.colors import HexColor
|
10 |
from datetime import datetime
|
11 |
|
12 |
-
# --- Certificate Generator ---
|
|
|
|
|
13 |
def generate_certificate(name, score, total, instructor="Instructor"):
|
|
|
|
|
|
|
|
|
14 |
unique_id = str(uuid.uuid4())
|
15 |
filename = f"cert_{unique_id}.pdf"
|
16 |
filepath = os.path.join(tempfile.gettempdir(), filename)
|
@@ -18,15 +24,16 @@ def generate_certificate(name, score, total, instructor="Instructor"):
|
|
18 |
c = canvas.Canvas(filepath, pagesize=landscape(A5))
|
19 |
width, height = landscape(A5)
|
20 |
|
21 |
-
|
|
|
22 |
c.rect(0, 0, width, height, stroke=0, fill=1)
|
23 |
-
|
24 |
-
c.setStrokeColor(HexColor("#001858"))
|
25 |
c.setLineWidth(3)
|
26 |
margin = 10 * mm
|
27 |
c.rect(margin, margin, width - 2 * margin, height - 2 * margin)
|
28 |
|
29 |
-
|
|
|
30 |
c.setFont("Helvetica-Bold", 24)
|
31 |
c.drawCentredString(width / 2, height - 60, "Certificate of Completion")
|
32 |
|
@@ -42,9 +49,9 @@ def generate_certificate(name, score, total, instructor="Instructor"):
|
|
42 |
c.setFont("Helvetica", 12)
|
43 |
c.drawCentredString(width / 2, height - 185, f"Score: {score} / {total}")
|
44 |
|
|
|
45 |
c.setFont("Helvetica-Oblique", 10)
|
46 |
c.drawString(margin + 10, margin + 20, f"Instructor: {instructor}")
|
47 |
-
|
48 |
date_str = datetime.now().strftime("%d %B %Y")
|
49 |
c.setFont("Helvetica", 10)
|
50 |
c.drawRightString(width - margin - 10, margin + 20, f"Issued on: {date_str}")
|
@@ -52,26 +59,31 @@ def generate_certificate(name, score, total, instructor="Instructor"):
|
|
52 |
c.save()
|
53 |
return filepath
|
54 |
|
55 |
-
|
56 |
# --- Main Quiz Code Generator ---
|
57 |
def generate_python_code(title, instructor, quiz_type, questions_text):
|
58 |
-
|
|
|
|
|
|
|
|
|
59 |
parsed_questions = []
|
60 |
for line in questions_text.strip().split("\n"):
|
61 |
if not line.strip():
|
62 |
continue
|
63 |
parts = [p.strip() for p in line.split(",")]
|
64 |
-
|
65 |
if quiz_type == "Multiple Choice":
|
|
|
66 |
q_text = parts[0]
|
67 |
-
options = parts[1:-1]
|
68 |
answer = parts[-1]
|
69 |
parsed_questions.append({
|
70 |
"question": q_text,
|
71 |
"options": options,
|
72 |
"answer_hash": hashlib.sha256(answer.lower().encode()).hexdigest()
|
73 |
})
|
74 |
-
else:
|
|
|
75 |
q_text = parts[0]
|
76 |
answer = parts[1]
|
77 |
parsed_questions.append({
|
@@ -79,8 +91,12 @@ def generate_python_code(title, instructor, quiz_type, questions_text):
|
|
79 |
"answer_hash": hashlib.sha256(answer.lower().encode()).hexdigest()
|
80 |
})
|
81 |
|
82 |
-
# Generate code for the student quiz
|
|
|
83 |
python_code = f'''
|
|
|
|
|
|
|
84 |
import gradio as gr
|
85 |
import uuid, os, tempfile, hashlib
|
86 |
from reportlab.lib.pagesizes import A5, landscape
|
@@ -89,6 +105,7 @@ from reportlab.lib.units import mm
|
|
89 |
from reportlab.lib.colors import HexColor
|
90 |
from datetime import datetime
|
91 |
|
|
|
92 |
def generate_certificate(name, score, total, instructor="{instructor}"):
|
93 |
unique_id = str(uuid.uuid4())
|
94 |
filename = f"cert_{{unique_id}}.pdf"
|
@@ -120,50 +137,91 @@ def generate_certificate(name, score, total, instructor="{instructor}"):
|
|
120 |
c.save()
|
121 |
return filepath
|
122 |
|
|
|
123 |
quiz_type = "{quiz_type}"
|
124 |
questions = {parsed_questions}
|
125 |
|
126 |
def eval_quiz(name, *answers):
|
|
|
|
|
|
|
|
|
|
|
127 |
score = 0
|
128 |
for i, ans in enumerate(answers):
|
129 |
-
if hashlib.sha256(ans.lower().strip().encode()).hexdigest() == questions[i]["answer_hash"]:
|
130 |
score += 1
|
|
|
131 |
cert_path = generate_certificate(name, score, len(questions), instructor="{instructor}")
|
132 |
-
|
|
|
133 |
|
134 |
-
|
|
|
135 |
gr.Markdown("## {title}")
|
136 |
-
|
|
|
|
|
|
|
137 |
answer_inputs = []
|
138 |
for q in questions:
|
139 |
-
gr.Markdown(q[
|
140 |
if quiz_type == "Multiple Choice":
|
141 |
-
answer_inputs.append(gr.Radio(choices=q["options"], label="Select
|
142 |
else:
|
143 |
-
answer_inputs.append(gr.Textbox(label="
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
148 |
|
149 |
-
app.launch()
|
150 |
'''
|
151 |
return python_code
|
152 |
|
153 |
-
|
154 |
# --- Instructor Interface ---
|
155 |
-
with gr.Blocks() as interface:
|
156 |
-
gr.Markdown("
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
168 |
|
169 |
interface.launch()
|
|
|
9 |
from reportlab.lib.colors import HexColor
|
10 |
from datetime import datetime
|
11 |
|
12 |
+
# --- Certificate Generator (This function is part of the generated code) ---
|
13 |
+
# Note: This function is defined here for completeness but is also embedded
|
14 |
+
# in the generated string.
|
15 |
def generate_certificate(name, score, total, instructor="Instructor"):
|
16 |
+
"""
|
17 |
+
Generates a PDF certificate of completion.
|
18 |
+
This entire function will be part of the output code string.
|
19 |
+
"""
|
20 |
unique_id = str(uuid.uuid4())
|
21 |
filename = f"cert_{unique_id}.pdf"
|
22 |
filepath = os.path.join(tempfile.gettempdir(), filename)
|
|
|
24 |
c = canvas.Canvas(filepath, pagesize=landscape(A5))
|
25 |
width, height = landscape(A5)
|
26 |
|
27 |
+
# Set background and border
|
28 |
+
c.setFillColor(HexColor("#fffdf6")) # Creamy background
|
29 |
c.rect(0, 0, width, height, stroke=0, fill=1)
|
30 |
+
c.setStrokeColor(HexColor("#001858")) # Dark blue border
|
|
|
31 |
c.setLineWidth(3)
|
32 |
margin = 10 * mm
|
33 |
c.rect(margin, margin, width - 2 * margin, height - 2 * margin)
|
34 |
|
35 |
+
# Add text content
|
36 |
+
c.setFillColor(HexColor("#001858")) # Dark blue text
|
37 |
c.setFont("Helvetica-Bold", 24)
|
38 |
c.drawCentredString(width / 2, height - 60, "Certificate of Completion")
|
39 |
|
|
|
49 |
c.setFont("Helvetica", 12)
|
50 |
c.drawCentredString(width / 2, height - 185, f"Score: {score} / {total}")
|
51 |
|
52 |
+
# Footer
|
53 |
c.setFont("Helvetica-Oblique", 10)
|
54 |
c.drawString(margin + 10, margin + 20, f"Instructor: {instructor}")
|
|
|
55 |
date_str = datetime.now().strftime("%d %B %Y")
|
56 |
c.setFont("Helvetica", 10)
|
57 |
c.drawRightString(width - margin - 10, margin + 20, f"Issued on: {date_str}")
|
|
|
59 |
c.save()
|
60 |
return filepath
|
61 |
|
|
|
62 |
# --- Main Quiz Code Generator ---
|
63 |
def generate_python_code(title, instructor, quiz_type, questions_text):
|
64 |
+
"""
|
65 |
+
Parses instructor input and generates a self-contained Python script
|
66 |
+
for a student-facing Gradio quiz app.
|
67 |
+
"""
|
68 |
+
# Parse questions and hash the answers for security
|
69 |
parsed_questions = []
|
70 |
for line in questions_text.strip().split("\n"):
|
71 |
if not line.strip():
|
72 |
continue
|
73 |
parts = [p.strip() for p in line.split(",")]
|
74 |
+
|
75 |
if quiz_type == "Multiple Choice":
|
76 |
+
if len(parts) < 3: continue # Skip malformed lines
|
77 |
q_text = parts[0]
|
78 |
+
options = parts[1:-1]
|
79 |
answer = parts[-1]
|
80 |
parsed_questions.append({
|
81 |
"question": q_text,
|
82 |
"options": options,
|
83 |
"answer_hash": hashlib.sha256(answer.lower().encode()).hexdigest()
|
84 |
})
|
85 |
+
else: # Text Answer
|
86 |
+
if len(parts) < 2: continue # Skip malformed lines
|
87 |
q_text = parts[0]
|
88 |
answer = parts[1]
|
89 |
parsed_questions.append({
|
|
|
91 |
"answer_hash": hashlib.sha256(answer.lower().encode()).hexdigest()
|
92 |
})
|
93 |
|
94 |
+
# Generate the complete Python code string for the student quiz app
|
95 |
+
# f-strings with {{ and }} are used to escape braces for the final code.
|
96 |
python_code = f'''
|
97 |
+
# --- Generated Quiz App ---
|
98 |
+
# Copy and paste this entire code block into a single Google Colab cell and run it.
|
99 |
+
|
100 |
import gradio as gr
|
101 |
import uuid, os, tempfile, hashlib
|
102 |
from reportlab.lib.pagesizes import A5, landscape
|
|
|
105 |
from reportlab.lib.colors import HexColor
|
106 |
from datetime import datetime
|
107 |
|
108 |
+
# Certificate generation function (included for a self-contained script)
|
109 |
def generate_certificate(name, score, total, instructor="{instructor}"):
|
110 |
unique_id = str(uuid.uuid4())
|
111 |
filename = f"cert_{{unique_id}}.pdf"
|
|
|
137 |
c.save()
|
138 |
return filepath
|
139 |
|
140 |
+
# Quiz data (answers are hashed)
|
141 |
quiz_type = "{quiz_type}"
|
142 |
questions = {parsed_questions}
|
143 |
|
144 |
def eval_quiz(name, *answers):
|
145 |
+
"""
|
146 |
+
Evaluates the student's answers against the stored hashes and generates a result.
|
147 |
+
"""
|
148 |
+
if not name.strip():
|
149 |
+
name = "Anonymous"
|
150 |
score = 0
|
151 |
for i, ans in enumerate(answers):
|
152 |
+
if ans and hashlib.sha256(str(ans).lower().strip().encode()).hexdigest() == questions[i]["answer_hash"]:
|
153 |
score += 1
|
154 |
+
|
155 |
cert_path = generate_certificate(name, score, len(questions), instructor="{instructor}")
|
156 |
+
|
157 |
+
return f"Hi {{name}}, your score is: {{score}} / {{len(questions)}}", cert_path
|
158 |
|
159 |
+
# Gradio interface for the student
|
160 |
+
with gr.Blocks(theme=gr.themes.Soft()) as app:
|
161 |
gr.Markdown("## {title}")
|
162 |
+
|
163 |
+
with gr.Row():
|
164 |
+
name = gr.Textbox(label="Enter Your Full Name to Generate Certificate", placeholder="e.g., Ada Lovelace")
|
165 |
+
|
166 |
answer_inputs = []
|
167 |
for q in questions:
|
168 |
+
gr.Markdown(f"**Question:** {q['question']}")
|
169 |
if quiz_type == "Multiple Choice":
|
170 |
+
answer_inputs.append(gr.Radio(choices=q["options"], label="Select your answer"))
|
171 |
else:
|
172 |
+
answer_inputs.append(gr.Textbox(label="Type your answer"))
|
173 |
+
|
174 |
+
submit_btn = gr.Button("Submit Quiz")
|
175 |
+
|
176 |
+
with gr.Row():
|
177 |
+
result_output = gr.Textbox(label="Your Result")
|
178 |
+
certificate_output = gr.File(label="Download Your Certificate")
|
179 |
+
|
180 |
+
submit_btn.click(
|
181 |
+
fn=eval_quiz,
|
182 |
+
inputs=[name] + answer_inputs,
|
183 |
+
outputs=[result_output, certificate_output]
|
184 |
+
)
|
185 |
|
186 |
+
app.launch(debug=True)
|
187 |
'''
|
188 |
return python_code
|
189 |
|
|
|
190 |
# --- Instructor Interface ---
|
191 |
+
with gr.Blocks(theme=gr.themes.Base()) as interface:
|
192 |
+
gr.Markdown("# Instructor Quiz Generator")
|
193 |
+
gr.Markdown("Create a secure, interactive quiz for your Google Colab notebooks.")
|
194 |
+
|
195 |
+
with gr.Row():
|
196 |
+
# Left column for inputs
|
197 |
+
with gr.Column(scale=1):
|
198 |
+
title = gr.Textbox(label="Quiz Title", placeholder="e.g. Python Basics Quiz")
|
199 |
+
instructor = gr.Textbox(label="Instructor Name", placeholder="e.g. Dr. Ada Lovelace")
|
200 |
+
quiz_type = gr.Dropdown(
|
201 |
+
choices=["Multiple Choice", "Text Answer"],
|
202 |
+
label="Quiz Type",
|
203 |
+
value="Multiple Choice"
|
204 |
+
)
|
205 |
+
questions = gr.Textbox(
|
206 |
+
lines=10,
|
207 |
+
label="Questions & Answers",
|
208 |
+
placeholder=(
|
209 |
+
"One question per line. Separate parts with commas.\n\n"
|
210 |
+
"MCQ Format: Question,Option1,Option2,CorrectOption\n"
|
211 |
+
"Text Format: Question,CorrectAnswer"
|
212 |
+
)
|
213 |
+
)
|
214 |
+
generate_btn = gr.Button("🚀 Generate Python Quiz Code", variant="primary")
|
215 |
+
|
216 |
+
# Right column for the generated code output
|
217 |
+
with gr.Column(scale=2):
|
218 |
+
output = gr.Code(label="Generated Python Code for Colab", language="python", lines=22)
|
219 |
+
|
220 |
+
# Link the button to the generation function
|
221 |
+
generate_btn.click(
|
222 |
+
fn=generate_python_code,
|
223 |
+
inputs=[title, instructor, quiz_type, questions],
|
224 |
+
outputs=output
|
225 |
+
)
|
226 |
|
227 |
interface.launch()
|