Sync from GitHub via hub-sync
Browse files- README.md +87 -0
- optimize-parquet.py +82 -0
README.md
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
viewer: false
|
| 3 |
+
tags:
|
| 4 |
+
- uv-script
|
| 5 |
+
- data-processing
|
| 6 |
+
- parquet
|
| 7 |
+
- buckets
|
| 8 |
+
- webhooks
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
# Data processing
|
| 12 |
+
|
| 13 |
+
> Part of [uv-scripts](https://huggingface.co/uv-scripts) — self-contained UV scripts you run on Hugging Face Jobs in one command.
|
| 14 |
+
|
| 15 |
+
General data processing recipes: convert, clean and prepare data files.
|
| 16 |
+
|
| 17 |
+
| Script | What it does |
|
| 18 |
+
|---|---|
|
| 19 |
+
| [`optimize-parquet.py`](#optimize-parquetpy-optimized-parquet-from-bucket-uploads) | Converts CSV, JSON and Parquet files uploaded to a bucket into optimized Parquet, triggered by a bucket webhook |
|
| 20 |
+
|
| 21 |
+
## optimize-parquet.py: optimized Parquet from bucket uploads
|
| 22 |
+
|
| 23 |
+
Upload a CSV, JSON or Parquet file to a [Storage Bucket](https://huggingface.co/docs/hub/storage-buckets) and get an optimized Parquet version in a second bucket, automatically. A bucket [webhook](https://huggingface.co/docs/hub/webhooks) starts a [Job](https://huggingface.co/docs/hub/jobs) for each upload, and the Job converts only the files that changed.
|
| 24 |
+
|
| 25 |
+
```
|
| 26 |
+
input bucket ──upload──▶ webhook ──▶ Job (optimize-parquet.py) ──▶ output bucket
|
| 27 |
+
data.csv data.csv/data/train-00000-of-00001.parquet
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
The output is written by [`datasets`](https://huggingface.co/docs/datasets), so it gets the same [optimizations](https://huggingface.co/docs/hub/datasets-libraries#optimized-parquet-files) as `push_to_hub`: content-defined chunking for Xet deduplication, a page index for fast filtering and random access, and row groups of at most 100 MB.
|
| 31 |
+
|
| 32 |
+
### Setup
|
| 33 |
+
|
| 34 |
+
You need two buckets: one you upload to, and one for the output. The Job writes to a different bucket so that its own output does not trigger it again.
|
| 35 |
+
|
| 36 |
+
```bash
|
| 37 |
+
hf buckets create my-raw-files --private
|
| 38 |
+
hf buckets create my-parquet --private
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
**1. Create a base Job for the webhook to re-run.** With no webhook payload, this first run exits straight away:
|
| 42 |
+
|
| 43 |
+
```bash
|
| 44 |
+
hf jobs run --flavor cpu-upgrade --timeout 2h -e OUTPUT_BUCKET=<user>/my-parquet \
|
| 45 |
+
ghcr.io/astral-sh/uv:python3.12-bookworm \
|
| 46 |
+
uv run https://huggingface.co/datasets/uv-scripts/data-processing/raw/main/optimize-parquet.py
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
Use `hf jobs run ... uv run <url>` here, not `hf jobs uv run <url>`. `hf jobs uv run` uploads the script as a volume, and webhook runs don't keep volumes.
|
| 50 |
+
|
| 51 |
+
**2. Create a webhook on the input bucket that re-runs this Job:**
|
| 52 |
+
|
| 53 |
+
```python
|
| 54 |
+
from huggingface_hub import create_webhook
|
| 55 |
+
|
| 56 |
+
create_webhook(
|
| 57 |
+
job_id="<job id from step 1>",
|
| 58 |
+
watched=[{"type": "bucket", "name": "<user>/my-raw-files"}],
|
| 59 |
+
domains=["repo"],
|
| 60 |
+
secret="<fine-grained token>",
|
| 61 |
+
)
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
The Job uses the webhook `secret` as its token to read and write the buckets. Use a fine-grained token, not your main one.
|
| 65 |
+
|
| 66 |
+
**3. Upload a file:**
|
| 67 |
+
|
| 68 |
+
```bash
|
| 69 |
+
hf buckets cp data.csv hf://buckets/<user>/my-raw-files/data.csv
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
After about a minute, the output is in `<user>/my-parquet/data.csv/`: the Parquet file(s) under `data/`, plus a README written by `datasets`.
|
| 73 |
+
|
| 74 |
+
### Options
|
| 75 |
+
|
| 76 |
+
| Environment variable | Default | Meaning |
|
| 77 |
+
|---|---|---|
|
| 78 |
+
| `OUTPUT_BUCKET` | required | Bucket to write the Parquet files to. Must differ from the watched bucket. |
|
| 79 |
+
| `STREAM_ABOVE_BYTES` | 1/3 of free disk | Files larger than this are streamed instead of loaded to disk. |
|
| 80 |
+
|
| 81 |
+
Files that fit on the Job's disk are loaded in full. Larger files are streamed, so they don't need to fit on the disk (50 GB on `cpu-upgrade`); raise `--timeout` for very large files. Supported inputs: `.csv`, `.json`, `.jsonl`, `.parquet`. Other files are skipped, and deleted files are ignored.
|
| 82 |
+
|
| 83 |
+
### Notes
|
| 84 |
+
|
| 85 |
+
- **Cost:** a small file takes about 20 seconds on `cpu-upgrade` ($0.03/hour). In testing, one `hf buckets sync` of several files sent one webhook event, so it started one Job.
|
| 86 |
+
- **Pin the script:** each webhook run downloads the script again. To stop changes to this recipe from reaching your webhook, replace `main` in the URL with a commit hash.
|
| 87 |
+
- **Limits:** a webhook can trigger at most 1,000 times per 24 hours. Above 10,000 changed files in one event, the payload list is truncated; those files are not converted.
|
optimize-parquet.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.10"
|
| 3 |
+
# dependencies = ["datasets>=5"]
|
| 4 |
+
# ///
|
| 5 |
+
"""Convert CSV, JSON and Parquet files added to a bucket into optimized Parquet
|
| 6 |
+
in a second bucket (OUTPUT_BUCKET).
|
| 7 |
+
|
| 8 |
+
Meant to run as a Job triggered by a bucket webhook: the Job receives the list of
|
| 9 |
+
changed files in WEBHOOK_PAYLOAD. `datasets` writes optimized Parquet by default
|
| 10 |
+
(content-defined chunking, page index, row groups of at most 100MB).
|
| 11 |
+
|
| 12 |
+
Setup (once):
|
| 13 |
+
|
| 14 |
+
# 1. A base Job for the webhook to re-run. With no payload, this first run exits.
|
| 15 |
+
# Use `hf jobs run ... uv run <url>`, not `hf jobs uv run <url>`: the latter uploads
|
| 16 |
+
# the script as a volume, and webhook runs don't keep volumes.
|
| 17 |
+
hf jobs run --flavor cpu-upgrade --timeout 2h -e OUTPUT_BUCKET=<user>/<output-bucket> \\
|
| 18 |
+
ghcr.io/astral-sh/uv:python3.12-bookworm \\
|
| 19 |
+
uv run https://huggingface.co/datasets/uv-scripts/data-processing/raw/main/optimize-parquet.py
|
| 20 |
+
|
| 21 |
+
# 2. A webhook on the input bucket that re-runs that Job on every change.
|
| 22 |
+
from huggingface_hub import create_webhook
|
| 23 |
+
create_webhook(
|
| 24 |
+
job_id="<job id from step 1>",
|
| 25 |
+
watched=[{"type": "bucket", "name": "<user>/<input-bucket>"}],
|
| 26 |
+
domains=["repo"],
|
| 27 |
+
secret="<fine-grained token>",
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
Then upload files to the input bucket, e.g.
|
| 31 |
+
`hf buckets cp data.csv hf://buckets/<user>/<input-bucket>/data.csv`,
|
| 32 |
+
and the output appears at `<output-bucket>/data.csv/data/train-00000-of-00001.parquet`.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
import json
|
| 36 |
+
import os
|
| 37 |
+
import shutil
|
| 38 |
+
import tempfile
|
| 39 |
+
from pathlib import PurePosixPath
|
| 40 |
+
|
| 41 |
+
from datasets import load_dataset
|
| 42 |
+
|
| 43 |
+
# Use the webhook secret as the token when HF_TOKEN is not set.
|
| 44 |
+
if "HF_TOKEN" not in os.environ and "WEBHOOK_SECRET" in os.environ:
|
| 45 |
+
os.environ["HF_TOKEN"] = os.environ["WEBHOOK_SECRET"]
|
| 46 |
+
|
| 47 |
+
BUILDERS = {".csv": "csv", ".json": "json", ".jsonl": "json", ".parquet": "parquet"}
|
| 48 |
+
|
| 49 |
+
event = json.loads(os.environ.get("WEBHOOK_PAYLOAD", "{}"))
|
| 50 |
+
input_bucket = os.environ.get("WEBHOOK_REPO_ID")
|
| 51 |
+
output_bucket = os.environ["OUTPUT_BUCKET"]
|
| 52 |
+
# Writing to the watched bucket would trigger this Job again for its own output.
|
| 53 |
+
if output_bucket == input_bucket:
|
| 54 |
+
raise SystemExit("OUTPUT_BUCKET must be different from the watched bucket")
|
| 55 |
+
|
| 56 |
+
# A full load needs disk for the download, the Arrow cache and the output.
|
| 57 |
+
# Larger files are streamed instead.
|
| 58 |
+
free_disk = shutil.disk_usage(tempfile.gettempdir()).free
|
| 59 |
+
stream_above = int(os.environ.get("STREAM_ABOVE_BYTES", free_disk // 3))
|
| 60 |
+
|
| 61 |
+
for changed_file in event.get("updatedFiles", []):
|
| 62 |
+
path = PurePosixPath(changed_file["path"])
|
| 63 |
+
if changed_file["action"] != "add":
|
| 64 |
+
continue
|
| 65 |
+
if path.suffix not in BUILDERS:
|
| 66 |
+
print(f"Skipping {path}: unsupported file type")
|
| 67 |
+
continue
|
| 68 |
+
|
| 69 |
+
streaming = changed_file["size"] > stream_above
|
| 70 |
+
mode = "streaming" if streaming else "full load"
|
| 71 |
+
print(f"{path} ({changed_file['size']:,} bytes): {mode}")
|
| 72 |
+
dataset = load_dataset(
|
| 73 |
+
BUILDERS[path.suffix],
|
| 74 |
+
data_files=f"hf://buckets/{input_bucket}/{path}",
|
| 75 |
+
split="train",
|
| 76 |
+
streaming=streaming,
|
| 77 |
+
)
|
| 78 |
+
# a/b.csv -> <output bucket>/a/b.csv/data/train-*.parquet (keeps b.csv and b.jsonl apart)
|
| 79 |
+
# Tabular files have no image/audio files to embed. Setting this also avoids a
|
| 80 |
+
# crash when pushing a streamed CSV/JSON dataset (its features are not known yet).
|
| 81 |
+
dataset.push_to_hub(f"buckets/{output_bucket}/{path}", embed_external_files=False)
|
| 82 |
+
print(f"Wrote buckets/{output_bucket}/{path}")
|