| 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 |
|
|
| |
| 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) |
| |
| |
| if os.path.exists(image_path): |
| valid_lines.append(line) |
| else: |
| removed_count += 1 |
| else: |
| |
| |
| removed_count += 1 |
| |
| except json.JSONDecodeError: |
| removed_count += 1 |
|
|
| |
| 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 |
| |
| |
| 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() |