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13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.10"
# dependencies = [
#     "datasets",
#     "huggingface_hub[hf_transfer]",
#     "tqdm",
# ]
# ///
"""

Chunked dataset preparation for large Android datasets that exceed 50GB ephemeral storage.



This script processes the Android dataset in chunks to stay under the HF Jobs 50GB limit,

then uploads intermediate chunk datasets. A final merge step combines all chunks.



Workflow:

1. Plan: Calculate chunks based on total files and chunk size

2. Process: Each HF Job processes one chunk (e.g., files 0-49, 50-99, etc.)

3. Upload: Each chunk becomes a separate dataset (e.g., android-text-chunk-0)

4. Merge: Final job merges all chunks into the complete dataset



Usage - Process a single chunk:

    hf jobs uv run train/prepare_chunked_dataset.py \\

        --flavor cpu-xl --secrets HF_TOKEN --timeout 4h \\

        -- --hf-username Tonic \\

           --base-repo android-text-full \\

           --chunk-index 0 \\

           --chunk-size 45 \\

           --upload



Usage - Merge all chunks:

    hf jobs uv run train/prepare_chunked_dataset.py \\

        --flavor cpu-basic --secrets HF_TOKEN --timeout 2h \\

        -- --hf-username Tonic \\

           --base-repo android-text-full \\

           --merge-chunks \\

           --total-chunks 6 \\

           --upload



Usage - Plan only (show chunk distribution without processing):

    uv run train/prepare_chunked_dataset.py \\

        --hf-username Tonic \\

        --base-repo android-text-full \\

        --chunk-size 45 \\

        --plan-only

"""

import argparse
import json
import logging
import os
import sys
from typing import Any, Dict, List, Optional, Tuple

# Force UTF-8 output
if hasattr(sys.stdout, "reconfigure"):
    try:
        sys.stdout.reconfigure(encoding="utf-8", line_buffering=True)
        sys.stderr.reconfigure(encoding="utf-8", line_buffering=True)
    except (AttributeError, OSError):
        pass

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)

# Constants
ANDROID_DATASET = "Tonic/android-operator-episodes"
MOBILE_ACTIONS_DATASET = "google/mobile-actions"
DEFAULT_CHUNK_SIZE = 45  # Files per chunk (~9GB per chunk)
TOTAL_TRAIN_FILES = 275  # Total train parquet files


def _get_train_parquet_files(

    token: Optional[str] = None,

    offset: int = 0,

    limit: Optional[int] = None,

) -> List[str]:
    """

    List train parquet files with offset/limit for chunking.

    

    Args:

        token: HF token

        offset: Start index (for chunking)

        limit: Max files to return (None = all from offset)

        

    Returns:

        List of hf:// URLs for the specified file range

    """
    from huggingface_hub import HfFileSystem
    
    fs = HfFileSystem(token=token)
    prefix = f"datasets/{ANDROID_DATASET}/data"
    raw = fs.glob(f"{prefix}/train-*.parquet")
    raw.sort()
    
    # Apply offset and limit
    end = offset + limit if limit else len(raw)
    selected = raw[offset:end]
    
    # Convert to hf:// URLs
    return [f"hf://{path.replace('/data/', '@main/data/', 1)}" for path in selected]


def _count_total_train_files(token: Optional[str] = None) -> int:
    """Count total train files in the dataset."""
    from huggingface_hub import HfFileSystem
    
    fs = HfFileSystem(token=token)
    prefix = f"datasets/{ANDROID_DATASET}/data"
    files = fs.glob(f"{prefix}/train-*.parquet")
    return len(files)


def calculate_chunks(chunk_size: int) -> List[Tuple[int, int, int]]:
    """

    Calculate chunk boundaries.

    

    Returns:

        List of (chunk_index, start_file, end_file) tuples

    """
    chunks = []
    for start in range(0, TOTAL_TRAIN_FILES, chunk_size):
        end = min(start + chunk_size, TOTAL_TRAIN_FILES)
        chunk_idx = start // chunk_size
        chunks.append((chunk_idx, start, end))
    return chunks


