ShIO-bash-26.1 / utils.py
jragsdale1's picture
Upload utils.py
f742d6c verified
import json
import os
import random
def load_data_dir(d_path: str, max_size: int = 1_000_000, seed: int = 1) -> list:
records = []
for root, _dirs, files in os.walk(d_path): # walks all levels
if len(records) >= max_size:
break
for fn in files:
if fn.endswith('.ndjson'):
path = os.path.join(root, fn)
with open(path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if not line:
continue
try:
records.append(json.loads(line))
except json.JSONDecodeError as e:
raise ValueError(f"Invalid JSON in {path}: {e}") from e
shuffler = random.Random(seed)
shuffler.shuffle(records)
return records[:max_size]