Vishal1122's picture
New Logic Added
ba0b0b3 verified
raw
history blame contribute delete
4.7 kB
import gradio as gr
from datasets import load_dataset, Dataset
from datetime import datetime, date
import os
from PIL import Image, ImageDraw, ImageFont
from huggingface_hub import login
from transformers import pipeline
# Authenticate with Hugging Face
login(token=os.environ["HUGGINGFACE_TOKEN"])
# Constants
SCORES_DATASET = "agents-course/unit4-students-scores"
CERTIFICATES_DATASET = "agents-course/course-certificates-of-excellence"
THRESHOLD_SCORE = 30
# Load text-generation pipeline (FLAN-T5)
qa_pipeline = pipeline("text2text-generation", model="google/flan-t5-base")
# Process question using model
def process_question(question):
if not question or not isinstance(question, str):
return "I don't understand the question."
result = qa_pipeline(question, max_new_tokens=50)
return result[0]["generated_text"].strip()
# Function to check user score
def check_user_score(username):
score_data = load_dataset(SCORES_DATASET, split="train", download_mode="force_redownload")
matches = [row for row in score_data if row["username"] == username]
return matches[0] if matches else None
# Check if user already has certificate
def has_certificate_entry(username):
cert_data = load_dataset(CERTIFICATES_DATASET, split="train", download_mode="force_redownload")
return any(row["username"] == username for row in cert_data)
# Add certificate entry
def add_certificate_entry(username, name, score):
ds = load_dataset(CERTIFICATES_DATASET, split="train", download_mode="force_redownload")
filtered_rows = [row for row in ds if row["username"] != username]
new_entry = {
"username": username,
"score": score,
"timestamp": datetime.now().isoformat()
}
filtered_rows.append(new_entry)
updated_ds = Dataset.from_list(filtered_rows)
updated_ds.push_to_hub(CERTIFICATES_DATASET)
# Generate certificate
def generate_certificate(name, score):
certificate_path = os.path.join(os.path.dirname(__file__), "templates", "certificate.png")
im = Image.open(certificate_path)
d = ImageDraw.Draw(im)
name_font = ImageFont.truetype("Quattrocento-Regular.ttf", 100)
date_font = ImageFont.truetype("Quattrocento-Regular.ttf", 48)
name = name.title()
d.text((1000, 740), name, fill="black", anchor="mm", font=name_font)
d.text((1480, 1170), str(date.today()), fill="black", anchor="mm", font=date_font)
pdf = im.convert("RGB")
pdf.save("certificate.pdf")
return im, "certificate.pdf"
# Handle certificate logic
def handle_certificate(name, profile: gr.OAuthProfile):
if profile is None:
return "You must be logged in with your Hugging Face account.", None, None
username = profile.username
user_score = check_user_score(username)
if not user_score:
return "You need to complete Unit 4 first.", None, None
score = user_score["score"]
if score < THRESHOLD_SCORE:
return f"Your score is {score}. You need at least {THRESHOLD_SCORE} to pass.", None, None
certificate_image, certificate_pdf = generate_certificate(name, score)
add_certificate_entry(username, name, score)
return "πŸŽ‰ Congratulations! Here's your certificate:", certificate_image, certificate_pdf
# Gradio UI
with gr.Blocks() as demo:
gr.Markdown("# πŸŽ“ Agents Course - Get Your Final Certificate")
gr.Markdown("Welcome! Follow the steps below to receive your official certificate:")
gr.Markdown("⚠️ **Note**: Due to high demand, you might experience occasional bugs. If something doesn't work, please try again after a moment!")
with gr.Group():
gr.Markdown("## βœ… How it works")
gr.Markdown("""
1. **Sign in** with your Hugging Face account using the button below.
2. **Enter your full name** (this will appear on the certificate).
3. Click **'Get My Certificate'** to check your score and download your certificate.
""")
gr.Markdown("---")
gr.Markdown("πŸ“ **Note**: You must have completed [Unit 4](https://huggingface.co/learn/agents-course/unit4/introduction) and your Agent must have scored **above 30** to get your certificate.")
gr.LoginButton()
with gr.Row():
name_input = gr.Text(label="Enter your name (this will appear on the certificate)")
generate_btn = gr.Button("Get my certificate")
output_text = gr.Textbox(label="Result")
cert_image = gr.Image(label="Your Certificate")
cert_file = gr.File(label="Download Certificate (PDF)", file_types=[".pdf"])
generate_btn.click(
fn=handle_certificate,
inputs=[name_input],
outputs=[output_text, cert_image, cert_file]
)
demo.launch()