def process_chunk(

    hf_username: str,

    base_repo: str,

    chunk_index: int,

    chunk_size: int,

    token: Optional[str] = None,

    upload: bool = False,

    system_message: Optional[str] = None,

    max_episodes: Optional[int] = None,

    include_mobile_actions: bool = True,

    max_mobile_actions: Optional[int] = None,

    android_ratio: float = 0.5,

    seed: int = 42,

) -> str:
    """

    Process a single chunk of Android files.

    

    Args:

        hf_username: HF username

        base_repo: Base repository name (chunk will be {base_repo}-chunk-{index})

        chunk_index: Which chunk to process (0-based)

        chunk_size: Number of files per chunk

        token: HF token

        upload: Whether to upload the chunk

        system_message: Custom system message

        max_episodes: Max episodes to process from this chunk

        include_mobile_actions: Whether to include mobile-actions in this chunk

        max_mobile_actions: Max mobile-actions samples

        android_ratio: Ratio for merging (if include_mobile_actions)

        seed: Random seed

        

    Returns:

        Dataset repo ID for the processed chunk

    """
    from datasets import Dataset, load_dataset
    from prepare_merged_text_dataset import (
        explode_android_episodes_to_steps,
        build_android_conversations,
        TEXT_ONLY_ACTION_TYPES,
        is_text_only_action,
        serialize_action_to_json,
        load_mobile_actions_data,
        merge_datasets,
        upload_dataset_to_hub,
    )
    
    offset = chunk_index * chunk_size
    chunk_repo = f"{hf_username}/{base_repo}-chunk-{chunk_index}"
    
    logger.info(f"=" * 70)
    logger.info(f"Processing Chunk {chunk_index}")
    logger.info(f"  Files: {offset} to {min(offset + chunk_size, TOTAL_TRAIN_FILES) - 1}")
    logger.info(f"  Estimated size: ~{chunk_size * 0.2:.1f}GB")
    logger.info(f"  Target repo: {chunk_repo}")
    logger.info(f"=" * 70)
    
    # Get file list for this chunk
    data_files = _get_train_parquet_files(token=token, offset=offset, limit=chunk_size)
    if not data_files:
        raise ValueError(f"No files found for chunk {chunk_index} (offset={offset})")
    
    logger.info(f"Loading {len(data_files)} parquet files for chunk {chunk_index}...")
    
    # Load Android data for this chunk
    ds = load_dataset(
        "parquet",
        data_files=data_files,
        split="train",
        token=token,
    )
    logger.info(f"Loaded {len(ds)} episodes in chunk {chunk_index}")
    
    # Limit episodes if specified
    if max_episodes and max_episodes > 0:
        ds = ds.select(range(min(max_episodes, len(ds))))
        logger.info(f"Limited to {len(ds)} episodes")
    
    # Explode to steps with filtering
    logger.info(f"Chunk {chunk_index}: Exploding episodes to text-only steps...")
    step_ds = ds.map(
        explode_android_episodes_to_steps,
        batched=True,
        remove_columns=ds.column_names,
        desc=f"Chunk {chunk_index}: Exploding",
    )
    logger.info(f"Chunk {chunk_index}: Created {len(step_ds)} text-only step examples")
    
    # Build conversations
    logger.info(f"Chunk {chunk_index}: Building conversation format...")
    conversation_ds = step_ds.map(
        lambda x: build_android_conversations(x, system_message),
        batched=True,
        desc=f"Chunk {chunk_index}: Conversations",
    )
    
    # Keep only conversations
    conversation_ds = conversation_ds.remove_columns(
        [col for col in conversation_ds.column_names if col != "conversations"]
    )
    
    # Optionally include mobile-actions in first chunk only (to avoid duplicates)
    if include_mobile_actions and max_mobile_actions and chunk_index == 0:
        logger.info(f"Chunk {chunk_index}: Including mobile-actions data...")
        mobile_ds = load_mobile_actions_data(max_samples=max_mobile_actions, split="train")
        conversation_ds = merge_datasets(
            android_ds=conversation_ds,
            mobile_actions_ds=mobile_ds,
            android_ratio=android_ratio,
            seed=seed,
        )
        logger.info(f"Chunk {chunk_index}: Final size with mobile-actions: {len(conversation_ds)}")
    
    # Upload if requested
    if upload:
        logger.info(f"Chunk {chunk_index}: Uploading to {chunk_repo}...")
        upload_dataset_to_hub(
            conversation_ds,
            repo_id=chunk_repo,
            private=True,
            token=token,
        )
        logger.info(f"Chunk {chunk_index}: Uploaded successfully!")
    
    return chunk_repo


