"""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'
HF_TOKEN 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", "β Registration is closed. 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"β
@{who}, you're registered. You can edit your details below until registration closes."
if open_ else f"β
@{who}, you're registered. 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"β Registration closed 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"π Signed in as @{who}. 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"