Spaces:
Runtime error
Runtime error
File size: 6,561 Bytes
eac3e12 9d9b17a eac3e12 dd9b764 eac3e12 39a14f4 eac3e12 3e0ccf2 eac3e12 9d9b17a eac3e12 c303b5e eac3e12 9d9b17a eac3e12 9d9b17a eac3e12 ef69b46 eac3e12 9d9b17a 9f8f6bf 9d9b17a fe5c277 9f8f6bf fe5c277 9d9b17a eac3e12 fe5c277 c59ebf3 fe5c277 eac3e12 9d9b17a eac3e12 | 1 2 3 4 5 6 7 8 9 10 11 12 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 | #!/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()
|