davanstrien HF Staff commited on
Commit
4ea6260
·
1 Parent(s): 1f6e59a

Add atlas-export UV script for HF Jobs

Browse files
Files changed (2) hide show
  1. README.md +94 -0
  2. atlas-export.py +432 -0
README.md ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🗺️ Atlas Export - One-Click Embedding Visualizations
2
+
3
+ Generate and deploy interactive embedding visualizations to HuggingFace Spaces with a single command.
4
+
5
+ ## Quick Start
6
+
7
+ ```bash
8
+ # Create a Space from any text dataset
9
+ uv run atlas-export.py stanfordnlp/imdb --space-name my-imdb-viz
10
+
11
+ # Your Space will be live at:
12
+ # https://huggingface.co/spaces/YOUR_USERNAME/my-imdb-viz
13
+ ```
14
+
15
+ ## Examples
16
+
17
+ ### Image Datasets
18
+
19
+ ```bash
20
+ # Visualize image datasets with CLIP
21
+ uv run atlas-export.py \
22
+ beans \
23
+ --space-name bean-disease-atlas \
24
+ --image-column image \
25
+ --model openai/clip-vit-base-patch32
26
+ ```
27
+
28
+ ### Custom Embeddings
29
+
30
+ ```bash
31
+ # Use a specific embedding model
32
+ uv run atlas-export.py \
33
+ wikipedia \
34
+ --space-name wiki-viz \
35
+ --model nomic-ai/nomic-embed-text-v1.5 \
36
+ --text-column text \
37
+ --sample 50000
38
+ ```
39
+
40
+ ### Pre-computed Embeddings
41
+
42
+ ```bash
43
+ # If you already have embeddings in your dataset
44
+ uv run atlas-export.py \
45
+ my-dataset-with-embeddings \
46
+ --space-name my-viz \
47
+ --no-compute-embeddings \
48
+ --x-column umap_x \
49
+ --y-column umap_y
50
+ ```
51
+
52
+ ### GPU Acceleration
53
+
54
+ ```bash
55
+ # Run on HF Jobs with GPU for faster embedding generation
56
+ hf jobs run --gpu t4 \
57
+ uv run https://huggingface.co/datasets/uv-scripts/build-atlas/raw/main/atlas-export.py \
58
+ stanfordnlp/imdb \
59
+ --space-name imdb-viz \
60
+ --model sentence-transformers/all-mpnet-base-v2 \
61
+ --sample 10000
62
+ ```
63
+
64
+ ## Key Options
65
+
66
+ | Option | Description | Default |
67
+ |--------|-------------|---------|
68
+ | `dataset_id` | HuggingFace dataset to visualize | Required |
69
+ | `--space-name` | Name for your Space | Required |
70
+ | `--model` | Embedding model to use | Auto-selected |
71
+ | `--text-column` | Column containing text | Auto-detected |
72
+ | `--image-column` | Column containing images | None |
73
+ | `--sample` | Number of samples to visualize | All |
74
+ | `--local-only` | Generate locally without deploying | False |
75
+ | `--output-dir` | Local output directory | Temp dir |
76
+
77
+ Run without arguments to see all options and more examples.
78
+
79
+ ## How It Works
80
+
81
+ 1. Loads dataset from HuggingFace Hub
82
+ 2. Generates embeddings (or uses pre-computed)
83
+ 3. Creates static web app with embedded data
84
+ 4. Deploys to HF Space
85
+
86
+ The resulting visualization runs entirely in the browser using WebGPU acceleration.
87
+
88
+ ## Credits
89
+
90
+ Built on [Embedding Atlas](https://github.com/apple/embedding-atlas) by Apple.
91
+
92
+ ---
93
+
94
+ Part of the [UV Scripts](https://huggingface.co/uv-scripts) collection 🚀
atlas-export.py ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = [
4
+ # "huggingface-hub[hf_transfer]",
5
+ # "torch", # For GPU detection
6
+ # ]
7
+ # ///
8
+
9
+ """
10
+ Generate static Embedding Atlas visualizations and deploy to HuggingFace Spaces.
11
+
12
+ This script creates interactive embedding visualizations that run entirely in the browser,
13
+ using WebGPU acceleration for smooth performance with millions of points.
14
+
15
+ Example usage:
16
+ # Basic usage (creates Space from dataset)
17
+ uv run atlas-export.py \
18
+ stanfordnlp/imdb \
19
+ --space-name my-imdb-viz
20
+
21
+ # With custom model and configuration
22
+ uv run atlas-export.py \
23
+ beans \
24
+ --space-name bean-disease-atlas \
25
+ --image-column image \
26
+ --model openai/clip-vit-base-patch32 \
27
+ --sample 10000
28
+
29
+ # Run on HF Jobs with GPU (if embedding generation benefits)
30
+ hf jobs run --gpu t4 \
31
+ uv run https://huggingface.co/datasets/uv-scripts/build-atlas/raw/main/atlas-export.py \
32
+ my-dataset \
33
+ --space-name my-atlas \
34
+ --model nomic-ai/nomic-embed-text-v1.5
35
+
36
+ # Use pre-computed embeddings
37
+ uv run atlas-export.py \
38
+ my-dataset-with-embeddings \
39
+ --space-name my-viz \
40
+ --no-compute-embeddings \
41
+ --x-column umap_x \
42
+ --y-column umap_y
43
+ """
44
+
45
+ import argparse
46
+ import logging
47
+ import os
48
+ import shutil
49
+ import subprocess
50
+ import sys
51
+ import tempfile
52
+ import zipfile
53
+ from pathlib import Path
54
+ from typing import Optional
55
+
56
+ from huggingface_hub import HfApi, create_repo, login, upload_folder
57
+
58
+ logging.basicConfig(level=logging.INFO)
59
+ logger = logging.getLogger(__name__)
60
+
61
+
62
+ def check_gpu_available() -> bool:
63
+ """Check if GPU is available for computation."""
64
+ try:
65
+ import torch
66
+ return torch.cuda.is_available()
67
+ except ImportError:
68
+ return False
69
+
70
+
71
+ def build_atlas_command(args) -> list:
72
+ """Build the embedding-atlas command with all parameters."""
73
+ # Use uvx to run embedding-atlas with required dependencies
74
+ cmd = ["uvx", "--with", "datasets", "embedding-atlas"]
75
+ cmd.append(args.dataset_id)
76
+
77
+ # Add all optional parameters
78
+ if args.model:
79
+ cmd.extend(["--model", args.model])
80
+
81
+ # Always specify text column to avoid interactive prompt
82
+ text_col = args.text_column or "text" # Default to "text" if not specified
83
+ cmd.extend(["--text", text_col])
84
+
85
+ if args.image_column:
86
+ cmd.extend(["--image", args.image_column])
87
+
88
+ if args.split:
89
+ cmd.extend(["--split", args.split])
90
+
91
+ if args.sample:
92
+ cmd.extend(["--sample", str(args.sample)])
93
+
94
+ if args.trust_remote_code:
95
+ cmd.append("--trust-remote-code")
96
+
97
+ if not args.compute_embeddings:
98
+ cmd.append("--no-compute-embeddings")
99
+
100
+ if args.x_column:
101
+ cmd.extend(["--x", args.x_column])
102
+
103
+ if args.y_column:
104
+ cmd.extend(["--y", args.y_column])
105
+
106
+ if args.neighbors_column:
107
+ cmd.extend(["--neighbors", args.neighbors_column])
108
+
109
+ # Add export flag with output path
110
+ export_path = "atlas_export.zip"
111
+ cmd.extend(["--export-application", export_path])
112
+
113
+ return cmd, export_path
114
+
115
+
116
+ def create_space_readme(args) -> str:
117
+ """Generate README.md content for the Space."""
118
+ title = args.space_name.replace("-", " ").title()
119
+
120
+ readme = f"""---
121
+ title: {title}
122
+ emoji: 🗺️
123
+ colorFrom: blue
124
+ colorTo: purple
125
+ sdk: static
126
+ pinned: false
127
+ license: mit
128
+ ---
129
+
130
+ # 🗺️ {title}
131
+
132
+ Interactive embedding visualization of [{args.dataset_id}](https://huggingface.co/datasets/{args.dataset_id}) using [Embedding Atlas](https://github.com/apple/embedding-atlas).
133
+
134
+ ## Features
135
+
136
+ - Interactive embedding visualization
137
+ - Real-time search and filtering
138
+ - Automatic clustering with labels
139
+ - WebGPU-accelerated rendering
140
+ """
141
+
142
+ if args.model:
143
+ readme += f"\n## Model\n\nEmbeddings generated using: `{args.model}`\n"
144
+
145
+ if args.sample:
146
+ readme += f"\n## Data\n\nVisualization includes {args.sample:,} samples from the dataset.\n"
147
+
148
+ readme += """
149
+ ## How to Use
150
+
151
+ - **Click and drag** to navigate
152
+ - **Scroll** to zoom in/out
153
+ - **Click** on points to see details
154
+ - **Search** using the search box
155
+ - **Filter** using metadata panels
156
+
157
+ ---
158
+
159
+ *Generated with [UV Scripts Atlas Export](https://huggingface.co/uv-scripts)*
160
+ """
161
+
162
+ return readme
163
+
164
+
165
+ def extract_and_prepare_static_files(zip_path: str, output_dir: Path) -> None:
166
+ """Extract the exported atlas ZIP and prepare for static deployment."""
167
+ logger.info(f"Extracting {zip_path} to {output_dir}")
168
+
169
+ with zipfile.ZipFile(zip_path, 'r') as zip_ref:
170
+ zip_ref.extractall(output_dir)
171
+
172
+ # The ZIP should contain index.html and associated files
173
+ if not (output_dir / "index.html").exists():
174
+ raise FileNotFoundError("index.html not found in exported atlas")
175
+
176
+ logger.info(f"Extracted {len(list(output_dir.iterdir()))} items")
177
+
178
+
179
+ def deploy_to_space(
180
+ output_dir: Path,
181
+ space_name: str,
182
+ organization: Optional[str] = None,
183
+ private: bool = False,
184
+ hf_token: Optional[str] = None
185
+ ) -> str:
186
+ """Deploy the static files to a HuggingFace Space."""
187
+ api = HfApi(token=hf_token)
188
+
189
+ # Construct full repo ID
190
+ if organization:
191
+ repo_id = f"{organization}/{space_name}"
192
+ else:
193
+ # Get username from API
194
+ user_info = api.whoami()
195
+ username = user_info["name"]
196
+ repo_id = f"{username}/{space_name}"
197
+
198
+ logger.info(f"Creating Space: {repo_id}")
199
+
200
+ # Create the Space repository
201
+ try:
202
+ create_repo(
203
+ repo_id,
204
+ repo_type="space",
205
+ space_sdk="static",
206
+ private=private,
207
+ token=hf_token
208
+ )
209
+ logger.info(f"Created new Space: {repo_id}")
210
+ except Exception as e:
211
+ if "already exists" in str(e):
212
+ logger.info(f"Space {repo_id} already exists, updating...")
213
+ else:
214
+ raise
215
+
216
+ # Upload all files
217
+ logger.info("Uploading files to Space...")
218
+ upload_folder(
219
+ folder_path=str(output_dir),
220
+ repo_id=repo_id,
221
+ repo_type="space",
222
+ token=hf_token
223
+ )
224
+
225
+ space_url = f"https://huggingface.co/spaces/{repo_id}"
226
+ logger.info(f"✅ Space deployed successfully: {space_url}")
227
+
228
+ return space_url
229
+
230
+
231
+ def main():
232
+ # Enable HF Transfer for faster downloads if available
233
+ os.environ.setdefault("HF_HUB_ENABLE_HF_TRANSFER", "1")
234
+
235
+ parser = argparse.ArgumentParser(
236
+ description="Generate and deploy static Embedding Atlas visualizations",
237
+ formatter_class=argparse.RawDescriptionHelpFormatter,
238
+ epilog=__doc__,
239
+ )
240
+
241
+ # Required arguments
242
+ parser.add_argument(
243
+ "dataset_id",
244
+ type=str,
245
+ help="HuggingFace dataset ID to visualize",
246
+ )
247
+
248
+ # Space configuration
249
+ parser.add_argument(
250
+ "--space-name",
251
+ type=str,
252
+ required=True,
253
+ help="Name for the HuggingFace Space",
254
+ )
255
+ parser.add_argument(
256
+ "--organization",
257
+ type=str,
258
+ help="HuggingFace organization (default: your username)",
259
+ )
260
+ parser.add_argument(
261
+ "--private",
262
+ action="store_true",
263
+ help="Make the Space private",
264
+ )
265
+
266
+ # Atlas configuration
267
+ parser.add_argument(
268
+ "--model",
269
+ type=str,
270
+ help="Embedding model to use (e.g., sentence-transformers/all-MiniLM-L6-v2)",
271
+ )
272
+ parser.add_argument(
273
+ "--text-column",
274
+ type=str,
275
+ help="Name of text column (default: auto-detect)",
276
+ )
277
+ parser.add_argument(
278
+ "--image-column",
279
+ type=str,
280
+ help="Name of image column for image datasets",
281
+ )
282
+ parser.add_argument(
283
+ "--split",
284
+ type=str,
285
+ default="train",
286
+ help="Dataset split to use (default: train)",
287
+ )
288
+ parser.add_argument(
289
+ "--sample",
290
+ type=int,
291
+ help="Number of samples to visualize (default: all)",
292
+ )
293
+ parser.add_argument(
294
+ "--trust-remote-code",
295
+ action="store_true",
296
+ help="Trust remote code in dataset/model",
297
+ )
298
+
299
+ # Pre-computed embeddings
300
+ parser.add_argument(
301
+ "--no-compute-embeddings",
302
+ action="store_false",
303
+ dest="compute_embeddings",
304
+ help="Use pre-computed embeddings from dataset",
305
+ )
306
+ parser.add_argument(
307
+ "--x-column",
308
+ type=str,
309
+ help="Column with X coordinates (for pre-computed projections)",
310
+ )
311
+ parser.add_argument(
312
+ "--y-column",
313
+ type=str,
314
+ help="Column with Y coordinates (for pre-computed projections)",
315
+ )
316
+ parser.add_argument(
317
+ "--neighbors-column",
318
+ type=str,
319
+ help="Column with neighbor indices (for pre-computed)",
320
+ )
321
+
322
+ # Additional options
323
+ parser.add_argument(
324
+ "--hf-token",
325
+ type=str,
326
+ help="HuggingFace API token (or set HF_TOKEN env var)",
327
+ )
328
+ parser.add_argument(
329
+ "--local-only",
330
+ action="store_true",
331
+ help="Only generate locally, don't deploy to Space",
332
+ )
333
+ parser.add_argument(
334
+ "--output-dir",
335
+ type=str,
336
+ help="Local directory for output (default: temp directory)",
337
+ )
338
+
339
+ args = parser.parse_args()
340
+
341
+ # Check GPU availability
342
+ if check_gpu_available():
343
+ logger.info("🚀 GPU detected - may accelerate embedding generation")
344
+ else:
345
+ logger.info("💻 Running on CPU - embedding generation may be slower")
346
+
347
+ # Login to HuggingFace if needed
348
+ if not args.local_only:
349
+ hf_token = args.hf_token or os.environ.get("HF_TOKEN")
350
+ if hf_token:
351
+ login(token=hf_token)
352
+ else:
353
+ logger.warning("No HF token provided. You may not be able to push to the Hub.")
354
+ response = input("Continue anyway? (y/n): ")
355
+ if response.lower() != 'y':
356
+ sys.exit(0)
357
+
358
+ # Set up output directory
359
+ if args.output_dir:
360
+ output_dir = Path(args.output_dir)
361
+ output_dir.mkdir(parents=True, exist_ok=True)
362
+ temp_dir = None
363
+ else:
364
+ temp_dir = tempfile.mkdtemp(prefix="atlas_export_")
365
+ output_dir = Path(temp_dir)
366
+ logger.info(f"Using temporary directory: {output_dir}")
367
+
368
+ try:
369
+ # Build and run embedding-atlas command
370
+ cmd, export_path = build_atlas_command(args)
371
+ logger.info(f"Running command: {' '.join(cmd)}")
372
+
373
+ # Run the command
374
+ result = subprocess.run(cmd, capture_output=True, text=True)
375
+
376
+ if result.returncode != 0:
377
+ logger.error(f"Atlas export failed with return code {result.returncode}")
378
+ logger.error(f"STDOUT: {result.stdout}")
379
+ logger.error(f"STDERR: {result.stderr}")
380
+ sys.exit(1)
381
+
382
+ logger.info("✅ Atlas export completed successfully")
383
+
384
+ # Extract the exported files
385
+ extract_and_prepare_static_files(export_path, output_dir)
386
+
387
+ # Create README for the Space
388
+ readme_content = create_space_readme(args)
389
+ (output_dir / "README.md").write_text(readme_content)
390
+
391
+ if args.local_only:
392
+ logger.info(f"✅ Static files prepared in: {output_dir}")
393
+ logger.info("To deploy manually, upload the contents to a HuggingFace Space with sdk: static")
394
+ else:
395
+ # Deploy to HuggingFace Space
396
+ space_url = deploy_to_space(
397
+ output_dir,
398
+ args.space_name,
399
+ args.organization,
400
+ args.private,
401
+ hf_token
402
+ )
403
+
404
+ logger.info(f"\n🎉 Success! Your atlas is live at: {space_url}")
405
+ logger.info(f"The visualization will be available in a few moments.")
406
+
407
+ # Clean up the ZIP file
408
+ if Path(export_path).exists():
409
+ os.remove(export_path)
410
+
411
+ finally:
412
+ # Clean up temp directory if used
413
+ if temp_dir and not args.local_only:
414
+ shutil.rmtree(temp_dir)
415
+ logger.info("Cleaned up temporary files")
416
+
417
+
418
+ if __name__ == "__main__":
419
+ # Show example commands if no args provided
420
+ if len(sys.argv) == 1:
421
+ print("Example commands:\n")
422
+ print("# Basic usage:")
423
+ print("uv run atlas-export.py stanfordnlp/imdb --space-name imdb-atlas\n")
424
+ print("# With custom model and sampling:")
425
+ print("uv run atlas-export.py my-dataset --space-name my-viz --model nomic-ai/nomic-embed-text-v1.5 --sample 10000\n")
426
+ print("# For HF Jobs with GPU:")
427
+ print("hf jobs run --gpu t4 uv run https://huggingface.co/datasets/uv-scripts/build-atlas/raw/main/atlas-export.py dataset --space-name viz --model sentence-transformers/all-mpnet-base-v2\n")
428
+ print("# Local generation only:")
429
+ print("uv run atlas-export.py dataset --space-name test --local-only --output-dir ./atlas-output")
430
+ sys.exit(0)
431
+
432
+ main()