File size: 2,464 Bytes
4195ac0
 
 
 
 
 
 
 
 
c8ac78a
4195ac0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8ac78a
 
4195ac0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from datasets import load_dataset, Dataset
from datetime import datetime
import io
import os

# Load the datasets
SCORES_DATASET = "agents-course/unit4-students-scores"
CERTIFICATES_DATASET = "agents-course/course-certificates-of-excellence"
THRESOLD_SCORE = 45

# Check the score based on username
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 this user already generated a 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)


def add_certificate_entry(username, name):
    # Create a new entry
    new_entry = {
        "username": username,
        "name": name,
        "date": datetime.now().strftime("%Y-%m-%d"),
    }

    # Download the dataset, append and push
    ds = load_dataset(CERTIFICATES_DATASET, split="train")
    updated = ds.add_item(new_entry)
    updated.push_to_hub(CERTIFICATES_DATASET)

def generate_certificate(name, score):
    pass


def handle_certificate(name, request: gr.Request):
    username = request.username

    if not username:
        return "You must be logged in with your Hugging Face account.", None

    user_score = check_user_score(username)

    if not user_score:
        return "You need to complete Unit 4 first.", None

    score = user_score["score"]

    if score < THRESOLD_SCORE:
        return f"Your score is {score}. You need at least {THRESOLD_SCORE} to pass.", None

    # Passed: check if already in certificate dataset
    if not has_certificate_entry(username):
        add_certificate_entry(username, name)

    certificate = generate_certificate(name, score)
    return "Congratulations! Here's your certificate:", certificate

with gr.Blocks(auth=True) as demo:
    gr.Markdown("# πŸŽ“ Unit 4 Certificate Generator")
    with gr.Row():
        name_input = gr.Text(label="Enter your name")
    generate_btn = gr.Button("Get my certificate")
    output_text = gr.Textbox(label="Result")
    cert_file = gr.File(label="Your Certificate", file_types=[".pdf"])

    generate_btn.click(
        fn=handle_certificate,
        inputs=[name_input],
        outputs=[output_text, cert_file]
    )

demo.launch()