Spaces:
Runtime error

Require HF sign-in and add per-user generation limits

#2
NVIDIA org
•
edited Oct 16

Requires a signed-in Hugging Face user to generate, and adds per-user limits. Stacked on #1 (logging): this branch contains #1's commit, so merge #1 first. No change to atomworks-studio.

How identity gets to generate()
Studio's handlers don't pass the user, but Gradio sets a per-event request context (gradio.context.LocalContext.request) and asyncio.to_thread copies it into the worker thread. generate() reads the login session from there. This relies on Gradio internals, so sdk_version: 6.29.1 should stay pinned.

Changes

  • README.md: hf_oauth: true, hf_oauth_expiration_minutes: 480.
  • space.py: signed_in_username(); generate() refuses with gr.Error when not signed in (UI and /generate_cif API), checks quota, and releases the slot in finally; enable_oauth() adds Gradio's /login/huggingface, /login/callback, /logout routes ahead of Studio's catch-all mount at / (otherwise Studio would swallow them).
  • New limits.py: 1 active generation per user and 10 per rolling hour (module constants), thread-safe, check_quota(username) -> (bool, str) reserves a slot and release(username) frees it. In-memory and per replica by design (no shared state).
  • telemetry.py: log records now carry the real username.
  • requirements.txt: authlib, itsdangerous (needed by Gradio's OAuth; not guaranteed to be pulled in otherwise).

Behaviour to know about

  • Users sign in at https://<space-host>/login/huggingface (the error message says so). There is no Login button in the UI because Studio owns the page.
  • The CIF API in the README (gradio_client with an HF token) will be refused, since it carries a token rather than a browser session. Needs a follow-up if API access should stay open.
  • A failed generation still counts toward the hourly cap.
  • Not included: consent checkbox/notice.

Tested (locally, stubbed)
Ran the real space.py logic with torch/hydra/Studio stubbed, in a stand-in app with the same shape as Studio (catch-all mount at /, async handler calling generate_fn in a thread): anonymous refused; signed-in succeeds with the username logged; slot released after an inference error; 11th request in an hour refused with a retry time; OAuth route reachable despite the catch-all. limits.py: 50 racing threads yield exactly one winner; double release is safe; window expiry works.

Not tested: needs a throwaway Space before relying on it

  • Real HF OAuth end to end (redirect, callback, cookie inside the huggingface.co iframe, /design mount path). The test faked the session.
  • That authlib/itsdangerous resolve alongside the pinned stack on the Space build.
  • On real hardware.

Merged via main on top of #1 (with the RFD4_REQUIRE_SIGN_IN toggle added). Closing this draft.

kierandidi changed pull request status to closed

Sign up or log in to comment