def merge_all_chunks(

    hf_username: str,

    base_repo: str,

    total_chunks: int,

    token: Optional[str] = None,

    upload: bool = False,

    final_repo: Optional[str] = None,

    test_ratio: float = 0.0,

    seed: int = 42,

) -> str:
    """

    Merge all processed chunks into the final dataset.

    

    Args:

        hf_username: HF username

        base_repo: Base repo name (chunks are {base_repo}-chunk-{N})

        total_chunks: Total number of chunks to merge

        token: HF token

        upload: Whether to upload the final merged dataset

        final_repo: Final repository name (default: {base_repo})

        test_ratio: Fraction to hold out as test split

        seed: Random seed

        

    Returns:

        Final dataset repo ID

    """
    from datasets import concatenate_datasets, DatasetDict
    from prepare_merged_text_dataset import upload_dataset_to_hub
    
    final_repo = final_repo or f"{hf_username}/{base_repo}"
    chunk_repos = [f"{hf_username}/{base_repo}-chunk-{i}" for i in range(total_chunks)]
    
    logger.info(f"=" * 70)
    logger.info(f"Merging {total_chunks} chunks into final dataset")
    logger.info(f"  Final repo: {final_repo}")
    logger.info(f"=" * 70)
    
    # Load and concatenate all chunks
    all_datasets = []
    for i, repo in enumerate(chunk_repos):
        logger.info(f"Loading chunk {i} from {repo}...")
        try:
            from datasets import load_dataset
            chunk_ds = load_dataset(repo, split="train", token=token)
            all_datasets.append(chunk_ds)
            logger.info(f"  Chunk {i}: {len(chunk_ds)} samples")
        except Exception as e:
            logger.error(f"Failed to load chunk {i} from {repo}: {e}")
            raise
    
    # Concatenate
    logger.info("Concatenating all chunks...")
    merged_ds = concatenate_datasets(all_datasets)
    logger.info(f"Total merged dataset size: {len(merged_ds)} samples")
    
    # Shuffle the merged dataset
    logger.info(f"Shuffling merged dataset (seed={seed})...")
    merged_ds = merged_ds.shuffle(seed=seed)
    
    # Apply test split if requested
    dataset_for_upload = merged_ds
    if test_ratio > 0:
        logger.info(f"Splitting dataset with test_ratio={test_ratio}...")
        split_dict = merged_ds.train_test_split(test_size=test_ratio, seed=seed)
        dataset_for_upload = DatasetDict({
            "train": split_dict["train"],
            "test": split_dict["test"],
        })
        logger.info(f"  Train: {len(split_dict['train'])}, Test: {len(split_dict['test'])}")
    
    # Upload if requested
    if upload:
        logger.info(f"Uploading final dataset to {final_repo}...")
        upload_dataset_to_hub(
            dataset_for_upload,
            repo_id=final_repo,
            private=True,
            token=token,
        )
        logger.info(f"Final dataset uploaded to {final_repo}!")
    
    return final_repo


def show_chunk_plan(chunk_size: int, total_files: int = TOTAL_TRAIN_FILES):
    """Display the chunking plan without processing."""
    chunks = calculate_chunks(chunk_size)
    
    print("\n" + "=" * 70)
    print(f"CHUNK PLAN: {total_files} files ÷ {chunk_size} files/chunk")
    print("=" * 70)
    
    total_est_gb = 0
    for idx, start, end in chunks:
        files_in_chunk = end - start
        est_gb = files_in_chunk * 0.2
        total_est_gb += est_gb
        print(f"  Chunk {idx}: files {start:3d}-{end-1:3d} ({files_in_chunk:2d} files, ~{est_gb:.1f}GB)")
    
    print("-" * 70)
    print(f"  Total: {len(chunks)} chunks, ~{total_est_gb:.1f}GB")
    print(f"  Each chunk safely under 50GB HF Jobs limit")
    print("=" * 70)
    print("\nTo process all chunks, run:")
    for idx, _, _ in chunks:
        print(f"  hf jobs uv run train/prepare_chunked_dataset.py \\")
        print(f"      --flavor cpu-xl --secrets HF_TOKEN --timeout 4h \\")
        print(f"      -- --hf-username YOUR_USER --base-repo YOUR_REPO --chunk-index {idx} --upload")
    print(f"\nThen merge:")
    print(f"  hf jobs uv run train/prepare_chunked_dataset.py \\")
    print(f"      --flavor cpu-basic --secrets HF_TOKEN --timeout 2h \\")
    print(f"      -- --hf-username YOUR_USER --base-repo YOUR_REPO --merge-chunks --total-chunks {len(chunks)} --upload")


