"""ICML 2026 Open Reproductions โ€” Certificate Generator ======================================================= 1. Sign in with Hugging Face (OAuth). 2. Eligibility is checked against the frozen challenge verdicts: every participant with at least one non-zero claim verdict qualifies (baked into eligible.json at challenge close). 3. The display name is editable; the certificate renders to PNG with headless Chromium (installed via packages.txt) โ€” no external renderer dependency. """ import json import base64 import binascii import hashlib import hmac import os import shutil import subprocess import tempfile import urllib.parse from html import escape import gradio as gr import uvicorn from fastapi import FastAPI, HTTPException from fastapi.responses import FileResponse, HTMLResponse, RedirectResponse DISCUSSIONS_URL = "https://huggingface.co/spaces/ICML-2026-agent-repro/challenge/discussions" CANVAS = (2000, 1414) # must match the body size in certificate_template.html PUBLIC_HOST = os.getenv( "SPACE_HOST", "icml-2026-agent-repro-certificate-generator.hf.space" ) _HERE = os.path.dirname(__file__) with open(os.path.join(_HERE, "certificate_template.html"), encoding="utf-8") as f: TEMPLATE = f.read() with open(os.path.join(_HERE, "eligible.json"), encoding="utf-8") as f: ELIGIBLE = json.load(f) # Hub usernames can change while the namespace stored in the frozen verdicts # does not. Keep known migrations explicit and auditable. USERNAME_ALIASES = { "deepak12kambala": "deepakkambala", } def find_chromium(): candidates = [ "chromium", "chromium-browser", "google-chrome", "google-chrome-stable", "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", # local dev ] for c in candidates: path = shutil.which(c) or (c if os.path.exists(c) else None) if path: return path raise RuntimeError("No Chromium binary found โ€” is `chromium` in packages.txt?") def render_html(html: str) -> str: out = os.path.join(tempfile.mkdtemp(), "certificate.png") with tempfile.NamedTemporaryFile("w", delete=False, suffix=".html", encoding="utf-8") as f: f.write(html) src = f.name try: subprocess.run( [find_chromium(), "--headless=new", "--no-sandbox", "--disable-gpu", "--hide-scrollbars", "--force-device-scale-factor=1", f"--window-size={CANVAS[0]},{CANVAS[1]}", f"--screenshot={out}", f"file://{src}"], check=True, capture_output=True, timeout=120, ) finally: try: os.unlink(src) except OSError: pass return out def plural(n, word): return f"{n} {word}" + ("" if n == 1 else "s") def stats_line(rec): return (f"{plural(rec['points'], 'leaderboard point')} across " f"{plural(rec['scored_logbooks'], 'judged logbook')}") def eligibility_for(username): username = str(username or "").lower() return ELIGIBLE.get(USERNAME_ALIASES.get(username, username)) def clean_display_name(name): """Keep names readable and bounded in both the image and public page.""" return " ".join(str(name or "").split())[:100] def _b64encode(value): return base64.urlsafe_b64encode(value).decode("ascii").rstrip("=") def _b64decode(value): return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4)) def _signing_key(): key = os.getenv("CERTIFICATE_SIGNING_KEY") or os.getenv("OAUTH_CLIENT_SECRET") if not key: raise RuntimeError("Certificate signing key is not configured") return key.encode("utf-8") def credential_token(username, name): payload = json.dumps( {"username": str(username).lower(), "name": clean_display_name(name)}, separators=(",", ":"), sort_keys=True, ).encode("utf-8") encoded = _b64encode(payload) signature = _b64encode( hmac.new(_signing_key(), encoded.encode("ascii"), hashlib.sha256).digest() ) return f"{encoded}.{signature}" def decode_credential_token(token): try: encoded, signature = token.split(".", 1) expected = _b64encode( hmac.new(_signing_key(), encoded.encode("ascii"), hashlib.sha256).digest() ) if not hmac.compare_digest(signature, expected): raise ValueError("invalid signature") payload = json.loads(_b64decode(encoded)) if not isinstance(payload, dict): raise ValueError("invalid payload") if not isinstance(payload.get("username"), str) or not isinstance(payload.get("name"), str): raise ValueError("invalid payload") return payload except (ValueError, TypeError, binascii.Error, json.JSONDecodeError, UnicodeDecodeError): raise HTTPException(status_code=404, detail="Credential not found") def public_credential_url(username, name): return f"https://{PUBLIC_HOST}/verify/{credential_token(username, name)}" def auth_control(profile: gr.OAuthProfile | None): """Render OAuth controls that work inside the sandboxed Space iframe.""" if profile is None: href = "/oauth-login" target = "_blank" label = "๐Ÿค— Sign in with Hugging Face" else: href = "/logout?_target_url=/" target = "_self" label = f"Logout (@{escape(profile.username)})" return ( f'' f"{label}" ) def on_load(profile: gr.OAuthProfile | None): if profile is None: return (auth_control(profile), gr.update(visible=False), "### ๐Ÿ‘‹ Sign in with Hugging Face to check your eligibility.", "") rec = eligibility_for(profile.username) if rec is None: return (auth_control(profile), gr.update(visible=False), f"### Sorry @{profile.username} โ€” no scored logbook found.\n" "Certificates go to participants with at least one non-zero " "Logbook Judge verdict before the Aug 2 deadline: **verified**, " "**falsified**, or **toy-scale**. " f"If you believe this is an error, please open a thread in the " f"[challenge discussions]({DISCUSSIONS_URL}).", "") return (auth_control(profile), gr.update(visible=True), f"### ๐ŸŽ‰ Congratulations @{profile.username} โ€” you qualify!\n" f"Your record: **{stats_line(rec)}** ({plural(rec['logbooks'], 'logbook')} judged). " "Adjust how your name should appear, then generate your certificate.", profile.name or profile.username) def linkedin_url(name, username): p = { "startTask": "CERTIFICATION_NAME", "name": "ICML 2026 Open Reproductions โ€” Certificate of Participation", "organizationName": "Hugging Face", "issueYear": "2026", "issueMonth": "8", "certUrl": public_credential_url(username, name), "certId": f"ICML2026-{str(username).lower()}", } return "https://www.linkedin.com/profile/add?" + urllib.parse.urlencode(p) def create_certificate(display_name, profile: gr.OAuthProfile | None): if profile is None: return None, "โŒ Please sign in first.", gr.update(visible=False) rec = eligibility_for(profile.username) if rec is None: return None, "โŒ No scored logbook found for your account.", gr.update(visible=False) name = clean_display_name(display_name) or clean_display_name(profile.name) or profile.username html = TEMPLATE.replace("{participant_name}", escape(name)).replace("{stats_line}", stats_line(rec)) try: image_path = render_html(html) except Exception as e: return None, f"โŒ Rendering failed: {e}. Please try again in a minute.", gr.update(visible=False) btn = (f'Add to LinkedIn profile โ†’') return image_path, "๐ŸŽ‰ Your certificate is ready โ€” download it or add it to your LinkedIn profile below.", gr.update(value=btn, visible=True) THEME = gr.themes.Base( primary_hue=gr.themes.colors.orange, neutral_hue=gr.themes.colors.stone, ) CSS = """ .gradio-container { background-color: #fdfcf9 !important; background-image: linear-gradient(rgba(31,41,55,.045) 1px, transparent 1px), linear-gradient(90deg, rgba(31,41,55,.045) 1px, transparent 1px); background-size: 26px 26px; } .dark .gradio-container { background-color: #17181c !important; background-image: linear-gradient(rgba(253,252,249,.04) 1px, transparent 1px), linear-gradient(90deg, rgba(253,252,249,.04) 1px, transparent 1px); } #hero h1 { font-family: ui-serif, "Iowan Old Style", Georgia, serif; } """ with gr.Blocks(title="ICML 2026 Open Reproductions โ€” Certificates", theme=THEME, css=CSS) as demo: gr.Markdown("# ๐ŸŽ“ ICML 2026 Open Reproductions โ€” Certificate of Participation", elem_id="hero") gr.Markdown( "Every participant with **at least one non-zero Logbook Judge verdict** " "(`verified`, `falsified`, or `toy`) in the challenge " "(July 15 โ€“ August 2, 2026) can generate their certificate here." ) # This hidden component enables Gradio's OAuth routes. The visible control above # uses a top-level navigation so browsers do not block the OAuth session cookie # as a third-party cookie inside the Hugging Face Space iframe. gr.LoginButton(visible=False) auth = gr.HTML() status = gr.Markdown() with gr.Column(visible=False) as main_box: name_box = gr.Textbox(label="Name on the certificate") gen_btn = gr.Button("Generate my certificate ๐ŸŽ“", variant="primary") cert_image = gr.Image(label="Your certificate", type="filepath", interactive=False) note = gr.Markdown() linkedin = gr.HTML(visible=False) demo.load(on_load, inputs=None, outputs=[auth, main_box, status, name_box]) gen_btn.click(create_certificate, inputs=[name_box], outputs=[cert_image, note, linkedin]) app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) def verified_credential(token): payload = decode_credential_token(token) rec = eligibility_for(payload["username"]) if rec is None: raise HTTPException(status_code=404, detail="Credential not found") return payload, rec @app.get("/verify/{token}", response_class=HTMLResponse, include_in_schema=False) def verify_page(token): """Public, signed credential page suitable for LinkedIn's credential URL.""" payload, rec = verified_credential(token) name = escape(payload["name"] or payload["username"]) username = escape(payload["username"]) image_url = f"/verify/{token}/certificate.png" profile_url = "https://huggingface.co/" + urllib.parse.quote(payload["username"], safe="") return HTMLResponse(f""" {name} โ€” ICML 2026 Certificate
โœ“ Publicly verified participation credential

