Commit ·
f93691f
1
Parent(s): 8811bbd
Add bucket-based atlas pipeline: build, deploy, and e2e scripts
Browse filesNew pipeline using HF Jobs + Storage Buckets + Spaces for building
and deploying large-scale Embedding Atlas visualizations:
- atlas-build-gpu.py: GPU atlas build with cuml.accel UMAP (~50x speedup)
- atlas-deploy.py: Deploy Docker Space from bucket data
- atlas-e2e.py: End-to-end orchestrator (experimental)
- atlas-build-gpu-test.py: Test script used during development
- hn-prep.py: DuckDB prep for Hacker News stories
- open-library-prep.py: DuckDB prep for Open Library works
- atlas-export-remote.py: Add --batch-size flag
Validated with 2M Open Library books (40 min on A100) and 1M TinyStories.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- atlas-build-gpu-test.py +86 -0
- atlas-build-gpu.py +132 -0
- atlas-deploy.py +203 -0
- atlas-e2e.py +218 -0
- atlas-export-remote.py +10 -4
- hn-prep.py +94 -0
- open-library-prep.py +104 -0
atlas-build-gpu-test.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.10"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "embedding-atlas>=0.18.0",
|
| 5 |
+
# "datasets",
|
| 6 |
+
# "cuml-cu12",
|
| 7 |
+
# ]
|
| 8 |
+
#
|
| 9 |
+
# [[tool.uv.index]]
|
| 10 |
+
# url = "https://pypi.nvidia.com/simple"
|
| 11 |
+
# ///
|
| 12 |
+
|
| 13 |
+
"""Test GPU UMAP via cuml.accel with embedding-atlas."""
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import subprocess
|
| 17 |
+
import sys
|
| 18 |
+
import time
|
| 19 |
+
|
| 20 |
+
# Enable cuml acceleration before anything imports umap
|
| 21 |
+
os.environ["CUML_ACCEL_ENABLED"] = "1"
|
| 22 |
+
|
| 23 |
+
def main():
|
| 24 |
+
import argparse
|
| 25 |
+
parser = argparse.ArgumentParser()
|
| 26 |
+
parser.add_argument("input", help="Dataset path or mount path (e.g. /input/dataset.parquet)")
|
| 27 |
+
parser.add_argument("--sample", type=int, default=None)
|
| 28 |
+
parser.add_argument("--output", default="/output/atlas")
|
| 29 |
+
parser.add_argument("--text", default="text")
|
| 30 |
+
parser.add_argument("--split", default=None)
|
| 31 |
+
parser.add_argument("--batch-size", type=int, default=256)
|
| 32 |
+
args = parser.parse_args()
|
| 33 |
+
|
| 34 |
+
print(f"Input: {args.input}")
|
| 35 |
+
print(f"Sample: {args.sample}")
|
| 36 |
+
print(f"Output: {args.output}")
|
| 37 |
+
print(f"Batch size: {args.batch_size}")
|
| 38 |
+
print(f"CUML_ACCEL_ENABLED={os.environ.get('CUML_ACCEL_ENABLED')}")
|
| 39 |
+
|
| 40 |
+
# Verify cuml is available
|
| 41 |
+
try:
|
| 42 |
+
import cuml
|
| 43 |
+
print(f"cuML version: {cuml.__version__}")
|
| 44 |
+
except ImportError as e:
|
| 45 |
+
print(f"WARNING: cuml not available: {e}")
|
| 46 |
+
|
| 47 |
+
# Verify GPU
|
| 48 |
+
try:
|
| 49 |
+
import torch
|
| 50 |
+
print(f"CUDA available: {torch.cuda.is_available()}")
|
| 51 |
+
if torch.cuda.is_available():
|
| 52 |
+
print(f"GPU: {torch.cuda.get_device_name()}")
|
| 53 |
+
except ImportError:
|
| 54 |
+
print("torch not installed, skipping GPU check")
|
| 55 |
+
|
| 56 |
+
start = time.time()
|
| 57 |
+
|
| 58 |
+
cmd = [
|
| 59 |
+
"embedding-atlas",
|
| 60 |
+
args.input,
|
| 61 |
+
"--text", args.text,
|
| 62 |
+
"--batch-size", str(args.batch_size),
|
| 63 |
+
"--export-application", args.output,
|
| 64 |
+
]
|
| 65 |
+
|
| 66 |
+
if args.split:
|
| 67 |
+
cmd.extend(["--split", args.split])
|
| 68 |
+
|
| 69 |
+
if args.sample:
|
| 70 |
+
cmd.extend(["--sample", str(args.sample)])
|
| 71 |
+
|
| 72 |
+
print(f"\nRunning: {' '.join(cmd)}")
|
| 73 |
+
result = subprocess.run(cmd, env=os.environ)
|
| 74 |
+
|
| 75 |
+
elapsed = time.time() - start
|
| 76 |
+
print(f"\nCompleted in {elapsed:.1f}s (exit code: {result.returncode})")
|
| 77 |
+
|
| 78 |
+
if result.returncode == 0:
|
| 79 |
+
# Check output
|
| 80 |
+
parquet = os.path.join(args.output, "data", "dataset.parquet")
|
| 81 |
+
if os.path.exists(parquet):
|
| 82 |
+
size_mb = os.path.getsize(parquet) / (1024**2)
|
| 83 |
+
print(f"Output parquet: {size_mb:.1f} MB")
|
| 84 |
+
|
| 85 |
+
if __name__ == "__main__":
|
| 86 |
+
main()
|
atlas-build-gpu.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.10"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "embedding-atlas>=0.19.1",
|
| 5 |
+
# "datasets",
|
| 6 |
+
# "cuml-cu12",
|
| 7 |
+
# ]
|
| 8 |
+
#
|
| 9 |
+
# [[tool.uv.index]]
|
| 10 |
+
# url = "https://pypi.nvidia.com/simple"
|
| 11 |
+
# ///
|
| 12 |
+
|
| 13 |
+
"""Build an Embedding Atlas visualization with GPU-accelerated UMAP.
|
| 14 |
+
|
| 15 |
+
Runs embedding-atlas with cuml.accel for ~50x faster UMAP on GPU.
|
| 16 |
+
Designed to run as an HF Job with a bucket volume mount for output.
|
| 17 |
+
|
| 18 |
+
Examples:
|
| 19 |
+
|
| 20 |
+
# From a prepped parquet in a bucket
|
| 21 |
+
hf jobs uv run --flavor a100-large \\
|
| 22 |
+
-v hf://buckets/user/atlas-data:/data \\
|
| 23 |
+
-s HF_TOKEN --timeout 2h \\
|
| 24 |
+
atlas-build-gpu.py /data/books.parquet \\
|
| 25 |
+
--text title --sample 2000000 --name my-atlas
|
| 26 |
+
|
| 27 |
+
# From an HF dataset
|
| 28 |
+
hf jobs uv run --flavor a100-large \\
|
| 29 |
+
-v hf://buckets/user/atlas-data:/data \\
|
| 30 |
+
-s HF_TOKEN --timeout 2h \\
|
| 31 |
+
atlas-build-gpu.py stanfordnlp/imdb \\
|
| 32 |
+
--text text --split train --name imdb-atlas
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
import argparse
|
| 36 |
+
import json
|
| 37 |
+
import os
|
| 38 |
+
import subprocess
|
| 39 |
+
import sys
|
| 40 |
+
import time
|
| 41 |
+
|
| 42 |
+
os.environ["CUML_ACCEL_ENABLED"] = "1"
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def main():
|
| 46 |
+
parser = argparse.ArgumentParser(description="Build an Embedding Atlas with GPU UMAP")
|
| 47 |
+
parser.add_argument("input", help="Parquet path or HF dataset ID")
|
| 48 |
+
parser.add_argument("--name", required=True, help="Atlas name (output subdirectory)")
|
| 49 |
+
parser.add_argument("--text", default="text", help="Text column name")
|
| 50 |
+
parser.add_argument("--image", default=None, help="Image column name")
|
| 51 |
+
parser.add_argument("--split", default=None, help="Dataset split")
|
| 52 |
+
parser.add_argument("--sample", type=int, default=None, help="Number of rows to sample")
|
| 53 |
+
parser.add_argument("--batch-size", type=int, default=256, help="Embedding batch size")
|
| 54 |
+
parser.add_argument("--model", default=None, help="Embedding model name")
|
| 55 |
+
parser.add_argument("--output-dir", default="/data", help="Base output directory")
|
| 56 |
+
args = parser.parse_args()
|
| 57 |
+
|
| 58 |
+
atlas_output = os.path.join(args.output_dir, args.name)
|
| 59 |
+
config_path = os.path.join(atlas_output, "atlas-config.json")
|
| 60 |
+
|
| 61 |
+
print(f"Input: {args.input}")
|
| 62 |
+
print(f"Name: {args.name}")
|
| 63 |
+
print(f"Output: {atlas_output}")
|
| 64 |
+
print(f"Sample: {args.sample}")
|
| 65 |
+
print(f"Batch size: {args.batch_size}")
|
| 66 |
+
|
| 67 |
+
# Report GPU/cuml status
|
| 68 |
+
gpu_info = {}
|
| 69 |
+
try:
|
| 70 |
+
import cuml
|
| 71 |
+
print(f"cuML: {cuml.__version__}")
|
| 72 |
+
gpu_info["cuml_version"] = cuml.__version__
|
| 73 |
+
except ImportError:
|
| 74 |
+
print("WARNING: cuml not available, falling back to CPU UMAP")
|
| 75 |
+
|
| 76 |
+
try:
|
| 77 |
+
import torch
|
| 78 |
+
if torch.cuda.is_available():
|
| 79 |
+
gpu_info["gpu"] = torch.cuda.get_device_name()
|
| 80 |
+
print(f"GPU: {gpu_info['gpu']}")
|
| 81 |
+
except ImportError:
|
| 82 |
+
pass
|
| 83 |
+
|
| 84 |
+
start = time.time()
|
| 85 |
+
|
| 86 |
+
cmd = ["embedding-atlas", args.input, "--text", args.text,
|
| 87 |
+
"--batch-size", str(args.batch_size),
|
| 88 |
+
"--export-application", atlas_output]
|
| 89 |
+
|
| 90 |
+
if args.image:
|
| 91 |
+
cmd.extend(["--image", args.image])
|
| 92 |
+
if args.model:
|
| 93 |
+
cmd.extend(["--model", args.model])
|
| 94 |
+
if args.split:
|
| 95 |
+
cmd.extend(["--split", args.split])
|
| 96 |
+
if args.sample:
|
| 97 |
+
cmd.extend(["--sample", str(args.sample)])
|
| 98 |
+
|
| 99 |
+
print(f"\nRunning: {' '.join(cmd)}\n")
|
| 100 |
+
result = subprocess.run(cmd, env=os.environ)
|
| 101 |
+
elapsed = time.time() - start
|
| 102 |
+
|
| 103 |
+
if result.returncode != 0:
|
| 104 |
+
print(f"\nFailed with exit code {result.returncode} after {elapsed:.1f}s")
|
| 105 |
+
sys.exit(result.returncode)
|
| 106 |
+
|
| 107 |
+
# Write config sidecar for atlas-deploy.py
|
| 108 |
+
parquet_path = os.path.join(atlas_output, "data", "dataset.parquet")
|
| 109 |
+
parquet_mb = os.path.getsize(parquet_path) / (1024**2) if os.path.exists(parquet_path) else 0
|
| 110 |
+
|
| 111 |
+
config = {
|
| 112 |
+
"name": args.name,
|
| 113 |
+
"text_column": args.text,
|
| 114 |
+
"image_column": args.image,
|
| 115 |
+
"model": args.model,
|
| 116 |
+
"sample": args.sample,
|
| 117 |
+
"input": args.input,
|
| 118 |
+
"parquet_size_mb": round(parquet_mb, 1),
|
| 119 |
+
"build_time_seconds": round(elapsed, 1),
|
| 120 |
+
"gpu_info": gpu_info,
|
| 121 |
+
}
|
| 122 |
+
os.makedirs(os.path.dirname(config_path), exist_ok=True)
|
| 123 |
+
with open(config_path, "w") as f:
|
| 124 |
+
json.dump(config, f, indent=2)
|
| 125 |
+
|
| 126 |
+
print(f"\nCompleted in {elapsed:.1f}s")
|
| 127 |
+
print(f"Parquet: {parquet_mb:.1f} MB")
|
| 128 |
+
print(f"Config: {config_path}")
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
if __name__ == "__main__":
|
| 132 |
+
main()
|
atlas-deploy.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.10"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "huggingface-hub>=1.7.0",
|
| 5 |
+
# ]
|
| 6 |
+
# ///
|
| 7 |
+
|
| 8 |
+
"""Deploy an Embedding Atlas Space from bucket data.
|
| 9 |
+
|
| 10 |
+
Reads atlas-config.json from the bucket to generate the right Dockerfile,
|
| 11 |
+
creates a Docker Space, and prints instructions to mount the bucket.
|
| 12 |
+
|
| 13 |
+
Examples:
|
| 14 |
+
|
| 15 |
+
# Deploy from existing atlas build in a bucket
|
| 16 |
+
uv run atlas-deploy.py \\
|
| 17 |
+
--name my-atlas \\
|
| 18 |
+
--bucket user/atlas-data \\
|
| 19 |
+
--space-id user/my-atlas-space
|
| 20 |
+
|
| 21 |
+
# With custom Space hardware
|
| 22 |
+
uv run atlas-deploy.py \\
|
| 23 |
+
--name my-atlas \\
|
| 24 |
+
--bucket user/atlas-data \\
|
| 25 |
+
--space-id user/my-atlas-space \\
|
| 26 |
+
--hardware cpu-upgrade
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
import argparse
|
| 30 |
+
import json
|
| 31 |
+
import os
|
| 32 |
+
|
| 33 |
+
from huggingface_hub import HfApi, create_repo, upload_file
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
DOCKERFILE_TEMPLATE = """FROM python:3.12-slim
|
| 37 |
+
|
| 38 |
+
RUN useradd -m -u 1000 user
|
| 39 |
+
RUN pip install --no-cache-dir "embedding-atlas>=0.19.1"
|
| 40 |
+
|
| 41 |
+
USER user
|
| 42 |
+
EXPOSE 7860
|
| 43 |
+
|
| 44 |
+
CMD ["embedding-atlas", \\
|
| 45 |
+
"/data/{name}/data/dataset.parquet", \\
|
| 46 |
+
"--text", "{text_column}", \\
|
| 47 |
+
"--x", "projection_x", \\
|
| 48 |
+
"--y", "projection_y", \\
|
| 49 |
+
"--disable-projection", \\
|
| 50 |
+
"--duckdb", "server", \\
|
| 51 |
+
"--host", "0.0.0.0", \\
|
| 52 |
+
"--port", "7860"]
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
README_TEMPLATE = """---
|
| 56 |
+
title: {title}
|
| 57 |
+
emoji: 🗺️
|
| 58 |
+
colorFrom: blue
|
| 59 |
+
colorTo: purple
|
| 60 |
+
sdk: docker
|
| 61 |
+
pinned: false
|
| 62 |
+
---
|
| 63 |
+
|
| 64 |
+
# 🗺️ {title}
|
| 65 |
+
|
| 66 |
+
Interactive embedding visualization of {sample_desc}.
|
| 67 |
+
|
| 68 |
+
Built with [HF Jobs](https://huggingface.co/docs/hub/jobs) + [Storage Buckets](https://huggingface.co/docs/hub/storage-buckets) + [Embedding Atlas](https://github.com/apple/embedding-atlas).
|
| 69 |
+
|
| 70 |
+
## How it works
|
| 71 |
+
|
| 72 |
+
- **Data**: Stored in a Storage Bucket (mounted read-only)
|
| 73 |
+
- **Server**: embedding-atlas in server mode with DuckDB
|
| 74 |
+
- **Build**: GPU UMAP via cuml.accel ({build_info})
|
| 75 |
+
|
| 76 |
+
## Features
|
| 77 |
+
|
| 78 |
+
- Interactive scatter plot with WebGPU acceleration
|
| 79 |
+
- Real-time search and filtering
|
| 80 |
+
- SQL queries via DuckDB server mode
|
| 81 |
+
- Click points to see details
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def main():
|
| 86 |
+
parser = argparse.ArgumentParser(description="Deploy an Atlas Space from bucket data")
|
| 87 |
+
parser.add_argument("--name", required=True, help="Atlas name (subdirectory in bucket)")
|
| 88 |
+
parser.add_argument("--bucket", required=True, help="Data bucket ID (e.g. user/atlas-data)")
|
| 89 |
+
parser.add_argument("--space-id", default=None, help="Space ID (default: {user}/{name})")
|
| 90 |
+
parser.add_argument("--hardware", default="cpu-basic", help="Space hardware (default: cpu-basic)")
|
| 91 |
+
parser.add_argument("--text-column", default=None, help="Override text column (reads from config if not set)")
|
| 92 |
+
parser.add_argument("--private", action="store_true", help="Make Space private")
|
| 93 |
+
args = parser.parse_args()
|
| 94 |
+
|
| 95 |
+
api = HfApi()
|
| 96 |
+
|
| 97 |
+
# Resolve space ID
|
| 98 |
+
if args.space_id is None:
|
| 99 |
+
user = api.whoami()["name"]
|
| 100 |
+
args.space_id = f"{user}/{args.name}"
|
| 101 |
+
|
| 102 |
+
# Try to read config from bucket
|
| 103 |
+
text_column = args.text_column or "text"
|
| 104 |
+
sample_desc = "dataset"
|
| 105 |
+
build_info = ""
|
| 106 |
+
|
| 107 |
+
try:
|
| 108 |
+
from huggingface_hub import download_bucket_files
|
| 109 |
+
import tempfile
|
| 110 |
+
|
| 111 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 112 |
+
config_remote = f"{args.name}/atlas-config.json"
|
| 113 |
+
config_local = os.path.join(tmp, "atlas-config.json")
|
| 114 |
+
download_bucket_files(args.bucket, files=[(config_remote, config_local)])
|
| 115 |
+
|
| 116 |
+
with open(config_local) as f:
|
| 117 |
+
config = json.load(f)
|
| 118 |
+
|
| 119 |
+
text_column = config.get("text_column", text_column)
|
| 120 |
+
sample = config.get("sample")
|
| 121 |
+
build_time = config.get("build_time_seconds")
|
| 122 |
+
gpu = config.get("gpu_info", {}).get("gpu", "")
|
| 123 |
+
|
| 124 |
+
if sample:
|
| 125 |
+
sample_desc = f"{sample:,} samples"
|
| 126 |
+
if build_time and gpu:
|
| 127 |
+
build_info = f"{build_time:.0f}s on {gpu}"
|
| 128 |
+
elif build_time:
|
| 129 |
+
build_info = f"{build_time:.0f}s"
|
| 130 |
+
|
| 131 |
+
print(f"Read config from bucket: text_column={text_column}, sample={sample}")
|
| 132 |
+
except Exception as e:
|
| 133 |
+
print(f"Could not read atlas-config.json from bucket: {e}")
|
| 134 |
+
print(f"Using defaults: text_column={text_column}")
|
| 135 |
+
|
| 136 |
+
if args.text_column:
|
| 137 |
+
text_column = args.text_column
|
| 138 |
+
|
| 139 |
+
# Create Space
|
| 140 |
+
print(f"\nCreating Space: {args.space_id}")
|
| 141 |
+
create_repo(
|
| 142 |
+
args.space_id,
|
| 143 |
+
repo_type="space",
|
| 144 |
+
space_sdk="docker",
|
| 145 |
+
private=args.private,
|
| 146 |
+
exist_ok=True,
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
# Generate and upload Dockerfile
|
| 150 |
+
dockerfile = DOCKERFILE_TEMPLATE.format(name=args.name, text_column=text_column)
|
| 151 |
+
upload_file(
|
| 152 |
+
path_or_fileobj=dockerfile.encode(),
|
| 153 |
+
path_in_repo="Dockerfile",
|
| 154 |
+
repo_id=args.space_id,
|
| 155 |
+
repo_type="space",
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
# Generate and upload README
|
| 159 |
+
title = args.name.replace("-", " ").replace("_", " ").title()
|
| 160 |
+
readme = README_TEMPLATE.format(
|
| 161 |
+
title=title,
|
| 162 |
+
sample_desc=sample_desc,
|
| 163 |
+
build_info=build_info,
|
| 164 |
+
)
|
| 165 |
+
upload_file(
|
| 166 |
+
path_or_fileobj=readme.encode(),
|
| 167 |
+
path_in_repo="README.md",
|
| 168 |
+
repo_id=args.space_id,
|
| 169 |
+
repo_type="space",
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
# Set hardware
|
| 173 |
+
if args.hardware != "cpu-basic":
|
| 174 |
+
api.request_space_hardware(args.space_id, args.hardware)
|
| 175 |
+
print(f"Hardware: {args.hardware}")
|
| 176 |
+
|
| 177 |
+
# Try programmatic volume mount (requires latest huggingface_hub)
|
| 178 |
+
mounted = False
|
| 179 |
+
try:
|
| 180 |
+
from huggingface_hub._jobs_api import Volume
|
| 181 |
+
api.set_space_volumes(
|
| 182 |
+
args.space_id,
|
| 183 |
+
volumes=[
|
| 184 |
+
Volume(type="bucket", source=args.bucket, mount_path="/data", read_only=True),
|
| 185 |
+
],
|
| 186 |
+
)
|
| 187 |
+
mounted = True
|
| 188 |
+
print(f"Bucket mounted: {args.bucket} -> /data (read-only)")
|
| 189 |
+
except (ImportError, AttributeError):
|
| 190 |
+
pass
|
| 191 |
+
|
| 192 |
+
space_url = f"https://huggingface.co/spaces/{args.space_id}"
|
| 193 |
+
print(f"\nSpace deployed: {space_url}")
|
| 194 |
+
|
| 195 |
+
if not mounted:
|
| 196 |
+
print("\n⚠️ Mount the bucket manually in Space settings:")
|
| 197 |
+
print(f" Bucket: {args.bucket}")
|
| 198 |
+
print(" Mount path: /data")
|
| 199 |
+
print(" Access mode: Read-only")
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
if __name__ == "__main__":
|
| 203 |
+
main()
|
atlas-e2e.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.10"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "huggingface-hub>=1.7.0",
|
| 5 |
+
# ]
|
| 6 |
+
# ///
|
| 7 |
+
|
| 8 |
+
"""Build and deploy an Embedding Atlas end-to-end.
|
| 9 |
+
|
| 10 |
+
Orchestrates the full pipeline:
|
| 11 |
+
1. Creates a storage bucket (if needed)
|
| 12 |
+
2. Submits a GPU Job to build the atlas (embedding + UMAP)
|
| 13 |
+
3. Waits for the Job to complete
|
| 14 |
+
4. Deploys a Docker Space that serves the atlas from the bucket
|
| 15 |
+
|
| 16 |
+
⚠️ EXPERIMENTAL — this workflow is new and may change.
|
| 17 |
+
|
| 18 |
+
Examples:
|
| 19 |
+
|
| 20 |
+
# Minimal — from HF dataset to deployed Space
|
| 21 |
+
uv run atlas-e2e.py stanfordnlp/imdb \\
|
| 22 |
+
--text text --split train \\
|
| 23 |
+
--name imdb-atlas --sample 50000
|
| 24 |
+
|
| 25 |
+
# From prepped parquet (already in a bucket)
|
| 26 |
+
uv run atlas-e2e.py hf://buckets/user/atlas-data/books.parquet \\
|
| 27 |
+
--text title --name open-library-atlas --sample 2000000
|
| 28 |
+
|
| 29 |
+
# Full control
|
| 30 |
+
uv run atlas-e2e.py my-org/my-dataset \\
|
| 31 |
+
--text text --split train \\
|
| 32 |
+
--name my-atlas \\
|
| 33 |
+
--sample 1000000 \\
|
| 34 |
+
--bucket user/atlas-data \\
|
| 35 |
+
--space-id user/my-atlas-viz \\
|
| 36 |
+
--flavor a100-large \\
|
| 37 |
+
--timeout 2h \\
|
| 38 |
+
--batch-size 512
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
import argparse
|
| 42 |
+
import subprocess
|
| 43 |
+
import sys
|
| 44 |
+
import time
|
| 45 |
+
from pathlib import Path
|
| 46 |
+
|
| 47 |
+
from huggingface_hub import HfApi, create_bucket
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def wait_for_job(api: HfApi, job_id: str, poll_interval: int = 30) -> str:
|
| 51 |
+
"""Poll a Job until it completes. Returns the final stage."""
|
| 52 |
+
print(f"\nWaiting for Job {job_id}...")
|
| 53 |
+
while True:
|
| 54 |
+
job = api.inspect_job(job_id=job_id)
|
| 55 |
+
stage = job.status.stage
|
| 56 |
+
if stage in ("COMPLETED", "ERROR"):
|
| 57 |
+
msg = job.status.message or ""
|
| 58 |
+
print(f"Job {stage}" + (f": {msg}" if msg else ""))
|
| 59 |
+
return stage
|
| 60 |
+
time.sleep(poll_interval)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def main():
|
| 64 |
+
parser = argparse.ArgumentParser(
|
| 65 |
+
description="Build and deploy an Embedding Atlas end-to-end (experimental)",
|
| 66 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 67 |
+
epilog=__doc__,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
# Required
|
| 71 |
+
parser.add_argument("input", help="HF dataset ID or parquet path")
|
| 72 |
+
parser.add_argument("--name", required=True, help="Atlas name")
|
| 73 |
+
parser.add_argument("--text", default="text", help="Text column name")
|
| 74 |
+
|
| 75 |
+
# Dataset options
|
| 76 |
+
parser.add_argument("--split", default=None, help="Dataset split")
|
| 77 |
+
parser.add_argument("--sample", type=int, default=None, help="Number of rows")
|
| 78 |
+
parser.add_argument("--image", default=None, help="Image column name")
|
| 79 |
+
parser.add_argument("--model", default=None, help="Embedding model")
|
| 80 |
+
|
| 81 |
+
# Infrastructure
|
| 82 |
+
parser.add_argument("--bucket", default=None, help="Bucket ID (default: {user}/atlas-data)")
|
| 83 |
+
parser.add_argument("--space-id", default=None, help="Space ID (default: {user}/{name})")
|
| 84 |
+
parser.add_argument("--flavor", default="a100-large", help="Job GPU flavor (default: a100-large)")
|
| 85 |
+
parser.add_argument("--timeout", default="2h", help="Job timeout (default: 2h)")
|
| 86 |
+
parser.add_argument("--batch-size", type=int, default=256, help="Embedding batch size")
|
| 87 |
+
parser.add_argument("--space-hardware", default="cpu-basic", help="Space hardware (default: cpu-basic)")
|
| 88 |
+
parser.add_argument("--private", action="store_true", help="Make Space private")
|
| 89 |
+
|
| 90 |
+
# Workflow control
|
| 91 |
+
parser.add_argument("--build-only", action="store_true", help="Only build, don't deploy Space")
|
| 92 |
+
parser.add_argument("--deploy-only", action="store_true", help="Only deploy from existing bucket data")
|
| 93 |
+
|
| 94 |
+
args = parser.parse_args()
|
| 95 |
+
|
| 96 |
+
api = HfApi()
|
| 97 |
+
user = api.whoami()["name"]
|
| 98 |
+
|
| 99 |
+
# Resolve defaults
|
| 100 |
+
if args.bucket is None:
|
| 101 |
+
args.bucket = f"{user}/atlas-data"
|
| 102 |
+
if args.space_id is None:
|
| 103 |
+
args.space_id = f"{user}/{args.name}"
|
| 104 |
+
|
| 105 |
+
print("=" * 60)
|
| 106 |
+
print("Embedding Atlas — End-to-End Pipeline")
|
| 107 |
+
print("=" * 60)
|
| 108 |
+
print(f"Input: {args.input}")
|
| 109 |
+
print(f"Name: {args.name}")
|
| 110 |
+
print(f"Bucket: {args.bucket}")
|
| 111 |
+
print(f"Space: {args.space_id}")
|
| 112 |
+
print(f"Flavor: {args.flavor}")
|
| 113 |
+
print(f"Sample: {args.sample}")
|
| 114 |
+
print("=" * 60)
|
| 115 |
+
|
| 116 |
+
# ── Step 1: Create bucket ──
|
| 117 |
+
if not args.deploy_only:
|
| 118 |
+
print(f"\n[1/3] Creating bucket {args.bucket}...")
|
| 119 |
+
create_bucket(args.bucket, exist_ok=True)
|
| 120 |
+
|
| 121 |
+
# ── Step 2: Submit build Job ──
|
| 122 |
+
if not args.deploy_only:
|
| 123 |
+
print(f"\n[2/3] Submitting build Job ({args.flavor})...")
|
| 124 |
+
|
| 125 |
+
build_script = Path(__file__).parent / "atlas-build-gpu.py"
|
| 126 |
+
if not build_script.exists():
|
| 127 |
+
print(f"ERROR: {build_script} not found")
|
| 128 |
+
print("atlas-build-gpu.py must be in the same directory as this script")
|
| 129 |
+
sys.exit(1)
|
| 130 |
+
|
| 131 |
+
# Build the hf jobs command
|
| 132 |
+
cmd = [
|
| 133 |
+
"hf", "jobs", "uv", "run",
|
| 134 |
+
"--flavor", args.flavor,
|
| 135 |
+
"-v", f"hf://buckets/{args.bucket}:/data",
|
| 136 |
+
"-s", "HF_TOKEN",
|
| 137 |
+
"--timeout", args.timeout,
|
| 138 |
+
str(build_script),
|
| 139 |
+
args.input,
|
| 140 |
+
"--name", args.name,
|
| 141 |
+
"--text", args.text,
|
| 142 |
+
"--batch-size", str(args.batch_size),
|
| 143 |
+
]
|
| 144 |
+
|
| 145 |
+
if args.split:
|
| 146 |
+
cmd.extend(["--split", args.split])
|
| 147 |
+
if args.sample:
|
| 148 |
+
cmd.extend(["--sample", str(args.sample)])
|
| 149 |
+
if args.image:
|
| 150 |
+
cmd.extend(["--image", args.image])
|
| 151 |
+
if args.model:
|
| 152 |
+
cmd.extend(["--model", args.model])
|
| 153 |
+
|
| 154 |
+
print(f"Command: {' '.join(cmd)}\n")
|
| 155 |
+
|
| 156 |
+
# Run and capture job ID from output
|
| 157 |
+
result = subprocess.run(cmd, capture_output=True, text=True)
|
| 158 |
+
output = result.stdout + result.stderr
|
| 159 |
+
|
| 160 |
+
# Extract job ID
|
| 161 |
+
job_id = None
|
| 162 |
+
for line in output.split("\n"):
|
| 163 |
+
if "Job started with ID:" in line:
|
| 164 |
+
job_id = line.split("Job started with ID:")[-1].strip()
|
| 165 |
+
break
|
| 166 |
+
|
| 167 |
+
if job_id is None:
|
| 168 |
+
print("ERROR: Could not extract Job ID from output:")
|
| 169 |
+
print(output)
|
| 170 |
+
sys.exit(1)
|
| 171 |
+
|
| 172 |
+
print(f"Job submitted: {job_id}")
|
| 173 |
+
print(f"View: https://huggingface.co/jobs/{user}/{job_id}")
|
| 174 |
+
|
| 175 |
+
# Wait for completion
|
| 176 |
+
stage = wait_for_job(api, job_id)
|
| 177 |
+
if stage != "COMPLETED":
|
| 178 |
+
print(f"\nJob failed. Check logs: https://huggingface.co/jobs/{user}/{job_id}")
|
| 179 |
+
sys.exit(1)
|
| 180 |
+
|
| 181 |
+
print("Build complete!")
|
| 182 |
+
|
| 183 |
+
if args.build_only:
|
| 184 |
+
print(f"\nBuild finished. Data in bucket: {args.bucket}/{args.name}/")
|
| 185 |
+
print(f"Deploy later with: uv run atlas-deploy.py --name {args.name} --bucket {args.bucket}")
|
| 186 |
+
return
|
| 187 |
+
|
| 188 |
+
# ── Step 3: Deploy Space ──
|
| 189 |
+
print(f"\n[3/3] Deploying Space {args.space_id}...")
|
| 190 |
+
|
| 191 |
+
deploy_script = Path(__file__).parent / "atlas-deploy.py"
|
| 192 |
+
if not deploy_script.exists():
|
| 193 |
+
print(f"ERROR: {deploy_script} not found")
|
| 194 |
+
sys.exit(1)
|
| 195 |
+
|
| 196 |
+
deploy_cmd = [
|
| 197 |
+
"uv", "run",
|
| 198 |
+
str(deploy_script),
|
| 199 |
+
"--name", args.name,
|
| 200 |
+
"--bucket", args.bucket,
|
| 201 |
+
"--space-id", args.space_id,
|
| 202 |
+
"--hardware", args.space_hardware,
|
| 203 |
+
"--text-column", args.text,
|
| 204 |
+
]
|
| 205 |
+
if args.private:
|
| 206 |
+
deploy_cmd.append("--private")
|
| 207 |
+
|
| 208 |
+
subprocess.run(deploy_cmd, check=True)
|
| 209 |
+
|
| 210 |
+
print("\n" + "=" * 60)
|
| 211 |
+
print("Done!")
|
| 212 |
+
print(f"Space: https://huggingface.co/spaces/{args.space_id}")
|
| 213 |
+
print(f"Bucket: https://huggingface.co/buckets/{args.bucket}")
|
| 214 |
+
print("=" * 60)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
if __name__ == "__main__":
|
| 218 |
+
main()
|
atlas-export-remote.py
CHANGED
|
@@ -177,6 +177,9 @@ def build_atlas_command(args, data_repo_id: str) -> Tuple[list, str]:
|
|
| 177 |
if args.sample:
|
| 178 |
cmd.extend(["--sample", str(args.sample)])
|
| 179 |
|
|
|
|
|
|
|
|
|
|
| 180 |
if args.trust_remote_code:
|
| 181 |
cmd.append("--trust-remote-code")
|
| 182 |
|
|
@@ -509,6 +512,11 @@ def main():
|
|
| 509 |
type=int,
|
| 510 |
help="Number of samples to visualize",
|
| 511 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 512 |
parser.add_argument(
|
| 513 |
"--trust-remote-code",
|
| 514 |
action="store_true",
|
|
@@ -627,12 +635,10 @@ def main():
|
|
| 627 |
cmd, export_dir_name = build_atlas_command(args, data_repo_id)
|
| 628 |
logger.info(f"Running: {' '.join(cmd)}")
|
| 629 |
|
| 630 |
-
result = subprocess.run(cmd
|
| 631 |
|
| 632 |
if result.returncode != 0:
|
| 633 |
-
logger.error(f"Atlas export failed
|
| 634 |
-
logger.error(f"STDOUT: {result.stdout}")
|
| 635 |
-
logger.error(f"STDERR: {result.stderr}")
|
| 636 |
sys.exit(1)
|
| 637 |
|
| 638 |
logger.info("Atlas export completed")
|
|
|
|
| 177 |
if args.sample:
|
| 178 |
cmd.extend(["--sample", str(args.sample)])
|
| 179 |
|
| 180 |
+
if args.batch_size:
|
| 181 |
+
cmd.extend(["--batch-size", str(args.batch_size)])
|
| 182 |
+
|
| 183 |
if args.trust_remote_code:
|
| 184 |
cmd.append("--trust-remote-code")
|
| 185 |
|
|
|
|
| 512 |
type=int,
|
| 513 |
help="Number of samples to visualize",
|
| 514 |
)
|
| 515 |
+
parser.add_argument(
|
| 516 |
+
"--batch-size",
|
| 517 |
+
type=int,
|
| 518 |
+
help="Batch size for embedding computation. Larger values are faster but use more GPU memory.",
|
| 519 |
+
)
|
| 520 |
parser.add_argument(
|
| 521 |
"--trust-remote-code",
|
| 522 |
action="store_true",
|
|
|
|
| 635 |
cmd, export_dir_name = build_atlas_command(args, data_repo_id)
|
| 636 |
logger.info(f"Running: {' '.join(cmd)}")
|
| 637 |
|
| 638 |
+
result = subprocess.run(cmd)
|
| 639 |
|
| 640 |
if result.returncode != 0:
|
| 641 |
+
logger.error(f"Atlas export failed with code {result.returncode}")
|
|
|
|
|
|
|
| 642 |
sys.exit(1)
|
| 643 |
|
| 644 |
logger.info("Atlas export completed")
|
hn-prep.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.10"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "duckdb",
|
| 5 |
+
# "huggingface-hub",
|
| 6 |
+
# ]
|
| 7 |
+
# ///
|
| 8 |
+
|
| 9 |
+
"""Prep Hacker News stories for atlas visualization.
|
| 10 |
+
|
| 11 |
+
Filters to stories with titles, adds year column for coloring.
|
| 12 |
+
Uses DuckDB to query HF parquet files directly (no full download).
|
| 13 |
+
Writes prepped parquet to output path (bucket mount or local).
|
| 14 |
+
|
| 15 |
+
Usage (as HF Job):
|
| 16 |
+
hf jobs uv run --flavor cpu-upgrade \
|
| 17 |
+
-v hf://buckets/davanstrien/atlas-data:/output \
|
| 18 |
+
-s HF_TOKEN --timeout 1h \
|
| 19 |
+
hn-prep.py --output /output/hn-stories/stories.parquet
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
import os
|
| 24 |
+
import time
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def main():
|
| 28 |
+
parser = argparse.ArgumentParser()
|
| 29 |
+
parser.add_argument("--output", default="/output/hn-stories/stories.parquet")
|
| 30 |
+
parser.add_argument("--max-rows", type=int, default=None,
|
| 31 |
+
help="Cap total rows after filtering")
|
| 32 |
+
args = parser.parse_args()
|
| 33 |
+
|
| 34 |
+
import duckdb
|
| 35 |
+
|
| 36 |
+
start = time.time()
|
| 37 |
+
|
| 38 |
+
con = duckdb.connect()
|
| 39 |
+
con.execute("SET enable_http_metadata_cache=true")
|
| 40 |
+
|
| 41 |
+
# DuckDB hf:// protocol picks up HF_TOKEN from env automatically
|
| 42 |
+
|
| 43 |
+
source = "hf://datasets/open-index/hacker-news/data/**/*.parquet"
|
| 44 |
+
|
| 45 |
+
os.makedirs(os.path.dirname(args.output), exist_ok=True)
|
| 46 |
+
print("Querying HN stories from HF parquet files via DuckDB...")
|
| 47 |
+
|
| 48 |
+
limit_clause = f"LIMIT {args.max_rows}" if args.max_rows else ""
|
| 49 |
+
|
| 50 |
+
query = f"""
|
| 51 |
+
COPY (
|
| 52 |
+
SELECT
|
| 53 |
+
id,
|
| 54 |
+
title,
|
| 55 |
+
score,
|
| 56 |
+
CAST(year(time) AS VARCHAR) AS year,
|
| 57 |
+
CASE
|
| 58 |
+
WHEN score <= 5 THEN '0-5'
|
| 59 |
+
WHEN score <= 25 THEN '6-25'
|
| 60 |
+
WHEN score <= 100 THEN '26-100'
|
| 61 |
+
WHEN score <= 500 THEN '101-500'
|
| 62 |
+
ELSE '500+'
|
| 63 |
+
END AS score_bucket,
|
| 64 |
+
"by",
|
| 65 |
+
url,
|
| 66 |
+
descendants
|
| 67 |
+
FROM '{source}'
|
| 68 |
+
WHERE type = 1
|
| 69 |
+
AND title IS NOT NULL
|
| 70 |
+
AND trim(title) != ''
|
| 71 |
+
ORDER BY random()
|
| 72 |
+
{limit_clause}
|
| 73 |
+
) TO '{args.output}' (FORMAT PARQUET)
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
con.execute(query)
|
| 77 |
+
elapsed = time.time() - start
|
| 78 |
+
|
| 79 |
+
# Check output
|
| 80 |
+
result = con.execute(f"SELECT count(*) FROM '{args.output}'").fetchone()
|
| 81 |
+
size_mb = os.path.getsize(args.output) / (1024**2)
|
| 82 |
+
print(f"\nWrote {result[0]:,} stories to {args.output} ({size_mb:.0f} MB)")
|
| 83 |
+
print(f"Total time: {elapsed:.0f}s")
|
| 84 |
+
|
| 85 |
+
# Quick stats
|
| 86 |
+
stats = con.execute(f"""
|
| 87 |
+
SELECT min(year) as min_year, max(year) as max_year, count(distinct year) as n_years
|
| 88 |
+
FROM '{args.output}'
|
| 89 |
+
""").fetchone()
|
| 90 |
+
print(f"Year range: {stats[0]} - {stats[1]} ({stats[2]} years)")
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
if __name__ == "__main__":
|
| 94 |
+
main()
|
open-library-prep.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.10"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "duckdb",
|
| 5 |
+
# "huggingface-hub",
|
| 6 |
+
# ]
|
| 7 |
+
# ///
|
| 8 |
+
|
| 9 |
+
"""Prep Open Library works for atlas visualization.
|
| 10 |
+
|
| 11 |
+
Filters to works with titles and subjects, adds broad category for coloring.
|
| 12 |
+
Uses DuckDB to query HF parquet files directly.
|
| 13 |
+
|
| 14 |
+
Usage (as HF Job):
|
| 15 |
+
hf jobs uv run --flavor cpu-upgrade \
|
| 16 |
+
-v hf://buckets/davanstrien/atlas-data:/output \
|
| 17 |
+
-s HF_TOKEN --timeout 1h \
|
| 18 |
+
open-library-prep.py --output /output/open-library/books.parquet
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
import argparse
|
| 22 |
+
import os
|
| 23 |
+
import time
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def main():
|
| 27 |
+
parser = argparse.ArgumentParser()
|
| 28 |
+
parser.add_argument("--output", default="/output/open-library/books.parquet")
|
| 29 |
+
parser.add_argument("--max-rows", type=int, default=2000000)
|
| 30 |
+
args = parser.parse_args()
|
| 31 |
+
|
| 32 |
+
import duckdb
|
| 33 |
+
|
| 34 |
+
start = time.time()
|
| 35 |
+
con = duckdb.connect()
|
| 36 |
+
con.execute("SET enable_http_metadata_cache=true")
|
| 37 |
+
|
| 38 |
+
os.makedirs(os.path.dirname(args.output), exist_ok=True)
|
| 39 |
+
|
| 40 |
+
source = "hf://datasets/open-index/open-library/data/works/*.parquet"
|
| 41 |
+
|
| 42 |
+
print(f"Querying Open Library works (max {args.max_rows:,} rows)...")
|
| 43 |
+
|
| 44 |
+
query = f"""
|
| 45 |
+
COPY (
|
| 46 |
+
SELECT
|
| 47 |
+
title,
|
| 48 |
+
CASE
|
| 49 |
+
WHEN subjects LIKE '%Fiction%' OR subjects LIKE '%Novel%' OR subjects LIKE '%Stories%' THEN 'Fiction'
|
| 50 |
+
WHEN subjects LIKE '%History%' OR subjects LIKE '%Antiquities%' OR subjects LIKE '%Civilization%' THEN 'History'
|
| 51 |
+
WHEN subjects LIKE '%Science%' OR subjects LIKE '%Physics%' OR subjects LIKE '%Chemistry%' OR subjects LIKE '%Biology%' OR subjects LIKE '%Geology%' OR subjects LIKE '%Astronomy%' THEN 'Science'
|
| 52 |
+
WHEN subjects LIKE '%Religion%' OR subjects LIKE '%Theology%' OR subjects LIKE '%Bible%' OR subjects LIKE '%Church%' THEN 'Religion'
|
| 53 |
+
WHEN subjects LIKE '%Biography%' OR subjects LIKE '%Correspondence%' THEN 'Biography'
|
| 54 |
+
WHEN subjects LIKE '%Poetry%' OR subjects LIKE '%Drama%' OR subjects LIKE '%Literature%' THEN 'Literature'
|
| 55 |
+
WHEN subjects LIKE '%Mathematics%' OR subjects LIKE '%Computer%' OR subjects LIKE '%Engineering%' OR subjects LIKE '%Technol%' THEN 'Tech & Engineering'
|
| 56 |
+
WHEN subjects LIKE '%Music%' THEN 'Music'
|
| 57 |
+
WHEN subjects LIKE '%Art%' OR subjects LIKE '%Photography%' OR subjects LIKE '%Architecture%' OR subjects LIKE '%Design%' THEN 'Art & Design'
|
| 58 |
+
WHEN subjects LIKE '%Law%' OR subjects LIKE '%Politics%' OR subjects LIKE '%Government%' OR subjects LIKE '%Foreign relations%' THEN 'Law & Politics'
|
| 59 |
+
WHEN subjects LIKE '%Education%' OR subjects LIKE '%Teaching%' THEN 'Education'
|
| 60 |
+
WHEN subjects LIKE '%Philosophy%' OR subjects LIKE '%Psychology%' THEN 'Philosophy'
|
| 61 |
+
WHEN subjects LIKE '%Medicine%' OR subjects LIKE '%Health%' OR subjects LIKE '%Disease%' THEN 'Medicine'
|
| 62 |
+
WHEN subjects LIKE '%Econom%' OR subjects LIKE '%Business%' OR subjects LIKE '%Commerce%' OR subjects LIKE '%Finance%' THEN 'Business & Economics'
|
| 63 |
+
WHEN subjects LIKE '%Children%' OR subjects LIKE '%Juvenile%' THEN 'Children'
|
| 64 |
+
WHEN subjects LIKE '%Travel%' OR subjects LIKE '%Guidebook%' OR subjects LIKE '%Description and travel%' THEN 'Travel'
|
| 65 |
+
WHEN subjects LIKE '%Agriculture%' OR subjects LIKE '%Gardening%' OR subjects LIKE '%Cook%' OR subjects LIKE '%Food%' THEN 'Food & Agriculture'
|
| 66 |
+
WHEN subjects LIKE '%Social%' OR subjects LIKE '%Sociology%' OR subjects LIKE '%Women%' OR subjects LIKE '%Feminism%' THEN 'Society'
|
| 67 |
+
WHEN subjects LIKE '%Military%' OR subjects LIKE '%War%' THEN 'Military'
|
| 68 |
+
WHEN subjects LIKE '%Sport%' OR subjects LIKE '%Games%' OR subjects LIKE '%Baseball%' OR subjects LIKE '%Football%' THEN 'Sports'
|
| 69 |
+
ELSE 'Other'
|
| 70 |
+
END as category,
|
| 71 |
+
first_publish_date,
|
| 72 |
+
json_extract_string(subjects, '$[0]') as primary_subject
|
| 73 |
+
FROM '{source}'
|
| 74 |
+
WHERE subjects IS NOT NULL
|
| 75 |
+
AND subjects != '[]'
|
| 76 |
+
AND title IS NOT NULL
|
| 77 |
+
AND trim(title) != ''
|
| 78 |
+
AND length(title) > 3
|
| 79 |
+
ORDER BY random()
|
| 80 |
+
LIMIT {args.max_rows}
|
| 81 |
+
) TO '{args.output}' (FORMAT PARQUET)
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
con.execute(query)
|
| 85 |
+
elapsed = time.time() - start
|
| 86 |
+
|
| 87 |
+
# Stats
|
| 88 |
+
result = con.execute(f"SELECT count(*) FROM '{args.output}'").fetchone()
|
| 89 |
+
size_mb = os.path.getsize(args.output) / (1024**2)
|
| 90 |
+
print(f"\nWrote {result[0]:,} books to {args.output} ({size_mb:.0f} MB)")
|
| 91 |
+
print(f"Total time: {elapsed:.0f}s")
|
| 92 |
+
|
| 93 |
+
cats = con.execute(f"""
|
| 94 |
+
SELECT category, count(*) as cnt
|
| 95 |
+
FROM '{args.output}'
|
| 96 |
+
GROUP BY 1 ORDER BY 2 DESC
|
| 97 |
+
""").df()
|
| 98 |
+
print("\nCategory distribution:")
|
| 99 |
+
for _, row in cats.iterrows():
|
| 100 |
+
print(f" {row['cnt']:6,} {row['category']}")
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
if __name__ == "__main__":
|
| 104 |
+
main()
|