Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,167 +1,511 @@
|
|
| 1 |
-
import
|
|
|
|
|
|
|
| 2 |
import requests
|
| 3 |
-
import
|
| 4 |
-
import
|
| 5 |
-
import csv
|
| 6 |
import tempfile
|
| 7 |
-
from
|
| 8 |
-
|
| 9 |
-
API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
-
|
| 11 |
-
# Load model safely
|
| 12 |
-
try:
|
| 13 |
-
qa_pipeline = pipeline(
|
| 14 |
-
"text-generation",
|
| 15 |
-
model="tiiuae/falcon-7b-instruct",
|
| 16 |
-
max_new_tokens=128,
|
| 17 |
-
do_sample=False,
|
| 18 |
-
device_map="auto"
|
| 19 |
-
)
|
| 20 |
-
except Exception as e:
|
| 21 |
-
raise RuntimeError(f"Failed to load model: {e}")
|
| 22 |
|
| 23 |
-
|
|
|
|
|
|
|
| 24 |
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
if any(keyword in question for keyword in skip_keywords):
|
| 35 |
-
return "SKIPPED"
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
result = qa_pipeline(prompt)[0]["generated_text"]
|
| 40 |
-
except Exception as e:
|
| 41 |
-
return f"PIPELINE ERROR: {e}"
|
| 42 |
|
| 43 |
-
|
| 44 |
-
if match:
|
| 45 |
-
return match.group(1)
|
| 46 |
|
| 47 |
-
|
| 48 |
-
|
| 49 |
|
| 50 |
-
|
| 51 |
-
try:
|
| 52 |
-
return requests.get(f"{API_URL}/random-question").json()
|
| 53 |
-
except Exception as e:
|
| 54 |
-
return {"task_id": "N/A", "question": f"Error fetching task: {e}"}
|
| 55 |
|
| 56 |
-
def test_random_question():
|
| 57 |
-
task = fetch_task()
|
| 58 |
-
answer = generate_answer(task)
|
| 59 |
-
return f"Task ID: {task['task_id']}\n\nQuestion: {task['question']}\n\nYour Answer: {answer}"
|
| 60 |
|
| 61 |
-
def
|
| 62 |
-
|
| 63 |
-
|
|
|
|
| 64 |
|
| 65 |
-
|
| 66 |
-
|
| 67 |
|
| 68 |
-
|
| 69 |
-
"
|
| 70 |
-
"
|
| 71 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
}
|
| 73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
try:
|
| 75 |
-
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
except Exception as e:
|
| 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 |
-
with gr.Row():
|
| 148 |
-
test_btn = gr.Button("π§ͺ Test Random Question")
|
| 149 |
-
submit_btn = gr.Button("π Submit One Question")
|
| 150 |
-
auto_btn = gr.Button("β»οΈ Auto-Submit Until Valid Answer")
|
| 151 |
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
|
| 164 |
-
|
| 165 |
-
|
|
|
|
|
|
|
|
|
|
| 166 |
|
| 167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
import random
|
| 4 |
import requests
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
from datetime import date
|
|
|
|
| 7 |
import tempfile
|
| 8 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 9 |
+
from huggingface_hub import upload_file
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
+
import pandas as pd
|
| 12 |
+
from huggingface_hub import HfApi, hf_hub_download, Repository
|
| 13 |
+
from huggingface_hub.repocard import metadata_load
|
| 14 |
|
| 15 |
+
import gradio as gr
|
| 16 |
+
from datasets import load_dataset, Dataset
|
| 17 |
+
from huggingface_hub import whoami
|
| 18 |
+
|
| 19 |
+
import asyncio
|
| 20 |
+
from functools import partial
|
| 21 |
+
|
| 22 |
+
EXAM_DATASET_ID = os.getenv("EXAM_DATASET_ID") or "agents-course/unit_1_quiz"
|
| 23 |
+
EXAM_MAX_QUESTIONS = os.getenv("EXAM_MAX_QUESTIONS") or 1
|
| 24 |
+
EXAM_PASSING_SCORE = os.getenv("EXAM_PASSING_SCORE") or 0.8
|
| 25 |
+
CERTIFYING_ORG_LINKEDIN_ID = os.getenv("CERTIFYING_ORG_LINKEDIN_ID", "000000")
|
| 26 |
+
COURSE_TITLE = os.getenv("COURSE_TITLE", "Fundamentals of MCP")
|
| 27 |
+
|
| 28 |
+
ds = load_dataset(EXAM_DATASET_ID, split="train")
|
| 29 |
+
|
| 30 |
+
DATASET_REPO_URL = "https://huggingface.co/datasets/mcp-course/certificates"
|
| 31 |
+
|
| 32 |
+
# Convert dataset to a list of dicts and randomly sort
|
| 33 |
+
quiz_data = ds.to_pandas().to_dict("records")
|
| 34 |
+
random.shuffle(quiz_data)
|
| 35 |
+
|
| 36 |
+
# Limit to max questions if specified
|
| 37 |
+
if EXAM_MAX_QUESTIONS:
|
| 38 |
+
quiz_data = quiz_data[: int(EXAM_MAX_QUESTIONS)]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def on_user_logged_in(token: gr.OAuthToken | None):
|
| 42 |
+
"""
|
| 43 |
+
If the user has a valid token, show Start button.
|
| 44 |
+
Otherwise, keep the login button visible.
|
| 45 |
+
"""
|
| 46 |
+
if token is not None:
|
| 47 |
+
return [
|
| 48 |
+
gr.update(visible=False), # login_btn
|
| 49 |
+
gr.update(visible=True), # start_btn
|
| 50 |
+
gr.update(visible=False), # next_btn
|
| 51 |
+
gr.update(visible=False), # submit_btn
|
| 52 |
+
"", # question_text
|
| 53 |
+
gr.update(choices=[], visible=False), # radio_choices
|
| 54 |
+
"Click 'Start' to begin the quiz", # status_text
|
| 55 |
+
0, # question_idx
|
| 56 |
+
[], # user_answers
|
| 57 |
+
gr.update(visible=False), # certificate_img
|
| 58 |
+
gr.update(
|
| 59 |
+
visible=True,
|
| 60 |
+
value="""
|
| 61 |
+
<div style="text-align: center; padding: 20px; border: 2px dashed #ccc;">
|
| 62 |
+
<h3>π― Complete the Quiz to Unlock</h3>
|
| 63 |
+
<p>Pass the quiz to add your certificate to LinkedIn!</p>
|
| 64 |
+
<img src="https://huggingface.co/spaces/mcp-course/unit_1_quiz/resolve/main/li_logo.webp" alt="LinkedIn Add to Profile" style="width: 80px; height: 80px; text-align: center;">
|
| 65 |
+
</div>
|
| 66 |
+
""",
|
| 67 |
+
), # linkedin_btn - now visible with explanatory text
|
| 68 |
+
token, # user_token
|
| 69 |
+
]
|
| 70 |
+
else:
|
| 71 |
+
return [
|
| 72 |
+
gr.update(visible=True), # login_btn
|
| 73 |
+
gr.update(visible=False), # start_btn
|
| 74 |
+
gr.update(visible=False), # next_btn
|
| 75 |
+
gr.update(visible=False), # submit_btn
|
| 76 |
+
"", # question_text
|
| 77 |
+
gr.update(choices=[], visible=False), # radio_choices
|
| 78 |
+
"", # status_text
|
| 79 |
+
0, # question_idx
|
| 80 |
+
[], # user_answers
|
| 81 |
+
gr.update(visible=False), # certificate_img
|
| 82 |
+
gr.update(
|
| 83 |
+
visible=True,
|
| 84 |
+
value="""
|
| 85 |
+
<div style="text-align: center; padding: 20px; border: 2px dashed #ccc; border-radius: 10px; margin-top: 20px;">
|
| 86 |
+
<h3>π Login Required</h3>
|
| 87 |
+
<img src="https://huggingface.co/spaces/mcp-course/unit_1_quiz/resolve/main/li_logo.webp" alt="LinkedIn Add to Profile" style="width: 80px; height: 80px; text-align: center;">
|
| 88 |
+
</div>
|
| 89 |
+
""",
|
| 90 |
+
), # linkedin_btn - visible with login prompt
|
| 91 |
+
None, # user_token
|
| 92 |
+
]
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def generate_certificate(name: str, profile_url: str):
|
| 96 |
+
"""Generate certificate image and PDF."""
|
| 97 |
+
certificate_path = os.path.join(
|
| 98 |
+
os.path.dirname(__file__), "templates", "certificate.png"
|
| 99 |
+
)
|
| 100 |
+
im = Image.open(certificate_path)
|
| 101 |
+
d = ImageDraw.Draw(im)
|
| 102 |
|
| 103 |
+
name_font = ImageFont.truetype("Quattrocento-Regular.ttf", 100)
|
| 104 |
+
date_font = ImageFont.truetype("Quattrocento-Regular.ttf", 48)
|
|
|
|
|
|
|
| 105 |
|
| 106 |
+
name = name.title()
|
| 107 |
+
d.text((1000, 740), name, fill="black", anchor="mm", font=name_font)
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
+
d.text((1480, 1170), str(date.today()), fill="black", anchor="mm", font=date_font)
|
|
|
|
|
|
|
| 110 |
|
| 111 |
+
pdf = im.convert("RGB")
|
| 112 |
+
pdf.save("certificate.pdf")
|
| 113 |
|
| 114 |
+
return im, "certificate.pdf"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
|
| 117 |
+
def create_linkedin_button(username: str, cert_url: str | None) -> str:
|
| 118 |
+
"""Create LinkedIn 'Add to Profile' button HTML."""
|
| 119 |
+
current_year = date.today().year
|
| 120 |
+
current_month = date.today().month
|
| 121 |
|
| 122 |
+
# Use the dataset certificate URL if available, otherwise fallback to default
|
| 123 |
+
certificate_url = cert_url or "https://huggingface.co/mcp-course"
|
| 124 |
|
| 125 |
+
linkedin_params = {
|
| 126 |
+
"startTask": "CERTIFICATION_NAME",
|
| 127 |
+
"name": COURSE_TITLE,
|
| 128 |
+
"organizationName": "Hugging Face",
|
| 129 |
+
"organizationId": CERTIFYING_ORG_LINKEDIN_ID,
|
| 130 |
+
"organizationIdissueYear": str(current_year),
|
| 131 |
+
"issueMonth": str(current_month),
|
| 132 |
+
"certUrl": certificate_url,
|
| 133 |
+
"certId": username, # Using username as cert ID
|
| 134 |
}
|
| 135 |
|
| 136 |
+
# Build the LinkedIn button URL
|
| 137 |
+
base_url = "https://www.linkedin.com/profile/add?"
|
| 138 |
+
params = "&".join(
|
| 139 |
+
f"{k}={requests.utils.quote(v)}" for k, v in linkedin_params.items()
|
| 140 |
+
)
|
| 141 |
+
button_url = base_url + params
|
| 142 |
+
|
| 143 |
+
message = f"""
|
| 144 |
+
<a href="{button_url}" target="_blank" style="display: block; margin-top: 20px; text-align: center;">
|
| 145 |
+
<img src="https://huggingface.co/spaces/mcp-course/unit_1_quiz/resolve/main/li_button.png"
|
| 146 |
+
alt="LinkedIn Add to Profile button" style="width: 300px; height: 80px;">
|
| 147 |
+
</a>
|
| 148 |
+
"""
|
| 149 |
+
return message
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
async def upload_certificate_to_hub(username: str, certificate_img) -> str:
|
| 153 |
+
"""Upload certificate to the dataset hub and return the URL asynchronously."""
|
| 154 |
+
# Save image to temporary file
|
| 155 |
+
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
|
| 156 |
+
certificate_img.save(tmp.name)
|
| 157 |
+
|
| 158 |
+
try:
|
| 159 |
+
# Run upload in a thread pool since upload_file is blocking
|
| 160 |
+
loop = asyncio.get_event_loop()
|
| 161 |
+
upload_func = partial(
|
| 162 |
+
upload_file,
|
| 163 |
+
path_or_fileobj=tmp.name,
|
| 164 |
+
path_in_repo=f"certificates/{username}/{date.today()}.png",
|
| 165 |
+
repo_id="mcp-course/certificates",
|
| 166 |
+
repo_type="dataset",
|
| 167 |
+
token=os.getenv("HF_TOKEN"),
|
| 168 |
+
)
|
| 169 |
+
await loop.run_in_executor(None, upload_func)
|
| 170 |
+
|
| 171 |
+
# Construct the URL to the image
|
| 172 |
+
cert_url = (
|
| 173 |
+
f"https://huggingface.co/datasets/mcp-course/certificates/"
|
| 174 |
+
f"resolve/main/certificates/{username}/{date.today()}.png"
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
# Clean up temp file
|
| 178 |
+
os.unlink(tmp.name)
|
| 179 |
+
return cert_url
|
| 180 |
+
|
| 181 |
+
except Exception as e:
|
| 182 |
+
print(f"Error uploading certificate: {e}")
|
| 183 |
+
os.unlink(tmp.name)
|
| 184 |
+
return None
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
async def push_results_to_hub(
|
| 188 |
+
user_answers,
|
| 189 |
+
custom_name: str | None,
|
| 190 |
+
token: gr.OAuthToken | None,
|
| 191 |
+
profile: gr.OAuthProfile | None,
|
| 192 |
+
):
|
| 193 |
+
"""Handle quiz completion and certificate generation."""
|
| 194 |
+
if token is None or profile is None:
|
| 195 |
+
gr.Warning("Please log in to Hugging Face before submitting!")
|
| 196 |
+
return (
|
| 197 |
+
gr.update(visible=True, value="Please login first"),
|
| 198 |
+
gr.update(visible=False),
|
| 199 |
+
gr.update(visible=False),
|
| 200 |
+
gr.update(visible=False), # hide custom name input
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
# Calculate grade
|
| 204 |
+
correct_count = sum(1 for answer in user_answers if answer["is_correct"])
|
| 205 |
+
total_questions = len(user_answers)
|
| 206 |
+
grade = correct_count / total_questions if total_questions > 0 else 0
|
| 207 |
+
|
| 208 |
+
if grade < float(EXAM_PASSING_SCORE):
|
| 209 |
+
return (
|
| 210 |
+
gr.update(visible=True, value=f"You scored {grade:.1%}..."),
|
| 211 |
+
gr.update(visible=False),
|
| 212 |
+
gr.update(visible=False),
|
| 213 |
+
gr.update(visible=False), # hide custom name input
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
try:
|
| 217 |
+
# Use custom name if provided, otherwise use profile name
|
| 218 |
+
name = (
|
| 219 |
+
custom_name.strip() if custom_name and custom_name.strip() else profile.name
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
# Generate certificate
|
| 223 |
+
certificate_img, _ = generate_certificate(
|
| 224 |
+
name=name, profile_url=profile.picture
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
# Start certificate upload asynchronously
|
| 228 |
+
gr.Info("Uploading your certificate...")
|
| 229 |
+
cert_url = await upload_certificate_to_hub(profile.username, certificate_img)
|
| 230 |
+
|
| 231 |
+
if cert_url is None:
|
| 232 |
+
gr.Warning("Certificate upload failed, but you still passed!")
|
| 233 |
+
cert_url = "https://huggingface.co/mcp-course"
|
| 234 |
+
|
| 235 |
+
# Create LinkedIn button
|
| 236 |
+
linkedin_button = create_linkedin_button(profile.username, cert_url)
|
| 237 |
+
|
| 238 |
+
result_message = f"""
|
| 239 |
+
π Congratulations! You passed with a score of {grade:.1%}!
|
| 240 |
+
|
| 241 |
+
{linkedin_button}
|
| 242 |
+
"""
|
| 243 |
+
|
| 244 |
+
return (
|
| 245 |
+
gr.update(visible=True, value=result_message),
|
| 246 |
+
gr.update(visible=True, value=certificate_img),
|
| 247 |
+
gr.update(visible=True),
|
| 248 |
+
gr.update(visible=True), # show custom name input
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
except Exception as e:
|
| 252 |
+
print(f"Error generating certificate: {e}")
|
| 253 |
+
return (
|
| 254 |
+
gr.update(visible=True, value=f"π You passed with {grade:.1%}!"),
|
| 255 |
+
gr.update(visible=False),
|
| 256 |
+
gr.update(visible=False),
|
| 257 |
+
gr.update(visible=False), # hide custom name input
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def handle_quiz(
|
| 262 |
+
question_idx,
|
| 263 |
+
user_answers,
|
| 264 |
+
selected_answer,
|
| 265 |
+
is_start,
|
| 266 |
+
token: gr.OAuthToken | None,
|
| 267 |
+
profile: gr.OAuthProfile | None,
|
| 268 |
+
):
|
| 269 |
+
"""Handle quiz state transitions and store answers"""
|
| 270 |
+
if token is None or profile is None:
|
| 271 |
+
gr.Warning("Please log in to Hugging Face before starting the quiz!")
|
| 272 |
+
return [
|
| 273 |
+
"", # question_text
|
| 274 |
+
gr.update(choices=[], visible=False), # radio choices
|
| 275 |
+
"Please login first", # status_text
|
| 276 |
+
question_idx, # question_idx
|
| 277 |
+
user_answers, # user_answers
|
| 278 |
+
gr.update(visible=True), # start button
|
| 279 |
+
gr.update(visible=False), # next button
|
| 280 |
+
gr.update(visible=False), # submit button
|
| 281 |
+
gr.update(visible=False), # certificate image
|
| 282 |
+
gr.update(
|
| 283 |
+
visible=True,
|
| 284 |
+
value="""
|
| 285 |
+
<div style="text-align: center; padding: 20px; border: 2px dashed #ccc;">
|
| 286 |
+
<h3>π Login Required</h3>
|
| 287 |
+
<p>Please log in with your Hugging Face account to access the quiz and earn your LinkedIn certificate!</p>
|
| 288 |
+
</div>
|
| 289 |
+
""",
|
| 290 |
+
), # linkedin button with login prompt
|
| 291 |
+
]
|
| 292 |
+
|
| 293 |
+
if not is_start and question_idx < len(quiz_data):
|
| 294 |
+
current_q = quiz_data[question_idx]
|
| 295 |
+
correct_reference = current_q["correct_answer"]
|
| 296 |
+
correct_reference = f"answer_{correct_reference}".lower()
|
| 297 |
+
is_correct = selected_answer == current_q[correct_reference]
|
| 298 |
+
user_answers.append(
|
| 299 |
+
{
|
| 300 |
+
"question": current_q["question"],
|
| 301 |
+
"selected_answer": selected_answer,
|
| 302 |
+
"correct_answer": current_q[correct_reference],
|
| 303 |
+
"is_correct": is_correct,
|
| 304 |
+
"correct_reference": correct_reference,
|
| 305 |
}
|
| 306 |
+
)
|
| 307 |
+
question_idx += 1
|
| 308 |
+
|
| 309 |
+
if question_idx >= len(quiz_data):
|
| 310 |
+
correct_count = sum(1 for answer in user_answers if answer["is_correct"])
|
| 311 |
+
grade = correct_count / len(user_answers)
|
| 312 |
+
has_passed = grade >= float(EXAM_PASSING_SCORE)
|
| 313 |
+
|
| 314 |
+
# LinkedIn button text for quiz completion
|
| 315 |
+
linkedin_completion_text = (
|
| 316 |
+
"""
|
| 317 |
+
<div style="text-align: center; padding: 20px; border: 2px dashed #4CAF50;">
|
| 318 |
+
<h3>π Ready for LinkedIn!</h3>
|
| 319 |
+
<p>Great! Click "Get your certificate" above to unlock the LinkedIn button.</p>
|
| 320 |
+
<img src="https://huggingface.co/spaces/mcp-course/unit_1_quiz/resolve/main/li_logo.webp" alt="LinkedIn Add to Profile" style="width: 80px; height: 80px; text-align: center;">
|
| 321 |
+
</div>
|
| 322 |
+
"""
|
| 323 |
+
if has_passed
|
| 324 |
+
else """
|
| 325 |
+
<div style="text-align: center; padding: 20px; border: 2px dashed #ff6b6b;">
|
| 326 |
+
<h3>β Try Again</h3>
|
| 327 |
+
<p>You need a higher score to earn the LinkedIn certificate. Please retake the quiz!</p>
|
| 328 |
+
</div>
|
| 329 |
+
"""
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
return [
|
| 333 |
+
"", # question_text
|
| 334 |
+
gr.update(choices=[], visible=False), # radio choices
|
| 335 |
+
f"{'π Passed! Click now on π Get your certificate!' if has_passed else 'β Did not pass'}", # status_text
|
| 336 |
+
question_idx, # question_idx
|
| 337 |
+
user_answers, # user_answers
|
| 338 |
+
gr.update(visible=False), # start button
|
| 339 |
+
gr.update(visible=False), # next button
|
| 340 |
+
gr.update(
|
| 341 |
+
visible=True,
|
| 342 |
+
value="π Get your certificate" if has_passed else "β Did not pass",
|
| 343 |
+
interactive=has_passed,
|
| 344 |
+
), # submit button
|
| 345 |
+
gr.update(visible=False), # certificate image
|
| 346 |
+
gr.update(visible=True, value=linkedin_completion_text), # linkedin button
|
| 347 |
+
]
|
| 348 |
+
|
| 349 |
+
# Show next question
|
| 350 |
+
q = quiz_data[question_idx]
|
| 351 |
+
return [
|
| 352 |
+
f"## Question {question_idx + 1} \n### {q['question']}", # question_text
|
| 353 |
+
gr.update( # radio choices
|
| 354 |
+
choices=[q["answer_a"], q["answer_b"], q["answer_c"], q["answer_d"]],
|
| 355 |
+
value=None,
|
| 356 |
+
visible=True,
|
| 357 |
+
),
|
| 358 |
+
"Select an answer and click 'Next' to continue.", # status_text
|
| 359 |
+
question_idx, # question_idx
|
| 360 |
+
user_answers, # user_answers
|
| 361 |
+
gr.update(visible=False), # start button
|
| 362 |
+
gr.update(visible=True), # next button
|
| 363 |
+
gr.update(visible=False), # submit button
|
| 364 |
+
gr.update(visible=False), # certificate image
|
| 365 |
+
gr.update(
|
| 366 |
+
visible=True,
|
| 367 |
+
value="""
|
| 368 |
+
<div style="text-align: center; padding: 20px; border: 2px dashed #ccc;">
|
| 369 |
+
<h3>π― Keep Going!</h3>
|
| 370 |
+
<p>Complete the quiz and pass to unlock your LinkedIn certificate!</p>
|
| 371 |
+
<img src="https://huggingface.co/spaces/mcp-course/unit_1_quiz/resolve/main/li_logo.webp" alt="LinkedIn Add to Profile" style="width: 80px; height: 80px; text-align: center;">
|
| 372 |
+
</div>
|
| 373 |
+
""",
|
| 374 |
+
), # linkedin button with progress message
|
| 375 |
+
]
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def success_message(response):
|
| 379 |
+
# response is whatever push_results_to_hub returned
|
| 380 |
+
return f"{response}\n\n**Success!**"
|
| 381 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 382 |
|
| 383 |
+
with gr.Blocks() as demo:
|
| 384 |
+
demo.title = f"Dataset Quiz for {EXAM_DATASET_ID}"
|
| 385 |
+
|
| 386 |
+
# State variables
|
| 387 |
+
question_idx = gr.State(value=0)
|
| 388 |
+
user_answers = gr.State(value=[])
|
| 389 |
+
user_token = gr.State(value=None)
|
| 390 |
+
|
| 391 |
+
with gr.Row(variant="compact"):
|
| 392 |
+
gr.Markdown(f"## Welcome to the {EXAM_DATASET_ID} Quiz")
|
| 393 |
+
|
| 394 |
+
with gr.Row(variant="compact"):
|
| 395 |
+
gr.Markdown(
|
| 396 |
+
"- Log in first, then click 'Start' to begin. \n- Answer each question, click 'Next' \n- click 'Submit' to publish your results to the Hugging Face Hub."
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
with gr.Row(variant="panel"):
|
| 400 |
+
question_text = gr.Markdown("")
|
| 401 |
+
radio_choices = gr.Radio(
|
| 402 |
+
choices=[], label="Your Answer", scale=1, visible=False
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
with gr.Row(variant="compact"):
|
| 406 |
+
status_text = gr.Markdown("")
|
| 407 |
+
certificate_img = gr.Image(type="pil", visible=False)
|
| 408 |
+
linkedin_btn = gr.HTML(
|
| 409 |
+
visible=True,
|
| 410 |
+
value="""
|
| 411 |
+
<div style="text-align: center; padding: 20px; border: 2px dashed #ccc; border-radius: 10px; margin-top: 20px;">
|
| 412 |
+
<h3>π Login Required</h3>
|
| 413 |
+
<p>Please log in with your Hugging Face account to access the quiz and earn your LinkedIn certificate!</p>
|
| 414 |
+
</div>
|
| 415 |
+
""",
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
with gr.Row(variant="compact"):
|
| 419 |
+
login_btn = gr.LoginButton(visible=True)
|
| 420 |
+
start_btn = gr.Button("Start βοΈ", visible=True)
|
| 421 |
+
next_btn = gr.Button("Next βοΈ", visible=False)
|
| 422 |
+
submit_btn = gr.Button("π Get your certificate", visible=False)
|
| 423 |
+
|
| 424 |
+
with gr.Row(variant="panel"):
|
| 425 |
+
custom_name_input = gr.Textbox(
|
| 426 |
+
label="Custom Name for Certificate",
|
| 427 |
+
placeholder="Enter name as you want it to appear on the certificate",
|
| 428 |
+
info="Leave empty to use your Hugging Face profile name",
|
| 429 |
+
visible=False,
|
| 430 |
+
value=None,
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
# Wire up the event handlers
|
| 434 |
+
login_btn.click(
|
| 435 |
+
fn=on_user_logged_in,
|
| 436 |
+
inputs=None,
|
| 437 |
+
outputs=[
|
| 438 |
+
login_btn,
|
| 439 |
+
start_btn,
|
| 440 |
+
next_btn,
|
| 441 |
+
submit_btn,
|
| 442 |
+
question_text,
|
| 443 |
+
radio_choices,
|
| 444 |
+
status_text,
|
| 445 |
+
question_idx,
|
| 446 |
+
user_answers,
|
| 447 |
+
certificate_img,
|
| 448 |
+
linkedin_btn,
|
| 449 |
+
user_token,
|
| 450 |
+
],
|
| 451 |
+
)
|
| 452 |
|
| 453 |
+
start_btn.click(
|
| 454 |
+
fn=handle_quiz,
|
| 455 |
+
inputs=[question_idx, user_answers, gr.State(""), gr.State(True)],
|
| 456 |
+
outputs=[
|
| 457 |
+
question_text,
|
| 458 |
+
radio_choices,
|
| 459 |
+
status_text,
|
| 460 |
+
question_idx,
|
| 461 |
+
user_answers,
|
| 462 |
+
start_btn,
|
| 463 |
+
next_btn,
|
| 464 |
+
submit_btn,
|
| 465 |
+
certificate_img,
|
| 466 |
+
linkedin_btn,
|
| 467 |
+
],
|
| 468 |
+
)
|
| 469 |
|
| 470 |
+
next_btn.click(
|
| 471 |
+
fn=handle_quiz,
|
| 472 |
+
inputs=[question_idx, user_answers, radio_choices, gr.State(False)],
|
| 473 |
+
outputs=[
|
| 474 |
+
question_text,
|
| 475 |
+
radio_choices,
|
| 476 |
+
status_text,
|
| 477 |
+
question_idx,
|
| 478 |
+
user_answers,
|
| 479 |
+
start_btn,
|
| 480 |
+
next_btn,
|
| 481 |
+
submit_btn,
|
| 482 |
+
certificate_img,
|
| 483 |
+
linkedin_btn,
|
| 484 |
+
],
|
| 485 |
+
)
|
| 486 |
+
|
| 487 |
+
submit_btn.click(
|
| 488 |
+
fn=push_results_to_hub,
|
| 489 |
+
inputs=[
|
| 490 |
+
user_answers,
|
| 491 |
+
custom_name_input,
|
| 492 |
+
],
|
| 493 |
+
outputs=[
|
| 494 |
+
status_text,
|
| 495 |
+
certificate_img,
|
| 496 |
+
linkedin_btn,
|
| 497 |
+
custom_name_input,
|
| 498 |
+
],
|
| 499 |
+
)
|
| 500 |
|
| 501 |
+
custom_name_input.submit(
|
| 502 |
+
fn=push_results_to_hub,
|
| 503 |
+
inputs=[user_answers, custom_name_input],
|
| 504 |
+
outputs=[status_text, certificate_img, linkedin_btn, custom_name_input],
|
| 505 |
+
)
|
| 506 |
|
| 507 |
+
if __name__ == "__main__":
|
| 508 |
+
# Note: If testing locally, you'll need to run `huggingface-cli login` or set HF_TOKEN
|
| 509 |
+
# environment variable for the login to work locally.
|
| 510 |
+
demo.queue() # Enable queuing for async operations
|
| 511 |
+
demo.launch()
|