Verammm commited on
Commit
286183b
·
verified ·
1 Parent(s): a838b6a

Delete build_dataset.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. build_dataset.py +0 -315
build_dataset.py DELETED
@@ -1,315 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Build dataset from merged_result.parquet + LakeFS.
4
- Downloads PCD and JPG files, packages into ~250 MB ZIP archives in 3D_o/.
5
- """
6
-
7
- import pandas as pd
8
- import numpy as np
9
- import requests
10
- import os
11
- import sys
12
- import json
13
- import time
14
- import shutil
15
- import zipfile
16
- import concurrent.futures
17
- import pickle
18
- from pathlib import Path
19
- from collections import defaultdict
20
-
21
- # Config
22
- LAKEFS_BASE = 'http://10.248.52.100:8001'
23
- AK = os.environ['LAKEFS_ACCESS_KEY']
24
- SK = os.environ['LAKEFS_SECRET_KEY']
25
- OUTPUT_DIR = Path('/workspace/3D_o')
26
- PCD_SIZE_FILE = '/workspace/pcd_file_sizes.parquet'
27
- JPG_SIZE_FILE = '/workspace/jpg_file_sizes.parquet'
28
- MERGED_FILE = '/workspace/merged_result.parquet'
29
- PLAN_FILE = '/workspace/chunks_data.pkl'
30
- CHUNK_TARGET = 250 * 1024 * 1024 # 250 MB
31
- CHUNK_MIN = 200 * 1024 * 1024 # 200 MB
32
- MAX_WORKERS = 30 # parallel downloads per chunk
33
- REQUEST_TIMEOUT = 120
34
-
35
- OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
36
-
37
- session = requests.Session()
38
- session.auth = (AK, SK)
39
-
40
- # ----- STEP 0: Load sizes -----
41
- print("[0] Loading data...")
42
- merged = pd.read_parquet(MERGED_FILE)
43
- pcd_sizes = pd.read_parquet(PCD_SIZE_FILE)
44
- jpg_sizes = pd.read_parquet(JPG_SIZE_FILE)
45
- pcd_size_map = dict(zip(pcd_sizes['path'], pcd_sizes['size']))
46
- jpg_size_map = dict(zip(jpg_sizes['path'], jpg_sizes['size']))
47
-
48
- # ----- STEP 1: Build deduplicated PCD list -----
49
- print("[1] Building deduplicated PCD list...")
50
- # For each unique PCD, get its bag_id (first occurrence's bag_id and timestamp)
51
- pcd_info = merged.drop_duplicates(subset='path')[['path', 'path_to_jpg', 'bag_id', 'main_timestamp']].copy()
52
- pcd_info = pcd_info.sort_values(['bag_id', 'main_timestamp']).reset_index(drop=True)
53
- print(f" Unique PCDs: {len(pcd_info)}")
54
-
55
- # Add sizes
56
- pcd_info['pcd_size'] = pcd_info['path'].map(pcd_size_map)
57
- pcd_info['jpg_size'] = pcd_info['path_to_jpg'].map(jpg_size_map).fillna(0).astype(int)
58
- pcd_info['total_size'] = pcd_info['pcd_size'] + pcd_info['jpg_size']
59
-
60
- missing_sizes = pcd_info['pcd_size'].isna().sum()
61
- if missing_sizes:
62
- print(f" WARNING: {missing_sizes} PCDs missing sizes, estimating at 5MB")
63
- pcd_info['pcd_size'] = pcd_info['pcd_size'].fillna(5_000_000).astype(int)
64
- pcd_info['total_size'] = pcd_info['pcd_size'] + pcd_info['jpg_size']
65
-
66
- total_data_size = pcd_info['total_size'].sum()
67
- print(f" Total dataset size: {total_data_size / 1e9:.1f} GB")
68
- print(f" Estimated archives: {total_data_size / CHUNK_TARGET:.0f}")
69
-
70
- # Count how many PCDs have JPGs
71
- with_jpg = (pcd_info['jpg_size'] > 0).sum()
72
- print(f" PCDs with JPGs: {with_jpg}")
73
-
74
- # ----- STEP 2: Build chunk plan -----
75
- chunk_plan_path = Path(PLAN_FILE)
76
- if chunk_plan_path.exists():
77
- print("[2] Loading existing chunk plan...")
78
- with open(chunk_plan_path, 'rb') as f:
79
- chunks = pickle.load(f)
80
- print(f" Loaded {len(chunks)} chunks")
81
- else:
82
- print("[2] Building chunk plan...")
83
- chunks = []
84
- current_chunk = []
85
- current_size = 0
86
- chunk_idx = 0
87
-
88
- for idx, row in pcd_info.iterrows():
89
- item_size = int(row['total_size'])
90
-
91
- if current_size > 0 and current_size + item_size > CHUNK_TARGET and current_size >= CHUNK_MIN:
92
- chunks.append({
93
- 'index': chunk_idx,
94
- 'name': f'data_{chunk_idx:04d}.zip',
95
- 'files': current_chunk,
96
- 'total_size': current_size,
97
- 'bag_ids': list(set(f['bag_id'] for f in current_chunk)),
98
- })
99
- chunk_idx += 1
100
- current_chunk = []
101
- current_size = 0
102
-
103
- current_chunk.append({
104
- 'pcd_path': row['path'],
105
- 'jpg_path': row['path_to_jpg'] if pd.notna(row['path_to_jpg']) else None,
106
- 'bag_id': row['bag_id'],
107
- 'pcd_size': int(row['pcd_size']),
108
- 'jpg_size': int(row['jpg_size']),
109
- 'main_timestamp': int(row['main_timestamp']),
110
- })
111
- current_size += item_size
112
-
113
- # Last chunk
114
- if current_chunk:
115
- chunks.append({
116
- 'index': chunk_idx,
117
- 'name': f'data_{chunk_idx:04d}.zip',
118
- 'files': current_chunk,
119
- 'total_size': current_size,
120
- 'bag_ids': list(set(f['bag_id'] for f in current_chunk)),
121
- })
122
-
123
- with open(chunk_plan_path, 'wb') as f:
124
- pickle.dump(chunks, f)
125
- print(f" Created {len(chunks)} chunks, saved plan")
126
-
127
- # Summary
128
- total_planned = sum(c['total_size'] for c in chunks)
129
- print(f" Total planned size: {total_planned / 1e9:.1f} GB")
130
- print(f" Chunks: {len(chunks)}, avg size: {total_planned/len(chunks)/1e6:.0f} MB")
131
-
132
- # ----- STEP 3: Process chunks (download + zip) -----
133
- # Find out which chunks are already done
134
- existing_zips = set(f.name for f in OUTPUT_DIR.iterdir() if f.suffix == '.zip')
135
- done_indices = set()
136
- for c in chunks:
137
- if c['name'] in existing_zips:
138
- # Verify zip is valid
139
- try:
140
- with zipfile.ZipFile(OUTPUT_DIR / c['name'], 'r') as zf:
141
- if zf.testzip() is None:
142
- done_indices.add(c['index'])
143
- except:
144
- pass
145
-
146
- todo_chunks = [c for c in chunks if c['index'] not in done_indices]
147
- print(f"\n[3] Processing chunks ({len(todo_chunks)} remaining, {len(done_indices)} done)...")
148
-
149
- def download_file(file_info):
150
- """Download a single PCD or JPG file to temp directory."""
151
- result = {}
152
-
153
- # Download PCD
154
- pcd_uuid = Path(file_info['pcd_path']).stem
155
- pcd_tmp = OUTPUT_DIR / f'tmp_{pcd_uuid}.pcd'
156
- if not pcd_tmp.exists():
157
- url = f'{LAKEFS_BASE}/api/v1/repositories/astraldb/refs/main/objects'
158
- r = session.get(url, params={'path': file_info['pcd_path']}, timeout=REQUEST_TIMEOUT)
159
- if r.status_code != 200:
160
- return {'error': f'PCD download failed: {r.status_code}', 'pcd_uuid': pcd_uuid}
161
- with open(pcd_tmp, 'wb') as f:
162
- f.write(r.content)
163
- result['pcd_tmp'] = str(pcd_tmp)
164
- result['pcd_arc'] = f"pcd/{pcd_uuid}.pcd"
165
-
166
- # Download JPG if exists
167
- if file_info['jpg_path']:
168
- jpg_uuid = Path(file_info['jpg_path']).stem
169
- jpg_tmp = OUTPUT_DIR / f'tmp_{jpg_uuid}.jpg'
170
- if not jpg_tmp.exists():
171
- url = f'{LAKEFS_BASE}/api/v1/repositories/ros2bags/refs/main/objects'
172
- r = session.get(url, params={'path': file_info['jpg_path']}, timeout=REQUEST_TIMEOUT)
173
- if r.status_code != 200:
174
- result['jpg_error'] = f'JPG download failed: {r.status_code}'
175
- else:
176
- with open(jpg_tmp, 'wb') as f:
177
- f.write(r.content)
178
- if jpg_tmp.exists():
179
- result['jpg_tmp'] = str(jpg_tmp)
180
- result['jpg_arc'] = f"jpg/{jpg_uuid}.jpg"
181
-
182
- return result
183
-
184
- def process_chunk(chunk):
185
- """Download all files for a chunk and create ZIP."""
186
- chunk_name = chunk['name']
187
- zip_path = OUTPUT_DIR / chunk_name
188
-
189
- if zip_path.exists():
190
- try:
191
- with zipfile.ZipFile(zip_path, 'r') as zf:
192
- if zf.testzip() is None:
193
- return {'index': chunk['index'], 'name': chunk_name, 'status': 'already_done'}
194
- except:
195
- pass
196
-
197
- # Parallel download
198
- with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as ex:
199
- dl_results = list(ex.map(download_file, chunk['files']))
200
-
201
- errors = [r for r in dl_results if 'error' in r]
202
- if errors:
203
- # Clean up temps
204
- for r in dl_results:
205
- for key in ['pcd_tmp', 'jpg_tmp']:
206
- if key in r and Path(r[key]).exists():
207
- Path(r[key]).unlink()
208
- return {'index': chunk['index'], 'name': chunk_name, 'status': 'error', 'errors': errors}
209
-
210
- # Create ZIP
211
- with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED, compresslevel=1) as zf:
212
- for r in dl_results:
213
- zf.write(r['pcd_tmp'], r['pcd_arc'])
214
- if 'jpg_tmp' in r:
215
- zf.write(r['jpg_tmp'], r['jpg_arc'])
216
-
217
- # Clean up temp files
218
- for r in dl_results:
219
- for key in ['pcd_tmp', 'jpg_tmp']:
220
- if key in r and Path(r[key]).exists():
221
- Path(r[key]).unlink()
222
-
223
- actual_size = zip_path.stat().st_size
224
- return {'index': chunk['index'], 'name': chunk_name, 'status': 'ok', 'size': actual_size}
225
-
226
- # Process chunks one by one to manage disk space
227
- for i, chunk in enumerate(todo_chunks):
228
- print(f" Chunk {i+1}/{len(todo_chunks)}: {chunk['name']} ({chunk['total_size']/1e6:.0f} MB, {len(chunk['files'])} files)...", end=' ')
229
- sys.stdout.flush()
230
- result = process_chunk(chunk)
231
- if result['status'] == 'ok':
232
- print(f"OK ({result['size']/1e6:.0f} MB)")
233
- elif result['status'] == 'error':
234
- print(f"ERROR: {result['errors'][:2]}")
235
- elif result['status'] == 'already_done':
236
- print("already done")
237
-
238
- # Save updated plan (in case we need to resume)
239
- final_chunks = []
240
- for c in chunks:
241
- zip_path = OUTPUT_DIR / c['name']
242
- c['actual_size'] = zip_path.stat().st_size if zip_path.exists() else 0
243
- final_chunks.append(c)
244
- with open(chunk_plan_path, 'wb') as f:
245
- pickle.dump(final_chunks, f)
246
-
247
- print(f"\n[3] Done processing. Zips in {OUTPUT_DIR}:")
248
- for f in sorted(OUTPUT_DIR.glob('*.zip')):
249
- print(f" {f.name}: {f.stat().st_size / 1e6:.0f} MB")
250
-
251
- # ----- STEP 4: Update merged_result.parquet -----
252
- print("\n[4] Updating merged_result.parquet...")
253
-
254
- # Build PCD -> archive mapping
255
- pcd_to_archive = {}
256
- pcd_to_arcpath = {}
257
- for c in chunks:
258
- zip_path = OUTPUT_DIR / c['name']
259
- if not zip_path.exists():
260
- continue
261
- for f_info in c['files']:
262
- pcd_path = f_info['pcd_path']
263
- pcd_uuid = Path(pcd_path).stem
264
- pcd_to_archive[pcd_path] = c['name']
265
- pcd_to_arcpath[pcd_path] = f'pcd/{pcd_uuid}.pcd'
266
-
267
- # Update merged_result
268
- merged['archive'] = merged['path'].map(pcd_to_archive)
269
- merged['pcd_path'] = merged['path'].map(pcd_to_arcpath)
270
-
271
- # Build JPG path mapping
272
- jpg_to_arcpath = {}
273
- for c in chunks:
274
- for f_info in c['files']:
275
- if f_info['jpg_path']:
276
- jpg_uuid = Path(f_info['jpg_path']).stem
277
- jpg_to_arcpath[f_info['jpg_path']] = f'jpg/{jpg_uuid}.jpg'
278
-
279
- merged['jpg_path'] = merged['path_to_jpg'].map(jpg_to_arcpath)
280
-
281
- # Drop old path columns
282
- merged = merged.drop(columns=['path', 'path_to_jpg'])
283
-
284
- # Reorder columns
285
- col_order = ['frame_id', 'label', 'data', 'main_timestamp', 'bag_id', 'archive', 'pcd_path', 'jpg_path']
286
- available_cols = [c for c in col_order if c in merged.columns]
287
- merged = merged[available_cols]
288
-
289
- # Save updated merged_result
290
- merged.to_parquet('/workspace/merged_result.parquet')
291
- print(f" Saved {len(merged)} rows to merged_result.parquet")
292
- print(f" Columns: {merged.columns.tolist()}")
293
-
294
- # ----- STEP 5: Create archive_index.parquet -----
295
- print("\n[5] Creating archive_index.parquet...")
296
- archive_index = []
297
- for c in chunks:
298
- zip_path = OUTPUT_DIR / c['name']
299
- if not zip_path.exists():
300
- continue
301
- timestamps = [f['main_timestamp'] for f in c['files']]
302
- archive_index.append({
303
- 'archive': c['name'],
304
- 'bag_ids': ','.join(c['bag_ids']),
305
- 'min_timestamp': min(timestamps),
306
- 'max_timestamp': max(timestamps),
307
- 'size_mb': round(zip_path.stat().st_size / 1e6, 1),
308
- 'file_count': len(c['files']),
309
- })
310
-
311
- index_df = pd.DataFrame(archive_index)
312
- index_df.to_parquet('/workspace/archive_index.parquet')
313
- print(f" Saved {len(index_df)} entries to archive_index.parquet")
314
-
315
- print("\nDone!")