{name}

@{username} ยท {escape(stats_line(rec))}

ICML 2026 Certificate of Participation for {name}

Issued by the ICML 2026 Agent Repro organizers with Hugging Face.

""") @app.get("/verify/{token}/certificate.png", include_in_schema=False) def public_certificate(token): payload, rec = verified_credential(token) name = payload["name"] or payload["username"] html = TEMPLATE.replace("{participant_name}", escape(name)).replace( "{stats_line}", stats_line(rec) ) return FileResponse( render_html(html), media_type="image/png", filename="icml-2026-certificate.png", ) @app.get("/oauth-login", include_in_schema=False) def oauth_login(): """Start OAuth after removing session state left by an interrupted login.""" response = RedirectResponse("/login/huggingface?_target_url=/", status_code=303) response.delete_cookie( "session", path="/", secure=True, httponly=True, samesite="none" ) return response # Gradio 5.49.1's Spaces SSR proxy corrupts frontend asset URLs when a Blocks # app is mounted at the root path. OAuth still needs the explicit FastAPI mount, # so disable SSR here until the upstream root-mount routing bug is fixed. app = gr.mount_gradio_app(app, demo, path="/", ssr_mode=False) if __name__ == "__main__": uvicorn.run( app, host=os.getenv("GRADIO_SERVER_NAME", "0.0.0.0"), port=int(os.getenv("GRADIO_SERVER_PORT", "7860")), )