jejunepixels commited on
Commit
603821f
·
verified ·
1 Parent(s): 4b38899

Shared start page, workspace and change-model button

Browse files
Files changed (9) hide show
  1. .streamlit/config.toml +7 -1
  2. README.md +106 -106
  3. app.py +112 -101
  4. brand.css +293 -0
  5. hub_ui.py +67 -38
  6. theme.css +81 -14
  7. upload_ui.py +1 -1
  8. viewer.css +9 -8
  9. viewer_ui.py +4 -2
.streamlit/config.toml CHANGED
@@ -1,7 +1,13 @@
 
 
1
  [theme]
2
  base = "light"
3
  primaryColor = "#F4BF67"
4
  backgroundColor = "#F4F8F6"
5
  secondaryBackgroundColor = "#EAF2EF"
6
  textColor = "#203C3A"
7
- font = "sans serif"
 
 
 
 
 
1
+ # Streamlit's own theme stays light so the mint control panel looks the same in both browser
2
+ # modes. The start page follows the browser's light/dark setting through brand.css tokens.
3
  [theme]
4
  base = "light"
5
  primaryColor = "#F4BF67"
6
  backgroundColor = "#F4F8F6"
7
  secondaryBackgroundColor = "#EAF2EF"
8
  textColor = "#203C3A"
