Delete cleanup_dataset.py with huggingface_hub
Browse files- cleanup_dataset.py +0 -180
cleanup_dataset.py
DELETED
|
@@ -1,180 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
"""
|
| 3 |
-
Clean dataset: remove black JPGs (brightness < 30), update metadata.
|
| 4 |
-
No PCD issues found — all PCD sizes are 2-6 MB (healthy).
|
| 5 |
-
"""
|
| 6 |
-
import pandas as pd
|
| 7 |
-
import zipfile
|
| 8 |
-
import io
|
| 9 |
-
import shutil
|
| 10 |
-
import concurrent.futures
|
| 11 |
-
from pathlib import Path
|
| 12 |
-
from collections import defaultdict
|
| 13 |
-
from PIL import Image
|
| 14 |
-
|
| 15 |
-
ZIP_DIR = Path('/workspace/3D_o')
|
| 16 |
-
MERGED_FILE = '/workspace/merged_result.parquet'
|
| 17 |
-
INDEX_FILE = '/workspace/archive_index.parquet'
|
| 18 |
-
CATALOG_FILE = '/workspace/file_catalog.parquet'
|
| 19 |
-
BAD_FILE = '/workspace/bad_files.parquet'
|
| 20 |
-
|
| 21 |
-
BRIGHTNESS_THRESHOLD = 30 # below this = black frame
|
| 22 |
-
|
| 23 |
-
print("=" * 60)
|
| 24 |
-
print("Finding black JPGs (brightness < 30)...")
|
| 25 |
-
print("=" * 60)
|
| 26 |
-
|
| 27 |
-
catalog = pd.read_parquet(CATALOG_FILE)
|
| 28 |
-
jpg_catalog = catalog[catalog['path'].str.startswith('jpg/')]
|
| 29 |
-
suspicious = jpg_catalog[jpg_catalog['size'] < 500_000]
|
| 30 |
-
print(f" Suspicious JPGs (< 500 KB): {len(suspicious)}")
|
| 31 |
-
|
| 32 |
-
def check_archive(archive):
|
| 33 |
-
bad = []
|
| 34 |
-
rows = suspicious[suspicious['archive'] == archive]
|
| 35 |
-
if len(rows) == 0:
|
| 36 |
-
return bad
|
| 37 |
-
try:
|
| 38 |
-
with zipfile.ZipFile(ZIP_DIR / archive, 'r') as zf:
|
| 39 |
-
for _, row in rows.iterrows():
|
| 40 |
-
data = zf.read(row['path'])
|
| 41 |
-
img = Image.open(io.BytesIO(data))
|
| 42 |
-
gray = img.convert('L')
|
| 43 |
-
pixels = gray.getdata()
|
| 44 |
-
n = gray.width * gray.height
|
| 45 |
-
mean = sum(pixels) / n
|
| 46 |
-
if mean < BRIGHTNESS_THRESHOLD:
|
| 47 |
-
bad.append((archive, row['path'], row['size'], mean))
|
| 48 |
-
except Exception as e:
|
| 49 |
-
print(f" ERROR {archive}: {e}")
|
| 50 |
-
return bad
|
| 51 |
-
|
| 52 |
-
archives = suspicious['archive'].unique()
|
| 53 |
-
bad_jpgs = []
|
| 54 |
-
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as ex:
|
| 55 |
-
results = ex.map(check_archive, archives)
|
| 56 |
-
for r in results:
|
| 57 |
-
bad_jpgs.extend(r)
|
| 58 |
-
|
| 59 |
-
print(f" Black JPGs found: {len(bad_jpgs)}")
|
| 60 |
-
|
| 61 |
-
bad_records = []
|
| 62 |
-
for a, p, sz, b in bad_jpgs:
|
| 63 |
-
bad_records.append({'archive': a, 'path': p, 'type': 'jpg', 'reason': f'black_frame:brightness={b:.1f}'})
|
| 64 |
-
|
| 65 |
-
bad_df = pd.DataFrame(bad_records)
|
| 66 |
-
bad_df.to_parquet(BAD_FILE)
|
| 67 |
-
print(f" Saved to {BAD_FILE}")
|
| 68 |
-
|
| 69 |
-
if len(bad_df) == 0:
|
| 70 |
-
print(" No bad files found. Dataset is clean!")
|
| 71 |
-
exit(0)
|
| 72 |
-
|
| 73 |
-
# Show affected archives
|
| 74 |
-
arc_counts = bad_df.groupby('archive').size().sort_index()
|
| 75 |
-
print(f"\n Affected archives:")
|
| 76 |
-
for arc, cnt in arc_counts.items():
|
| 77 |
-
print(f" {arc}: {cnt} black JPGs")
|
| 78 |
-
|
| 79 |
-
# ─── Phase 2: Update merged_result.parquet ────────────────────────────────
|
| 80 |
-
print("\n" + "=" * 60)
|
| 81 |
-
print("Updating merged_result.parquet...")
|
| 82 |
-
print("=" * 60)
|
| 83 |
-
|
| 84 |
-
bad_set = set(zip(bad_df['archive'], bad_df['path']))
|
| 85 |
-
|
| 86 |
-
merged = pd.read_parquet(MERGED_FILE)
|
| 87 |
-
print(f" Original rows: {len(merged)}")
|
| 88 |
-
|
| 89 |
-
# Find rows with bad JPGs
|
| 90 |
-
merged['_bad_jpg'] = merged.apply(
|
| 91 |
-
lambda r: pd.notna(r['jpg_path']) and (r['archive'], r['jpg_path']) in bad_set, axis=1
|
| 92 |
-
)
|
| 93 |
-
n_bad = merged['_bad_jpg'].sum()
|
| 94 |
-
print(f" Rows with black JPG: {n_bad}")
|
| 95 |
-
|
| 96 |
-
# Clear jpg_path for rows with bad JPGs (keep the row, PCD is fine)
|
| 97 |
-
merged.loc[merged['_bad_jpg'], 'jpg_path'] = None
|
| 98 |
-
merged = merged.drop(columns=['_bad_jpg'])
|
| 99 |
-
|
| 100 |
-
merged.to_parquet(MERGED_FILE)
|
| 101 |
-
print(f" Saved {len(merged)} rows")
|
| 102 |
-
|
| 103 |
-
# ─── Phase 3: Repack ZIPs ────────────────────────────────────────────────
|
| 104 |
-
print("\n" + "=" * 60)
|
| 105 |
-
print("Repacking affected ZIP archives...")
|
| 106 |
-
print("=" * 60)
|
| 107 |
-
|
| 108 |
-
bad_by_archive = defaultdict(list)
|
| 109 |
-
for _, row in bad_df.iterrows():
|
| 110 |
-
bad_by_archive[row['archive']].append(row['path'])
|
| 111 |
-
|
| 112 |
-
def repack(archive):
|
| 113 |
-
zip_path = ZIP_DIR / archive
|
| 114 |
-
tmp_path = zip_path.with_suffix('.tmp.zip')
|
| 115 |
-
bad_files = set(bad_by_archive[archive])
|
| 116 |
-
try:
|
| 117 |
-
with zipfile.ZipFile(zip_path, 'r') as zin:
|
| 118 |
-
with zipfile.ZipFile(tmp_path, 'w', zipfile.ZIP_DEFLATED, compresslevel=1) as zout:
|
| 119 |
-
for info in zin.infolist():
|
| 120 |
-
if info.filename not in bad_files:
|
| 121 |
-
zout.writestr(info, zin.read(info.filename))
|
| 122 |
-
orig_size = zip_path.stat().st_size
|
| 123 |
-
shutil.move(tmp_path, zip_path)
|
| 124 |
-
new_size = zip_path.stat().st_size
|
| 125 |
-
removed = sum(1 for f in bad_files)
|
| 126 |
-
return (archive, 'ok', orig_size, new_size, removed)
|
| 127 |
-
except Exception as e:
|
| 128 |
-
if tmp_path.exists():
|
| 129 |
-
tmp_path.unlink()
|
| 130 |
-
return (archive, 'error', str(e)[:100])
|
| 131 |
-
|
| 132 |
-
archives_to_fix = sorted(bad_by_archive.keys())
|
| 133 |
-
print(f" Archives to repack: {len(archives_to_fix)}")
|
| 134 |
-
|
| 135 |
-
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as ex:
|
| 136 |
-
results = list(ex.map(repack, archives_to_fix))
|
| 137 |
-
|
| 138 |
-
for r in results:
|
| 139 |
-
if r[1] == 'ok':
|
| 140 |
-
saving = (r[2] - r[3]) / 1e6
|
| 141 |
-
print(f" {r[0]}: {r[2]/1e6:.0f} MB -> {r[3]/1e6:.0f} MB ({r[4]} files removed, -{saving:.0f} MB)")
|
| 142 |
-
else:
|
| 143 |
-
print(f" {r[0]}: ERROR - {r[2]}")
|
| 144 |
-
|
| 145 |
-
# ─── Phase 4: Update archive_index.parquet ────────────────────────────────
|
| 146 |
-
print("\n" + "=" * 60)
|
| 147 |
-
print("Updating archive_index.parquet...")
|
| 148 |
-
print("=" * 60)
|
| 149 |
-
|
| 150 |
-
records = []
|
| 151 |
-
for zp in sorted(ZIP_DIR.glob('*.zip')):
|
| 152 |
-
try:
|
| 153 |
-
with zipfile.ZipFile(zp, 'r') as zf:
|
| 154 |
-
info_list = zf.infolist()
|
| 155 |
-
records.append({
|
| 156 |
-
'archive': zp.name,
|
| 157 |
-
'size_mb': round(zp.stat().st_size / 1e6, 1),
|
| 158 |
-
'file_count': len(info_list),
|
| 159 |
-
'pcd_count': sum(1 for i in info_list if i.filename.startswith('pcd/')),
|
| 160 |
-
'jpg_count': sum(1 for i in info_list if i.filename.startswith('jpg/')),
|
| 161 |
-
})
|
| 162 |
-
except Exception as e:
|
| 163 |
-
print(f" ERROR {zp.name}: {e}")
|
| 164 |
-
|
| 165 |
-
new_index = pd.DataFrame(records)
|
| 166 |
-
new_index.to_parquet(INDEX_FILE)
|
| 167 |
-
print(f" Saved {len(new_index)} entries")
|
| 168 |
-
|
| 169 |
-
# ─── Summary ──────────────────────────────────────────────────────────────
|
| 170 |
-
print("\n" + "=" * 60)
|
| 171 |
-
print("CLEANUP SUMMARY")
|
| 172 |
-
print("=" * 60)
|
| 173 |
-
print(f" Black JPGs removed: {len(bad_jpgs)}")
|
| 174 |
-
print(f" Archives repacked: {len(archives_to_fix)}")
|
| 175 |
-
print(f" Rows with cleared jpg_path: {n_bad}")
|
| 176 |
-
print(f" Total dataset size: {new_index['size_mb'].sum():.0f} MB")
|
| 177 |
-
print(f" Total valid files: {new_index['file_count'].sum()}")
|
| 178 |
-
print(f" Total valid PCDs: {new_index['pcd_count'].sum()}")
|
| 179 |
-
print(f" Total valid JPGs: {new_index['jpg_count'].sum()}")
|
| 180 |
-
print("\nDone! Dataset is clean.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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