Spaces:
Running
Running
burtenshaw commited on
Commit Β·
359570c
1
Parent(s): 768c800
implement certificate in app
Browse filesFiles changed (5)
- Quattrocento-Bold.ttfAdded
- Quattrocento-Regular.ttfAdded
- app.py+205-96
- certificate.pdfAdded
- templates/certificate.pngAdded
1234563 unmodified lines10111213141516171819202122232425262728293031323335 unmodified lines697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111 unmodified line1131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471484 unmodified lines15315415515615715815916016116216316419 unmodified lines18418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721 unmodified lines2392402412422432442452462472482492502512522532542552569 unmodified lines26626726826927027127210 unmodified lines2832842852862872882899 unmodified lines299300301302303304305306307308309310311import osfrom datetime import datetimeimport randomimport pandas as pdfrom huggingface_hub import HfApi, hf_hub_download, Repository3 unmodified linesfrom datasets import load_dataset, Datasetfrom huggingface_hub import whoamiEXAM_DATASET_ID = os.getenv("EXAM_DATASET_ID") or "agents-course/unit_1_quiz"EXAM_MAX_QUESTIONS = os.getenv("EXAM_MAX_QUESTIONS") or 10EXAM_PASSING_SCORE = os.getenv("EXAM_PASSING_SCORE") or 0.8ds = load_dataset(EXAM_DATASET_ID, split="train")DATASET_REPO_URL = "https://huggingface.co/datasets/agents-course/certificates"CERTIFIED_USERS_FILENAME = "certified_students.csv"CERTIFIED_USERS_DIR = "certificates"repo = Repository(local_dir=CERTIFIED_USERS_DIR,clone_from=DATASET_REPO_URL,use_auth_token=os.getenv("HF_TOKEN"),)# Convert dataset to a list of dicts and randomly sortquiz_data = ds.to_pandas().to_dict("records")random.shuffle(quiz_data)# Limit to max questions if specifiedif EXAM_MAX_QUESTIONS:35 unmodified lines]def add_certified_user(hf_username, pass_percentage, submission_time):"""Add the certified user to the database"""print("ADD CERTIFIED USER")repo.git_pull()history = pd.read_csv(os.path.join(CERTIFIED_USERS_DIR, 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,"pass_percentage": pass_percentage,"datetime": submission_time,},index=[0],)history = pd.concat([new_row, history[:]]).reset_index(drop=True)history.to_csv(os.path.join(CERTIFIED_USERS_DIR, CERTIFIED_USERS_FILENAME), index=False)repo.push_to_hub(commit_message="Update certified users list")def push_results_to_hub(user_answers, token: gr.OAuthToken | None):"""Create a new dataset from user_answers and push it to the Hub.Calculates grade and checks against passing threshold."""if token is None:gr.Warning("Please log in to Hugging Face before pushing!")return# Calculate gradecorrect_count = sum(1 for answer in user_answers if answer["is_correct"])1 unmodified linegrade = correct_count / total_questions if total_questions > 0 else 0if grade < float(EXAM_PASSING_SCORE):gr.Warning(f"Score {grade:.1%} below passing threshold of {float(EXAM_PASSING_SCORE):.1%}")return f"You scored {grade:.1%}. Please try again to achieve at least {float(EXAM_PASSING_SCORE):.1%}"gr.Info("Submitting answers to the Hub. Please wait...", duration=2)user_info = whoami(token=token.token)repo_id = f"{EXAM_DATASET_ID}_student_responses"submission_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")# filter down user answers to only include first character of the question and the answernew_ds = Dataset.from_list(user_answers)new_ds = new_ds.map(lambda x: {"username": user_info["name"],"datetime": submission_time,"grade": grade,})sanitized_name = user_info["name"].replace("-", "000")new_ds.push_to_hub(repo_id=repo_id, split=sanitized_name)# I'm adding a csv version# The idea, if the user passed, we create a simple row in a csvprint("ADD CERTIFIED USER")# Add this user to our databaseadd_certified_user(sanitized_name, grade, submission_time)return f"Your responses have been submitted to the Hub! Final grade: {grade:.1%}"def handle_quiz(4 unmodified linestoken: gr.OAuthToken | None,profile: gr.OAuthProfile | None,):"""Handle quiz state transitions and store answers"""if token is None or profile is None:gr.Warning("Please log in to Hugging Face before starting the quiz!")returnif not is_start and question_idx < len(quiz_data):current_q = quiz_data[question_idx]19 unmodified linesf"Your score: {grade:.1%}\n"f"Passing score: {float(EXAM_PASSING_SCORE):.1%}\n\n")return ["", # question_textgr.update(choices=[], visible=False), # hide radio choicesf"{'π Passed! Click now on β Submit to save your exam score!' if grade >= float(EXAM_PASSING_SCORE) else 'β Did not pass'}",question_idx,user_answers,gr.update(visible=False), # start button visibilitygr.update(visible=False), # next button visibilitygr.update(visible=True), # submit button visibilityresults_text, # final results text]# Show next questionq = quiz_data[question_idx]return [f"## Question {question_idx + 1} \n### {q['question']}", # question textgr.update( # properly update radio choiceschoices=[q["answer_a"], q["answer_b"], q["answer_c"], q["answer_d"]],value=None,visible=True,),"Select an answer and click 'Next' to continue.",question_idx,user_answers,gr.update(visible=False), # start button visibilitygr.update(visible=True), # next button visibilitygr.update(visible=False), # submit button visibility"", # clear final markdown]21 unmodified lineswith gr.Row(variant="panel"):question_text = gr.Markdown("")radio_choices = gr.Radio(choices=[], label="Your Answer", scale=1.5, visible=False)with gr.Row(variant="compact"):status_text = gr.Markdown("")final_markdown = gr.Markdown("")with gr.Row(variant="compact"):login_btn = gr.LoginButton(visible=True)start_btn = gr.Button("Start βοΈ", visible=True)next_btn = gr.Button("Next βοΈ", visible=False)submit_btn = gr.Button("Submit β ", visible=False)# Wire up the event handlerslogin_btn.click(9 unmodified linesstatus_text,question_idx,user_answers,final_markdown,user_token,],)10 unmodified linesstart_btn,next_btn,submit_btn,final_markdown,],)9 unmodified linesstart_btn,next_btn,submit_btn,final_markdown,],)submit_btn.click(fn=push_results_to_hub, inputs=[user_answers])if __name__ == "__main__":# Note: If testing locally, you'll need to run `huggingface-cli login` or set HF_TOKEN# environment variable for the login to work locally.demo.launch()1234567891011123 unmodified lines1617181920212223242526272829303132333435363735 unmodified lines7374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811 unmodified line1831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352364 unmodified lines24124224324424524624724824925025125225325425525625725825926026119 unmodified lines28128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631721 unmodified lines3393403413423433443453463473483493503513523533543553563579 unmodified lines36736836937037137237337410 unmodified lines3853863873883893903913929 unmodified lines402403404405406407408409410411412413414415416417418419420import osfrom datetime import datetimeimport randomimport requestsfrom io import BytesIOfrom datetime import dateimport tempfilefrom PIL import Image, ImageDraw, ImageFontfrom huggingface_hub import upload_fileimport pandas as pdfrom huggingface_hub import HfApi, hf_hub_download, Repository3 unmodified linesfrom datasets import load_dataset, Datasetfrom huggingface_hub import whoamiimport asynciofrom functools import partialEXAM_DATASET_ID = os.getenv("EXAM_DATASET_ID") or "agents-course/unit_1_quiz"EXAM_MAX_QUESTIONS = os.getenv("EXAM_MAX_QUESTIONS") or 1EXAM_PASSING_SCORE = os.getenv("EXAM_PASSING_SCORE") or 0.8CERTIFYING_ORG_LINKEDIN_ID = os.getenv("CERTIFYING_ORG_LINKEDIN_ID", "000000")COURSE_TITLE = os.getenv("COURSE_TITLE", "AI Agents Fundamentals")ds = load_dataset(EXAM_DATASET_ID, split="train")DATASET_REPO_URL = "https://huggingface.co/datasets/agents-course/certificates"# Convert dataset to a list of dicts and randomly sortquiz_data = ds.to_pandas().to_dict("records")# random.shuffle(quiz_data)# Limit to max questions if specifiedif EXAM_MAX_QUESTIONS:35 unmodified lines]def generate_certificate(name: str, profile_url: str):"""Generate certificate image and PDF."""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"def create_linkedin_button(username: str, cert_url: str | None) -> str:"""Create LinkedIn 'Add to Profile' button HTML."""current_year = date.today().yearcurrent_month = date.today().month# Use the dataset certificate URL if available, otherwise fallback to defaultcertificate_url = cert_url or "https://huggingface.co/agents-course-finishers"linkedin_params = {"startTask": "CERTIFICATION_NAME","name": COURSE_TITLE,"organizationName": "Hugging Face","organizationId": CERTIFYING_ORG_LINKEDIN_ID,"organizationIdissueYear": str(current_year),"issueMonth": str(current_month),"certUrl": certificate_url,"certId": username, # Using username as cert ID}# Build the LinkedIn button URLbase_url = "https://www.linkedin.com/profile/add?"params = "&".join(f"{k}={requests.utils.quote(v)}" for k, v in linkedin_params.items())button_url = base_url + paramsmessage = f"""<a href="{button_url}" target="_blank" style="display: block; margin-top: 20px; text-align: center;"><img src="https://download.linkedin.com/desktop/add2profile/buttons/en_US.png"alt="LinkedIn Add to Profile button"></a>"""return messageasync def upload_certificate_to_hub(username: str, certificate_img) -> str:"""Upload certificate to the dataset hub and return the URL asynchronously."""# Save image to temporary filewith tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:certificate_img.save(tmp.name)try:# Run upload in a thread pool since upload_file is blockingloop = asyncio.get_event_loop()upload_func = partial(upload_file,path_or_fileobj=tmp.name,path_in_repo=f"certificates/{username}/{date.today()}.png",repo_id="agents-course/certificates",repo_type="dataset",token=os.getenv("HF_TOKEN"),)await loop.run_in_executor(None, upload_func)# Construct the URL to the imagecert_url = (f"https://huggingface.co/datasets/agents-course/certificates/"f"resolve/main/certificates/{username}/{date.today()}.png")# Clean up temp fileos.unlink(tmp.name)return cert_urlexcept Exception as e:print(f"Error uploading certificate: {e}")os.unlink(tmp.name)return Noneasync def push_results_to_hub(user_answers, token: gr.OAuthToken | None, profile: gr.OAuthProfile | None):"""Handle quiz completion and certificate generation."""if token is None or profile is None:gr.Warning("Please log in to Hugging Face before submitting!")return (gr.update(visible=True, value="Please login first"),gr.update(visible=False),gr.update(visible=False),)# Calculate gradecorrect_count = sum(1 for answer in user_answers if answer["is_correct"])1 unmodified linegrade = correct_count / total_questions if total_questions > 0 else 0if grade < float(EXAM_PASSING_SCORE):return (gr.update(visible=True,value=f"You scored {grade:.1%}. Please try again to achieve at least "f"{float(EXAM_PASSING_SCORE):.1%}",),gr.update(visible=False),gr.update(visible=False),)try:# Generate certificatecertificate_img, _ = generate_certificate(name=profile.name, profile_url=profile.picture)# Start certificate upload asynchronouslygr.Info("Uploading your certificate...")cert_url = await upload_certificate_to_hub(profile.username, certificate_img)if cert_url is None:gr.Warning("Certificate upload failed, but you still passed!")cert_url = "https://huggingface.co/agents-course"# Create LinkedIn buttonlinkedin_button = create_linkedin_button(profile.username, cert_url)result_message = f"""π Congratulations! You passed with a score of {grade:.1%}!{linkedin_button}"""return (gr.update(visible=True, value=result_message),gr.update(visible=True, value=certificate_img),gr.update(visible=True),)except Exception as e:print(f"Error generating certificate: {e}")return (gr.update(visible=True, value=f"π Congratulations! You passed with {grade:.1%}!"),gr.update(visible=False),gr.update(visible=False),)def handle_quiz(4 unmodified linestoken: gr.OAuthToken | None,profile: gr.OAuthProfile | None,):"""Handle quiz state transitions and store answers"""if token is None or profile is None:gr.Warning("Please log in to Hugging Face before starting the quiz!")return ["", # question_textgr.update(choices=[], visible=False), # radio choices"Please login first", # status_textquestion_idx, # question_idxuser_answers, # user_answersgr.update(visible=True), # start buttongr.update(visible=False), # next buttongr.update(visible=False), # submit buttongr.update(visible=False), # certificate imagegr.update(visible=False), # linkedin button]if not is_start and question_idx < len(quiz_data):current_q = quiz_data[question_idx]19 unmodified linesf"Your score: {grade:.1%}\n"f"Passing score: {float(EXAM_PASSING_SCORE):.1%}\n\n")has_passed = grade >= float(EXAM_PASSING_SCORE)return ["", # question_textgr.update(choices=[], visible=False), # radio choicesf"{'π Passed! Click now on π Get your certificate!' if has_passed else 'β Did not pass'}", # status_textquestion_idx, # question_idxuser_answers, # user_answersgr.update(visible=False), # start buttongr.update(visible=False), # next buttongr.update(visible=True, value=f"π Get your certificate" if has_passed else "β Did not pass", interactive=has_passed), # submit buttongr.update(visible=False), # certificate imagegr.update(visible=False), # linkedin button]# Show next questionq = quiz_data[question_idx]return [f"## Question {question_idx + 1} \n### {q['question']}", # question_textgr.update( # radio choiceschoices=[q["answer_a"], q["answer_b"], q["answer_c"], q["answer_d"]],value=None,visible=True,),"Select an answer and click 'Next' to continue.", # status_textquestion_idx, # question_idxuser_answers, # user_answersgr.update(visible=False), # start buttongr.update(visible=True), # next buttongr.update(visible=False), # submit buttongr.update(visible=False), # certificate imagegr.update(visible=False), # linkedin button]21 unmodified lineswith gr.Row(variant="panel"):question_text = gr.Markdown("")radio_choices = gr.Radio(choices=[], label="Your Answer", scale=1, visible=False)with gr.Row(variant="compact"):status_text = gr.Markdown("")certificate_img = gr.Image(type="pil", visible=False)linkedin_btn = gr.HTML(visible=False)with gr.Row(variant="compact"):login_btn = gr.LoginButton(visible=True)start_btn = gr.Button("Start βοΈ", visible=True)next_btn = gr.Button("Next βοΈ", visible=False)submit_btn = gr.Button("π Get your certificate", visible=False)# Wire up the event handlerslogin_btn.click(9 unmodified linesstatus_text,question_idx,user_answers,certificate_img,linkedin_btn,user_token,],)10 unmodified linesstart_btn,next_btn,submit_btn,certificate_img,linkedin_btn,],)9 unmodified linesstart_btn,next_btn,submit_btn,certificate_img,linkedin_btn,],)submit_btn.click(fn=push_results_to_hub,inputs=[user_answers],outputs=[status_text, certificate_img, linkedin_btn],)if __name__ == "__main__":# Note: If testing locally, you'll need to run `huggingface-cli login` or set HF_TOKEN# environment variable for the login to work locally.demo.queue() # Enable queuing for async operationsdemo.launch()
Quattrocento-Bold.ttfAdded
Quattrocento-Regular.ttfAdded
app.py+205-96
certificate.pdfAdded
templates/certificate.pngAdded
