File size: 8,165 Bytes
ce9fae3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7db876
 
ce9fae3
f7db876
 
 
 
ce9fae3
f7db876
 
 
 
 
 
 
ce9fae3
f7db876
ce9fae3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7db876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7dfb009
e237e5f
f7db876
 
 
 
 
 
 
 
 
 
 
651ec30
ff49e85
f7db876
 
ce9fae3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff49e85
ce9fae3
63c1123
651ec30
63c1123
651ec30
ce9fae3
 
 
651ec30
 
ce9fae3
 
 
 
 
 
 
 
 
 
 
 
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import gradio as gr
from huggingface_hub import HfApi, hf_hub_download, Repository
from huggingface_hub.repocard import metadata_load
from gradio_client import Client
from PIL import Image, ImageDraw, ImageFont

from datetime import date
import time  

import os
import pandas as pd
import json

api = HfApi()
HF_TOKEN = os.environ.get("HF_TOKEN")

# Private dataset repo containing the list of already certified users
DATASET_REPO_URL = "https://huggingface.co/datasets/MariaK/audio-course"
CERTIFIED_USERS_FILENAME = "usernames.csv"

# Private space to check if a user has passed. 
SPACE_ID = "MariaK/Check-Audio-Course-Progress"


def check_if_passed(username):
    """
    Check if given user passed enough assignments
    :param username: User HF username
    """
    
    passed = False  
    certificate_type = ""

    client = Client(SPACE_ID, hf_token=HF_TOKEN)
    result = client.predict(username, fn_index=0)
    with open(result) as json_data:
      data = json.load(json_data)

    df = pd.DataFrame(data['data'])
    if len(df[df.iloc[:,0] == 'βœ…']) == 4:
      passed = True
      certificate_type = "excellence"
    elif len(df[df.iloc[:,0] == 'βœ…']) == 3:
      passed = True
      certificate_type = "completion"

    return passed, certificate_type


def generate_certificate(certificate_template, first_name, last_name):
    """
    Generates certificate from the template
    :param certificate_template: type of the certificate to generate
    :param first_name: first name entered by user
    :param last_name: last name entered by user
    """

    im = Image.open(certificate_template)
    d = ImageDraw.Draw(im)

    name_font = ImageFont.truetype("Quattrocento-Regular.ttf", 100)
    date_font = ImageFont.truetype("Quattrocento-Regular.ttf", 48)
    
    name = str(first_name) + " " + str(last_name)
    print("NAME", name)
    
    # Debug line name
    #d.line(((200, 740), (1800, 740)), "gray")
    #d.line(((1000, 0), (1000, 1400)), "gray")
    
    # Name
    d.text((1000, 740), name, fill="black", anchor="mm", font=name_font)

    # Debug line date
    #d.line(((1500, 0), (1500, 1400)), "gray")

    # Date of certification
    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"


def add_certified_user(hf_username, first_name, last_name, certificate_type):
  """
  Add the certified user to the database
  """
    
  print("ADD CERTIFIED USER")
  repo = Repository(local_dir="usernames", clone_from=DATASET_REPO_URL, use_auth_token=HF_TOKEN)
  repo.git_pull()

  history = pd.read_csv(os.path.join("usernames", CERTIFIED_USERS_FILENAME))

  # Check if this hf_username is already in our dataset:
  check = history.loc[history['hf_username'] == hf_username]
  if not check.empty:
    history = history.drop(labels=check.index[0], axis=0)
  
  new_row = pd.DataFrame({'hf_username': hf_username, 'first_name': first_name, 'last_name': last_name, 'certificate_type': certificate_type, 'datetime': time.time()}, index=[0])
  history = pd.concat([new_row, history[:]]).reset_index(drop=True)
    
  history.to_csv(os.path.join("usernames", CERTIFIED_USERS_FILENAME), index=False)
  repo.push_to_hub(commit_message="Update certified users list")