9
+ # Same system font stack as brand.css (--brand-sans) and the Gradio Spaces.
10
+ font = "system-ui, -apple-system, Segoe UI, Roboto, sans-serif"
11
+
12
+ [client]
13
+ toolbarMode = "minimal"
README.md CHANGED
@@ -1,106 +1,106 @@
1
- ---
2
- title: Token Visualiser
3
- emoji: 🔬
4
- colorFrom: blue
5
- colorTo: purple
6
- sdk: docker
7
- app_port: 7860
8
- pinned: false
9
- short_description: Explore token curves, move ranges and find word analogies
10
- ---
11
-
12
- # Token Visualiser
13
-
14
- Explore the numbers inside token embeddings. Plot individual tokens as coloured curves, shade the range between a pair, or move that range to a different starting token and discover tokens near its other edge. No GPU is required.
15
-
16
- **[Open the public app](https://jejunepixels-token-visualiser.hf.space/)** · **[Hugging Face Space and source](https://huggingface.co/spaces/jejunepixels/token-visualiser)**
17
-
18
- ## Three examples observed with Qwen
19
-
20
- A relationship can sometimes be reused at another starting point. These three examples were found while exploring a Qwen model with this app:
21
-
22
- | First token | Second token | New starting token | Observed matching token |
23
- | --- | --- | --- | --- |
24
- | `man` | `father` | `woman` | `mother` |
25
- | `man` | `king` | `woman` | `queen` |
26
- | `man` | `boy` | `woman` | `girl` |
27
-
28
- Read the first row as: **take the change from man to father, apply it to woman, and look for a token near the result.** The same idea applies to the other two rows.
29
-
30
- ```text
31
- woman + (father − man) ≈ mother
32
- woman + (king − man) ≈ queen
33
- woman + (boy − man) ≈ girl
34
- ```
35
-
36
- Each word here stands for its embedding vector. The app calculates **new start + (second − first)**, then searches for stored token vectors closest to that calculated endpoint. The subtraction direction matters: choose `man` as **First token** and `king` as **Second token** for the queen example.
37
-
38
- These are reported observations with Qwen, rather than guaranteed results for every model. Results and rankings depend on the model version and the exact tokens, including capitalisation and leading spaces. The examples do not specify an exact Qwen checkpoint or result rank. The suggested model list includes **Qwen3 0.6B** as an available starting point.
39
-
40
- ### Try an example
41
-
42
- 1. Open the app, choose **Hugging Face**, select a model, and click **Find model files** followed by **Load into Space**. You can also use another model URL or upload supported weights.
43
- 2. Under **Add tokens**, add `man`, `father` and `woman` as separate text inputs. If your model splits a word into pieces, inspect the token pieces: this tool works with individual token embeddings.
44
- 3. Choose **Range between two tokens**. Set **First token** to `man` and **Second token** to `father`.
45
- 4. Tick **Move range to another token** and set **New starting token** to `woman`.
46
- 5. Click **Find matching tokens**. The list shows the 20 closest results by default; look for `mother` and click **Show on chart** to overlay its actual curve.
47
- 6. To try the other examples, add `king` or `boy`, use it as **Second token**, and search again. Look for `queen` or `girl` respectively.
48
-
49
- The **solid green edge** is the new starting token. The **dashed orange edge** is the calculated endpoint, not a real token until you find a match. The shaded band preserves the original pair's signed change at every dimension. Overlaying a result lets you compare the actual token curve with that predicted edge. **Show average** toggles the band's centre line.
50
-
51
- ## Use the viewer
52
-
53
- 1. Load a model from local files or Hugging Face. The hosted Space also accepts file uploads.
54
- 2. Under **Add tokens**, type text and add its token pieces, or search the GGUF vocabulary and click **Add token**. Earlier additions stay in **Available tokens**. Remove an entry with its cross button. Up to 20 tokens can be kept available.
55
- 3. Under **Display**, choose **Individual tokens** to see all available tokens as separate coloured lines. This is the default, and works with a single token. Click a legend entry to hide or show a line.
56
- 4. Choose **Range between two tokens** to select **First token** and **Second token** and show their ribbon. Tick **Show average** to display the centre line, or untick it to show the range alone. Switching modes keeps your tokens, line colours, selected pair and average setting.
57
- 5. To reuse that change, tick **Move range to another token** and choose a **New starting token** from your available tokens. The solid green edge follows that token; the dashed orange edge is the calculated endpoint: `new start + (second − first)`. This preserves the signed difference at every dimension, including where the original curves cross. It is not a constant vertical shift.
58
- 6. Click **Find matching tokens** to scan the vocabulary for real tokens closest to the dashed edge. Each result has **Show on chart** / **Hide from chart**. The list shows 20 results by default. Change **Number of matches** to show up to 50 results without rescanning. Changing the pair or starting token requires a new search. The input tokens are excluded. Matches use Euclidean distance across all raw embedding dimensions: lower is closer and 0 is exact. Numerical matches do not guarantee a meaningful word analogy.
59
-
60
- The horizontal axis is embedding dimension; the vertical axis is the stored value. The band's edges are the two tokens' values, its centre line is their average, and a wider band means a larger absolute gap. The band pinches to zero where the values meet. Hover for both values, their average and their difference. Drag to zoom and double-click to reset.
61
-
62
- The chart fills the workspace at all times. A separately scrolling controls panel floats on the left; click **Tokens & display** to collapse it and expose the chart underneath. **Model details & data** contains tensor selection, exact values and CSV export for the visible tokens or chosen pair. In a moved range, the export also includes the original inputs, new start, calculated endpoint and any displayed matches. **Clear model** unloads it and returns to the loading screen.
63
-
64
- These are stored input embeddings, before layer processing or model-specific scaling. A difference in their values is not a semantic similarity percentage. Tokenization requires the matching tokenizer. Without a tokenizer JSON, GGUF supports vocabulary substring search. Any model supports **Add by token ID**.
65
-
66
- ## Run on Windows
67
-
68
- Install Python 3.11 or newer, open PowerShell in this folder and run:
69
-
70
- ```powershell
71
- powershell -ExecutionPolicy Bypass -File .\start.ps1
72
- ```
73
-
74
- The launcher creates a project-local environment, installs dependencies and opens http://localhost:8501. Model inspection needs no GPU. Stop the server with Ctrl+C.
75
-
76
- ## Supported models
77
-
78
- - Single-file GGUF, with row-by-row dequantization supported by the installed gguf package.
79
- - F64/F32/F16/BF16 safetensors, including sharded folders and recognised embedding indexes.
80
- - Packed quantized safetensors, split GGUF and PyTorch pickle .bin files are unsupported.
81
-
82
- Local files stay on this computer. Use **Open model** or enter a file/folder path. A matching tokenizer.json is detected beside the weights or can be selected explicitly. Keep the local server bound to localhost.
83
-
84
- ## Load from Hugging Face
85
-
86
- Choose a suggested model (SmolLM2 135M, GPT-2, Gemma 3 1B Q4 GGUF or Qwen3 0.6B), or paste a model repository ID/URL. Click **Find model files**, choose weights and then **Load into Space** (hosted) or **Download & load** (local). Downloads go directly to the computer running the app; a local download and manual upload are unnecessary.
87
-
88
- Repository, tree, blob and resolve URLs are supported, with an optional revision. Downloads are pinned to the resolved commit. Recognised safetensors indexes fetch embedding shards only; otherwise all indexed shards are fetched. A matching tokenizer is included when available. Repository Python code is not executed.
89
-
90
- Public models need no token. Gated/private models require approved access and a read token. Tokens entered into the app are sent to its server and Hugging Face, are not saved as a login, and are cleared after loading. The Space owner operates the server. Authenticated downloads use session folders removed on **Clear model**. Public downloads may be reused; Space restarts can clear cached data.
91
-
92
- ## Hosting
93
-
94
- Run python scripts/prepare_space.py to prepare the explicit source package with pinned direct dependencies. Use the Docker SDK on port 7860. Hosted mode replaces host filesystem browsing with uploads.
95
-
96
- Hub downloads default to a 16 GB limit with known sizes and a free-space check, reserving 2 GB for the app. The owner can change the positive integer TOKEN_VISUALISER_MAX_DOWNLOAD_GB. One model downloads at a time per app process. Uploads allow 1 GB per file and 2 GB in total; session copies are removed on **Clear model**. Local Hub loading has no app-imposed size limit. Available storage and RAM still limit very large files.
97
-
98
- ## Checks
99
-
100
- ```powershell
101
- .\.venv\Scripts\python.exe -m unittest discover -s tests -v
102
- ```
103
-
104
- ## Credits
105
-
106
- Created by [jejunepixels](https://huggingface.co/jejunepixels), with development assistance from [Claude Code](https://claude.com/product/claude-code).
 
1
+ ---
2
+ title: Token Visualiser
3
+ emoji: 🔬
4
+ colorFrom: blue
5
+ colorTo: purple
6
+ sdk: docker
7
+ app_port: 7860
8
+ pinned: false
9
+ short_description: Explore token curves, move ranges and find word analogies
10
+ ---
11
+
12
+ # Token Visualiser
13
+
14
+ Explore the numbers inside token embeddings. Plot individual tokens as coloured curves, shade the range between a pair, or move that range to a different starting token and discover tokens near its other edge. No GPU is required.
15
+
16
+ **[Open the public app](https://jejunepixels-token-visualiser.hf.space/)** · **[Hugging Face Space and source](https://huggingface.co/spaces/jejunepixels/token-visualiser)**
17
+
18
+ ## Three examples observed with Qwen
19
+
20
+ A relationship can sometimes be reused at another starting point. These three examples were found while exploring a Qwen model with this app:
21
+
22
+ | First token | Second token | New starting token | Observed matching token |
23
+ | --- | --- | --- | --- |
24
+ | `man` | `father` | `woman` | `mother` |
25
+ | `man` | `king` | `woman` | `queen` |
26
+ | `man` | `boy` | `woman` | `girl` |
27
+
28
+ Read the first row as: **take the change from man to father, apply it to woman, and look for a token near the result.** The same idea applies to the other two rows.
29
+
30
+ ```text
31
+ woman + (father − man) ≈ mother
32
+ woman + (king − man) ≈ queen
33
+ woman + (boy − man) ≈ girl
34
+ ```
35
+
36
+ Each word here stands for its embedding vector. The app calculates **new start + (second − first)**, then searches for stored token vectors closest to that calculated endpoint. The subtraction direction matters: choose `man` as **First token** and `king` as **Second token** for the queen example.
37
+
38
+ These are reported observations with Qwen, rather than guaranteed results for every model. Results and rankings depend on the model version and the exact tokens, including capitalisation and leading spaces. The examples do not specify an exact Qwen checkpoint or result rank. The suggested model list includes **Qwen3 0.6B** as an available starting point.
39
+
40
+ ### Try an example
41
+
42
+ 1. Open the app, choose a model under **Model** (Qwen3 0.6B for these examples) and click **Load model**. Under **Other sources** you can also paste another model URL or upload supported weights.
43
+ 2. Under **Add tokens**, add `man`, `father` and `woman` as separate text inputs. If your model splits a word into pieces, inspect the token pieces: this tool works with individual token embeddings.
44
+ 3. Choose **Range between two tokens**. Set **First token** to `man` and **Second token** to `father`.
45
+ 4. Tick **Move range to another token** and set **New starting token** to `woman`.
46
+ 5. Click **Find matching tokens**. The list shows the 20 closest results by default; look for `mother` and click **Show on chart** to overlay its actual curve.
47
+ 6. To try the other examples, add `king` or `boy`, use it as **Second token**, and search again. Look for `queen` or `girl` respectively.
48
+
49
+ The **solid green edge** is the new starting token. The **dashed orange edge** is the calculated endpoint, not a real token until you find a match. The shaded band preserves the original pair's signed change at every dimension. Overlaying a result lets you compare the actual token curve with that predicted edge. **Show average** toggles the band's centre line.
50
+
51
+ ## Use the viewer
52
+
53
+ 1. Load a model from local files or Hugging Face. The hosted Space also accepts file uploads.
54
+ 2. Under **Add tokens**, type text and add its token pieces, or search the GGUF vocabulary and click **Add token**. Earlier additions stay in **Available tokens**. Remove an entry with its cross button. Up to 20 tokens can be kept available.
55
+ 3. Under **Display**, choose **Individual tokens** to see all available tokens as separate coloured lines. This is the default, and works with a single token. Click a legend entry to hide or show a line.
56
+ 4. Choose **Range between two tokens** to select **First token** and **Second token** and show their ribbon. Tick **Show average** to display the centre line, or untick it to show the range alone. Switching modes keeps your tokens, line colours, selected pair and average setting.
57
+ 5. To reuse that change, tick **Move range to another token** and choose a **New starting token** from your available tokens. The solid green edge follows that token; the dashed orange edge is the calculated endpoint: `new start + (second − first)`. This preserves the signed difference at every dimension, including where the original curves cross. It is not a constant vertical shift.
58
+ 6. Click **Find matching tokens** to scan the vocabulary for real tokens closest to the dashed edge. Each result has **Show on chart** / **Hide from chart**. The list shows 20 results by default. Change **Number of matches** to show up to 50 results without rescanning. Changing the pair or starting token requires a new search. The input tokens are excluded. Matches use Euclidean distance across all raw embedding dimensions: lower is closer and 0 is exact. Numerical matches do not guarantee a meaningful word analogy.
59
+
60
+ The horizontal axis is embedding dimension; the vertical axis is the stored value. The band's edges are the two tokens' values, its centre line is their average, and a wider band means a larger absolute gap. The band pinches to zero where the values meet. Hover for both values, their average and their difference. Drag to zoom and double-click to reset.
61
+
62
+ The chart fills the workspace at all times. A separately scrolling controls panel floats on the left; click **Tokens & display** to collapse it and expose the chart underneath. **Model details & data** contains tensor selection, exact values and CSV export for the visible tokens or chosen pair. In a moved range, the export also includes the original inputs, new start, calculated endpoint and any displayed matches. The round ↺ button at the bottom right (**Change model**) unloads it and returns to the start page.
63
+
64
+ These are stored input embeddings, before layer processing or model-specific scaling. A difference in their values is not a semantic similarity percentage. Tokenization requires the matching tokenizer. Without a tokenizer JSON, GGUF supports vocabulary substring search. Any model supports **Add by token ID**.
65
+
66
+ ## Run on Windows
67
+
68
+ Install Python 3.11 or newer, open PowerShell in this folder and run:
69
+
70
+ ```powershell
71
+ powershell -ExecutionPolicy Bypass -File .\start.ps1
72
+ ```
73
+
74
+ The launcher creates a project-local environment, installs dependencies and opens http://localhost:8501. Model inspection needs no GPU. Stop the server with Ctrl+C.
75
+
76
+ ## Supported models
77
+
78
+ - Single-file GGUF, with row-by-row dequantization supported by the installed gguf package.
79
+ - F64/F32/F16/BF16 safetensors, including sharded folders and recognised embedding indexes.
80
+ - Packed quantized safetensors, split GGUF and PyTorch pickle .bin files are unsupported.
81
+
82
+ Local files stay on this computer. Use **Open model** or enter a file/folder path. A matching tokenizer.json is detected beside the weights or can be selected explicitly. Keep the local server bound to localhost.
83
+
84
+ ## Load from Hugging Face
85
+
86
+ Choose a suggested model (SmolLM2 135M, GPT-2, Gemma 3 1B Q4 GGUF or Qwen3 0.6B) and click **Load model**; its preferred weights are found and loaded in one step. To use another repository, open **Other sources**, paste a model repository ID/URL, click **Find model files**, choose weights and then **Load into Space** (hosted) or **Download & load** (local). Downloads go directly to the computer running the app; a local download and manual upload are unnecessary.
87
+
88
+ Repository, tree, blob and resolve URLs are supported, with an optional revision. Downloads are pinned to the resolved commit. Recognised safetensors indexes fetch embedding shards only; otherwise all indexed shards are fetched. A matching tokenizer is included when available. Repository Python code is not executed.
89
+
90
+ Public models need no token. Gated/private models require approved access and a read token. Tokens entered into the app are sent to its server and Hugging Face, are not saved as a login, and are cleared after loading. The Space owner operates the server. Authenticated downloads use session folders removed on **Change model**. Public downloads may be reused; Space restarts can clear cached data.
91
+
92
+ ## Hosting
93
+
94
+ Run python scripts/prepare_space.py to prepare the explicit source package with pinned direct dependencies. `brand.css` is shared with the author's Automatic Drawing and Automatic Token Generation Spaces; the start page follows the browser's light or dark setting. Use the Docker SDK on port 7860. Hosted mode replaces host filesystem browsing with uploads.
95
+
96
+ Hub downloads default to a 16 GB limit with known sizes and a free-space check, reserving 2 GB for the app. The owner can change the positive integer TOKEN_VISUALISER_MAX_DOWNLOAD_GB. One model downloads at a time per app process. Uploads allow 1 GB per file and 2 GB in total; session copies are removed on **Change model**. Local Hub loading has no app-imposed size limit. Available storage and RAM still limit very large files.
97
+
98
+ ## Checks
99
+
100
+ ```powershell
101
+ .\.venv\Scripts\python.exe -m unittest discover -s tests -v
102
+ ```
103
+
104
+ ## Credits
105
+
106
+ Created by [jejunepixels](https://huggingface.co/jejunepixels), with development assistance from [Claude Code](https://claude.com/product/claude-code).
app.py CHANGED
@@ -1,101 +1,112 @@
1
- from pathlib import Path
2
-
3
- import streamlit as st
4
-
5
- from embeddings import Model, load_tokenizer
6
- from viewer_ui import render_viewer
7
- from model_picker import show_model_picker
8
- from hub_ui import render_hub_loader
9
- from upload_ui import render_upload_loader
10
- from app_environment import hosted_mode, remove_session_directory, UPLOAD_ROOT, PRIVATE_CACHE_ROOT
11
-
12
-
13
- st.set_page_config(page_title='Token Visualiser', page_icon='🔬', layout='wide', initial_sidebar_state='collapsed')
14
- st.markdown('<style>' + Path(__file__).with_name('theme.css').read_text(encoding='utf-8') + '</style>',
15
- unsafe_allow_html=True)
16
- hosted = hosted_mode()
17
- if st.session_state.pop('clear_hub_token', False):
18
- st.session_state.pop('hf_token', None)
19
- if 'pending_model' in st.session_state:
20
- pending_model = st.session_state.pop('pending_model')
21
- if not hosted:
22
- st.session_state.model_location = pending_model
23
-
24
-
25
- def clear_model():
26
- # Keep the last browsing location, but release model data and all analysis state.
27
- model = st.session_state.get('model')
28
- if model is not None:
29
- model.close()
30
- for key, root in [('upload_directory', UPLOAD_ROOT), ('private_hub_cache', PRIVATE_CACHE_ROOT)]:
31
- if key in st.session_state:
32
- try:
33
- remove_session_directory(st.session_state[key], root)
34
- except OSError:
35
- pass # Files still held by a disconnected worker disappear on restart.
36
- for key in list(st.session_state):
37
- if key not in {'picker_directory', 'picker_address'}:
38
- del st.session_state[key]
39
-
40
-
41
- def activate_model(location, tokenizer_location=None, display_name=None):
42
- model = Model(location)
43
- try:
44
- p = model.path
45
- auto = (p if p.is_dir() else p.parent) / 'tokenizer.json'
46
- selected_tokenizer = tokenizer_location or (auto if auto.exists() else None)
47
- tok = load_tokenizer(selected_tokenizer) if selected_tokenizer else None
48
- except Exception:
49
- model.close()
50
- raise
51
- st.session_state.model = model
52
- st.session_state.tok = tok
53
- st.session_state.loaded = str(model.path)
54
- st.session_state.model_display_name = display_name or model.path.name
55
- st.session_state.nearest_results = {}
56
- st.session_state.clear_hub_token = True
57
-
58
-
59
- if 'model' not in st.session_state:
60
- with st.container(key='start_page'):
61
- st.markdown('<div class="eyebrow">AN EXPERIMENT IN TOKEN EMBEDDINGS</div>', unsafe_allow_html=True)
62
- st.title('Token Visualiser')
63
- st.write('Explore the numbers inside a token. Compare embedding curves, follow the change between two tokens, and discover where that change leads.')
64
- st.caption('Models run in this Space · No GPU required' if hosted else 'Local model files · No GPU required')
65
- with st.container(key='model_loader', border=True):
66
- st.header('Load a model')
67
- st.write('Choose a suggested model, paste a Hugging Face link, or upload weights. Models load on this Space.'
68
- if hosted else 'Open a local model or download weights from Hugging Face to explore token embeddings.')
69
- if hosted:
70
- hub_tab, local_tab = st.tabs(['Hugging Face', 'Upload files'])
71
- else:
72
- local_tab, hub_tab = st.tabs(['Local files', 'Hugging Face'])
73
- with local_tab:
74
- if hosted:
75
- render_upload_loader(activate_model)
76
- if not hosted:
77
- with local_tab:
78
- if st.button('Open model…', key='open_model', use_container_width=True):
79
- st.session_state.picker_open = True
80
- if st.session_state.get('picker_open', False):
81
- show_model_picker()
82
- location = st.text_input('Model file or folder', placeholder=r'C:\Models\gemma.gguf', key='model_location')
83
- with st.expander('Tokenizer (optional)'):
84
- tokenizer_path = st.text_input('Tokenizer JSON or folder', key='tokenizer_location',
85
- help='Use the tokenizer from the exact same model. Enables text tokenization without added special tokens. Detected automatically beside the model when available.')
86
- load = st.button('Load model', key='load_model', type='primary', disabled=not location.strip(), use_container_width=True)
87
- st.caption('GGUF · F32/F16/BF16 safetensors · Sharded model folders')
88
- st.caption('Files stay on this computer.')
89
- if load:
90
- try:
91
- with st.spinner('Reading model metadata…'):
92
- activate_model(location.strip().strip('"'), tokenizer_path)
93
- st.rerun()
94
- except Exception as e:
95
- st.error(f'Could not load model: {e}')
96
- with hub_tab:
97
- render_hub_loader(activate_model)
98
- st.stop()
99
-
100
- render_viewer(st.session_state.model, st.session_state.tok, st.session_state.loaded,
101
- st.session_state.get('model_display_name', Path(st.session_state.loaded).name), on_clear=clear_model)
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ import streamlit as st
4
+
5
+ from embeddings import Model, load_tokenizer
6
+ from viewer_ui import render_viewer
7
+ from model_picker import show_model_picker
8
+ from hub_ui import render_link_loader, render_preset_loader
9
+ from upload_ui import render_upload_loader
10
+ from app_environment import hosted_mode, remove_session_directory, UPLOAD_ROOT, PRIVATE_CACHE_ROOT
11
+
12
+
13
+ st.set_page_config(page_title='Token Visualiser', page_icon='🔬', layout='wide', initial_sidebar_state='collapsed')
14
+ # Shared look (brand.css, from shared-ui/) first, then this app's Streamlit-specific rules.
15
+ st.markdown('<style>' + ''.join(Path(__file__).with_name(name).read_text(encoding='utf-8')
16
+ for name in ('brand.css', 'theme.css')) + '</style>',
17
+ unsafe_allow_html=True)
18
+ hosted = hosted_mode()
19
+ if st.session_state.pop('clear_hub_token', False):
20
+ st.session_state.pop('hf_token', None)
21
+ if 'pending_model' in st.session_state:
22
+ pending_model = st.session_state.pop('pending_model')
23
+ if not hosted:
24
+ st.session_state.model_location = pending_model
25
+
26
+
27
+ def clear_model():
28
+ # Keep the last browsing location, but release model data and all analysis state.
29
+ model = st.session_state.get('model')
30
+ if model is not None:
31
+ model.close()
32
+ for key, root in [('upload_directory', UPLOAD_ROOT), ('private_hub_cache', PRIVATE_CACHE_ROOT)]:
33
+ if key in st.session_state:
34
+ try:
35
+ remove_session_directory(st.session_state[key], root)
36
+ except OSError:
37
+ pass # Files still held by a disconnected worker disappear on restart.
38
+ for key in list(st.session_state):
39
+ if key not in {'picker_directory', 'picker_address'}:
40
+ del st.session_state[key]
41
+
42
+
43
+ def activate_model(location, tokenizer_location=None, display_name=None):
44
+ model = Model(location)
45
+ try:
46
+ p = model.path
47
+ auto = (p if p.is_dir() else p.parent) / 'tokenizer.json'
48
+ selected_tokenizer = tokenizer_location or (auto if auto.exists() else None)
49
+ tok = load_tokenizer(selected_tokenizer) if selected_tokenizer else None
50
+ except Exception:
51
+ model.close()
52
+ raise
53
+ st.session_state.model = model
54
+ st.session_state.tok = tok
55
+ st.session_state.loaded = str(model.path)
56
+ st.session_state.model_display_name = display_name or model.path.name
57
+ st.session_state.nearest_results = {}
58
+ st.session_state.clear_hub_token = True
59
+
60
+
61
+ def render_local_loader():
62
+ if st.button('Open model…', key='open_model', use_container_width=True):
63
+ st.session_state.picker_open = True
64
+ if st.session_state.get('picker_open', False):
65
+ show_model_picker()
66
+ location = st.text_input('Model file or folder', placeholder=r'C:\Models\gemma.gguf', key='model_location')
67
+ with st.expander('Tokenizer (optional)'):
68
+ tokenizer_path = st.text_input('Tokenizer JSON or folder', key='tokenizer_location',
69
+ help='Use the tokenizer from the exact same model. Enables text tokenization without added special tokens. Detected automatically beside the model when available.')
70
+ load = st.button('Load model', key='load_model', type='primary', disabled=not location.strip(), use_container_width=True)
71
+ st.caption('GGUF · F32/F16/BF16 safetensors · Sharded model folders')
72
+ st.caption('Files stay on this computer.')
73
+ if load:
74
+ try:
75
+ with st.spinner('Reading model metadata…'):
76
+ activate_model(location.strip().strip('"'), tokenizer_path)
77
+ st.rerun()
78
+ except Exception as e:
79
+ st.error(f'Could not load model: {e}')
80
+
81
+
82
+ # Start page, in the same order as the other Spaces: eyebrow, title, intro, model, primary action, note.
83
+ # There is no sign-in: models run on CPU, and gated models take a read token under Other sources.
84
+ START_HEADER = ('<header class="brand-header"><div class="eyebrow">AN EXPERIMENT IN TOKEN EMBEDDINGS</div>'
85
+ '<h1 class="brand-title">Token Visualiser<span class="title-stop">.</span></h1>'
86
+ '<p class="brand-intro">Explore the numbers inside a token. Compare embedding curves, follow the change '
87
+ 'between two tokens, and discover where that change leads.</p></header>')
88
+
89
+ if 'model' not in st.session_state:
90
+ with st.container(key='start_page'):
91
+ st.markdown(START_HEADER, unsafe_allow_html=True)
92
+ render_preset_loader(activate_model)
93
+ with st.expander('Other sources', expanded=not hosted):
94
+ if hosted:
95
+ link_tab, files_tab = st.tabs(['Hugging Face link', 'Upload files'])
96
+ with files_tab:
97
+ render_upload_loader(activate_model)
98
+ else:
99
+ files_tab, link_tab = st.tabs(['Local files', 'Hugging Face link'])
100
+ with files_tab:
101
+ render_local_loader()
102
+ with link_tab:
103
+ render_link_loader(activate_model)
104
+ st.markdown('<p class="brand-note"><strong>What you will see:</strong> each token’s stored embedding drawn as '
105
+ 'a curve across its dimensions, on a full-screen chart. Compare tokens, shade the range between '
106
+ 'two, and move that range to find related tokens. '
107
+ + ('Models run in this Space · No GPU required.' if hosted else
108
+ 'Local model files · No GPU required.') + '</p>', unsafe_allow_html=True)
109
+ st.stop()
110
+
111
+ render_viewer(st.session_state.model, st.session_state.tok, st.session_state.loaded,
112
+ st.session_state.get('model_display_name', Path(st.session_state.loaded).name), on_clear=clear_model)
brand.css ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ==========================================================================
2
+ Shared look for the Hugging Face Spaces in this folder:
3
+ Automatic Drawing, Stream of Consciousness (Let It Flow), Token Visualiser.
4
+
5
+ Canonical copy: shared-ui/brand.css. Edit it there, then run
6
+ `python shared-ui/sync.py` to copy it into each project.
7
+
8
+ - Start page: follows the browser's light/dark setting.
9
+ - Workspace: a dark stage with a pale mint control panel, identical in
10
+ both modes.
11
+ ========================================================================== */
12
+
13
+ :root {
14
+ /* Workspace: the same in light and dark browser modes. */
15
+ --brand-stage: #080f18;
16
+ --brand-stage-raised: #112530;
17
+ --brand-stage-line: #577f89;
18
+ --brand-stage-text: #eef3f5;
19
+ --brand-stage-caption: #c5e2dd;
20
+ --brand-amber: #f4bf67;
21
+ --brand-amber-hover: #e7aa45;
22
+ --brand-amber-deep: #b77a20;
23
+ --brand-on-amber: #17242b;
24
+ --brand-mint: #eaf2eff2;
25
+ --brand-mint-solid: #eaf2ef;
26
+ --brand-mint-surface: #f4f8f6;
27
+ --brand-mint-text: #203c3a;
28
+ --brand-mint-label: #29433f;
29
+ --brand-mint-subdued: #526b68;
30
+ --brand-mint-line: #b3c7bd;
31
+ --brand-mint-border: #6d9f9b66;
32
+ --brand-shadow: 0 12px 50px #0006;
33
+ --brand-radius-panel: 18px;
34
+ --brand-radius-control: 10px;
35
+ --brand-serif: Georgia, 'Times New Roman', serif;
36
+ --brand-sans: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
37
+
38
+ /* Start page, light browser mode. */
39
+ --brand-page: #f4f8f6;
40
+ --brand-surface: #ffffff;
41
+ --brand-heading: #17242b;
42
+ --brand-text: #203c3a;
43
+ --brand-subdued: #526b68;
44
+ --brand-eyebrow: #92601c;
45
+ --brand-link: #92601c;
46
+ --brand-line: #b3c7bd;
47
+ --brand-input: #ffffff;
48
+ --brand-input-hover: #f4f8f6;
49
+ --brand-focus: #b77a20;
50
+ }
51
+
52
+ /* Start page, dark browser mode. Gradio puts .dark on an ancestor of the app and
53
+ honours ?__theme=. Streamlit follows the system setting, hence the media query. */
54
+ .dark {
55
+ --brand-page: #080f18;
56
+ --brand-surface: #091622;
57
+ --brand-heading: #eef3f5;
58
+ --brand-text: #d5e3e6;
59
+ --brand-subdued: #a8bdc4;
60
+ --brand-eyebrow: #f4bf67;
61
+ --brand-link: #f4bf67;
62
+ --brand-line: #577f89;
63
+ --brand-input: #112530;
64
+ --brand-input-hover: #193442;
65
+ --brand-focus: #f4bf67;
66
+ }
67
+ @media (prefers-color-scheme: dark) {
68
+ .stApp {
69
+ --brand-page: #080f18;
70
+ --brand-surface: #091622;
71
+ --brand-heading: #eef3f5;
72
+ --brand-text: #d5e3e6;
73
+ --brand-subdued: #a8bdc4;
74
+ --brand-eyebrow: #f4bf67;
75
+ --brand-link: #f4bf67;
76
+ --brand-line: #577f89;
77
+ --brand-input: #112530;
78
+ --brand-input-hover: #193442;
79
+ --brand-focus: #f4bf67;
80
+ }
81
+ }
82
+
83
+ /* ---- Start page --------------------------------------------------------- */
84
+ /* Order: eyebrow, title, intro, sign-in + note, model, primary action, note. */
85
+ /* .st-key-start_page is Token Visualiser's Streamlit start-page container. */
86
+ .brand-start, .st-key-start_page {
87
+ box-sizing: border-box;
88
+ width: calc(100% - 24px) !important;
89
+ max-width: 680px !important;
90
+ margin: 7vh auto !important;
91
+ padding: 24px !important;
92
+ gap: 18px !important;
93
+ }
94
+ /* Gradio wraps fields in a bordered card; keep the start page flat (label above field),
95
+ as in Token Visualiser. */
96
+ .brand-start .form { border: 0 !important; background: transparent !important; box-shadow: none !important; }
97
+ .brand-start .form > .block {
98
+ padding: 0 !important;
99
+ border: 0 !important;
100
+ background: transparent !important;
101
+ box-shadow: none !important;
102
+ }
103
+ .brand-start .form > .block [data-testid="block-info"] {
104
+ padding-left: 0 !important;
105
+ padding-right: 0 !important;
106
+ font-weight: 600;
107
+ color: var(--brand-text) !important;
108
+ }
109
+ /* Gradio pads HTML blocks; align the title with the controls below it. */
110
+ .brand-start .html-container { padding-left: 0 !important; padding-right: 0 !important; }
111
+ .brand-header { padding: 12px 0 6px; }
112
+ .eyebrow {
113
+ font: 600 11px/1.5 var(--brand-sans);
114
+ letter-spacing: .18em;
115
+ text-transform: uppercase;
116
+ color: var(--brand-eyebrow) !important;
117
+ }
118
+ .brand-title {
119
+ margin: 14px 0 18px !important;
120
+ padding: 0 !important;
121
+ border: 0 !important;
122
+ font: 400 clamp(38px, 6vw, 62px)/1.06 var(--brand-serif) !important;
123
+ letter-spacing: -.04em !important;
124
+ color: var(--brand-heading) !important;
125
+ }
126
+ .title-stop { color: var(--brand-amber) !important; }
127
+ .brand-intro {
128
+ margin: 0 0 12px !important;
129
+ font: 16px/1.7 var(--brand-sans) !important;
130
+ color: var(--brand-text) !important;
131
+ }
132
+ .brand-note, .brand-note p, .brand-note li,
133
+ .signin-note, .signin-note p {
134
+ margin: 0;
135
+ font: 14px/1.6 var(--brand-sans) !important;
136
+ color: var(--brand-subdued) !important;
137
+ }
138
+ .brand-note strong, .signin-note strong { color: var(--brand-text) !important; }
139
+ .brand-note a, .signin-note a, .brand-header a { color: var(--brand-link) !important; }
140
+ /* .st-key-hf_load_preset is Token Visualiser's "Load model" button. */
141
+ .brand-primary, .st-key-hf_load_preset button {
142
+ min-height: 48px !important;
143
+ border: 0 !important;
144
+ border-radius: var(--brand-radius-control) !important;
145
+ background: var(--brand-amber) !important;
146
+ color: var(--brand-on-amber) !important;
147
+ font: 600 16px/1.4 var(--brand-sans) !important;
148
+ }
149
+ .brand-primary:hover, .st-key-hf_load_preset button:hover { background: var(--brand-amber-hover) !important; }
150
+ .brand-primary:focus-visible, .st-key-hf_load_preset button:focus-visible {
151
+ outline: 3px solid var(--brand-focus) !important;
152
+ outline-offset: 2px;
153
+ }
154
+ @media (max-width: 640px) {
155
+ .brand-start, .st-key-start_page { margin: 3vh auto !important; padding: 18px !important; }
156
+ }
157
+
158
+ /* ---- Workspace ---------------------------------------------------------- */
159
+ /* Floating mint panel. A light island: readable in both browser modes. */
160
+ .brand-dock {
161
+ box-sizing: border-box;
162
+ border: 1px solid var(--brand-mint-border) !important;
163
+ border-radius: var(--brand-radius-panel) !important;
164
+ background: var(--brand-mint) !important;
165
+ backdrop-filter: blur(18px);
166
+ box-shadow: var(--brand-shadow);
167
+ color: var(--brand-mint-text);
168
+ color-scheme: light;
169
+ /* Start-page tokens revert to their light values inside the panel. */
170
+ --brand-heading: #17242b;
171
+ --brand-text: #203c3a;
172
+ --brand-subdued: #526b68;
173
+ --brand-eyebrow: #92601c;
174
+ --brand-link: #92601c;
175
+ --brand-line: #b3c7bd;
176
+ --brand-input: #ffffff;
177
+ --brand-input-hover: #f4f8f6;
178
+ --brand-focus: #b77a20;
179
+ /* Gradio theme variables, so the panel ignores Gradio's dark mode. */
180
+ --body-text-color: #203c3a;
181
+ --body-text-color-subdued: #526b68;
182
+ --block-background-fill: #f4f8f6;
183
+ --background-fill-primary: #f4f8f6;
184
+ --background-fill-secondary: #e3ece7;
185
+ --block-label-background-fill: #f4f8f6;
186
+ --block-label-text-color: #29433f;
187
+ --block-title-text-color: #203c3a;
188
+ --block-title-background-fill: transparent;
189
+ --block-title-border-color: transparent;
190
+ --block-info-text-color: #526b68;
191
+ --block-border-color: #bdcdc5;
192
+ --border-color-primary: #b3c7bd;
193
+ --input-background-fill: #ffffff;
194
+ --input-background-fill-hover: #f4f8f6;
195
+ --input-background-fill-focus: #ffffff;
196
+ --input-border-color: #b3c7bd;
197
+ --input-text-color: #1c3536;
198
+ --input-placeholder-color: #526b68;
199
+ --accordion-text-color: #203c3a;
200
+ --checkbox-background-color: #ffffff;
201
+ --checkbox-border-color: #8aa49c;
202
+ --checkbox-label-background-fill: #f4f8f6;
203
+ --checkbox-label-text-color: #203c3a;
204
+ --button-secondary-background-fill: #f4f8f6;
205
+ --button-secondary-background-fill-hover: #dce9e1;
206
+ --button-secondary-text-color: #203c3a;
207
+ --button-secondary-text-color-hover: #17242b;
208
+ --button-secondary-border-color: #b3c7bd;
209
+ --link-text-color: #725020;
210
+ --table-even-background-fill: #ffffff;
211
+ --table-odd-background-fill: #f4f8f6;
212
+ }
213
+ .brand-dock .prose, .brand-dock .prose strong { color: var(--brand-mint-text) !important; }
214
+ .brand-dock label, .brand-dock .label-wrap, .brand-dock .label-wrap span {
215
+ color: var(--brand-mint-label) !important;
216
+ background: transparent !important;
217
+ }
218
+ .brand-dock input[type="number"], .brand-dock input[type="text"], .brand-dock textarea {
219
+ max-width: 100%;
220
+ color: #1c3536 !important;
221
+ -webkit-text-fill-color: #1c3536 !important;
222
+ background: #ffffff !important;
223
+ }
224
+ .brand-dock .block-info { color: var(--brand-mint-subdued) !important; }
225
+ .brand-dock button:focus-visible { outline: 3px solid var(--brand-amber-deep) !important; outline-offset: 2px; }
226
+
227
+ /* Model and status line at the top left of the stage. */
228
+ .brand-caption, .brand-caption .prose, .brand-caption p {
229
+ color: var(--brand-stage-caption) !important;
230
+ font: 13px/1.5 var(--brand-sans) !important;
231
+ }
232
+ .brand-caption strong { color: var(--brand-amber) !important; font-weight: 600; }
233
+
234
+ /* Round "change model" button, bottom right, outside the panel.
235
+ Its text stays as the accessible name; the ↺ glyph is drawn instead.
236
+ .st-key-clear_model is the Streamlit wrapper of Token Visualiser's button. */
237
+ .return-home, .st-key-clear_model button {
238
+ position: fixed !important;
239
+ right: max(16px, env(safe-area-inset-right));
240
+ bottom: max(16px, env(safe-area-inset-bottom));
241
+ z-index: 60;
242
+ display: flex !important;
243
+ align-items: center;
244
+ justify-content: center;
245
+ box-sizing: border-box;
246
+ width: 40px !important;
247
+ height: 40px !important;
248
+ min-width: 40px !important;
249
+ min-height: 40px !important;
250
+ padding: 0 !important;
251
+ border: 1px solid #86b6b366 !important;
252
+ border-radius: 50% !important;
253
+ background: #112530ed !important;
254
+ color: var(--brand-stage-caption) !important;
255
+ font-size: 0 !important;
256
+ box-shadow: 0 3px 16px #0004;
257
+ cursor: pointer;
258
+ }
259
+ .return-home::before, .st-key-clear_model button::before {
260
+ content: "\21ba";
261
+ font: 22px/1 var(--brand-sans);
262
+ color: var(--brand-stage-caption);
263
+ }
264
+ .return-home::after, .st-key-clear_model button::after {
265
+ content: var(--brand-return-label, "Change model");
266
+ position: absolute;
267
+ top: 50%;
268
+ right: 50px;
269
+ transform: translateY(-50%);
270
+ padding: 5px 9px;
271
+ border: 1px solid #78949d66;
272
+ border-radius: 7px;
273
+ background: #07121ff5;
274
+ color: #e2edf0;
275
+ font: 12px/1.4 var(--brand-sans);
276
+ white-space: nowrap;
277
+ opacity: 0;
278
+ pointer-events: none;
279
+ transition: opacity .15s;
280
+ }
281
+ .return-home:hover, .st-key-clear_model button:hover { background: #23434d !important; }
282
+ .return-home:hover::after, .return-home:focus-visible::after,
283
+ .st-key-clear_model button:hover::after, .st-key-clear_model button:focus-visible::after { opacity: 1; }
284
+ .return-home:focus-visible, .st-key-clear_model button:focus-visible {
285
+ outline: 2px solid var(--brand-amber) !important;
286
+ outline-offset: 3px;
287
+ }
288
+ @media (max-width: 640px) {
289
+ .return-home, .st-key-clear_model button { right: 12px; bottom: 12px; }
290
+ }
291
+
292
+ /* Gradio's "Use via API · Built with Gradio" footer. */
293
+ footer { display: none !important; }
hub_ui.py CHANGED
@@ -17,18 +17,69 @@ MODEL_PRESETS = {
17
  'About 720 MB · quantized GGUF'),
18
  'Qwen3 0.6B · multilingual': ('Qwen/Qwen3-0.6B', 'About 1.52 GB · multilingual · safetensors'),
19
  }
 
 
20
 
21
 
22
- def render_hub_loader(activate_model):
23
- st.caption('Choose a suggested model or paste a Hugging Face link. Weights download directly to this Space.'
24
- if hosted_mode() else 'Choose a suggested model or paste a Hugging Face link. Weights download to this computer.')
25
- source = st.radio('Model source', ['Choose from list', 'Paste URL or repository ID'], horizontal=True, key='hf_source')
26
- if source == 'Choose from list':
27
- preset = st.selectbox('Suggested model', list(MODEL_PRESETS), key='hf_preset')
28
- repo, description = MODEL_PRESETS[preset]
29
- st.caption(description + ' · downloaded on first use; cached copies are reused')
30
- else:
31
- repo = st.text_input('Hugging Face repository or URL', placeholder='owner/model or https://huggingface.co/owner/model', key='hf_repo')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  if hosted_mode():
33
  st.caption(f'Up to {format_size(hosted_download_limit())} per model, subject to free storage. Larger vocabularies take longer to search.')
34
  with st.expander('Revision & access token (optional)'):
@@ -36,7 +87,7 @@ def render_hub_loader(activate_model):
36
  token = st.text_input('Hugging Face read token', type='password', key='hf_token',
37
  help='For private or gated models. Sent to this app server and Hugging Face for this session; it is not saved as a login.')
38
  identity = (repo.strip(), revision.strip())
39
- if st.button('Find model files', key='hf_find_files', type='primary', disabled=not repo.strip(), use_container_width=True):
40
  st.session_state.pop('hf_catalog', None)
41
  try:
42
  with st.spinner('Reading Hugging Face repository…'):
@@ -49,7 +100,7 @@ def render_hub_loader(activate_model):
49
  return
50
  st.link_button('View repository on Hugging Face', f'https://huggingface.co/{catalog.repo_id}')
51
  if not catalog.choices:
52
- st.info('No supported weights found. Choose a single-file GGUF, standalone safetensors, or a safetensors index. Split GGUF and PyTorch .bin files are not supported.')
53
  return
54
  preferred = catalog.choices.index(catalog.preferred) if catalog.preferred else 0
55
  selection = st.selectbox('Model weights', catalog.choices, index=preferred,
@@ -82,31 +133,9 @@ def render_hub_loader(activate_model):
82
  st.info(str(error))
83
  return
84
  load_label = 'Load into Space' if hosted_mode() else 'Download & load'
85
- if st.button(load_label, key='hf_download', type='primary', use_container_width=True):
86
- events = Queue()
87
- progress = st.progress(0, text='Preparing download…')
88
- try:
89
- with ThreadPoolExecutor(max_workers=1) as executor:
90
- future = executor.submit(download_model, plan, token, lambda done, text: events.put((done, text)))
91
- while not future.done():
92
- try:
93
- done, text = events.get(timeout=.15)
94
- # Drop outdated progress events without touching Streamlit on a worker.
95
- while not events.empty():
96
- done, text = events.get_nowait()
97
- progress.progress(done, text=text)
98
- except Empty:
99
- pass
100
- model_path, tokenizer_path = future.result()
101
- progress.progress(1., text='Download complete. Reading embeddings…')
102
- activate_model(model_path, tokenizer_path, f'{catalog.repo_id} · {selection}')
103
- st.session_state.clear_hub_token = True
104
- st.rerun()
105
- except Exception as error:
106
- st.error(friendly_hub_error(error, token))
107
- finally:
108
- progress.empty()
109
  if private:
110
- st.caption('Token-authenticated downloads use a private session folder, removed when you clear the model. The Space owner operates this server.')
111
  else:
112
- st.caption('Downloads are cached and reused. Clearing a model keeps public downloaded files. Space restarts may clear the cache.' if hosted_mode() else 'Downloads are cached in this project’s .model-cache folder and reused. Clearing a model keeps its downloaded files.')
 
17
  'About 720 MB · quantized GGUF'),
18
  'Qwen3 0.6B · multilingual': ('Qwen/Qwen3-0.6B', 'About 1.52 GB · multilingual · safetensors'),
19
  }
20
+ NO_SUPPORTED_WEIGHTS = ('No supported weights found. Choose a single-file GGUF, standalone safetensors, or a '
21
+ 'safetensors index. Split GGUF and PyTorch .bin files are not supported.')
22
 
23
 
24
+ def download_and_activate(activate_model, catalog, selection, plan, token=None):
25
+ """Download the planned files with a progress bar, then open the model."""
26
+ events = Queue()
27
+ progress = st.progress(0, text='Preparing download…')
28
+ try:
29
+ with ThreadPoolExecutor(max_workers=1) as executor:
30
+ future = executor.submit(download_model, plan, token, lambda done, text: events.put((done, text)))
31
+ while not future.done():
32
+ try:
33
+ done, text = events.get(timeout=.15)
34
+ # Drop outdated progress events without touching Streamlit on a worker.
35
+ while not events.empty():
36
+ done, text = events.get_nowait()
37
+ progress.progress(done, text=text)
38
+ except Empty:
39
+ pass
40
+ model_path, tokenizer_path = future.result()
41
+ progress.progress(1., text='Download complete. Reading embeddings…')
42
+ activate_model(model_path, tokenizer_path, f'{catalog.repo_id} · {selection}')
43
+ st.session_state.clear_hub_token = True
44
+ st.rerun()
45
+ except Exception as error:
46
+ st.error(friendly_hub_error(error, token))
47
+ finally:
48
+ progress.empty()
49
+
50
+
51
+ def render_preset_loader(activate_model):
52
+ """Model choice and one primary action, as on the other Spaces' start pages."""
53
+ preset = st.selectbox('Model', list(MODEL_PRESETS), key='hf_preset')
54
+ repo, description = MODEL_PRESETS[preset]
55
+ st.caption(description + ' · downloaded on first use; cached copies are reused')
56
+ if not st.button('Load model', key='hf_load_preset', type='primary', width='stretch'):
57
+ return
58
+ try:
59
+ with st.spinner('Reading Hugging Face repository…'):
60
+ catalog = discover_models(repo, '', None)
61
+ if not catalog.choices:
62
+ st.info(NO_SUPPORTED_WEIGHTS)
63
+ return
64
+ selection = catalog.preferred or catalog.choices[0]
65
+ with st.spinner('Checking required model files…'):
66
+ plan = build_plan(catalog, selection, None, cache_root=CACHE_ROOT)
67
+ except Exception as error:
68
+ st.error(friendly_hub_error(error))
69
+ return
70
+ try:
71
+ check_hosted_download(plan)
72
+ except (ValueError, OSError) as error:
73
+ st.info(str(error))
74
+ return
75
+ download_and_activate(activate_model, catalog, selection, plan)
76
+
77
+
78
+ def render_link_loader(activate_model):
79
+ """Any Hugging Face repository or file link: find its weights, choose, then load."""
80
+ st.caption('Paste a Hugging Face model link or repository ID. Weights download directly to this Space.'
81
+ if hosted_mode() else 'Paste a Hugging Face model link or repository ID. Weights download to this computer.')
82
+ repo = st.text_input('Hugging Face repository or URL', placeholder='owner/model or https://huggingface.co/owner/model', key='hf_repo')
83
  if hosted_mode():
84
  st.caption(f'Up to {format_size(hosted_download_limit())} per model, subject to free storage. Larger vocabularies take longer to search.')
85
  with st.expander('Revision & access token (optional)'):
 
87
  token = st.text_input('Hugging Face read token', type='password', key='hf_token',
88
  help='For private or gated models. Sent to this app server and Hugging Face for this session; it is not saved as a login.')
89
  identity = (repo.strip(), revision.strip())
90
+ if st.button('Find model files', key='hf_find_files', disabled=not repo.strip(), width='stretch'):
91
  st.session_state.pop('hf_catalog', None)
92
  try:
93
  with st.spinner('Reading Hugging Face repository…'):
 
100
  return
101
  st.link_button('View repository on Hugging Face', f'https://huggingface.co/{catalog.repo_id}')
102
  if not catalog.choices:
103
+ st.info(NO_SUPPORTED_WEIGHTS)
104
  return
105
  preferred = catalog.choices.index(catalog.preferred) if catalog.preferred else 0
106
  selection = st.selectbox('Model weights', catalog.choices, index=preferred,
 
133
  st.info(str(error))
134
  return
135
  load_label = 'Load into Space' if hosted_mode() else 'Download & load'
136
+ if st.button(load_label, key='hf_download', type='primary', width='stretch'):
137
+ download_and_activate(activate_model, catalog, selection, plan, token)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  if private:
139
+ st.caption('Token-authenticated downloads use a private session folder, removed when you change model. The Space owner operates this server.')
140
  else:
141
+ st.caption('Downloads are cached and reused. Changing model keeps public downloaded files. Space restarts may clear the cache.' if hosted_mode() else 'Downloads are cached in this project’s .model-cache folder and reused. Changing model keeps its downloaded files.')
theme.css CHANGED
@@ -1,23 +1,83 @@
1
- h1 { font: 400 clamp(38px, 5vw, 62px)/1.05 Georgia, serif !important; letter-spacing: -.04em; }
2
- h1::after { content: '.'; color: #f4bf67; }
3
- h2, h3 { font-family: Georgia, serif !important; font-weight: 400 !important; }
4
- .eyebrow { font: 600 11px/1.5 system-ui, sans-serif; letter-spacing: .18em; color: #92601c; }
5
- .st-key-start_page, .st-key-model_loader { max-width: 680px; margin-left: auto; margin-right: auto; }
6
- .st-key-start_page { padding: 3vh 8px 20px; }
7
- .st-key-start_page p { font-size: 16px; line-height: 1.7; }
8
- .st-key-model_loader { padding: 24px; background: #eaf2ef; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  [data-testid="stVerticalBlockBorderWrapper"], [data-testid="stExpander"] {
10
  border-color: #82968b40 !important;
11
  border-radius: 14px !important;
12
  }
13
- [data-baseweb="input"], [data-baseweb="base-input"], [data-baseweb="select"] > div,
14
  [data-baseweb="textarea"], [data-testid="stFileUploaderDropzone"] {
15
  border-radius: 10px !important;
16
  border-color: #82968b66 !important;
17
  background-color: #fff !important;
18
  color: #203c3a;
19
  }
20
- [data-baseweb="input"]:focus-within, [data-baseweb="select"]:focus-within {
21
  border-color: #f4bf67 !important;
22
  box-shadow: 0 0 0 2px #f4bf6733;
23
  }
@@ -28,7 +88,14 @@ h2, h3 { font-family: Georgia, serif !important; font-weight: 400 !important; }
28
  }
29
  button[kind="primary"] { background: #f4bf67 !important; border-color: #f4bf67 !important; color: #17242b !important; }
30
  button[kind="primary"]:hover { background: #e7aa45 !important; border-color: #e7aa45 !important; }
31
- @media(max-width:640px) {
32
- .st-key-start_page { padding-top: 0; }
33
- .st-key-model_loader { padding: 14px; }
34
- }
 
 
 
 
 
 
 
 
1
+ /* Token Visualiser: Streamlit hooks for the shared look in brand.css (shared-ui/).
2
+ Streamlit's own theme stays light (.streamlit/config.toml), so the mint control panel is
3
+ unchanged. The start page follows the browser's light/dark setting through brand.css tokens. */
4
+
5
+ /* No Streamlit top bar: the start page and chart stage fill the window, as in the Gradio Spaces. */
6
+ [data-testid="stHeader"] { display: none !important; }
7
+ [data-testid="stMainBlockContainer"]:has(.st-key-start_page) { padding-top: 0; }
8
+
9
+ /* Serif subheadings in the workspace panel. */
10
+ h2, h3 { font-family: var(--brand-serif) !important; font-weight: 400 !important; }
11
+ .brand-header [data-testid="stHeaderActionElements"] { display: none !important; }
12
+
13
+ /* ---- Start page ---------------------------------------------------------- */
14
+ .stApp:has(.st-key-start_page) { background: var(--brand-page) !important; }
15
+ .st-key-start_page { color: var(--brand-text); }
16
+ .st-key-start_page [data-testid="stWidgetLabel"], .st-key-start_page [data-testid="stWidgetLabel"] p {
17
+ color: var(--brand-text) !important;
18
+ font-weight: 600;
19
+ }
20
+ .st-key-start_page [data-testid="stCaptionContainer"], .st-key-start_page [data-testid="stCaptionContainer"] p {
21
+ color: var(--brand-subdued) !important;
22
+ }
23
+ .st-key-start_page [data-testid="stMarkdownContainer"], .st-key-start_page [data-testid="stText"] { color: var(--brand-text); }
24
+ .st-key-start_page [data-baseweb="select"] > div, .st-key-start_page .react-aria-ComboBox > div,
25
+ .st-key-start_page [data-baseweb="input"], .st-key-start_page [data-baseweb="base-input"],
26
+ .st-key-start_page [data-testid="stFileUploaderDropzone"] {
27
+ border-radius: var(--brand-radius-control) !important;
28
+ border-color: var(--brand-line) !important;
29
+ background-color: var(--brand-input) !important;
30
+ color: var(--brand-text) !important;
31
+ }
32
+ .st-key-start_page [data-baseweb="select"] *, .st-key-start_page .react-aria-ComboBox *, .st-key-start_page input,
33
+ .st-key-start_page [data-testid="stFileUploaderDropzoneInstructions"] * {
34
+ color: var(--brand-text) !important;
35
+ -webkit-text-fill-color: var(--brand-text);
36
+ }
37
+ .st-key-start_page input::placeholder { color: var(--brand-subdued) !important; -webkit-text-fill-color: var(--brand-subdued); }
38
+ .st-key-start_page [data-baseweb="select"]:focus-within > div, .st-key-start_page .react-aria-ComboBox:focus-within > div,
39
+ .st-key-start_page [data-baseweb="input"]:focus-within {
40
+ border-color: var(--brand-amber) !important;
41
+ box-shadow: 0 0 0 2px #f4bf6733;
42
+ }
43
+ .st-key-start_page [data-testid="stExpander"] details {
44
+ border-color: var(--brand-line) !important;
45
+ border-radius: 14px !important;
46
+ background: transparent !important;
47
+ }
48
+ .st-key-start_page [data-testid="stExpander"] summary, .st-key-start_page [data-testid="stExpander"] summary * {
49
+ color: var(--brand-text) !important;
50
+ }
51
+ .st-key-start_page [data-testid="stExpander"] summary:hover * { color: var(--brand-link) !important; }
52
+ .st-key-start_page [data-baseweb="tab"] p { color: var(--brand-subdued) !important; }
53
+ .st-key-start_page [data-baseweb="tab"][aria-selected="true"] p { color: var(--brand-text) !important; }
54
+ .st-key-start_page [data-baseweb="tab-border"] { background-color: var(--brand-line) !important; }
55
+ .st-key-start_page button[kind="secondary"], .st-key-start_page [data-testid="stLinkButton"] a {
56
+ border-radius: var(--brand-radius-control);
57
+ border-color: var(--brand-line) !important;
58
+ background: var(--brand-input-hover) !important;
59
+ color: var(--brand-text) !important;
60
+ }
61
+ .st-key-start_page button[kind="secondary"]:hover, .st-key-start_page [data-testid="stLinkButton"] a:hover {
62
+ border-color: var(--brand-amber) !important;
63
+ }
64
+ .st-key-start_page button[kind="primary"], .st-key-start_page button[kind="primary"] * { color: var(--brand-on-amber) !important; }
65
+ .st-key-hf_load_preset button p { font: 600 16px/1.4 var(--brand-sans) !important; }
66
+ .st-key-start_page [data-testid="stProgress"] p, .st-key-start_page [data-testid="stSpinner"] * { color: var(--brand-text) !important; }
67
+
68
+ /* ---- Shared controls ------------------------------------------------------ */
69
  [data-testid="stVerticalBlockBorderWrapper"], [data-testid="stExpander"] {
70
  border-color: #82968b40 !important;
71
  border-radius: 14px !important;
72
  }
73
+ [data-baseweb="input"], [data-baseweb="base-input"], [data-baseweb="select"] > div, .react-aria-ComboBox > div,
74
  [data-baseweb="textarea"], [data-testid="stFileUploaderDropzone"] {
75
  border-radius: 10px !important;
76
  border-color: #82968b66 !important;
77
  background-color: #fff !important;
78
  color: #203c3a;
79
  }
80
+ [data-baseweb="input"]:focus-within, [data-baseweb="select"]:focus-within, .react-aria-ComboBox:focus-within > div {
81
  border-color: #f4bf67 !important;
82
  box-shadow: 0 0 0 2px #f4bf6733;
83
  }
 
88
  }
89
  button[kind="primary"] { background: #f4bf67 !important; border-color: #f4bf67 !important; color: #17242b !important; }
90
  button[kind="primary"]:hover { background: #e7aa45 !important; border-color: #e7aa45 !important; }
91
+
92
+ /* The round "Change model" button keeps its label for screen readers only. */
93
+ .st-key-clear_model button p {
94
+ position: absolute !important;
95
+ width: 1px;
96
+ height: 1px;
97
+ overflow: hidden;
98
+ clip-path: inset(50%);
99
+ white-space: nowrap;
100
+ }
101
+ .st-key-clear_model { --brand-return-label: "Change model"; }
upload_ui.py CHANGED
@@ -47,7 +47,7 @@ def render_upload_loader(activate_model):
47
  st.caption('Upload a single GGUF file or safetensors weights. Up to 1 GB per file, 2 GB total.')
48
  files = st.file_uploader('Model files', type=['gguf', 'safetensors'], accept_multiple_files=True, key='uploaded_models')
49
  tokenizer = st.file_uploader('Matching tokenizer.json (optional)', type=['json'], key='uploaded_tokenizer')
50
- st.caption('Uploads are processed by this Space in your session and removed when you clear the model. Restarting the Space also clears uploads.')
51
  if st.button('Load uploaded model', key='load_upload', type='primary', disabled=not files, use_container_width=True):
52
  directory = None
53
  try:
 
47
  st.caption('Upload a single GGUF file or safetensors weights. Up to 1 GB per file, 2 GB total.')
48
  files = st.file_uploader('Model files', type=['gguf', 'safetensors'], accept_multiple_files=True, key='uploaded_models')
49
  tokenizer = st.file_uploader('Matching tokenizer.json (optional)', type=['json'], key='uploaded_tokenizer')
50
+ st.caption('Uploads are processed by this Space in your session and removed when you change model. Restarting the Space also clears uploads.')
51
  if st.button('Load uploaded model', key='load_upload', type='primary', disabled=not files, use_container_width=True):
52
  directory = None
53
  try:
viewer.css CHANGED
@@ -1,9 +1,10 @@
1
- /* Full viewport chart with an independently scrolling overlay on the left. */
 
2
  [data-testid="stMain"] { overflow: hidden; background: #080f18; }
3
  [data-testid="stMainBlockContainer"] { padding: 0; max-width: none; }
4
  .st-key-chart_pane {
5
  position: fixed;
6
- inset: 3.75rem 0 0;
7
  width: auto !important;
8
  height: auto !important;
9
  min-height: 0;
@@ -16,11 +17,11 @@
16
  }
17
  .st-key-controls_pane {
18
  position: fixed;
19
- top: 4.5rem;
20
  left: 1rem;
21
  width: 340px !important;
22
  max-width: calc(100vw - 2rem);
23
- max-height: calc(100dvh - 5.5rem);
24
  height: auto !important;
25
  overflow-x: hidden;
26
  overflow-y: auto;
@@ -42,9 +43,9 @@
42
  .st-key-controls_pane [data-testid="stVerticalBlockBorderWrapper"] { background: #f4f8f6; }
43
  @media (max-width: 640px) {
44
  .st-key-controls_pane {
45
- top: 4rem;
46
  left: .5rem;
47
- max-width: calc(100vw - 3rem);
48
- max-height: calc(100dvh - 4.75rem);
49
  }
50
- }
 
1
+ /* Full viewport chart with an independently scrolling overlay on the left.
2
+ The round return button is styled in brand.css (shared-ui/). */
3
  [data-testid="stMain"] { overflow: hidden; background: #080f18; }
4
  [data-testid="stMainBlockContainer"] { padding: 0; max-width: none; }
5
  .st-key-chart_pane {
6
  position: fixed;
7
+ inset: 0;
8
  width: auto !important;
9
  height: auto !important;
10
  min-height: 0;
 
17
  }
18
  .st-key-controls_pane {
19
  position: fixed;
20
+ top: 1rem;
21
  left: 1rem;
22
  width: 340px !important;
23
  max-width: calc(100vw - 2rem);
24
+ max-height: calc(100dvh - 2rem);
25
  height: auto !important;
26
  overflow-x: hidden;
27
  overflow-y: auto;
 
43
  .st-key-controls_pane [data-testid="stVerticalBlockBorderWrapper"] { background: #f4f8f6; }
44
  @media (max-width: 640px) {
45
  .st-key-controls_pane {
46
+ top: .5rem;
47
  left: .5rem;
48
+ max-width: calc(100vw - 1rem);
49
+ max-height: calc(100dvh - 4.5rem);
50
  }
51
+ }
viewer_ui.py CHANGED
@@ -24,11 +24,13 @@ def render_viewer(model, tokenizer, loaded, display_name, on_clear=None):
24
  tokens_panel = st.container(border=True)
25
  pair_panel = st.container(border=True)
26
  model_panel = st.container(border=True)
 
 
 
 
27
 
28
  with model_panel:
29
  st.subheader('Model')
30
- if on_clear is not None:
31
- st.button('Clear model', key='clear_model', on_click=on_clear, width='stretch')
32
  advanced = st.expander('Model details & data')
33
  with advanced:
34
  names = sorted(model.tensors, key=lambda name: (not embedding_name(name), name))
 
24
  tokens_panel = st.container(border=True)
25
  pair_panel = st.container(border=True)
26
  model_panel = st.container(border=True)
27
+ if on_clear is not None:
28
+ # Round ↺ button at the bottom right (brand.css), as in the other Spaces. It sits outside the
29
+ # panel, whose backdrop-filter would trap position:fixed, and returns to the start page.
30
+ st.button('Change model', key='clear_model', on_click=on_clear)
31
 
32
  with model_panel:
33
  st.subheader('Model')
 
 
34
  advanced = st.expander('Model details & data')
35
  with advanced:
36
  names = sorted(model.tensors, key=lambda name: (not embedding_name(name), name))