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
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
# /// script
# requires-python = ">=3.10"
# dependencies = [
#     "huggingface-hub[hf_transfer]",
#     "torch",  # For GPU detection
# ]
# ///

"""
Generate static Embedding Atlas visualizations and deploy to HuggingFace Spaces.

This script creates interactive embedding visualizations that run entirely in the browser,
using WebGPU acceleration for smooth performance with millions of points.

Example usage:
    # Basic usage (creates Space from dataset)
    uv run atlas-export.py \
        stanfordnlp/imdb \
        --space-name my-imdb-viz

    # With custom model and configuration
    uv run atlas-export.py \
        beans \
        --space-name bean-disease-atlas \
        --image-column image \
        --model openai/clip-vit-base-patch32 \
        --sample 10000

    # Run on HF Jobs with GPU (requires HF token for Space deployment)
    hf jobs uv run \
        --flavor t4-small \
        https://huggingface.co/datasets/uv-scripts/build-atlas/raw/main/atlas-export.py \
        my-dataset \
        --space-name my-atlas \
        --model nomic-ai/nomic-embed-text-v1.5

    # Use pre-computed embeddings
    uv run atlas-export.py \
        my-dataset-with-embeddings \
        --space-name my-viz \
        --no-compute-embeddings \
        --x-column umap_x \
        --y-column umap_y
"""

import argparse
import logging
import os
import shutil
import subprocess
import sys
import tempfile
import zipfile
from pathlib import Path
from typing import Optional

from huggingface_hub import HfApi, create_repo, get_token, login, upload_folder

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def check_gpu_available() -> bool:
    """Check if GPU is available for computation."""
    try:
        import torch
        return torch.cuda.is_available()
    except ImportError:
        return False


def build_atlas_command(args) -> list:
    """Build the embedding-atlas command with all parameters."""
    # Use uvx to run embedding-atlas with required dependencies
    cmd = ["uvx", "--with", "datasets", "embedding-atlas"]
    cmd.append(args.dataset_id)
    
    # Add all optional parameters
    if args.model:
        cmd.extend(["--model", args.model])
    
    # Always specify text column to avoid interactive prompt
    text_col = args.text_column or "text"  # Default to "text" if not specified
    cmd.extend(["--text", text_col])
    
    if args.image_column:
        cmd.extend(["--image", args.image_column])
    
    if args.split:
        cmd.extend(["--split", args.split])
    
    if args.sample:
        cmd.extend(["--sample", str(args.sample)])
    
    if args.trust_remote_code:
        cmd.append("--trust-remote-code")
    
    if not args.compute_embeddings:
        cmd.append("--no-compute-embeddings")
        
        if args.x_column:
            cmd.extend(["--x", args.x_column])
        
        if args.y_column:
            cmd.extend(["--y", args.y_column])
        
        if args.neighbors_column:
            cmd.extend(["--neighbors", args.neighbors_column])
    
    # Add export flag with output path
    export_path = "atlas_export.zip"
    cmd.extend(["--export-application", export_path])
    
    return cmd, export_path


def create_space_readme(args) -> str:
    """Generate README.md content for the Space."""
    title = args.space_name.replace("-", " ").title()
    
    readme = f"""---
title: {title}
emoji: ๐Ÿ—บ๏ธ
colorFrom: blue
colorTo: purple
sdk: static
pinned: false
license: mit
---

# ๐Ÿ—บ๏ธ {title}

Interactive embedding visualization of [{args.dataset_id}](https://huggingface.co/datasets/{args.dataset_id}) using [Embedding Atlas](https://github.com/apple/embedding-atlas).

## Features

- Interactive embedding visualization
- Real-time search and filtering
- Automatic clustering with labels
- WebGPU-accelerated rendering
"""
    
    if args.model:
        readme += f"\n## Model\n\nEmbeddings generated using: `{args.model}`\n"
    
    if args.sample:
        readme += f"\n## Data\n\nVisualization includes {args.sample:,} samples from the dataset.\n"
    
    readme += """
## How to Use

- **Click and drag** to navigate
- **Scroll** to zoom in/out
- **Click** on points to see details
- **Search** using the search box
- **Filter** using metadata panels

---

*Generated with [UV Scripts Atlas Export](https://huggingface.co/uv-scripts)*
"""
    
    return readme


