cdda-cataclysm-gameplay / cleanup_dataset.py
Xnsviel's picture
Upload 2 files
3feefba verified
import os
import json
import argparse
def clean_jsonl(jsonl_path):
"""
Reads a jsonl file, checks if referenced images exist,
and rewrites the file without the missing entries.
"""
base_dir = os.path.dirname(jsonl_path)
img_dir = os.path.join(base_dir, "images")
if not os.path.exists(img_dir):
print(f"[!] Skipping {base_dir}: 'images' folder not found.")
return
# Read all lines
with open(jsonl_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
valid_lines = []
removed_count = 0
total_count = len(lines)
for line in lines:
if not line.strip():
continue
try:
entry = json.loads(line)
image_name = entry.get("image")
if image_name:
image_path = os.path.join(img_dir, image_name)
# THE CORE CHECK: Does the file exist?
if os.path.exists(image_path):
valid_lines.append(line)
else:
removed_count += 1
else:
# If entry has no "image" field, decide to keep or drop.
# For this dataset format, we drop it.
removed_count += 1
except json.JSONDecodeError:
removed_count += 1
# Only rewrite if we actually removed something
if removed_count > 0:
with open(jsonl_path, 'w', encoding='utf-8') as f:
f.writelines(valid_lines)
print(f"[✓] Cleaned {jsonl_path}")
print(f" - Total Lines: {total_count}")
print(f" - Removed: {removed_count}")
print(f" - Remaining: {len(valid_lines)}")
else:
print(f"[.] No changes needed for {jsonl_path}")
def main():
parser = argparse.ArgumentParser(description="Remove JSONL lines pointing to missing images.")
parser.add_argument("dir", default=".", help="Root directory to scan (default: current dir).")
args = parser.parse_args()
print(f"[*] Scanning for data.jsonl files in '{args.dir}'...")
found_files = 0
# Walk through all directories recursively
for root, dirs, files in os.walk(args.dir):
if "data.jsonl" in files:
found_files += 1
full_path = os.path.join(root, "data.jsonl")
clean_jsonl(full_path)
if found_files == 0:
print("[!] No 'data.jsonl' files found.")
else:
print("\n[*] Cleanup complete.")
if __name__ == "__main__":
main()