jejunepixels commited on
Commit
cae297d
·
verified ·
1 Parent(s): 9d3e0c7

Open Hugging Face sign-in in a first-party tab to avoid embedded OAuth cookie loops

Browse files
Files changed (3) hide show
  1. README.md +6 -2
  2. app.py +4 -3
  3. hf_login.py +37 -0
README.md CHANGED
@@ -36,7 +36,7 @@ GPU are available. Start with SmolLM2-135M; larger models can be slow on CPU.
36
  ## Hugging Face Space
37
 
38
  Create a **Gradio** Space and upload `app.py`, `engine.py`, `models.py`, `style.css`,
39
- `gpu_runtime.py`, `english_bias.py`, `representations.py`, `projection_axes.py`, `token_space.py`, `token_space.js`, `attention_view.py`, `requirements.txt`, and this `README.md`. The README contains the Space metadata.
40
  The app detects Spaces and binds to `0.0.0.0:7860` there; local runs bind to localhost.
41
  `FLOW_HOST` and `PORT` can override these defaults. No API token is
42
  needed for the supported public, ungated models. Start with CPU Basic and a small
@@ -44,7 +44,7 @@ model; hardware determines the practical model size. This project is prepared fo
44
  Spaces but does not create or publish a remote Space automatically.
45
 
46
  Run `python scripts/prepare_space.py` to create `outputs/let-it-flow-space.zip`.
47
- Extract the archive and upload its thirteen files to the root of your Gradio Space.
48
 
49
  ## Token space
50
 
@@ -282,3 +282,7 @@ Vectors are unit-normalised. One shared PCA basis and scale are fitted jointly a
282
  All projected dimensions is off initially. Enable the checkbox above the connection panel for faint white guides, with opacity and origin options. Every original feature coordinate direction is transformed by the active PCA basis. A single common extent makes the guides visible while preserving their relative projected lengths. Axes may overlap or collapse when compressed into 3D; these are not attention links, model layers, semantic labels or individual learned parameters. Hover identifies a zero-based dimension index.
283
 
284
  The default translates these directions to the PCA mean. Original vector origin instead uses the affine projection of the zero vector. In Layer representations, the basis belongs to the frozen, unit-normalised hidden-state projection, so axes stay fixed during layer playback. Embedding and representation geometry are sent only when first available or with full snapshots, rather than on every generated token. Controls are local to the visualisation and do not change generation.
 
 
 
 
 
36
  ## Hugging Face Space
37
 
38
  Create a **Gradio** Space and upload `app.py`, `engine.py`, `models.py`, `style.css`,
39
+ `gpu_runtime.py`, `hf_login.py`, `english_bias.py`, `representations.py`, `projection_axes.py`, `token_space.py`, `token_space.js`, `attention_view.py`, `requirements.txt`, and this `README.md`. The README contains the Space metadata.
40
  The app detects Spaces and binds to `0.0.0.0:7860` there; local runs bind to localhost.
41
  `FLOW_HOST` and `PORT` can override these defaults. No API token is
42
  needed for the supported public, ungated models. Start with CPU Basic and a small
 
44
  Spaces but does not create or publish a remote Space automatically.
45
 
46
  Run `python scripts/prepare_space.py` to create `outputs/let-it-flow-space.zip`.
47
+ Extract the archive and upload its fourteen files to the root of your Gradio Space.
48
 
49
  ## Token space
50
 
 
282
  All projected dimensions is off initially. Enable the checkbox above the connection panel for faint white guides, with opacity and origin options. Every original feature coordinate direction is transformed by the active PCA basis. A single common extent makes the guides visible while preserving their relative projected lengths. Axes may overlap or collapse when compressed into 3D; these are not attention links, model layers, semantic labels or individual learned parameters. Hover identifies a zero-based dimension index.
283
 
284
  The default translates these directions to the PCA mean. Original vector origin instead uses the affine projection of the zero vector. In Layer representations, the basis belongs to the frozen, unit-normalised hidden-state projection, so axes stay fixed during layer playback. Embedding and representation geometry are sent only when first available or with full snapshots, rather than on every generated token. Controls are local to the visualisation and do not change generation.
285
+
286
+ ## Sign-in and embedded browsers
287
+
288
+ The sign-in buttons open the canonical hf.space OAuth route in a new top-level tab, returning to the direct app after login. This avoids doing the cookie-based OAuth round trip inside the huggingface.co iframe. Gradio's normal OAuth state validation, callback, expiry checks and logout remain in use. Query strings from the embedding page are not copied into the login URL. If a browser blocks all cookies, users still need to allow site cookies for sign-in to complete. The direct app URL is https://jejunepixels-let-it-flow.hf.space/.
app.py CHANGED
@@ -10,6 +10,7 @@ import gradio as gr
10
  from engine import Flow, generate