def extract_and_prepare_static_files(zip_path: str, output_dir: Path) -> None:
    """Extract the exported atlas ZIP and prepare for static deployment."""
    logger.info(f"Extracting {zip_path} to {output_dir}")
    
    with zipfile.ZipFile(zip_path, 'r') as zip_ref:
        zip_ref.extractall(output_dir)
    
    # The ZIP should contain index.html and associated files
    if not (output_dir / "index.html").exists():
        raise FileNotFoundError("index.html not found in exported atlas")
    
    logger.info(f"Extracted {len(list(output_dir.iterdir()))} items")


def deploy_to_space(
    output_dir: Path,
    space_name: str,
    organization: Optional[str] = None,
    private: bool = False,
    hf_token: Optional[str] = None
) -> str:
    """Deploy the static files to a HuggingFace Space."""
    api = HfApi(token=hf_token)
    
    # Construct full repo ID
    if organization:
        repo_id = f"{organization}/{space_name}"
    else:
        # Get username from API
        user_info = api.whoami()
        username = user_info["name"]
        repo_id = f"{username}/{space_name}"
    
    logger.info(f"Creating Space: {repo_id}")
    
    # Create the Space repository
    try:
        create_repo(
            repo_id,
            repo_type="space",
            space_sdk="static",
            private=private,
            token=hf_token
        )
        logger.info(f"Created new Space: {repo_id}")
    except Exception as e:
        if "already exists" in str(e):
            logger.info(f"Space {repo_id} already exists, updating...")
        else:
            raise
    
    # Upload all files
    logger.info("Uploading files to Space...")
    upload_folder(
        folder_path=str(output_dir),
        repo_id=repo_id,
        repo_type="space",
        token=hf_token
    )
    
    space_url = f"https://huggingface.co/spaces/{repo_id}"
    logger.info(f"โœ… Space deployed successfully: {space_url}")
    
    return space_url


