File size: 6,709 Bytes
1beb20f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9cb442
1beb20f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
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()