AbrFerdowsi's picture
Upload folder using huggingface_hub (part 3)
6a125ea verified
Raw History Blame Contribute Delete
2.21 kB
import os
import json
import gc
import subprocess
from datasets import Dataset, Features, Sequence, Value
# Define features
FEATURES = Features(
{
"input_features": Sequence(Sequence(Value("float32"))),
"labels": Sequence(Value("int64")),
}
)
INPUT_FILE = "/home/ubuntu/tmp_batch.jsonl.gz"
def has_huge_outliers(data):
if isinstance(data, list):
for item in data:
if has_huge_outliers(item):
return True
return False
if isinstance(data, (int, float)):
if abs(data) > 1e14:
return True
return False
def gen():
print(f"Reading {INPUT_FILE} using system gzip...")
dropped_count = 0
with subprocess.Popen(
["gzip", "-fdc", INPUT_FILE],
stdout=subprocess.PIPE,
# stderr=subprocess.DEVNULL,
text=True,
bufsize=1024 * 1024,
) as proc:
for i, line in enumerate(proc.stdout):
try:
if not line.strip():
continue
row = json.loads(line)
if has_huge_outliers(row["input_features"]):
if dropped_count % 100 == 0:
print(
f"⚠️ Skipping row {i}: Contains huge outlier integers (Garbage data)"
)
dropped_count += 1
continue
yield row
except json.JSONDecodeError:
print(f"⚠️ Skipping corrupted JSON line {i}")
continue
except Exception as e:
print(f"⚠️ Error processing line {i}: {e}")
continue
print(f"Total rows dropped due to huge integers: {dropped_count}")
print("Loading dataset and recovering valid data...")
shard_ds = Dataset.from_generator(
gen,
features=FEATURES,
writer_batch_size=2,
)
os.makedirs("/home/ubuntu/Clean-HF-Dataset-7/shards", exist_ok=True)
shard_path = os.path.join("/home/ubuntu/Clean-HF-Dataset-7/shards", "test_2")
print(f"Saving to {shard_path}...")
shard_ds.save_to_disk(shard_path)
print(f"File successfully saved in {shard_path}")
del shard_ds
gc.collect()