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
+
# dependencies = [
|
| 5 |
+
# "datasets",
|
| 6 |
+
# "huggingface_hub[hf_transfer]",
|
| 7 |
+
# "tqdm",
|
| 8 |
+
# ]
|
| 9 |
+
# ///
|
| 10 |
+
"""
|
| 11 |
+
Chunked dataset preparation for large Android datasets that exceed 50GB ephemeral storage.
|
| 12 |
+
|
| 13 |
+
This script processes the Android dataset in chunks to stay under the HF Jobs 50GB limit,
|
| 14 |
+
then uploads intermediate chunk datasets. A final merge step combines all chunks.
|
| 15 |
+
|
| 16 |
+
Workflow:
|
| 17 |
+
1. Plan: Calculate chunks based on total files and chunk size
|
| 18 |
+
2. Process: Each HF Job processes one chunk (e.g., files 0-49, 50-99, etc.)
|
| 19 |
+
3. Upload: Each chunk becomes a separate dataset (e.g., android-text-chunk-0)
|
| 20 |
+
4. Merge: Final job merges all chunks into the complete dataset
|
| 21 |
+
|
| 22 |
+
Usage - Process a single chunk:
|
| 23 |
+
hf jobs uv run train/prepare_chunked_dataset.py \\
|
| 24 |
+
--flavor cpu-xl --secrets HF_TOKEN --timeout 4h \\
|
| 25 |
+
-- --hf-username Tonic \\
|
| 26 |
+
--base-repo android-text-full \\
|
| 27 |
+
--chunk-index 0 \\
|
| 28 |
+
--chunk-size 45 \\
|
| 29 |
+
--upload
|
| 30 |
+
|
| 31 |
+
Usage - Merge all chunks:
|
| 32 |
+
hf jobs uv run train/prepare_chunked_dataset.py \\
|
| 33 |
+
--flavor cpu-basic --secrets HF_TOKEN --timeout 2h \\
|
| 34 |
+
-- --hf-username Tonic \\
|
| 35 |
+
--base-repo android-text-full \\
|
| 36 |
+
--merge-chunks \\
|
| 37 |
+
--total-chunks 6 \\
|
| 38 |
+
--upload
|
| 39 |
+
|
| 40 |
+
Usage - Plan only (show chunk distribution without processing):
|
| 41 |
+
uv run train/prepare_chunked_dataset.py \\
|
| 42 |
+
--hf-username Tonic \\
|
| 43 |
+
--base-repo android-text-full \\
|
| 44 |
+
--chunk-size 45 \\
|
| 45 |
+
--plan-only
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
import argparse
|
| 49 |
+
import json
|
| 50 |
+
import logging
|
| 51 |
+
import os
|
| 52 |
+
import sys
|
| 53 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 54 |
+
|
| 55 |
+
# Force UTF-8 output
|
| 56 |
+
if hasattr(sys.stdout, "reconfigure"):
|
| 57 |
+
try:
|
| 58 |
+
sys.stdout.reconfigure(encoding="utf-8", line_buffering=True)
|
| 59 |
+
sys.stderr.reconfigure(encoding="utf-8", line_buffering=True)
|
| 60 |
+
except (AttributeError, OSError):
|
| 61 |
+
pass
|
| 62 |
+
|
| 63 |
+
logging.basicConfig(
|
| 64 |
+
level=logging.INFO,
|
| 65 |
+
format="%(asctime)s - %(levelname)s - %(message)s",
|
| 66 |
+
)
|
| 67 |
+
logger = logging.getLogger(__name__)
|
| 68 |
+
|
| 69 |
+
# Constants
|
| 70 |
+
ANDROID_DATASET = "Tonic/android-operator-episodes"
|
| 71 |
+
MOBILE_ACTIONS_DATASET = "google/mobile-actions"
|
| 72 |
+
DEFAULT_CHUNK_SIZE = 45 # Files per chunk (~9GB per chunk)
|
| 73 |
+
TOTAL_TRAIN_FILES = 275 # Total train parquet files
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _get_train_parquet_files(
|
| 77 |
+
token: Optional[str] = None,
|
| 78 |
+
offset: int = 0,
|
| 79 |
+
limit: Optional[int] = None,
|
| 80 |
+
) -> List[str]:
|
| 81 |
+
"""
|
| 82 |
+
List train parquet files with offset/limit for chunking.
|
| 83 |
+
|
| 84 |
+
Args:
|
| 85 |
+
token: HF token
|
| 86 |
+
offset: Start index (for chunking)
|
| 87 |
+
limit: Max files to return (None = all from offset)
|
| 88 |
+
|
| 89 |
+
Returns:
|
| 90 |
+
List of hf:// URLs for the specified file range
|
| 91 |
+
"""
|
| 92 |
+
from huggingface_hub import HfFileSystem
|
| 93 |
+
|
| 94 |
+
fs = HfFileSystem(token=token)
|
| 95 |
+
prefix = f"datasets/{ANDROID_DATASET}/data"
|
| 96 |
+
raw = fs.glob(f"{prefix}/train-*.parquet")
|
| 97 |
+
raw.sort()
|
| 98 |
+
|
| 99 |
+
# Apply offset and limit
|
| 100 |
+
end = offset + limit if limit else len(raw)
|
| 101 |
+
selected = raw[offset:end]
|
| 102 |
+
|
| 103 |
+
# Convert to hf:// URLs
|
| 104 |
+
return [f"hf://{path.replace('/data/', '@main/data/', 1)}" for path in selected]
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def _count_total_train_files(token: Optional[str] = None) -> int:
|
| 108 |
+
"""Count total train files in the dataset."""
|
| 109 |
+
from huggingface_hub import HfFileSystem
|
| 110 |
+
|
| 111 |
+
fs = HfFileSystem(token=token)
|
| 112 |
+
prefix = f"datasets/{ANDROID_DATASET}/data"
|
| 113 |
+
files = fs.glob(f"{prefix}/train-*.parquet")
|
| 114 |
+
return len(files)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def calculate_chunks(chunk_size: int) -> List[Tuple[int, int, int]]:
|
| 118 |
+
"""
|
| 119 |
+
Calculate chunk boundaries.
|
| 120 |
+
|
| 121 |
+
Returns:
|
| 122 |
+
List of (chunk_index, start_file, end_file) tuples
|
| 123 |
+
"""
|
| 124 |
+
chunks = []
|
| 125 |
+
for start in range(0, TOTAL_TRAIN_FILES, chunk_size):
|
| 126 |
+
end = min(start + chunk_size, TOTAL_TRAIN_FILES)
|
| 127 |
+
chunk_idx = start // chunk_size
|
| 128 |
+
chunks.append((chunk_idx, start, end))
|
| 129 |
+
return chunks
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def process_chunk(
|
| 133 |
+
hf_username: str,
|
| 134 |
+
base_repo: str,
|
| 135 |
+
chunk_index: int,
|
| 136 |
+
chunk_size: int,
|
| 137 |
+
token: Optional[str] = None,
|
| 138 |
+
upload: bool = False,
|
| 139 |
+
system_message: Optional[str] = None,
|
| 140 |
+
max_episodes: Optional[int] = None,
|
| 141 |
+
include_mobile_actions: bool = True,
|
| 142 |
+
max_mobile_actions: Optional[int] = None,
|
| 143 |
+
android_ratio: float = 0.5,
|
| 144 |
+
seed: int = 42,
|
| 145 |
+
) -> str:
|
| 146 |
+
"""
|
| 147 |
+
Process a single chunk of Android files.
|
| 148 |
+
|
| 149 |
+
Args:
|
| 150 |
+
hf_username: HF username
|
| 151 |
+
base_repo: Base repository name (chunk will be {base_repo}-chunk-{index})
|
| 152 |
+
chunk_index: Which chunk to process (0-based)
|
| 153 |
+
chunk_size: Number of files per chunk
|
| 154 |
+
token: HF token
|
| 155 |
+
upload: Whether to upload the chunk
|
| 156 |
+
system_message: Custom system message
|
| 157 |
+
max_episodes: Max episodes to process from this chunk
|
| 158 |
+
include_mobile_actions: Whether to include mobile-actions in this chunk
|
| 159 |
+
max_mobile_actions: Max mobile-actions samples
|
| 160 |
+
android_ratio: Ratio for merging (if include_mobile_actions)
|
| 161 |
+
seed: Random seed
|
| 162 |
+
|
| 163 |
+
Returns:
|
| 164 |
+
Dataset repo ID for the processed chunk
|
| 165 |
+
"""
|
| 166 |
+
from datasets import Dataset, load_dataset
|
| 167 |
+
from prepare_merged_text_dataset import (
|
| 168 |
+
explode_android_episodes_to_steps,
|
| 169 |
+
build_android_conversations,
|
| 170 |
+
TEXT_ONLY_ACTION_TYPES,
|
| 171 |
+
is_text_only_action,
|
| 172 |
+
serialize_action_to_json,
|
| 173 |
+
load_mobile_actions_data,
|
| 174 |
+
merge_datasets,
|
| 175 |
+
upload_dataset_to_hub,
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
offset = chunk_index * chunk_size
|
| 179 |
+
chunk_repo = f"{hf_username}/{base_repo}-chunk-{chunk_index}"
|
| 180 |
+
|
| 181 |
+
logger.info(f"=" * 70)
|
| 182 |
+
logger.info(f"Processing Chunk {chunk_index}")
|
| 183 |
+
logger.info(f" Files: {offset} to {min(offset + chunk_size, TOTAL_TRAIN_FILES) - 1}")
|
| 184 |
+
logger.info(f" Estimated size: ~{chunk_size * 0.2:.1f}GB")
|
| 185 |
+
logger.info(f" Target repo: {chunk_repo}")
|
| 186 |
+
logger.info(f"=" * 70)
|
| 187 |
+
|
| 188 |
+
# Get file list for this chunk
|
| 189 |
+
data_files = _get_train_parquet_files(token=token, offset=offset, limit=chunk_size)
|
| 190 |
+
if not data_files:
|
| 191 |
+
raise ValueError(f"No files found for chunk {chunk_index} (offset={offset})")
|
| 192 |
+
|
| 193 |
+
logger.info(f"Loading {len(data_files)} parquet files for chunk {chunk_index}...")
|
| 194 |
+
|
| 195 |
+
# Load Android data for this chunk
|
| 196 |
+
ds = load_dataset(
|
| 197 |
+
"parquet",
|
| 198 |
+
data_files=data_files,
|
| 199 |
+
split="train",
|
| 200 |
+
token=token,
|
| 201 |
+
)
|
| 202 |
+
logger.info(f"Loaded {len(ds)} episodes in chunk {chunk_index}")
|
| 203 |
+
|
| 204 |
+
# Limit episodes if specified
|
| 205 |
+
if max_episodes and max_episodes > 0:
|
| 206 |
+
ds = ds.select(range(min(max_episodes, len(ds))))
|
| 207 |
+
logger.info(f"Limited to {len(ds)} episodes")
|
| 208 |
+
|
| 209 |
+
# Explode to steps with filtering
|
| 210 |
+
logger.info(f"Chunk {chunk_index}: Exploding episodes to text-only steps...")
|
| 211 |
+
step_ds = ds.map(
|
| 212 |
+
explode_android_episodes_to_steps,
|
| 213 |
+
batched=True,
|
| 214 |
+
remove_columns=ds.column_names,
|
| 215 |
+
desc=f"Chunk {chunk_index}: Exploding",
|
| 216 |
+
)
|
| 217 |
+
logger.info(f"Chunk {chunk_index}: Created {len(step_ds)} text-only step examples")
|
| 218 |
+
|
| 219 |
+
# Build conversations
|
| 220 |
+
logger.info(f"Chunk {chunk_index}: Building conversation format...")
|
| 221 |
+
conversation_ds = step_ds.map(
|
| 222 |
+
lambda x: build_android_conversations(x, system_message),
|
| 223 |
+
batched=True,
|
| 224 |
+
desc=f"Chunk {chunk_index}: Conversations",
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
# Keep only conversations
|
| 228 |
+
conversation_ds = conversation_ds.remove_columns(
|
| 229 |
+
[col for col in conversation_ds.column_names if col != "conversations"]
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
# Optionally include mobile-actions in first chunk only (to avoid duplicates)
|
| 233 |
+
if include_mobile_actions and max_mobile_actions and chunk_index == 0:
|
| 234 |
+
logger.info(f"Chunk {chunk_index}: Including mobile-actions data...")
|
| 235 |
+
mobile_ds = load_mobile_actions_data(max_samples=max_mobile_actions, split="train")
|
| 236 |
+
conversation_ds = merge_datasets(
|
| 237 |
+
android_ds=conversation_ds,
|
| 238 |
+
mobile_actions_ds=mobile_ds,
|
| 239 |
+
android_ratio=android_ratio,
|
| 240 |
+
seed=seed,
|
| 241 |
+
)
|
| 242 |
+
logger.info(f"Chunk {chunk_index}: Final size with mobile-actions: {len(conversation_ds)}")
|
| 243 |
+
|
| 244 |
+
# Upload if requested
|
| 245 |
+
if upload:
|
| 246 |
+
logger.info(f"Chunk {chunk_index}: Uploading to {chunk_repo}...")
|
| 247 |
+
upload_dataset_to_hub(
|
| 248 |
+
conversation_ds,
|
| 249 |
+
repo_id=chunk_repo,
|
| 250 |
+
private=True,
|
| 251 |
+
token=token,
|
| 252 |
+
)
|
| 253 |
+
logger.info(f"Chunk {chunk_index}: Uploaded successfully!")
|
| 254 |
+
|
| 255 |
+
return chunk_repo
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def merge_all_chunks(
|
| 259 |
+
hf_username: str,
|
| 260 |
+
base_repo: str,
|
| 261 |
+
total_chunks: int,
|
| 262 |
+
token: Optional[str] = None,
|
| 263 |
+
upload: bool = False,
|
| 264 |
+
final_repo: Optional[str] = None,
|
| 265 |
+
test_ratio: float = 0.0,
|
| 266 |
+
seed: int = 42,
|
| 267 |
+
) -> str:
|
| 268 |
+
"""
|
| 269 |
+
Merge all processed chunks into the final dataset.
|
| 270 |
+
|
| 271 |
+
Args:
|
| 272 |
+
hf_username: HF username
|
| 273 |
+
base_repo: Base repo name (chunks are {base_repo}-chunk-{N})
|
| 274 |
+
total_chunks: Total number of chunks to merge
|
| 275 |
+
token: HF token
|
| 276 |
+
upload: Whether to upload the final merged dataset
|
| 277 |
+
final_repo: Final repository name (default: {base_repo})
|
| 278 |
+
test_ratio: Fraction to hold out as test split
|
| 279 |
+
seed: Random seed
|
| 280 |
+
|
| 281 |
+
Returns:
|
| 282 |
+
Final dataset repo ID
|
| 283 |
+
"""
|
| 284 |
+
from datasets import concatenate_datasets, DatasetDict
|
| 285 |
+
from prepare_merged_text_dataset import upload_dataset_to_hub
|
| 286 |
+
|
| 287 |
+
final_repo = final_repo or f"{hf_username}/{base_repo}"
|
| 288 |
+
chunk_repos = [f"{hf_username}/{base_repo}-chunk-{i}" for i in range(total_chunks)]
|
| 289 |
+
|
| 290 |
+
logger.info(f"=" * 70)
|
| 291 |
+
logger.info(f"Merging {total_chunks} chunks into final dataset")
|
| 292 |
+
logger.info(f" Final repo: {final_repo}")
|
| 293 |
+
logger.info(f"=" * 70)
|
| 294 |
+
|
| 295 |
+
# Load and concatenate all chunks
|
| 296 |
+
all_datasets = []
|
| 297 |
+
for i, repo in enumerate(chunk_repos):
|
| 298 |
+
logger.info(f"Loading chunk {i} from {repo}...")
|
| 299 |
+
try:
|
| 300 |
+
from datasets import load_dataset
|
| 301 |
+
chunk_ds = load_dataset(repo, split="train", token=token)
|
| 302 |
+
all_datasets.append(chunk_ds)
|
| 303 |
+
logger.info(f" Chunk {i}: {len(chunk_ds)} samples")
|
| 304 |
+
except Exception as e:
|
| 305 |
+
logger.error(f"Failed to load chunk {i} from {repo}: {e}")
|
| 306 |
+
raise
|
| 307 |
+
|
| 308 |
+
# Concatenate
|
| 309 |
+
logger.info("Concatenating all chunks...")
|
| 310 |
+
merged_ds = concatenate_datasets(all_datasets)
|
| 311 |
+
logger.info(f"Total merged dataset size: {len(merged_ds)} samples")
|
| 312 |
+
|
| 313 |
+
# Shuffle the merged dataset
|
| 314 |
+
logger.info(f"Shuffling merged dataset (seed={seed})...")
|
| 315 |
+
merged_ds = merged_ds.shuffle(seed=seed)
|
| 316 |
+
|
| 317 |
+
# Apply test split if requested
|
| 318 |
+
dataset_for_upload = merged_ds
|
| 319 |
+
if test_ratio > 0:
|
| 320 |
+
logger.info(f"Splitting dataset with test_ratio={test_ratio}...")
|
| 321 |
+
split_dict = merged_ds.train_test_split(test_size=test_ratio, seed=seed)
|
| 322 |
+
dataset_for_upload = DatasetDict({
|
| 323 |
+
"train": split_dict["train"],
|
| 324 |
+
"test": split_dict["test"],
|
| 325 |
+
})
|
| 326 |
+
logger.info(f" Train: {len(split_dict['train'])}, Test: {len(split_dict['test'])}")
|
| 327 |
+
|
| 328 |
+
# Upload if requested
|
| 329 |
+
if upload:
|
| 330 |
+
logger.info(f"Uploading final dataset to {final_repo}...")
|
| 331 |
+
upload_dataset_to_hub(
|
| 332 |
+
dataset_for_upload,
|
| 333 |
+
repo_id=final_repo,
|
| 334 |
+
private=True,
|
| 335 |
+
token=token,
|
| 336 |
+
)
|
| 337 |
+
logger.info(f"Final dataset uploaded to {final_repo}!")
|
| 338 |
+
|
| 339 |
+
return final_repo
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def show_chunk_plan(chunk_size: int, total_files: int = TOTAL_TRAIN_FILES):
|
| 343 |
+
"""Display the chunking plan without processing."""
|
| 344 |
+
chunks = calculate_chunks(chunk_size)
|
| 345 |
+
|
| 346 |
+
print("\n" + "=" * 70)
|
| 347 |
+
print(f"CHUNK PLAN: {total_files} files ÷ {chunk_size} files/chunk")
|
| 348 |
+
print("=" * 70)
|
| 349 |
+
|
| 350 |
+
total_est_gb = 0
|
| 351 |
+
for idx, start, end in chunks:
|
| 352 |
+
files_in_chunk = end - start
|
| 353 |
+
est_gb = files_in_chunk * 0.2
|
| 354 |
+
total_est_gb += est_gb
|
| 355 |
+
print(f" Chunk {idx}: files {start:3d}-{end-1:3d} ({files_in_chunk:2d} files, ~{est_gb:.1f}GB)")
|
| 356 |
+
|
| 357 |
+
print("-" * 70)
|
| 358 |
+
print(f" Total: {len(chunks)} chunks, ~{total_est_gb:.1f}GB")
|
| 359 |
+
print(f" Each chunk safely under 50GB HF Jobs limit")
|
| 360 |
+
print("=" * 70)
|
| 361 |
+
print("\nTo process all chunks, run:")
|
| 362 |
+
for idx, _, _ in chunks:
|
| 363 |
+
print(f" hf jobs uv run train/prepare_chunked_dataset.py \\")
|
| 364 |
+
print(f" --flavor cpu-xl --secrets HF_TOKEN --timeout 4h \\")
|
| 365 |
+
print(f" -- --hf-username YOUR_USER --base-repo YOUR_REPO --chunk-index {idx} --upload")
|
| 366 |
+
print(f"\nThen merge:")
|
| 367 |
+
print(f" hf jobs uv run train/prepare_chunked_dataset.py \\")
|
| 368 |
+
print(f" --flavor cpu-basic --secrets HF_TOKEN --timeout 2h \\")
|
| 369 |
+
print(f" -- --hf-username YOUR_USER --base-repo YOUR_REPO --merge-chunks --total-chunks {len(chunks)} --upload")
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def parse_args() -> argparse.Namespace:
|
| 373 |
+
"""Parse command line arguments."""
|
| 374 |
+
parser = argparse.ArgumentParser(
|
| 375 |
+
description="Chunked dataset preparation for large Android datasets",
|
| 376 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 377 |
+
epilog="""
|
| 378 |
+
Examples:
|
| 379 |
+
# Plan only - show chunk distribution
|
| 380 |
+
uv run train/prepare_chunked_dataset.py --hf-username Tonic --base-repo android-text --chunk-size 45 --plan-only
|
| 381 |
+
|
| 382 |
+
# Process a single chunk
|
| 383 |
+
uv run train/prepare_chunked_dataset.py --hf-username Tonic --base-repo android-text --chunk-index 0 --upload
|
| 384 |
+
|
| 385 |
+
# Merge all chunks into final dataset
|
| 386 |
+
uv run train/prepare_chunked_dataset.py --hf-username Tonic --base-repo android-text --merge-chunks --total-chunks 6 --upload
|
| 387 |
+
""",
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
# Required
|
| 391 |
+
parser.add_argument("--hf-username", required=True, help="HuggingFace username")
|
| 392 |
+
parser.add_argument("--base-repo", required=True, help="Base repository name")
|
| 393 |
+
|
| 394 |
+
# Chunk processing
|
| 395 |
+
parser.add_argument("--chunk-index", type=int, default=None, help="Which chunk to process (0-based)")
|
| 396 |
+
parser.add_argument("--chunk-size", type=int, default=DEFAULT_CHUNK_SIZE, help=f"Files per chunk (default: {DEFAULT_CHUNK_SIZE})")
|
| 397 |
+
parser.add_argument("--total-chunks", type=int, default=None, help="Total number of chunks (for merge)")
|
| 398 |
+
|
| 399 |
+
# Merge mode
|
| 400 |
+
parser.add_argument("--merge-chunks", action="store_true", help="Merge all chunks instead of processing")
|
| 401 |
+
parser.add_argument("--final-repo", default=None, help="Final repo name (default: base-repo)")
|
| 402 |
+
|
| 403 |
+
# Data options
|
| 404 |
+
parser.add_argument("--max-episodes", type=int, default=None, help="Max episodes per chunk")
|
| 405 |
+
parser.add_argument("--max-mobile-actions", type=int, default=None, help="Mobile actions to include in chunk 0")
|
| 406 |
+
parser.add_argument("--android-ratio", type=float, default=0.5, help="Android ratio when merging with mobile-actions")
|
| 407 |
+
parser.add_argument("--test-ratio", type=float, default=0.0, help="Test split ratio for final dataset")
|
| 408 |
+
parser.add_argument("--seed", type=int, default=42, help="Random seed")
|
| 409 |
+
|
| 410 |
+
# Control
|
| 411 |
+
parser.add_argument("--upload", action="store_true", help="Upload to HuggingFace Hub")
|
| 412 |
+
parser.add_argument("--plan-only", action="store_true", help="Show chunk plan without processing")
|
| 413 |
+
parser.add_argument("--skip-mobile-actions", action="store_true", help="Skip mobile-actions even in chunk 0")
|
| 414 |
+
|
| 415 |
+
return parser.parse_args()
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def main():
|
| 419 |
+
"""Main entry point."""
|
| 420 |
+
args = parse_args()
|
| 421 |
+
|
| 422 |
+
# Get token
|
| 423 |
+
token = os.environ.get("HF_TOKEN") or os.environ.get("hfjob")
|
| 424 |
+
if not token:
|
| 425 |
+
logger.error("HF_TOKEN environment variable not set!")
|
| 426 |
+
sys.exit(1)
|
| 427 |
+
|
| 428 |
+
# Plan only mode
|
| 429 |
+
if args.plan_only:
|
| 430 |
+
show_chunk_plan(args.chunk_size)
|
| 431 |
+
return
|
| 432 |
+
|
| 433 |
+
# Merge mode
|
| 434 |
+
if args.merge_chunks:
|
| 435 |
+
if not args.total_chunks:
|
| 436 |
+
logger.error("--total-chunks required when using --merge-chunks")
|
| 437 |
+
sys.exit(1)
|
| 438 |
+
|
| 439 |
+
final_repo = merge_all_chunks(
|
| 440 |
+
hf_username=args.hf_username,
|
| 441 |
+
base_repo=args.base_repo,
|
| 442 |
+
total_chunks=args.total_chunks,
|
| 443 |
+
token=token,
|
| 444 |
+
upload=args.upload,
|
| 445 |
+
final_repo=f"{args.hf_username}/{args.final_repo}" if args.final_repo else None,
|
| 446 |
+
test_ratio=args.test_ratio,
|
| 447 |
+
seed=args.seed,
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
print("\n" + "=" * 70)
|
| 451 |
+
print("MERGE COMPLETE!")
|
| 452 |
+
print("=" * 70)
|
| 453 |
+
print(f"Final dataset: https://huggingface.co/datasets/{final_repo}")
|
| 454 |
+
return
|
| 455 |
+
|
| 456 |
+
# Process single chunk mode
|
| 457 |
+
if args.chunk_index is None:
|
| 458 |
+
logger.error("Either --chunk-index or --merge-chunks or --plan-only required")
|
| 459 |
+
sys.exit(1)
|
| 460 |
+
|
| 461 |
+
# Validate chunk index
|
| 462 |
+
total_chunks_estimated = (TOTAL_TRAIN_FILES + args.chunk_size - 1) // args.chunk_size
|
| 463 |
+
if args.chunk_index < 0 or args.chunk_index >= total_chunks_estimated:
|
| 464 |
+
logger.error(f"Invalid chunk index {args.chunk_index}. Valid range: 0 to {total_chunks_estimated - 1}")
|
| 465 |
+
sys.exit(1)
|
| 466 |
+
|
| 467 |
+
# Process the chunk
|
| 468 |
+
chunk_repo = process_chunk(
|
| 469 |
+
hf_username=args.hf_username,
|
| 470 |
+
base_repo=args.base_repo,
|
| 471 |
+
chunk_index=args.chunk_index,
|
| 472 |
+
chunk_size=args.chunk_size,
|
| 473 |
+
token=token,
|
| 474 |
+
upload=args.upload,
|
| 475 |
+
max_episodes=args.max_episodes,
|
| 476 |
+
include_mobile_actions=not args.skip_mobile_actions,
|
| 477 |
+
max_mobile_actions=args.max_mobile_actions,
|
| 478 |
+
android_ratio=args.android_ratio,
|
| 479 |
+
seed=args.seed,
|
| 480 |
+
)
|
| 481 |
+
|
| 482 |
+
print("\n" + "=" * 70)
|
| 483 |
+
print(f"CHUNK {args.chunk_index} COMPLETE!")
|
| 484 |
+
print("=" * 70)
|
| 485 |
+
print(f"Chunk dataset: https://huggingface.co/datasets/{chunk_repo}")
|
| 486 |
+
print(f"\nNext steps:")
|
| 487 |
+
print(f" 1. Process remaining chunks (change --chunk-index)")
|
| 488 |
+
print(f" 2. Merge all chunks with: --merge-chunks --total-chunks {total_chunks_estimated} --upload")
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
if __name__ == "__main__":
|
| 492 |
+
main()
|