Spaces:
Runtime error
Runtime error
Download process_small.py from mohit-vashishta/c4-en-processor: direct link, hf CLI and curl.
- Browser
- Download file 6.56 kB
-
https://huggingface.co/spaces/mohit-vashishta/c4-en-processor/resolve/main/process_small.py
- Command line
-
hf download hf://spaces/mohit-vashishta/c4-en-processor/process_small.py
-
curl -L -o process_small.py https://huggingface.co/spaces/mohit-vashishta/c4-en-processor/resolve/main/process_small.py
6.56 kB
| #!/usr/bin/env python3 | |
| """ | |
| HF Space - Small dataset processor | |
| Downloads from HF Datasets, tokenizes, uploads back to HF Datasets. | |
| Uses HF Datasets as storage (no external bucket needed). | |
| """ | |
| import json, time, os, sys | |
| from pathlib import Path | |
| from huggingface_hub import HfApi, hf_hub_download, upload_file | |
| TOKEN = os.environ.get("HF_TOKEN", "") | |
| HF_REPO = "mohit-vashishta/bhaari-training-data-100b" | |
| WORK_DIR = Path("/app") | |
| DATA_DIR = WORK_DIR / "data" | |
| TOKENIZER_PATH = WORK_DIR / "tokenizer" / "tokenizer.json" | |
| for d in [DATA_DIR]: | |
| d.mkdir(parents=True, exist_ok=True) | |
| def log(msg): | |
| ts = time.strftime("%H:%M:%S") | |
| print(f"[{ts}] {msg}") | |
| sys.stdout.flush() | |
| def check_disk(): | |
| stat = os.statvfs("/app") | |
| free_gb = (stat.f_bavail * stat.f_frsize) / 1e9 | |
| used_gb = ((stat.f_blocks - stat.f_bfree) * stat.f_frsize) / 1e9 | |
| total_gb = (stat.f_blocks * stat.f_frsize) / 1e9 | |
| return total_gb, used_gb, free_gb | |
| def main(): | |
| log("=" * 60) | |
| log("HF Space - Small Dataset Processor") | |
| log("=" * 60) | |
| # Debug: list available env var names | |
| log(f"Available env vars: {[k for k in os.environ.keys() if 'HF' in k or 'TOKEN' in k or 'SECRET' in k]}") | |
| total, used, free = check_disk() | |
| log(f"Disk: Total={total:.1f}GB, Used={used:.1f}GB, Free={free:.1f}GB") | |
| if not TOKEN: | |
| log("ERROR: HF_TOKEN not set in Space secrets") | |
| log("Set it at: Space Settings > Variables and secrets") | |
| return | |
| api = HfApi(token=TOKEN) | |
| # Download tokenizer | |
| log("Downloading tokenizer...") | |
| try: | |
| hf_hub_download(HF_REPO, "tokenizer/tokenizer.json", | |
| local_dir=str(WORK_DIR), token=TOKEN, repo_type="dataset") | |
| log("Tokenizer downloaded") | |
| except Exception as e: | |
| log(f"Tokenizer download failed: {e}") | |
| return | |
| # List available small files to process | |
| log("Scanning for pending JSONL files...") | |
| try: | |
| all_items = list(api.list_repo_tree(HF_REPO, repo_type="dataset", recursive=True)) | |
| jsonl_items = [item for item in all_items if item.path.endswith(".jsonl")] | |
| log(f"Found {len(jsonl_items)} JSONL files on HF") | |
| # Build set of existing NPY files | |
| npy_paths = set(item.path for item in all_items if item.path.endswith(".npy")) | |
| # Find pending JSONL files (no NPY counterpart) | |
| pending = [] | |
| for item in jsonl_items: | |
| npy_path = item.path.replace(".jsonl", ".npy") | |
| if npy_path not in npy_paths: | |
| pending.append((item.path, item.size)) | |
| log(f"Found {len(pending)} pending JSONL files") | |
| if not pending: | |
| log("No pending files to process") | |
| return | |
| # Sort by size and pick all files under 500MB | |
| pending.sort(key=lambda x: x[1]) | |
| small_pending = [(p, s) for p, s in pending if s < 500_000_000] | |
| if not small_pending: | |
| log("No pending files under 500MB") | |
| return | |
| log(f"Found {len(small_pending)} files under 500MB to process") | |
| except Exception as e: | |
| log(f"File scan failed: {e}") | |
| return | |
| # Process all small files | |
| for idx, (test_file, file_size) in enumerate(small_pending): | |
| file_size_mb = file_size / 1e6 | |
| log(f"\n[{idx+1}/{len(small_pending)}] Processing: {test_file} ({file_size_mb:.1f}MB)") | |
| # Download JSONL | |
| log(f"Downloading {test_file}...") | |
| try: | |
| local_jsonl = hf_hub_download(HF_REPO, test_file, | |
| repo_type="dataset", token=TOKEN) | |
| log(f"Downloaded: {os.path.getsize(local_jsonl)/1e6:.1f}MB") | |
| except Exception as e: | |
| log(f"Download failed: {e}") | |
| continue | |
| total, used, free = check_disk() | |
| log(f"Disk after download: Used={used:.1f}GB, Free={free:.1f}GB") | |
| # Tokenize | |
| log("Loading tokenizer...") | |
| from tokenizers import Tokenizer | |
| tok = Tokenizer.from_file(str(TOKENIZER_PATH)) | |
| log("Tokenizing...") | |
| t0 = time.time() | |
| all_tokens = [] | |
| row_count = 0 | |
| with open(local_jsonl) as f: | |
| for line in f: | |
| try: | |
| obj = json.loads(line) | |
| text = obj.get("text", "").strip() | |
| if len(text) >= 50: | |
| encoded = tok.encode(text) | |
| all_tokens.extend(encoded.ids) | |
| row_count += 1 | |
| except: | |
| continue | |
| tok_time = time.time() - t0 | |
| log(f"Tokenized {row_count:,} rows, {len(all_tokens):,} tokens in {tok_time:.1f}s") | |
| log(f"Speed: {len(all_tokens)/tok_time/1000:.0f}K tokens/sec") | |
| # Save as BHRI format | |
| output_name = test_file.replace(".jsonl", ".npy") | |
| output_path = DATA_DIR / output_name | |
| log(f"Saving BHRI format to {output_path}...") | |
| # Create parent directory if needed | |
| output_path.parent.mkdir(parents=True, exist_ok=True) | |
| import struct | |
| with open(output_path, "wb") as f: | |
| f.write(b"BHRI") | |
| f.write(struct.pack("<I", 1)) # version | |
| f.write(struct.pack("<I", len(all_tokens))) | |
| f.write(struct.pack("<I", 500000)) # control token | |
| for token in all_tokens: | |
| f.write(struct.pack("<I", token)) | |
| output_size = output_path.stat().st_size | |
| log(f"Output: {output_size/1e6:.1f}MB") | |
| total, used, free = check_disk() | |
| log(f"Disk after tokenize: Used={used:.1f}GB, Free={free:.1f}GB") | |
| # Upload back to HF | |
| log(f"Uploading {output_name} to HF...") | |
| try: | |
| api.upload_file( | |
| path_or_fileobj=str(output_path), | |
| path_in_repo=output_name, | |
| repo_id=HF_REPO, | |
| repo_type="dataset" | |
| ) | |
| log("Upload successful!") | |
| except Exception as e: | |
| log(f"Upload failed: {e}") | |
| # Clean up downloaded files to free space | |
| log("Cleaning up local files...") | |
| os.remove(local_jsonl) | |
| os.remove(output_path) | |
| total, used, free = check_disk() | |
| log(f"Disk after cleanup: Used={used:.1f}GB, Free={free:.1f}GB") | |
| log("=" * 60) | |
| log("PROCESSING COMPLETE") | |
| log("=" * 60) | |
| if __name__ == "__main__": | |
| main() | |