nesting-tasks-2d / download_dataset.py
clallier's picture
Upload folder using huggingface_hub
5400759 verified
Raw
History Blame
5.94 kB
# /// script
# dependencies = [
# "pandas",
# "pyarrow",
# "hf",
# ]
# ///
"""Downloader script to fetch the Nesting Tasks Dataset from Zenodo."""
import os
import urllib.request
import time
def download_file(url: str, dest_path: str) -> None:
"""Downloads a file with clean progress printouts.
Args:
url (str): The direct download URL.
dest_path (str): File destination path.
"""
print(f"๐Ÿ“ฅ Downloading {os.path.basename(dest_path)}...")
start_time = time.time()
def reporthook(count, block_size, total_size):
if total_size <= 0:
return
current_progress = count * block_size
percent = min(100, int(current_progress * 100 / total_size))
# Keep progress line on same terminal line
print(
f"\r [{'=' * (percent // 5)}{' ' * (20 - percent // 5)}] {percent}% ({current_progress / (1024 * 1024):.1f}MB / {total_size / (1024 * 1024):.1f}MB)",
end="",
flush=True,
)
urllib.request.urlretrieve(url, dest_path, reporthook) # nosec B310
duration = time.time() - start_time
print(f"\n โœ… Completed in {duration:.1f}s!\n")
def convert_to_parquet() -> None:
"""Loads gzipped pickles with pandas and saves them as modern Parquet files.
Cleans up the raw .gz files afterwards to keep the repository secure and light.
"""
import pandas as pd
files = ["tasks", "parts", "constraints", "shapes"]
print("============================================================")
print("๐Ÿ”„ Converting Pickle splits to Parquet format...")
print("============================================================")
for name in files:
pickle_file = f"{name}.gz"
parquet_file = f"{name}.parquet"
if not os.path.exists(pickle_file):
continue
print(f"โšก Processing '{pickle_file}' -> '{parquet_file}'...")
try:
# 1. Read pickled dataframe
df = pd.read_pickle(pickle_file)
# 2. Write to Parquet (removing pandas index to keep schema clean)
df.to_parquet(parquet_file, index=False)
print(f" โœ… Saved {parquet_file}")
# 3. Clean up the insecure raw pickle file
os.remove(pickle_file)
print(f" ๐Ÿ—‘๏ธ Removed raw {pickle_file}")
except Exception as err:
print(f" โŒ Failed to convert {pickle_file}: {err}")
return
print()
def main() -> None:
"""Orchestrates the downloading of the Zenodo dataset files."""
print("============================================================")
print("๐Ÿ“ฆ Zenodo Nesting Tasks Dataset Downloader")
print("============================================================")
# 1. Zenodo records API endpoints for version 1.1 of Lallier et al. (2022)
files_to_download = {
"tasks.gz": "https://zenodo.org/api/records/7030786/files/tasks.gz/content",
"parts.gz": "https://zenodo.org/api/records/7030786/files/parts.gz/content",
"constraints.gz": "https://zenodo.org/api/records/7030786/files/constraints.gz/content",
"shapes.gz": "https://zenodo.org/api/records/7030786/files/shapes.gz/content",
}
# 2. Iterate and download each file directly into workspace
for filename, url in files_to_download.items():
# Check if either the converted parquet or the raw .gz file already exists
parquet_name = filename.replace(".gz", ".parquet")
if os.path.exists(parquet_name):
print(
f"โ„น๏ธ File '{parquet_name}' already exists locally (converted). Skipping download.\n"
)
elif os.path.exists(filename):
print(
f"โ„น๏ธ File '{filename}' already exists locally (raw .gz). Skipping download.\n"
)
else:
try:
download_file(url, filename)
except Exception as err:
print(f"โŒ Failed to download {filename}: {err}")
return
# 3. Perform automatic conversion and cleanup
convert_to_parquet()
# 4. Validate and pretty-print heads of all parquet files
print_dataset_head()
print("============================================================")
print("๐ŸŽ‰ All dataset splits converted to Parquet successfully!")
print("============================================================")
print("๐Ÿ’ก Next Step: To push this dataset to your Hugging Face profile, run:")
print(" $ uv run hf upload clallier/nesting-tasks-2d . --repo-type=dataset")
print("============================================================")
def print_dataset_head() -> None:
"""Loads and pretty-prints the first 10 rows of all Parquet files to verify conversion."""
import pandas as pd
# Configure pandas to show all columns without wrapping or ellipsis
pd.set_option("display.max_columns", None)
pd.set_option("display.width", 1000)
files = ["tasks", "parts", "constraints", "shapes"]
print("============================================================")
print("๐Ÿ”ฌ Verifying Parquet Schemas (First 10 rows of each split)")
print("============================================================")
for name in files:
parquet_file = f"{name}.parquet"
if not os.path.exists(parquet_file):
print(f"โš ๏ธ Warning: '{parquet_file}' not found for validation.\n")
continue
print(f"\n๐Ÿ“„ Split: {parquet_file}")
print("------------------------------------------------------------")
try:
df = pd.read_parquet(parquet_file)
print(df.head(10))
except Exception as err:
print(f"โŒ Failed to read {parquet_file}: {err}")
print("------------------------------------------------------------")
print()
if __name__ == "__main__":
main()