def parse_args() -> argparse.Namespace:
    """Parse command line arguments."""
    parser = argparse.ArgumentParser(
        description="Chunked dataset preparation for large Android datasets",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""

Examples:

  # Plan only - show chunk distribution

  uv run train/prepare_chunked_dataset.py --hf-username Tonic --base-repo android-text --chunk-size 45 --plan-only



  # Process a single chunk

  uv run train/prepare_chunked_dataset.py --hf-username Tonic --base-repo android-text --chunk-index 0 --upload



  # Merge all chunks into final dataset

  uv run train/prepare_chunked_dataset.py --hf-username Tonic --base-repo android-text --merge-chunks --total-chunks 6 --upload

        """,
    )
    
    # Required
    parser.add_argument("--hf-username", required=True, help="HuggingFace username")
    parser.add_argument("--base-repo", required=True, help="Base repository name")
    
    # Chunk processing
    parser.add_argument("--chunk-index", type=int, default=None, help="Which chunk to process (0-based)")
    parser.add_argument("--chunk-size", type=int, default=DEFAULT_CHUNK_SIZE, help=f"Files per chunk (default: {DEFAULT_CHUNK_SIZE})")
    parser.add_argument("--total-chunks", type=int, default=None, help="Total number of chunks (for merge)")
    
    # Merge mode
    parser.add_argument("--merge-chunks", action="store_true", help="Merge all chunks instead of processing")
    parser.add_argument("--final-repo", default=None, help="Final repo name (default: base-repo)")
    
    # Data options
    parser.add_argument("--max-episodes", type=int, default=None, help="Max episodes per chunk")
    parser.add_argument("--max-mobile-actions", type=int, default=None, help="Mobile actions to include in chunk 0")
    parser.add_argument("--android-ratio", type=float, default=0.5, help="Android ratio when merging with mobile-actions")
    parser.add_argument("--test-ratio", type=float, default=0.0, help="Test split ratio for final dataset")
    parser.add_argument("--seed", type=int, default=42, help="Random seed")
    
    # Control
    parser.add_argument("--upload", action="store_true", help="Upload to HuggingFace Hub")
    parser.add_argument("--plan-only", action="store_true", help="Show chunk plan without processing")
    parser.add_argument("--skip-mobile-actions", action="store_true", help="Skip mobile-actions even in chunk 0")
    
    return parser.parse_args()


def main():
    """Main entry point."""
    args = parse_args()
    
    # Get token
    token = os.environ.get("HF_TOKEN") or os.environ.get("hfjob")
    if not token:
        logger.error("HF_TOKEN environment variable not set!")
        sys.exit(1)
    
    # Plan only mode
    if args.plan_only:
        show_chunk_plan(args.chunk_size)
        return
    
    # Merge mode
    if args.merge_chunks:
        if not args.total_chunks:
            logger.error("--total-chunks required when using --merge-chunks")
            sys.exit(1)
        
        final_repo = merge_all_chunks(
            hf_username=args.hf_username,
            base_repo=args.base_repo,
            total_chunks=args.total_chunks,
            token=token,
            upload=args.upload,
            final_repo=f"{args.hf_username}/{args.final_repo}" if args.final_repo else None,
            test_ratio=args.test_ratio,
            seed=args.seed,
        )
        
        print("\n" + "=" * 70)
        print("MERGE COMPLETE!")
        print("=" * 70)
        print(f"Final dataset: https://huggingface.co/datasets/{final_repo}")
        return
    
    # Process single chunk mode
    if args.chunk_index is None:
        logger.error("Either --chunk-index or --merge-chunks or --plan-only required")
        sys.exit(1)
    
    # Validate chunk index
    total_chunks_estimated = (TOTAL_TRAIN_FILES + args.chunk_size - 1) // args.chunk_size
    if args.chunk_index < 0 or args.chunk_index >= total_chunks_estimated:
        logger.error(f"Invalid chunk index {args.chunk_index}. Valid range: 0 to {total_chunks_estimated - 1}")
        sys.exit(1)
    
    # Process the chunk
    chunk_repo = process_chunk(
        hf_username=args.hf_username,
        base_repo=args.base_repo,
        chunk_index=args.chunk_index,
        chunk_size=args.chunk_size,
        token=token,
        upload=args.upload,
        max_episodes=args.max_episodes,
        include_mobile_actions=not args.skip_mobile_actions,
        max_mobile_actions=args.max_mobile_actions,
        android_ratio=args.android_ratio,
        seed=args.seed,
    )
    
    print("\n" + "=" * 70)
    print(f"CHUNK {args.chunk_index} COMPLETE!")
    print("=" * 70)
    print(f"Chunk dataset: https://huggingface.co/datasets/{chunk_repo}")
    print(f"\nNext steps:")
    print(f"  1. Process remaining chunks (change --chunk-index)")
    print(f"  2. Merge all chunks with: --merge-chunks --total-chunks {total_chunks_estimated} --upload")


if __name__ == "__main__":
    main()