11
  from models import ModelStore, PRESETS, MODEL_LABELS, repository
12
  from token_space import SCENE, frame
 
13
 
14
  STORE = ModelStore()
15
  POOL = {}
@@ -259,8 +260,8 @@ def build_app():
259
  '<p>The model has no unconscious mind to uncover. This demo offers a look under the hood of how large language models generate text '
260
  'through learned patterns, attention, and probabilistic sampling within a limited context window.</p></header>')
261
  if ZERO_GPU:
262
- gr.LoginButton()
263
- gr.Markdown("Sign in to use your Hugging Face ZeroGPU quota. Generation uses short GPU sessions; Pause releases the GPU.")
264
  repo = gr.Dropdown(PRESETS, value=PRESETS[0], allow_custom_value=not ZERO_GPU,
265
  label="Public model repository or Hugging Face URL")
266
  model_note = gr.Textbox(value=MODEL_LABELS[PRESETS[0]], label="Model description", interactive=False)
@@ -289,7 +290,7 @@ def build_app():
289
  elem_id="generation-toggle")
290
  with gr.Accordion("Settings, model & attention", open=False, elem_id="settings-drawer"):
291
  if ZERO_GPU:
292
- gr.LoginButton()
293
  with gr.Row(elem_id="sampling-controls"):
294
  temperature = gr.Slider(.05, 2, value=1.3, step=.05, label="Temperature")
295
  top_p = gr.Slider(.05, 1, value=1, step=.01, label="Top-p")
 
10
  from engine import Flow, generate
11
  from models import ModelStore, PRESETS, MODEL_LABELS, repository
12
  from token_space import SCENE, frame
13
+ from hf_login import TopLevelLoginButton
14
 
15
  STORE = ModelStore()
16
  POOL = {}
 
260
  '<p>The model has no unconscious mind to uncover. This demo offers a look under the hood of how large language models generate text '
261
  'through learned patterns, attention, and probabilistic sampling within a limited context window.</p></header>')
262
  if ZERO_GPU:
263
+ TopLevelLoginButton(elem_id="hf-login-picker")
264
+ gr.Markdown("Sign in to use your Hugging Face ZeroGPU quota. Sign-in opens the app in a new tab to avoid embedded-browser cookie issues. Generation uses short GPU sessions; Pause releases the GPU.")
265
  repo = gr.Dropdown(PRESETS, value=PRESETS[0], allow_custom_value=not ZERO_GPU,
266
  label="Public model repository or Hugging Face URL")
267
  model_note = gr.Textbox(value=MODEL_LABELS[PRESETS[0]], label="Model description", interactive=False)
 
290
  elem_id="generation-toggle")
291
  with gr.Accordion("Settings, model & attention", open=False, elem_id="settings-drawer"):
292
  if ZERO_GPU:
293
+ TopLevelLoginButton(elem_id="hf-login-settings")
294
  with gr.Row(elem_id="sampling-controls"):
295
  temperature = gr.Slider(.05, 2, value=1.3, step=.05, label="Temperature")
296
  top_p = gr.Slider(.05, 1, value=1, step=.01, label="Top-p")
hf_login.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Keep Hugging Face OAuth outside embedded frames; retain Gradio's auth checks."""
2
+ import json
3
+ import os
4
+ import re
5
+ import gradio as gr
6
+
7
+
8
+ def canonical_space_origin():
9
+ host=os.environ.get("SPACE_HOST","jejunepixels-let-it-flow.hf.space").split(",",1)[0].strip().lower()
10
+ if not re.fullmatch(r"[a-z0-9][a-z0-9-]*\.hf\.space",host):
11
+ raise ValueError("Expected the canonical hf.space hostname for OAuth.")
12
+ return "https://"+host
13
+
14
+
15
+ def login_redirect_js(default_value):
16
+ origin=json.dumps(canonical_space_origin())
17
+ default=json.dumps(default_value)
18
+ return """(buttonValue) => {
19
+ const origin = ORIGIN;
20
+ const route = buttonValue === DEFAULT ? '/login/huggingface' : '/logout';
21
+ const url = new URL(route, origin);
22
+ url.searchParams.set('_target_url', '/');
23
+ window.open(url.href, '_blank', 'noopener,noreferrer');
24
+ }""".replace("ORIGIN",origin).replace("DEFAULT",default)
25
+
26
+
27
+ class TopLevelLoginButton(gr.LoginButton):
28
+ """Use the regular button renderer and OAuth status, with a first-party login tab."""
29
+ def get_block_name(self):
30
+ return "button"
31
+
32
+ def get_block_class(self):
33
+ return "button"
34
+
35
+ def activate(self):
36
+ self.click(fn=None,inputs=[self],outputs=None,js=login_redirect_js(self.value))
37
+ self.attach_load_event(self._check_login_status,None)