import json import os import tempfile import uuid from datetime import date, datetime from pathlib import Path from typing import Any import gradio as gr from PIL import Image, ImageDraw, ImageFont from datasets import load_dataset from huggingface_hub import upload_file BASE_DIR = Path(__file__).resolve().parent TEMPLATE_PATH = BASE_DIR / "templates" / "certificate.png" REGULAR_FONT_PATH = BASE_DIR / "Quattrocento-Regular.ttf" VALIDATION_DATASET_ID = "diffusers/mvp-candidates" PUSH_TOKEN = os.getenv("VALIDATION_DATASET_TOKEN") CERTIFICATES_DATASET_REPO = "diffusers/mvp-certificates" CERTIFICATES_DATASET_SUBDIR = Path("certificates") CERTIFICATES_METADATA_SUBDIR = Path("metadata") def _normalize_username(value: Any) -> str: return str(value or "").strip().lower() def _normalize_pr(value: Any) -> str: return str(value or "").strip() dataset = load_dataset(VALIDATION_DATASET_ID, split="train", token=PUSH_TOKEN) _VALIDATION_INDEX = { ( _normalize_username(record.get("github_username")), _normalize_pr(record.get("pr_number")), ): record for record in dataset } def generate_certificate(name: str, output_path: str | os.PathLike[str] | None = None): """Generate certificate image and PDF.""" im = Image.open(TEMPLATE_PATH) d = ImageDraw.Draw(im) name_font = ImageFont.truetype(str(REGULAR_FONT_PATH), 100) date_font = ImageFont.truetype(str(REGULAR_FONT_PATH), 48) formatted_name = name.title() d.text((1000, 740), formatted_name, fill="black", anchor="mm", font=name_font) d.text((1480, 1170), str(date.today()), fill="black", anchor="mm", font=date_font) pdf_path = Path(output_path) if output_path else BASE_DIR / "certificate.pdf" pdf_path.parent.mkdir(parents=True, exist_ok=True) pdf = im.convert("RGB") pdf.save(pdf_path) return im, str(pdf_path) def _require_validation_record(github_username: str, pr_number: str) -> dict[str, Any]: key = (_normalize_username(github_username), _normalize_pr(pr_number)) record = _VALIDATION_INDEX.get(key) if record is None: raise gr.Error( "No matching submission was found. Make sure the PR was accepted and " "your GitHub handle is correct." ) return record def _build_metadata( *, github_username: str, pr_number: str, profile: gr.OAuthProfile, record: dict[str, Any], display_name: str, ) -> dict[str, Any]: return { "github_username": github_username.strip(), "pr_number": pr_number, "issued_at": datetime.now().isoformat() + "Z", "display_name": display_name, "huggingface": { "username": profile.username, "name": profile.name, "profile_url": profile.profile, "avatar": profile.picture, }, "validation_record": record, } def _upload_certificate( pdf_path: Path, metadata: dict[str, Any], token: str | None = None ) -> str: if not CERTIFICATES_DATASET_REPO: raise gr.Error( "Set CERTIFICATES_DATASET_REPO so the app knows where to store certificates." ) issued_at = datetime.now().strftime("%Y%m%dT%H%M%S") unique_suffix = uuid.uuid4().hex[:8] pdf_filename = f"certificate-{issued_at}-{unique_suffix}.pdf" metadata_filename = pdf_filename.replace(".pdf", ".json") pdf_remote_path = CERTIFICATES_DATASET_SUBDIR / pdf_filename metadata_remote_path = CERTIFICATES_METADATA_SUBDIR / metadata_filename with tempfile.TemporaryDirectory() as tmpdir: metadata_path = Path(tmpdir) / metadata_filename metadata_path.write_text(json.dumps(metadata, indent=2), encoding="utf-8") upload_file( path_or_fileobj=str(pdf_path), path_in_repo=str(pdf_remote_path), repo_id=CERTIFICATES_DATASET_REPO, repo_type="dataset", token=PUSH_TOKEN ) upload_file( path_or_fileobj=str(metadata_path), path_in_repo=str(metadata_remote_path), repo_id=CERTIFICATES_DATASET_REPO, repo_type="dataset", token=PUSH_TOKEN ) return ( "https://huggingface.co/datasets/" f"{CERTIFICATES_DATASET_REPO}/resolve/main/{pdf_remote_path}" ) def issue_certificate( github_username: str, pr_number: str, name: str, profile: gr.OAuthProfile | None, ) -> str: if not github_username.strip() or not pr_number: raise gr.Error("Both GitHub username and PR number are required.") if not name.strip(): raise gr.Error("Please provide the full name for the certificate.") if profile is None: raise gr.Error("Please sign in with your Hugging Face account to continue.") record = _require_validation_record(github_username, pr_number) normalized_pr = _normalize_pr(pr_number) sanitized_username = _normalize_username(github_username).replace("/", "-") with tempfile.TemporaryDirectory() as tmpdir: pdf_path = Path(tmpdir) / f"{sanitized_username}-pr{normalized_pr}.pdf" _, generated_pdf_path = generate_certificate(name, output_path=str(pdf_path)) pdf_path = Path(generated_pdf_path) metadata = _build_metadata( github_username=github_username, pr_number=normalized_pr, profile=profile, record=record, display_name=name.title(), ) certificate_url = _upload_certificate( pdf_path=pdf_path, metadata=metadata, ) return f"[Open certificate ↗]({certificate_url})" with gr.Blocks(title="MVP Certificate Generator") as demo: gr.Markdown( """ # MVP Certificate Generator Sign in with your Hugging Face account, verify your merged PR, and mint a certificate. """ ) gr.LoginButton() with gr.Row(): github_username_input = gr.Textbox( label="GitHub Username", placeholder="huggingface", autofocus=True, ) pr_number_input = gr.Textbox(label="PR Number", placeholder="42") name_input = gr.Textbox(label="Name on Certificate", placeholder="Jane Doe") generate_button = gr.Button("Generate certificate", variant="primary") certificate_output = gr.Markdown( value="_Certificate link will appear here after successful verification._", elem_id="certificate-link-output", ) generate_button.click( fn=issue_certificate, inputs=[github_username_input, pr_number_input, name_input], outputs=certificate_output, ) if __name__ == "__main__": demo.launch()