Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Download app.py from Neurips-2026-MLIntern-Repro/registration: direct link, hf CLI and curl.
- Browser
- Download file 31.8 kB
-
https://huggingface.co/spaces/Neurips-2026-MLIntern-Repro/registration/resolve/main/app.py
- Command line
-
hf download hf://spaces/Neurips-2026-MLIntern-Repro/registration/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Neurips-2026-MLIntern-Repro/registration/resolve/main/app.py
31.8 kB
| """Registration Space for the NeurIPS 2026 Papers · Reproduce with ML Intern hackathon. | |
| Sign-in is with Hugging Face (OAuth), so the HF username on every registration is verified and | |
| can't be typed wrong or registered on someone else's behalf. One registration per HF account and | |
| per email. Participants can edit or withdraw their registration until registration closes. | |
| Config (Space variables / secrets): | |
| HF_TOKEN secret, write access to REG_DATASET. Unset = dry run (saved to a local folder only). | |
| REG_DATASET private dataset for registrations (default ysharma/neurips-2026-mlintern-registrations) | |
| REG_CLOSES ISO time registration closes (default 2026-11-19T23:59:00Z, i.e. Nov 19 23:59 GMT) | |
| DISCORD_INVITE optional; shown in next steps and the footer when set | |
| SUPPORT_EMAIL optional; shown in the footer when set | |
| """ | |
| from __future__ import annotations | |
| import html | |
| import logging | |
| import os | |
| import re | |
| import tempfile | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| import gradio as gr | |
| from store import EmailTaken, HubBackend, LocalBackend, Store, StoreUnavailable, user_key | |
| logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") | |
| logger = logging.getLogger("registration") | |
| HERE = Path(__file__).parent | |
| ORG = "Neurips-2026-MLIntern-Repro" | |
| PAPERS_URL = "https://huggingface.co/spaces/Neurips-2026-MLIntern-Repro/papers" | |
| ORG_URL = f"https://huggingface.co/{ORG}" | |
| HF_TOKEN = os.environ.get("HF_TOKEN") | |
| # Temporarily in a personal namespace: the org can't have resource groups until it gets Team status, and without one | |
| # every org member could read a private org dataset. Move it to f"{ORG}/registrations" once Team status is in place. | |
| # The Space's own domain. Signing in here works even when the browser blocks cookies inside the huggingface.co iframe. | |
| DIRECT_URL = "https://" + (os.environ.get("SPACE_HOST", "").split(",")[0].strip() or "neurips-2026-mlintern-repro-registration.hf.space") | |
| REG_DATASET = os.environ.get("REG_DATASET", "ysharma/neurips-2026-mlintern-registrations") | |
| DISCORD_INVITE = os.environ.get("DISCORD_INVITE", "").strip() | |
| SUPPORT_EMAIL = os.environ.get("SUPPORT_EMAIL", "").strip() | |
| REG_CLOSES = datetime.fromisoformat(os.environ.get("REG_CLOSES", "2026-11-19T23:59:00+00:00").replace("Z", "+00:00")) | |
| DRY_RUN = not HF_TOKEN | |
| REGISTER_LABEL = "🧪 Register for the hackathon" | |
| SHOW_COUNT_FROM = 50 # a tiny count looks like an empty room, so hide it until it is meaningful | |
| # ------------------------------------------------------------------ choices | |
| ROLES = [ | |
| "Student (undergrad or master's)", | |
| "PhD student", | |
| "Academic researcher or faculty", | |
| "Industry researcher or engineer", | |
| "Independent researcher or hobbyist", | |
| "Other", | |
| ] | |
| NO_INFRA = "None of these yet" | |
| HF_INFRA = [ | |
| "Jobs", | |
| "Buckets", | |
| "Trackio", | |
| "Models and Datasets", | |
| "Spaces", | |
| NO_INFRA, | |
| ] | |
| ML_INTERN_USE = [ | |
| "Haven't tried it yet", | |
| "Tried it a few times", | |
| "Use it regularly", | |
| ] | |
| HOW_HEARD = [ | |
| "Hugging Face email or newsletter", | |
| "Hugging Face org page or Space", | |
| "X / Twitter", | |
| "LinkedIn", | |
| "Bluesky", | |
| "Discord", | |
| "Colleague or friend", | |
| "At NeurIPS or another conference", | |
| "Previous Hugging Face hackathon", | |
| "Other", | |
| ] | |
| EMAIL_RE = re.compile(r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}$") | |
| CONTROL_RE = re.compile(r"[\x00-\x1f\x7f]") | |
| LIMITS = {"full_name": 80, "affiliation": 120, "email": 254, "paper_interest": 600, "goals": 1000} | |
| # ------------------------------------------------------------------ storage | |
| class PublicRepoGuard: | |
| """Stands in for the Hub backend when the dataset is public, so the store can't load and nothing is written.""" | |
| def __init__(self, repo_id): | |
| self.repo_id = repo_id | |
| def list_names(self, *a, **k): | |
| raise RuntimeError(f"{self.repo_id} is public; refusing to read or write registrations") | |
| read_json = commit = list_names | |
| if DRY_RUN: | |
| _local = os.path.join(tempfile.gettempdir(), "neurips26-registrations-dryrun-v2") | |
| logger.warning("HF_TOKEN not set: DRY RUN, registrations go to %s only", _local) | |
| store = Store(LocalBackend(_local)) | |
| else: | |
| backend = HubBackend(REG_DATASET, HF_TOKEN) | |
| try: | |
| backend.api.create_repo(REG_DATASET, repo_type="dataset", private=True, exist_ok=True) | |
| if not backend.api.repo_info(REG_DATASET, repo_type="dataset").private: | |
| # Never write names and emails into a public repo: with no index, every save is refused. | |
| logger.error("%s is PUBLIC. Make it private; nothing will be saved until then.", REG_DATASET) | |
| backend = PublicRepoGuard(REG_DATASET) | |
| except Exception as e: # noqa: BLE001 | |
| logger.error("Could not create or reach %s: %s", REG_DATASET, e) | |
| store = Store(backend) | |
| store.load_index() # if this fails, every request retries it, and nothing is written until it works | |
| # ------------------------------------------------------------------ helpers | |
| def now_utc() -> datetime: | |
| return datetime.now(timezone.utc) | |
| def is_open() -> bool: | |
| return now_utc() <= REG_CLOSES | |
| def close_label() -> str: | |
| c = REG_CLOSES.astimezone(timezone.utc) | |
| return f"Closes {c:%a, %b} {c.day} · {c:%H:%M} GMT" | |
| def md_escape(text) -> str: | |
| """Escape user text before it goes into Markdown: no HTML, links, images or emphasis tricks.""" | |
| text = html.escape(str(text or ""), quote=False) | |
| return re.sub(r"([\\`*_{}\[\]()#+!|~>])", r"\\\1", text) | |
| def clean(text, limit) -> str: | |
| text = CONTROL_RE.sub(" ", str(text or "")) | |
| return re.sub(r"[ \t]+", " ", text).strip()[: limit + 1] | |
| def clean_multiline(text, limit) -> str: | |
| text = str(text or "").replace("\r\n", "\n") | |
| text = re.sub(r"[\x00-\x08\x0b-\x1f\x7f]", " ", text) | |
| return re.sub(r"\n{3,}", "\n\n", text).strip()[: limit + 1] | |
| def account_info(username: str) -> dict: | |
| """Best effort: HF account creation date and public org membership, for organizers. Never blocks.""" | |
| try: | |
| from huggingface_hub import HfApi | |
| u = HfApi(token=HF_TOKEN).get_user_overview(username) | |
| created = getattr(u, "createdAt", None) or getattr(u, "created_at", None) | |
| orgs = [getattr(o, "name", "") for o in (getattr(u, "orgs", None) or [])] | |
| return { | |
| "hf_account_created": str(created) if created else None, | |
| "in_org_at_registration": any(o.lower() == ORG.lower() for o in orgs), | |
| } | |
| except Exception as e: # noqa: BLE001 | |
| logger.info("Account lookup failed for %s: %s", username, str(e)[:120]) | |
| return {"hf_account_created": None, "in_org_at_registration": None} | |
| # ------------------------------------------------------------------ rendering | |
| def next_steps_md() -> str: | |
| discord = f"\n- 💬 Join the community on [Discord]({DISCORD_INVITE}) for office hours and help." if DISCORD_INVITE else "" | |
| return f"""**Next steps** | |
| - 🏛️ **Join the [{ORG}]({ORG_URL}) org** on Hugging Face (click *Request to join*). Hackathon resources are shared there. | |
| - 📚 **Browse the [papers]({PAPERS_URL})** now and shortlist the ones you'd like to reproduce. Claiming opens **Nov 20**, up to **5 papers per person**. | |
| - 🎟️ **HF credits** go to every registered participant before the hackathon starts. Watch your email. | |
| - 🧪 **Reproduce with ML Intern** from **Nov 20 to Dec 5, 2026**.{discord}""" | |
| def summary_md(rec: dict, created: bool | None = None) -> str: | |
| head = {True: "## ✅ You're registered!", False: "## ✅ Registration updated", None: "## ✅ You're registered"}[created] | |
| infra = ", ".join(md_escape(a) for a in rec.get("hf_infra", [])) or "_none selected_" | |
| papers = md_escape(rec.get("paper_interest")) if rec.get("paper_interest") else "_not yet_" | |
| affiliation = md_escape(rec.get("affiliation")) if rec.get("affiliation") else "_not given_" | |
| updated = "" | |
| if rec.get("update_count"): | |
| updated = f" · last updated {md_escape(rec['updated_at'].replace('T', ' ').replace('Z', ' UTC'))}" | |
| return f"""{head} | |
| Thanks, **{md_escape(rec['full_name'])}**. Registered on {md_escape(rec['created_at'].replace('T', ' ').replace('Z', ' UTC'))}{updated}. | |
| - **Hugging Face account:** [{md_escape(rec['hf_username'])}](https://huggingface.co/{rec['hf_username']}) | |
| - **Email:** {md_escape(rec['email'])} | |
| - **Affiliation:** {affiliation} | |
| - **Role:** {md_escape(rec['role'])} | |
| - **Hugging Face infrastructure used:** {infra} | |
| - **ML Intern:** {md_escape(rec['ml_intern_use'])} | |
| - **Papers you're eyeing:** {papers} | |
| {next_steps_md()} | |
| """ | |
| def status_html(kind: str, text: str) -> str: | |
| return f'<div class="nr-status nr-status-{kind}">{text}</div>' | |
| def dry_run_banner() -> str: | |
| if not DRY_RUN: | |
| return "" | |
| return status_html("warn", "🧪 <b>Dry run:</b> no <code>HF_TOKEN</code> is set, so registrations are saved to a local folder only.") | |
| # ------------------------------------------------------------------ events | |
| FORM_FIELDS = [ | |
| "full_name", "email", "affiliation", "role", "hf_infra", | |
| "ml_intern_use", "how_heard", "paper_interest", "goals", "agree", | |
| ] | |
| def blank_values(profile) -> list: | |
| name = (profile.get("name") or "") if profile else "" | |
| email = "" | |
| if profile and profile.get("email") and profile.get("email_verified", True): | |
| email = profile["email"] | |
| return [name, email, "", None, [], None, None, "", "", False] | |
| def record_values(rec: dict) -> list: | |
| return [ | |
| rec["full_name"], rec["email"], rec.get("affiliation", ""), rec.get("role"), rec.get("hf_infra", []), | |
| rec.get("ml_intern_use"), rec.get("how_heard"), | |
| rec.get("paper_interest", ""), rec.get("goals", ""), True, | |
| ] | |
| def on_load(profile: gr.OAuthProfile | None): | |
| """Decide what the page shows: sign-in prompt, empty form, filled form, or closed.""" | |
| open_ = is_open() | |
| n = store.count() if store.ready else None | |
| count = f"**{n:,}** researchers registered so far" if n and n >= SHOW_COUNT_FROM else "" | |
| if profile is None: | |
| msg = "" if open_ else status_html("error", "⛔ <b>Registration is closed.</b> Sign in to see your registration.") | |
| return ( | |
| gr.update(visible=True), msg, gr.update(visible=False), "", | |
| *[gr.update() for _ in FORM_FIELDS], gr.update(), gr.update(visible=False), gr.update(visible=False), count, | |
| ) | |
| try: | |
| rec = store.get(profile.username) | |
| except StoreUnavailable: | |
| return ( | |
| gr.update(visible=False), | |
| status_html("error", "⚠️ Registration is temporarily unavailable. Please reload the page in a few minutes."), | |
| gr.update(visible=False), "", *[gr.update() for _ in FORM_FIELDS], gr.update(), | |
| gr.update(visible=False), gr.update(visible=False), count, | |
| ) | |
| who = md_escape(profile.username) | |
| if rec: | |
| note = ( | |
| f"✅ <b>@{who}, you're registered.</b> You can edit your details below until registration closes." | |
| if open_ else f"✅ <b>@{who}, you're registered.</b> Registration is closed, so details can no longer be edited." | |
| ) | |
| values = record_values(rec) | |
| btn = gr.update(value="💾 Save changes", interactive=open_) | |
| summary = summary_md(rec) | |
| withdraw_visible = True | |
| else: | |
| if not open_: | |
| return ( | |
| gr.update(visible=False), | |
| status_html("error", f"⛔ <b>Registration closed</b> on {close_label()}. No registration was found for @{who}."), | |
| gr.update(visible=False), "", *[gr.update() for _ in FORM_FIELDS], gr.update(), | |
| gr.update(visible=False), gr.update(visible=False), count, | |
| ) | |
| note = f"👋 <b>Signed in as @{who}.</b> Fill in the form below to register. Fields marked * are required." | |
| values = blank_values(profile) | |
| btn = gr.update(value=REGISTER_LABEL, interactive=True) | |
| summary = "" | |
| withdraw_visible = False | |
| return ( | |
| gr.update(visible=False), status_html("ok" if rec else "info", note), gr.update(visible=True), summary, | |
| *[gr.update(value=v, interactive=open_) for v in values], btn, | |
| gr.update(visible=withdraw_visible), gr.update(visible=False), count, | |
| ) | |
| def validate(full_name, email, affiliation, role, infra, ml_intern, how_heard, paper_interest, goals, agree): | |
| errors = [] | |
| full_name = clean(full_name, LIMITS["full_name"]) | |
| email = clean(email, LIMITS["email"]).lower() | |
| affiliation = clean(affiliation, LIMITS["affiliation"]) | |
| paper_interest = clean_multiline(paper_interest, LIMITS["paper_interest"]) | |
| goals = clean_multiline(goals, LIMITS["goals"]) | |
| infra = list(dict.fromkeys(infra or [])) | |
| if len(full_name) < 2 or not re.search(r"[^\W\d_]", full_name): | |
| errors.append("Please enter your full name.") | |
| elif len(full_name) > LIMITS["full_name"]: | |
| errors.append(f"Full name must be at most {LIMITS['full_name']} characters.") | |
| if not email: | |
| errors.append("Please enter your email address.") | |
| elif len(email) > LIMITS["email"] or not EMAIL_RE.match(email) or ".." in email: | |
| errors.append("Please enter a valid email address.") | |
| if len(affiliation) > LIMITS["affiliation"]: | |
| errors.append(f"Affiliation must be at most {LIMITS['affiliation']} characters.") | |
| # Choice fields are checked against the allowed lists because the API can be called directly. | |
| if role not in ROLES: | |
| errors.append("Please pick your role.") | |
| if not infra: | |
| errors.append(f"Please pick the Hugging Face infrastructure you've used, or “{NO_INFRA}”.") | |
| elif any(a not in HF_INFRA for a in infra): | |
| errors.append("Please pick Hugging Face infrastructure from the list.") | |
| elif NO_INFRA in infra and len(infra) > 1: | |
| errors.append(f"“{NO_INFRA}” can't be combined with other options.") | |
| if ml_intern not in ML_INTERN_USE: | |
| errors.append("Please tell us whether you've used ML Intern.") | |
| if how_heard not in HOW_HEARD: | |
| errors.append("Please tell us how you heard about the hackathon.") | |
| if len(paper_interest) > LIMITS["paper_interest"]: | |
| errors.append(f"Papers you're eyeing must be at most {LIMITS['paper_interest']} characters.") | |
| if len(goals) > LIMITS["goals"]: | |
| errors.append(f"Your goals must be at most {LIMITS['goals']} characters.") | |
| if agree is not True: | |
| errors.append("Please accept the participation terms.") | |
| data = { | |
| "full_name": full_name, "email": email, "affiliation": affiliation, "role": role, | |
| "hf_infra": infra, "ml_intern_use": ml_intern, | |
| "how_heard": how_heard, "paper_interest": paper_interest, "goals": goals, | |
| } | |
| return errors, data | |
| def on_submit(full_name, email, affiliation, role, infra, ml_intern, how_heard, paper_interest, goals, agree, | |
| profile: gr.OAuthProfile | None): | |
| """Validate and save. Every outcome re-enables the button so people can fix and retry.""" | |
| fields = (full_name, email, affiliation, role, infra, ml_intern, how_heard, paper_interest, goals, agree) | |
| registered = bool(profile and store.ready and user_key(profile.username) in store.users) | |
| idle = gr.update(value="💾 Save changes" if registered else REGISTER_LABEL, interactive=True) | |
| if profile is None: | |
| return status_html("error", "🔒 Your sign-in expired. Please sign in with Hugging Face again."), gr.update(), idle, gr.update() | |
| if not is_open(): | |
| return status_html("error", f"⛔ Registration closed on {close_label()}. Nothing was saved."), gr.update(), gr.update(value="Registration closed", interactive=False), gr.update() | |
| errors, data = validate(*fields) | |
| if errors: | |
| items = "".join(f"<li>{html.escape(e)}</li>" for e in errors) | |
| return status_html("error", f"<b>Please fix the following:</b><ul>{items}</ul>"), gr.update(), idle, gr.update() | |
| record = { | |
| "schema_version": 1, | |
| "hf_username": profile.username, | |
| "hf_user_id": profile.get("sub"), | |
| **data, | |
| "agreed_terms": True, | |
| "dry_run": DRY_RUN, | |
| } | |
| try: | |
| existing = store.get(profile.username) | |
| except StoreUnavailable: | |
| existing = None | |
| record.update( | |
| {k: existing[k] for k in ("hf_account_created", "in_org_at_registration") if existing and k in existing} | |
| or account_info(profile.username) | |
| ) | |
| try: | |
| saved, created = store.save(record) | |
| except EmailTaken: | |
| return ( | |
| status_html("error", "❌ That email is already used by another registration. Each person registers once, with one HF account. " | |
| "If you registered with a different HF account, sign in with that one."), | |
| gr.update(), idle, gr.update(), | |
| ) | |
| except StoreUnavailable: | |
| return ( | |
| status_html("error", "⚠️ We couldn't save your registration because the Hub is busy. <b>Nothing was saved.</b> " | |
| "Please try again in a minute."), | |
| gr.update(), idle, gr.update(), | |
| ) | |
| except Exception as e: # noqa: BLE001 | |
| logger.exception("Unexpected error while saving %s", profile.username) | |
| return status_html("error", f"❌ Something went wrong and nothing was saved ({html.escape(type(e).__name__)}). Please try again."), gr.update(), idle, gr.update() | |
| logger.info("%s %s", "Registered" if created else "Updated", profile.username) | |
| note = "🎉 <b>You're in!</b> Your confirmation is at the top of this page, and you can still edit your details here." if created else "💾 <b>Saved.</b> Your registration is up to date." | |
| return status_html("ok", note), summary_md(saved, created), gr.update(value="💾 Save changes", interactive=True), gr.update(visible=True) | |
| def on_withdraw(profile: gr.OAuthProfile | None): | |
| if profile is None: | |
| return status_html("error", "🔒 Please sign in again."), gr.update(), gr.update(), gr.update() | |
| try: | |
| removed = store.withdraw(profile.username) | |
| except StoreUnavailable: | |
| return status_html("error", "⚠️ Couldn't withdraw right now. Nothing changed. Please try again in a minute."), gr.update(), gr.update(visible=True), gr.update(visible=False) | |
| if not removed: | |
| return status_html("info", "There was no registration to withdraw."), "", gr.update(visible=False), gr.update(visible=False) | |
| logger.info("Withdrew %s", profile.username) | |
| msg = "Your registration was withdrawn. You can register again any time before registration closes." if is_open() \ | |
| else "Your registration was withdrawn. Registration is closed, so you can't register again." | |
| return status_html("info", "👋 " + msg), "", gr.update(visible=False), gr.update(visible=False) | |
| # ------------------------------------------------------------------ page | |
| BANNER = f"/gradio_api/file={(HERE / 'static' / 'banner.webp').as_posix()}" | |
| BANNER_TALL = f"/gradio_api/file={(HERE / 'static' / 'banner_portrait.webp').as_posix()}" | |
| CLOSE_MS = int(REG_CLOSES.timestamp() * 1000) | |
| HERO_HTML = f""" | |
| <div class="nr-hero"> | |
| <picture class="nr-banner"> | |
| <source media="(max-width: 640px)" srcset="{BANNER_TALL}"> | |
| <img src="{BANNER}" alt="Reproduce with ML Intern: NeurIPS 2026 Papers. Nov 20 to Dec 5, 2026. Register by Nov 19. HF credits to all registered participants. 5 papers per person." /> | |
| </picture> | |
| <div class="nr-side"> | |
| <div class="nr-card nr-how"> | |
| <div class="nr-kicker">How it works</div> | |
| <ol> | |
| <li><b>Register</b> here with your HF account</li> | |
| <li><b>Pick</b> up to 5 <a href="{PAPERS_URL}" target="_blank" rel="noopener">NeurIPS 2026 papers</a></li> | |
| <li><b>Reproduce</b> each key claim with ML Intern</li> | |
| <li><b>Submit</b> your results by Dec 5</li> | |
| </ol> | |
| </div> | |
| <div class="nr-counter" id="nr-counter" data-close="{CLOSE_MS}"> | |
| <div class="nr-kicker nr-kicker-light" id="nr-counter-title">Registration closes in</div> | |
| <div class="nr-nums"> | |
| <div><span id="nr-d">--</span><small>days</small></div> | |
| <div><span id="nr-h">--</span><small>hrs</small></div> | |
| <div><span id="nr-m">--</span><small>min</small></div> | |
| <div><span id="nr-s">--</span><small>sec</small></div> | |
| </div> | |
| <div class="nr-local" id="nr-local">{close_label()}</div> | |
| </div> | |
| </div> | |
| </div> | |
| """ | |
| COUNTDOWN_JS = """ | |
| () => { | |
| const box = document.getElementById('nr-counter'); | |
| if (!box) return; | |
| const close = Number(box.dataset.close); | |
| const local = document.getElementById('nr-local'); | |
| try { | |
| const d = new Date(close); | |
| // The deadline is shown in GMT; add the visitor's local time when they aren't on GMT. | |
| if (d.getTimezoneOffset() !== 0) { | |
| local.textContent += ' · ' + d.toLocaleString(undefined, {weekday: 'short', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit'}) + ' your time'; | |
| } | |
| } catch (e) {} | |
| const pad = v => String(v).padStart(2, '0'); | |
| const set = (id, v) => { const el = document.getElementById(id); if (el) el.textContent = pad(v); }; | |
| function tick() { | |
| const diff = close - Date.now(); | |
| if (diff <= 0) { | |
| document.getElementById('nr-counter-title').textContent = 'Registration is closed'; | |
| ['nr-d','nr-h','nr-m','nr-s'].forEach(id => set(id, 0)); | |
| return; | |
| } | |
| set('nr-d', Math.floor(diff / 864e5)); | |
| set('nr-h', Math.floor(diff % 864e5 / 36e5)); | |
| set('nr-m', Math.floor(diff % 36e5 / 6e4)); | |
| set('nr-s', Math.floor(diff % 6e4 / 1e3)); | |
| setTimeout(tick, 1000); | |
| } | |
| tick(); | |
| } | |
| """ | |
| TERMS = ( | |
| "I'll take part in good faith: report what my runs actually show (including failed reproductions), " | |
| "use the HF credits only for hackathon work, keep my submissions public, and follow the " | |
| "Hugging Face code of conduct. I agree to be emailed about the hackathon (credits, deadlines, results)." | |
| ) | |
| FOOTER_BITS = [f'<a href="{PAPERS_URL}" target="_blank" rel="noopener">Browse the papers</a>', | |
| f'<a href="{ORG_URL}" target="_blank" rel="noopener">Hackathon org</a>'] | |
| if DISCORD_INVITE: | |
| FOOTER_BITS.append(f'<a href="{html.escape(DISCORD_INVITE)}" target="_blank" rel="noopener">Discord</a>') | |
| if SUPPORT_EMAIL: | |
| FOOTER_BITS.append(f'Questions? <a href="mailto:{html.escape(SUPPORT_EMAIL)}">{html.escape(SUPPORT_EMAIL)}</a>') | |
| FOOTER_HTML = '<div class="nr-footer">' + " · ".join(FOOTER_BITS) + "</div>" | |
| CSS = (HERE / "style.css").read_text(encoding="utf-8") | |
| HEAD = """ | |
| <link rel="preconnect" href="https://fonts.googleapis.com"> | |
| <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> | |
| <link href="https://fonts.googleapis.com/css2?family=Anton&family=Archivo:wght@400;500;600;700;800&display=swap" rel="stylesheet"> | |
| <script> | |
| /* On Spaces the app runs in an iframe that Gradio sizes. Gradio stops growing it after 4 growth steps in a row | |
| (a guard against resize loops), and this page grows more than that while it loads (fonts, banner, the form | |
| appearing after sign-in), so the bottom got cut off. Report the real content height whenever it grows. | |
| Measured from our own footer, whose position doesn't depend on the iframe height, so this can't loop. */ | |
| (function () { | |
| function fit() { | |
| var pi = window.parentIFrame, end = document.querySelector('.nr-footer'); | |
| if (!pi || !end) return; | |
| var gfoot = document.querySelector('footer'); | |
| var need = Math.ceil(end.getBoundingClientRect().bottom + window.scrollY + (gfoot ? gfoot.offsetHeight : 0) + 48); | |
| if (need > window.innerHeight + 2) pi.size(need); | |
| } | |
| var t = null; | |
| function soon() { clearTimeout(t); t = setTimeout(fit, 120); } | |
| function start() { | |
| new ResizeObserver(soon).observe(document.body); | |
| new MutationObserver(soon).observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); | |
| window.addEventListener('load', soon); | |
| var n = 0, iv = setInterval(function () { fit(); if (++n > 20) clearInterval(iv); }, 500); | |
| } | |
| if (document.body) start(); else document.addEventListener('DOMContentLoaded', start); | |
| })(); | |
| /* Sign-in inside the huggingface.co iframe needs a third-party cookie on hf.space. Safari, Brave, Firefox strict | |
| mode and private windows block it, so Gradio's OAuth flow loops until HF says "max attempts reached". | |
| In the iframe, unless the browser confirms cookie access, open sign-in in a new tab on the Space's own domain, | |
| where the cookie is first-party. Decided synchronously in the click so the new tab isn't treated as a pop-up. */ | |
| (function () { | |
| var framed = false; | |
| try { framed = window.self !== window.top; } catch (e) { framed = true; } | |
| if (!framed) return; | |
| var cookiesOk = false; | |
| try { | |
| if (document.hasStorageAccess) document.hasStorageAccess().then(function (ok) { cookiesOk = ok; }, function () {}); | |
| } catch (e) {} | |
| document.addEventListener('click', function (ev) { | |
| var btn = ev.target.closest && ev.target.closest('#nr-login-btn'); | |
| if (!btn || cookiesOk) return; | |
| if (!/^\\s*sign in/i.test(btn.textContent || '')) return; // "Sign out" keeps the normal behaviour | |
| var w = window.open(location.origin + '/login/huggingface?_target_url=/', '_blank'); | |
| if (!w) return; // pop-up blocked: fall back to Gradio's own in-frame flow | |
| ev.preventDefault(); ev.stopImmediatePropagation(); | |
| }, true); | |
| })(); | |
| </script> | |
| """ | |
| THEME = gr.themes.Base( | |
| primary_hue=gr.themes.colors.indigo, | |
| secondary_hue=gr.themes.colors.amber, | |
| neutral_hue=gr.themes.colors.slate, | |
| font=[gr.themes.GoogleFont("Archivo"), "Helvetica Neue", "Arial", "sans-serif"], | |
| radius_size=gr.themes.sizes.radius_sm, | |
| ).set( | |
| body_background_fill="#e9ecf5", | |
| body_background_fill_dark="#0f1330", | |
| button_primary_background_fill="#3d5afe", | |
| button_primary_background_fill_hover="#2f47e0", | |
| button_primary_text_color="#ffffff", | |
| checkbox_background_color_selected="#3d5afe", | |
| color_accent="#3d5afe", | |
| ) | |
| gr.set_static_paths(paths=[HERE / "static"]) | |
| with gr.Blocks(title="Register · NeurIPS 2026 Papers · Reproduce with ML Intern") as demo: | |
| gr.HTML(HERO_HTML) | |
| gr.HTML(dry_run_banner()) | |
| with gr.Row(elem_classes="nr-auth-row"): | |
| count_md = gr.Markdown(elem_classes="nr-count") | |
| gr.LoginButton(value="Sign in with Hugging Face", logout_value="Sign out ({})", size="md", scale=0, min_width=260, elem_id="nr-login-btn") | |
| status = gr.HTML() | |
| with gr.Column(visible=True, elem_classes="nr-card nr-login") as login_box: | |
| gr.Markdown( | |
| "### Sign in to register\n" | |
| "Registration uses your **Hugging Face account**, so credits and paper claims go to the right profile. " | |
| "No account yet? [Create one for free](https://huggingface.co/join), then come back and sign in.\n\n" | |
| f"**Sign-in not working** (for example *\"max attempts reached\"*)? Open the [registration page directly]({DIRECT_URL}) " | |
| "in its own tab and sign in there. Some browsers block sign-in inside the embedded page." | |
| ) | |
| summary = gr.Markdown(elem_classes="nr-card nr-summary") | |
| with gr.Column(visible=False, elem_classes="nr-form") as form_box: | |
| with gr.Row(equal_height=False): | |
| with gr.Column(elem_classes="nr-card"): | |
| gr.HTML('<div class="nr-section"><span>1</span>About you</div>') | |
| full_name = gr.Textbox(label="Full name *", placeholder="As you'd like it on certificates", max_lines=1, max_length=LIMITS["full_name"]) | |
| email = gr.Textbox(label="Email *", placeholder="We'll send credits and updates here", max_lines=1, max_length=LIMITS["email"], type="email") | |
| affiliation = gr.Textbox(label="Affiliation (optional)", placeholder="University, company or lab", max_lines=1, max_length=LIMITS["affiliation"]) | |
| role = gr.Radio(ROLES, label="What best describes you? *") | |
| with gr.Column(elem_classes="nr-stack"): | |
| with gr.Column(elem_classes="nr-card"): | |
| gr.HTML('<div class="nr-section"><span>2</span>Your experience</div>') | |
| hf_infra = gr.CheckboxGroup(HF_INFRA, label="Which Hugging Face infrastructure have you used? *", info="Pick all that apply.") | |
| ml_intern_use = gr.Radio(ML_INTERN_USE, label="Have you used ML Intern? *") | |
| with gr.Column(elem_classes="nr-card"): | |
| gr.HTML('<div class="nr-section"><span>3</span>A bit more</div>') | |
| how_heard = gr.Dropdown(HOW_HEARD, label="How did you hear about this hackathon? *", value=None) | |
| with gr.Column(elem_classes="nr-card"): | |
| gr.HTML('<div class="nr-section"><span>4</span>Your plans (optional)</div>') | |
| paper_interest = gr.Textbox( | |
| label="Any papers you already have your eye on?", | |
| placeholder="arXiv IDs or titles from the papers Space, e.g. 2608.16210", | |
| lines=2, max_length=LIMITS["paper_interest"], | |
| ) | |
| goals = gr.Textbox(label="What do you hope to get out of the hackathon?", lines=3, max_length=LIMITS["goals"]) | |
| with gr.Column(elem_classes="nr-card nr-terms"): | |
| agree = gr.Checkbox(label="I'm in *", info=TERMS) | |
| submit_btn = gr.Button(REGISTER_LABEL, variant="primary", size="lg", elem_id="nr-submit") | |
| form_status = gr.HTML() | |
| with gr.Row(): | |
| withdraw_btn = gr.Button("Withdraw my registration", variant="secondary", size="sm", visible=False, elem_id="nr-withdraw") | |
| confirm_btn = gr.Button("Yes, withdraw it", variant="stop", size="sm", visible=False) | |
| gr.HTML(FOOTER_HTML) | |
| inputs = [full_name, email, affiliation, role, hf_infra, | |
| ml_intern_use, how_heard, paper_interest, goals, agree] | |
| demo.load( | |
| on_load, inputs=None, | |
| outputs=[login_box, status, form_box, summary, *inputs, submit_btn, withdraw_btn, confirm_btn, count_md], | |
| ) | |
| demo.load(None, js=COUNTDOWN_JS) | |
| # Disable the button first (no queue) so a double click can't send two registrations. | |
| submit_btn.click( | |
| lambda: (gr.update(value="⏳ Saving…", interactive=False), status_html("info", "⏳ Saving your registration…")), | |
| outputs=[submit_btn, form_status], queue=False, api_visibility="private", | |
| ).then( | |
| on_submit, inputs=inputs, outputs=[form_status, summary, submit_btn, withdraw_btn], | |
| concurrency_limit=1, api_visibility="private", | |
| ) | |
| withdraw_btn.click(lambda: (gr.update(visible=False), gr.update(visible=True)), outputs=[withdraw_btn, confirm_btn], | |
| queue=False, api_visibility="private") | |
| confirm_btn.click( | |
| on_withdraw, outputs=[form_status, summary, withdraw_btn, confirm_btn], api_visibility="private", | |
| ).then(on_load, outputs=[login_box, status, form_box, summary, *inputs, submit_btn, withdraw_btn, confirm_btn, count_md]) | |
| if __name__ == "__main__": | |
| demo.queue(default_concurrency_limit=8).launch(theme=THEME, css=CSS, head=HEAD, allowed_paths=[str(HERE / "static")]) | |