def create_certificate(passed, certificate_type, hf_username, first_name, last_name):  
    """
    Generates certificate, adds message, saves username of the certified user 
    :param passed: boolean whether the user passed enough assignments
    :param certificate_type: type of the certificate - completion or excellence
    :param first_name: first name entered by user
    :param last_name: last name entered by user
    """

    if passed and certificate_type == "excellence":
        # Generate a certificate of 
        certificate, pdf = generate_certificate("./certificate-excellence.png", first_name, last_name)
        # Add this user to our database
        add_certified_user(hf_username, first_name, last_name, certificate_type)    
        # Add a message
        message = """
        Congratulations, you successfully completed the Hugging Face Audio Course πŸŽ‰! \n 
        Since you pass 100% of the hands-on you get a Certificate of Excellence πŸŽ“. \n
        You can download your certificate below ⬇️ \n
        Don't hesitate to share your certificate image below on Twitter and Linkedin (you can tag me @mariakhalusova and @huggingface) πŸ€—
        """
    elif passed and certificate_type == "completion":    
        # Generate a certificate of completion
        certificate, pdf = generate_certificate("./certificate-completion.png", first_name, last_name)
        # Add this user to our database
        add_certified_user(hf_username, first_name, last_name, certificate_type)    
        # Add a message
        message = """
        Congratulations, you successfully completed the Hugging Face Audio Course πŸŽ‰! \n 
        Since you pass 3 out of 4 of the hands-on you get a Certificate of Completion πŸŽ“. \n 
        You can download your certificate below ⬇️ \n
        Don't hesitate to share your certificate image below on Twitter and Linkedin (you can tag me @mariakhalusova and @huggingface) πŸ€— \n
        You can try to get a Certificate of Excellence if you pass 100% of the hands-on, don't hesitate to check which unit you didn't pass and update these models.
        """
    else:
        # Not passed yet
        certificate = Image.new("RGB", (100, 100), (255, 255, 255))
        pdf = "./fail.pdf"        
        # Add a message
        message = """
          You didn't pass the minimum of 3 out of 4 of the hands-on to get a certificate of completion. 
          For more information about the certification process, refer to Unit 8 of the course. To see what hands-on you still need to complete, use the self-evaluation space linked in the description above. 
          If the results here differ from your results in the self-evaluation space, make sure that your model's metrics automatically uploaded by Trainer have not been manually altered.
          """
    return certificate, message, pdf


def certification(hf_username, first_name, last_name):
  passed, certificate_type = check_if_passed(hf_username)
  certificate, message, pdf = create_certificate(passed, certificate_type, hf_username, first_name, last_name)
  print("MESSAGE", message)

  if passed:
    visible = True
  else:
    visible = False
  
  return message, pdf, certificate, output_row.update(visible=visible) 

with gr.Blocks() as demo:
    gr.Markdown(f"""
    # Get your Hugging Face Audio Course Certificate πŸŽ“
    The certification process is completely free:
    - To get a *certificate of completion*: you need to **pass 3 out of 4 hands-on assignments**.
    - To get a *certificate of excellence*: you need to **pass 4 out of 4 hands-on assignments**.
    
    For more information about the certification process [check the course page on certification](https://huggingface.co/learn/audio-course/chapter8/certification).
    
    To check which assignments you still need to complete, use the [self-evaluation space](https://huggingface.co/spaces/MariaK/Check-my-progress-Audio-Course). 
    
    Don't hesitate to share your certificate on Twitter (tag me [@mariakhalusova](https://twitter.com/mariaKhalusova) and [@huggingface](https://twitter.com/huggingface)) and on LinkedIn.
    """)
    
    hf_username = gr.Textbox(placeholder="MariaK", label="Your Hugging Face Username (case sensitive)")
    first_name = gr.Textbox(placeholder="Maria", label="Your First Name")
    last_name = gr.Textbox(placeholder="Khalusova", label="Your Last Name")

    check_progress_button = gr.Button(value="Check if I pass and get the certificate")
    output_text = gr.components.Textbox()

    with gr.Row(visible=True) as output_row:
        output_pdf = gr.File()
        output_img = gr.components.Image(type="pil")

    check_progress_button.click(fn=certification, inputs=[hf_username, first_name, last_name], outputs=[output_text, output_pdf, output_img, output_row])

    
demo.launch(debug=True)