def main():
    # Enable HF Transfer for faster downloads if available
    os.environ.setdefault("HF_HUB_ENABLE_HF_TRANSFER", "1")
    
    parser = argparse.ArgumentParser(
        description="Generate and deploy static Embedding Atlas visualizations",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=__doc__,
    )
    
    # Required arguments
    parser.add_argument(
        "dataset_id",
        type=str,
        help="HuggingFace dataset ID to visualize",
    )
    
    # Space configuration
    parser.add_argument(
        "--space-name",
        type=str,
        required=True,
        help="Name for the HuggingFace Space",
    )
    parser.add_argument(
        "--organization",
        type=str,
        help="HuggingFace organization (default: your username)",
    )
    parser.add_argument(
        "--private",
        action="store_true",
        help="Make the Space private",
    )
    
    # Atlas configuration
    parser.add_argument(
        "--model",
        type=str,
        help="Embedding model to use (e.g., sentence-transformers/all-MiniLM-L6-v2)",
    )
    parser.add_argument(
        "--text-column",
        type=str,
        help="Name of text column (default: auto-detect)",
    )
    parser.add_argument(
        "--image-column",
        type=str,
        help="Name of image column for image datasets",
    )
    parser.add_argument(
        "--split",
        type=str,
        default="train",
        help="Dataset split to use (default: train)",
    )
    parser.add_argument(
        "--sample",
        type=int,
        help="Number of samples to visualize (default: all)",
    )
    parser.add_argument(
        "--trust-remote-code",
        action="store_true",
        help="Trust remote code in dataset/model",
    )
    
    # Pre-computed embeddings
    parser.add_argument(
        "--no-compute-embeddings",
        action="store_false",
        dest="compute_embeddings",
        help="Use pre-computed embeddings from dataset",
    )
    parser.add_argument(
        "--x-column",
        type=str,
        help="Column with X coordinates (for pre-computed projections)",
    )
    parser.add_argument(
        "--y-column",
        type=str,
        help="Column with Y coordinates (for pre-computed projections)",
    )
    parser.add_argument(
        "--neighbors-column",
        type=str,
        help="Column with neighbor indices (for pre-computed)",
    )
    
    # Additional options
    parser.add_argument(
        "--hf-token",
        type=str,
        help="HuggingFace API token (or set HF_TOKEN env var)",
    )
    parser.add_argument(
        "--local-only",
        action="store_true",
        help="Only generate locally, don't deploy to Space",
    )
    parser.add_argument(
        "--output-dir",
        type=str,
        help="Local directory for output (default: temp directory)",
    )
    
    args = parser.parse_args()
    
    # Check GPU availability
    if check_gpu_available():
        logger.info("๐Ÿš€ GPU detected - may accelerate embedding generation")
    else:
        logger.info("๐Ÿ’ป Running on CPU - embedding generation may be slower")
    
    # Login to HuggingFace if needed
    if not args.local_only:
        # Try to get token from various sources
        hf_token = (
            args.hf_token 
            or os.environ.get("HF_TOKEN")
            or os.environ.get("HUGGING_FACE_HUB_TOKEN")
            or get_token()  # This will check HF CLI login
        )
        
        if hf_token:
            login(token=hf_token)
            logger.info("โœ… Authenticated with Hugging Face")
        else:
            # Check if running in non-interactive environment (HF Jobs, CI, etc.)
            is_interactive = sys.stdin.isatty()
            
            if is_interactive:
                logger.warning("No HF token provided. You may not be able to push to the Hub.")
                response = input("Continue anyway? (y/n): ")
                if response.lower() != 'y':
                    sys.exit(0)
            else:
                # In non-interactive environments, fail immediately if no token
                logger.error("No HF token found. Cannot deploy to Space in non-interactive environment.")
                logger.error("Please set HF_TOKEN environment variable or use --hf-token argument.")
                logger.error("Checked: HF_TOKEN, HUGGING_FACE_HUB_TOKEN, and HF CLI login")
                sys.exit(1)
    
    # Set up output directory
    if args.output_dir:
        output_dir = Path(args.output_dir)
        output_dir.mkdir(parents=True, exist_ok=True)
        temp_dir = None
    else:
        temp_dir = tempfile.mkdtemp(prefix="atlas_export_")
        output_dir = Path(temp_dir)
        logger.info(f"Using temporary directory: {output_dir}")
    
    try:
        # Build and run embedding-atlas command
        cmd, export_path = build_atlas_command(args)
        logger.info(f"Running command: {' '.join(cmd)}")
        
        # Run the command
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        if result.returncode != 0:
            logger.error(f"Atlas export failed with return code {result.returncode}")
            logger.error(f"STDOUT: {result.stdout}")
            logger.error(f"STDERR: {result.stderr}")
            sys.exit(1)
        
        logger.info("โœ… Atlas export completed successfully")
        
        # Extract the exported files
        extract_and_prepare_static_files(export_path, output_dir)
        
        # Create README for the Space
        readme_content = create_space_readme(args)
        (output_dir / "README.md").write_text(readme_content)
        
        if args.local_only:
            logger.info(f"โœ… Static files prepared in: {output_dir}")
            logger.info("To deploy manually, upload the contents to a HuggingFace Space with sdk: static")
        else:
            # Deploy to HuggingFace Space
            space_url = deploy_to_space(
                output_dir,
                args.space_name,
                args.organization,
                args.private,
                hf_token
            )
            
            logger.info(f"\n๐ŸŽ‰ Success! Your atlas is live at: {space_url}")
            logger.info(f"The visualization will be available in a few moments.")
        
        # Clean up the ZIP file
        if Path(export_path).exists():
            os.remove(export_path)
        
    finally:
        # Clean up temp directory if used
        if temp_dir and not args.local_only:
            shutil.rmtree(temp_dir)
            logger.info("Cleaned up temporary files")


if __name__ == "__main__":
    # Show example commands if no args provided
    if len(sys.argv) == 1:
        print("Example commands:\n")
        print("# Basic usage:")
        print("uv run atlas-export.py stanfordnlp/imdb --space-name imdb-atlas\n")
        print("# With custom model and sampling:")
        print("uv run atlas-export.py my-dataset --space-name my-viz --model nomic-ai/nomic-embed-text-v1.5 --sample 10000\n")
        print("# For HF Jobs with GPU (experimental UV support):")
        print("hf jobs uv run --flavor t4-small 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")
        print("# Local generation only:")
        print("uv run atlas-export.py dataset --space-name test --local-only --output-dir ./atlas-output")
        sys.exit(0)
    
    main()