davanstrien HF Staff commited on
Commit
31ad4fe
ยท
1 Parent(s): ab2fedd

Refactor atlas-export.py for improved readability and maintainability

Browse files
Files changed (1) hide show
  1. atlas-export.py +93 -75
atlas-export.py CHANGED
@@ -65,6 +65,7 @@ def check_gpu_available() -> bool:
65
  """Check if GPU is available for computation."""
66
  try:
67
  import torch
 
68
  return torch.cuda.is_available()
69
  except ImportError:
70
  return False
@@ -74,52 +75,58 @@ def build_atlas_command(args) -> list:
74
  """Build the embedding-atlas command with all parameters."""
75
  # Use uvx to run embedding-atlas with required dependencies
76
  # Include hf-transfer for faster downloads when HF_HUB_ENABLE_HF_TRANSFER is set
77
- cmd = ["uvx", "--with", "datasets", "--with", "hf-transfer", "embedding-atlas"]
78
- cmd.append(args.dataset_id)
79
-
 
 
 
 
 
 
80
  # Add all optional parameters
81
  if args.model:
82
  cmd.extend(["--model", args.model])
83
-
84
  # Always specify text column to avoid interactive prompt
85
  text_col = args.text_column or "text" # Default to "text" if not specified
86
  cmd.extend(["--text", text_col])
87
-
88
  if args.image_column:
89
  cmd.extend(["--image", args.image_column])
90
-
91
  if args.split:
92
  cmd.extend(["--split", args.split])
93
-
94
  if args.sample:
95
  cmd.extend(["--sample", str(args.sample)])
96
-
97
  if args.trust_remote_code:
98
  cmd.append("--trust-remote-code")
99
-
100
  if not args.compute_embeddings:
101
  cmd.append("--no-compute-embeddings")
102
-
103
  if args.x_column:
104
  cmd.extend(["--x", args.x_column])
105
-
106
  if args.y_column:
107
  cmd.extend(["--y", args.y_column])
108
-
109
  if args.neighbors_column:
110
  cmd.extend(["--neighbors", args.neighbors_column])
111
-
112
  # Add export flag with output path
113
  export_path = "atlas_export.zip"
114
  cmd.extend(["--export-application", export_path])
115
-
116
  return cmd, export_path
117
 
118
 
119
  def create_space_readme(args) -> str:
120
  """Generate README.md content for the Space."""
121
  title = args.space_name.replace("-", " ").title()
122
-
123
  readme = f"""---
124
  title: {title}
125
  emoji: ๐Ÿ—บ๏ธ
@@ -141,13 +148,13 @@ Interactive embedding visualization of [{args.dataset_id}](https://huggingface.c
141
  - Automatic clustering with labels
142
  - WebGPU-accelerated rendering
143
  """
144
-
145
  if args.model:
146
  readme += f"\n## Model\n\nEmbeddings generated using: `{args.model}`\n"
147
-
148
  if args.sample:
149
  readme += f"\n## Data\n\nVisualization includes {args.sample:,} samples from the dataset.\n"
150
-
151
  readme += """
152
  ## How to Use
153
 
@@ -161,21 +168,21 @@ Interactive embedding visualization of [{args.dataset_id}](https://huggingface.c
161
 
162
  *Generated with [UV Scripts Atlas Export](https://huggingface.co/uv-scripts)*
163
  """
164
-
165
  return readme
166
 
167
 
168
  def extract_and_prepare_static_files(zip_path: str, output_dir: Path) -> None:
169
  """Extract the exported atlas ZIP and prepare for static deployment."""
170
  logger.info(f"Extracting {zip_path} to {output_dir}")
171
-
172
- with zipfile.ZipFile(zip_path, 'r') as zip_ref:
173
  zip_ref.extractall(output_dir)
174
-
175
  # The ZIP should contain index.html and associated files
176
  if not (output_dir / "index.html").exists():
177
  raise FileNotFoundError("index.html not found in exported atlas")
178
-
179
  logger.info(f"Extracted {len(list(output_dir.iterdir()))} items")
180
 
181
 
@@ -184,11 +191,11 @@ def deploy_to_space(
184
  space_name: str,
185
  organization: Optional[str] = None,
186
  private: bool = False,
187
- hf_token: Optional[str] = None
188
  ) -> str:
189
  """Deploy the static files to a HuggingFace Space."""
190
  api = HfApi(token=hf_token)
191
-
192
  # Construct full repo ID
193
  if organization:
194
  repo_id = f"{organization}/{space_name}"
@@ -197,9 +204,9 @@ def deploy_to_space(
197
  user_info = api.whoami()
198
  username = user_info["name"]
199
  repo_id = f"{username}/{space_name}"
200
-
201
  logger.info(f"Creating Space: {repo_id}")
202
-
203
  # Create the Space repository
204
  try:
205
  create_repo(
@@ -207,7 +214,7 @@ def deploy_to_space(
207
  repo_type="space",
208
  space_sdk="static",
209
  private=private,
210
- token=hf_token
211
  )
212
  logger.info(f"Created new Space: {repo_id}")
213
  except Exception as e:
@@ -215,39 +222,36 @@ def deploy_to_space(
215
  logger.info(f"Space {repo_id} already exists, updating...")
216
  else:
217
  raise
218
-
219
  # Upload all files
220
  logger.info("Uploading files to Space...")
221
  upload_folder(
222
- folder_path=str(output_dir),
223
- repo_id=repo_id,
224
- repo_type="space",
225
- token=hf_token
226
  )
227
-
228
  space_url = f"https://huggingface.co/spaces/{repo_id}"
229
  logger.info(f"โœ… Space deployed successfully: {space_url}")
230
-
231
  return space_url
232
 
233
 
234
  def main():
235
  # Enable HF Transfer for faster downloads if available
236
  os.environ.setdefault("HF_HUB_ENABLE_HF_TRANSFER", "1")
237
-
238
  parser = argparse.ArgumentParser(
239
  description="Generate and deploy static Embedding Atlas visualizations",
240
  formatter_class=argparse.RawDescriptionHelpFormatter,
241
  epilog=__doc__,
242
  )
243
-
244
  # Required arguments
245
  parser.add_argument(
246
  "dataset_id",
247
  type=str,
248
  help="HuggingFace dataset ID to visualize",
249
  )
250
-
251
  # Space configuration
252
  parser.add_argument(
253
  "--space-name",
@@ -265,7 +269,7 @@ def main():
265
  action="store_true",
266
  help="Make the Space private",
267
  )
268
-
269
  # Atlas configuration
270
  parser.add_argument(
271
  "--model",
@@ -298,7 +302,7 @@ def main():
298
  action="store_true",
299
  help="Trust remote code in dataset/model",
300
  )
301
-
302
  # Pre-computed embeddings
303
  parser.add_argument(
304
  "--no-compute-embeddings",
@@ -321,7 +325,7 @@ def main():
321
  type=str,
322
  help="Column with neighbor indices (for pre-computed)",
323
  )
324
-
325
  # Additional options
326
  parser.add_argument(
327
  "--hf-token",
@@ -338,44 +342,52 @@ def main():
338
  type=str,
339
  help="Local directory for output (default: temp directory)",
340
  )
341
-
342
  args = parser.parse_args()
343
-
344
  # Check GPU availability
345
  if check_gpu_available():
346
  logger.info("๐Ÿš€ GPU detected - may accelerate embedding generation")
347
  else:
348
  logger.info("๐Ÿ’ป Running on CPU - embedding generation may be slower")
349
-
350
  # Login to HuggingFace if needed
351
  if not args.local_only:
352
  # Try to get token from various sources
353
  hf_token = (
354
- args.hf_token
355
  or os.environ.get("HF_TOKEN")
356
  or os.environ.get("HUGGING_FACE_HUB_TOKEN")
357
  or get_token() # This will check HF CLI login
358
  )
359
-
360
  if hf_token:
361
  login(token=hf_token)
362
  logger.info("โœ… Authenticated with Hugging Face")
363
  else:
364
  # Check if running in non-interactive environment (HF Jobs, CI, etc.)
365
  is_interactive = sys.stdin.isatty()
366
-
367
  if is_interactive:
368
- logger.warning("No HF token provided. You may not be able to push to the Hub.")
 
 
369
  response = input("Continue anyway? (y/n): ")
370
- if response.lower() != 'y':
371
  sys.exit(0)
372
  else:
373
  # In non-interactive environments, fail immediately if no token
374
- logger.error("No HF token found. Cannot deploy to Space in non-interactive environment.")
375
- logger.error("Please set HF_TOKEN environment variable or use --hf-token argument.")
376
- logger.error("Checked: HF_TOKEN, HUGGING_FACE_HUB_TOKEN, and HF CLI login")
 
 
 
 
 
 
377
  sys.exit(1)
378
-
379
  # Set up output directory
380
  if args.output_dir:
381
  output_dir = Path(args.output_dir)
@@ -385,50 +397,48 @@ def main():
385
  temp_dir = tempfile.mkdtemp(prefix="atlas_export_")
386
  output_dir = Path(temp_dir)
387
  logger.info(f"Using temporary directory: {output_dir}")
388
-
389
  try:
390
  # Build and run embedding-atlas command
391
  cmd, export_path = build_atlas_command(args)
392
  logger.info(f"Running command: {' '.join(cmd)}")
393
-
394
  # Run the command
395
  result = subprocess.run(cmd, capture_output=True, text=True)
396
-
397
  if result.returncode != 0:
398
  logger.error(f"Atlas export failed with return code {result.returncode}")
399
  logger.error(f"STDOUT: {result.stdout}")
400
  logger.error(f"STDERR: {result.stderr}")
401
  sys.exit(1)
402
-
403
  logger.info("โœ… Atlas export completed successfully")
404
-
405
  # Extract the exported files
406
  extract_and_prepare_static_files(export_path, output_dir)
407
-
408
  # Create README for the Space
409
  readme_content = create_space_readme(args)
410
  (output_dir / "README.md").write_text(readme_content)
411
-
412
  if args.local_only:
413
  logger.info(f"โœ… Static files prepared in: {output_dir}")
414
- logger.info("To deploy manually, upload the contents to a HuggingFace Space with sdk: static")
 
 
415
  else:
416
  # Deploy to HuggingFace Space
417
  space_url = deploy_to_space(
418
- output_dir,
419
- args.space_name,
420
- args.organization,
421
- args.private,
422
- hf_token
423
  )
424
-
425
  logger.info(f"\n๐ŸŽ‰ Success! Your atlas is live at: {space_url}")
426
  logger.info(f"The visualization will be available in a few moments.")
427
-
428
  # Clean up the ZIP file
429
  if Path(export_path).exists():
430
  os.remove(export_path)
431
-
432
  finally:
433
  # Clean up temp directory if used
434
  if temp_dir and not args.local_only:
@@ -443,12 +453,20 @@ if __name__ == "__main__":
443
  print("# Basic usage:")
444
  print("uv run atlas-export.py stanfordnlp/imdb --space-name imdb-atlas\n")
445
  print("# With custom model and sampling:")
446
- print("uv run atlas-export.py my-dataset --space-name my-viz --model nomic-ai/nomic-embed-text-v1.5 --sample 10000\n")
 
 
447
  print("# For HF Jobs with GPU (experimental UV support):")
448
- print("# First get your token: python -c \"from huggingface_hub import get_token; print(get_token())\"")
449
- print("hf jobs uv run --flavor t4-small -s HF_TOKEN=your-token-here 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")
 
 
 
 
450
  print("# Local generation only:")
451
- print("uv run atlas-export.py dataset --space-name test --local-only --output-dir ./atlas-output")
 
 
452
  sys.exit(0)
453
-
454
- main()
 
65
  """Check if GPU is available for computation."""
66
  try:
67
  import torch
68
+
69
  return torch.cuda.is_available()
70
  except ImportError:
71
  return False
 
75
  """Build the embedding-atlas command with all parameters."""
76
  # Use uvx to run embedding-atlas with required dependencies
77
  # Include hf-transfer for faster downloads when HF_HUB_ENABLE_HF_TRANSFER is set
78
+ cmd = [
79
+ "uvx",
80
+ "--with",
81
+ "datasets",
82
+ "--with",
83
+ "hf-transfer",
84
+ "embedding-atlas",
85
+ args.dataset_id,
86
+ ]
87
  # Add all optional parameters
88
  if args.model:
89
  cmd.extend(["--model", args.model])
90
+
91
  # Always specify text column to avoid interactive prompt
92
  text_col = args.text_column or "text" # Default to "text" if not specified
93
  cmd.extend(["--text", text_col])
94
+
95
  if args.image_column:
96
  cmd.extend(["--image", args.image_column])
97
+
98
  if args.split:
99
  cmd.extend(["--split", args.split])
100
+
101
  if args.sample:
102
  cmd.extend(["--sample", str(args.sample)])
103
+
104
  if args.trust_remote_code:
105
  cmd.append("--trust-remote-code")
106
+
107
  if not args.compute_embeddings:
108
  cmd.append("--no-compute-embeddings")
109
+
110
  if args.x_column:
111
  cmd.extend(["--x", args.x_column])
112
+
113
  if args.y_column:
114
  cmd.extend(["--y", args.y_column])
115
+
116
  if args.neighbors_column:
117
  cmd.extend(["--neighbors", args.neighbors_column])
118
+
119
  # Add export flag with output path
120
  export_path = "atlas_export.zip"
121
  cmd.extend(["--export-application", export_path])
122
+
123
  return cmd, export_path
124
 
125
 
126
  def create_space_readme(args) -> str:
127
  """Generate README.md content for the Space."""
128
  title = args.space_name.replace("-", " ").title()
129
+
130
  readme = f"""---
131
  title: {title}
132
  emoji: ๐Ÿ—บ๏ธ
 
148
  - Automatic clustering with labels
149
  - WebGPU-accelerated rendering
150
  """
151
+
152
  if args.model:
153
  readme += f"\n## Model\n\nEmbeddings generated using: `{args.model}`\n"
154
+
155
  if args.sample:
156
  readme += f"\n## Data\n\nVisualization includes {args.sample:,} samples from the dataset.\n"
157
+
158
  readme += """
159
  ## How to Use
160
 
 
168
 
169
  *Generated with [UV Scripts Atlas Export](https://huggingface.co/uv-scripts)*
170
  """
171
+
172
  return readme
173
 
174
 
175
  def extract_and_prepare_static_files(zip_path: str, output_dir: Path) -> None:
176
  """Extract the exported atlas ZIP and prepare for static deployment."""
177
  logger.info(f"Extracting {zip_path} to {output_dir}")
178
+
179
+ with zipfile.ZipFile(zip_path, "r") as zip_ref:
180
  zip_ref.extractall(output_dir)
181
+
182
  # The ZIP should contain index.html and associated files
183
  if not (output_dir / "index.html").exists():
184
  raise FileNotFoundError("index.html not found in exported atlas")
185
+
186
  logger.info(f"Extracted {len(list(output_dir.iterdir()))} items")
187
 
188
 
 
191
  space_name: str,
192
  organization: Optional[str] = None,
193
  private: bool = False,
194
+ hf_token: Optional[str] = None,
195
  ) -> str:
196
  """Deploy the static files to a HuggingFace Space."""
197
  api = HfApi(token=hf_token)
198
+
199
  # Construct full repo ID
200
  if organization:
201
  repo_id = f"{organization}/{space_name}"
 
204
  user_info = api.whoami()
205
  username = user_info["name"]
206
  repo_id = f"{username}/{space_name}"
207
+
208
  logger.info(f"Creating Space: {repo_id}")
209
+
210
  # Create the Space repository
211
  try:
212
  create_repo(
 
214
  repo_type="space",
215
  space_sdk="static",
216
  private=private,
217
+ token=hf_token,
218
  )
219
  logger.info(f"Created new Space: {repo_id}")
220
  except Exception as e:
 
222
  logger.info(f"Space {repo_id} already exists, updating...")
223
  else:
224
  raise
225
+
226
  # Upload all files
227
  logger.info("Uploading files to Space...")
228
  upload_folder(
229
+ folder_path=str(output_dir), repo_id=repo_id, repo_type="space", token=hf_token
 
 
 
230
  )
231
+
232
  space_url = f"https://huggingface.co/spaces/{repo_id}"
233
  logger.info(f"โœ… Space deployed successfully: {space_url}")
234
+
235
  return space_url
236
 
237
 
238
  def main():
239
  # Enable HF Transfer for faster downloads if available
240
  os.environ.setdefault("HF_HUB_ENABLE_HF_TRANSFER", "1")
241
+
242
  parser = argparse.ArgumentParser(
243
  description="Generate and deploy static Embedding Atlas visualizations",
244
  formatter_class=argparse.RawDescriptionHelpFormatter,
245
  epilog=__doc__,
246
  )
247
+
248
  # Required arguments
249
  parser.add_argument(
250
  "dataset_id",
251
  type=str,
252
  help="HuggingFace dataset ID to visualize",
253
  )
254
+
255
  # Space configuration
256
  parser.add_argument(
257
  "--space-name",
 
269
  action="store_true",
270
  help="Make the Space private",
271
  )
272
+
273
  # Atlas configuration
274
  parser.add_argument(
275
  "--model",
 
302
  action="store_true",
303
  help="Trust remote code in dataset/model",
304
  )
305
+
306
  # Pre-computed embeddings
307
  parser.add_argument(
308
  "--no-compute-embeddings",
 
325
  type=str,
326
  help="Column with neighbor indices (for pre-computed)",
327
  )
328
+
329
  # Additional options
330
  parser.add_argument(
331
  "--hf-token",
 
342
  type=str,
343
  help="Local directory for output (default: temp directory)",
344
  )
345
+
346
  args = parser.parse_args()
347
+
348
  # Check GPU availability
349
  if check_gpu_available():
350
  logger.info("๐Ÿš€ GPU detected - may accelerate embedding generation")
351
  else:
352
  logger.info("๐Ÿ’ป Running on CPU - embedding generation may be slower")
353
+
354
  # Login to HuggingFace if needed
355
  if not args.local_only:
356
  # Try to get token from various sources
357
  hf_token = (
358
+ args.hf_token
359
  or os.environ.get("HF_TOKEN")
360
  or os.environ.get("HUGGING_FACE_HUB_TOKEN")
361
  or get_token() # This will check HF CLI login
362
  )
363
+
364
  if hf_token:
365
  login(token=hf_token)
366
  logger.info("โœ… Authenticated with Hugging Face")
367
  else:
368
  # Check if running in non-interactive environment (HF Jobs, CI, etc.)
369
  is_interactive = sys.stdin.isatty()
370
+
371
  if is_interactive:
372
+ logger.warning(
373
+ "No HF token provided. You may not be able to push to the Hub."
374
+ )
375
  response = input("Continue anyway? (y/n): ")
376
+ if response.lower() != "y":
377
  sys.exit(0)
378
  else:
379
  # In non-interactive environments, fail immediately if no token
380
+ logger.error(
381
+ "No HF token found. Cannot deploy to Space in non-interactive environment."
382
+ )
383
+ logger.error(
384
+ "Please set HF_TOKEN environment variable or use --hf-token argument."
385
+ )
386
+ logger.error(
387
+ "Checked: HF_TOKEN, HUGGING_FACE_HUB_TOKEN, and HF CLI login"
388
+ )
389
  sys.exit(1)
390
+
391
  # Set up output directory
392
  if args.output_dir:
393
  output_dir = Path(args.output_dir)
 
397
  temp_dir = tempfile.mkdtemp(prefix="atlas_export_")
398
  output_dir = Path(temp_dir)
399
  logger.info(f"Using temporary directory: {output_dir}")
400
+
401
  try:
402
  # Build and run embedding-atlas command
403
  cmd, export_path = build_atlas_command(args)
404
  logger.info(f"Running command: {' '.join(cmd)}")
405
+
406
  # Run the command
407
  result = subprocess.run(cmd, capture_output=True, text=True)
408
+
409
  if result.returncode != 0:
410
  logger.error(f"Atlas export failed with return code {result.returncode}")
411
  logger.error(f"STDOUT: {result.stdout}")
412
  logger.error(f"STDERR: {result.stderr}")
413
  sys.exit(1)
414
+
415
  logger.info("โœ… Atlas export completed successfully")
416
+
417
  # Extract the exported files
418
  extract_and_prepare_static_files(export_path, output_dir)
419
+
420
  # Create README for the Space
421
  readme_content = create_space_readme(args)
422
  (output_dir / "README.md").write_text(readme_content)
423
+
424
  if args.local_only:
425
  logger.info(f"โœ… Static files prepared in: {output_dir}")
426
+ logger.info(
427
+ "To deploy manually, upload the contents to a HuggingFace Space with sdk: static"
428
+ )
429
  else:
430
  # Deploy to HuggingFace Space
431
  space_url = deploy_to_space(
432
+ output_dir, args.space_name, args.organization, args.private, hf_token
 
 
 
 
433
  )
434
+
435
  logger.info(f"\n๐ŸŽ‰ Success! Your atlas is live at: {space_url}")
436
  logger.info(f"The visualization will be available in a few moments.")
437
+
438
  # Clean up the ZIP file
439
  if Path(export_path).exists():
440
  os.remove(export_path)
441
+
442
  finally:
443
  # Clean up temp directory if used
444
  if temp_dir and not args.local_only:
 
453
  print("# Basic usage:")
454
  print("uv run atlas-export.py stanfordnlp/imdb --space-name imdb-atlas\n")
455
  print("# With custom model and sampling:")
456
+ print(
457
+ "uv run atlas-export.py my-dataset --space-name my-viz --model nomic-ai/nomic-embed-text-v1.5 --sample 10000\n"
458
+ )
459
  print("# For HF Jobs with GPU (experimental UV support):")
460
+ print(
461
+ '# First get your token: python -c "from huggingface_hub import get_token; print(get_token())"'
462
+ )
463
+ print(
464
+ "hf jobs uv run --flavor t4-small -s HF_TOKEN=your-token-here 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"
465
+ )
466
  print("# Local generation only:")
467
+ print(
468
+ "uv run atlas-export.py dataset --space-name test --local-only --output-dir ./atlas-output"
469
+ )
470
  sys.exit(0)
471
+
472
+ main()