cfahlgren1 HF Staff commited on
Commit
cd8fead
·
verified ·
1 Parent(s): 00e7557

stream jsonl to parquet in chunks to fix oom

Browse files
Files changed (1) hide show
  1. hub-stats.py +75 -33
hub-stats.py CHANGED
@@ -14,6 +14,7 @@
14
  import json
15
  import os
16
  import asyncio
 
17
  import time
18
 
19
  import pandas as pd
@@ -202,13 +203,12 @@ async def fetch_data_page(session, url, params=None, headers=None):
202
  return await response.json(), response.headers.get("Link")
203
 
204
 
205
- def jsonl_to_parquet(endpoint, jsonl_file, output_file):
206
- if not os.path.exists(jsonl_file):
207
- print(f"✗ {jsonl_file} not found")
208
- return 0
209
 
210
- # Collect all dataframes first to get unified schema
211
- all_dfs = []
 
212
  with open(jsonl_file, "r") as f:
213
  for line in f:
214
  line = line.strip()
@@ -216,41 +216,63 @@ def jsonl_to_parquet(endpoint, jsonl_file, output_file):
216
  continue
217
  data = json.loads(line)
218
  if endpoint == "posts":
219
- items = data.get("socialPosts", [])
220
  else:
221
- items = data
222
-
223
- if not items:
224
  continue
225
 
226
- df = pd.DataFrame(items)
227
- if df.empty:
228
- continue
 
 
 
 
 
 
 
 
229
 
230
- df = process_dataframe(df, endpoint)
231
- all_dfs.append(df)
232
 
233
- if not all_dfs:
 
 
 
 
 
 
 
 
 
 
234
  print(f" No data found for {endpoint}")
235
  return 0
236
 
237
- # Concatenate all dataframes - pandas will unify types
238
- combined_df = pd.concat(all_dfs, ignore_index=True)
239
- total_rows = len(combined_df)
240
 
241
- # Write to parquet with controlled row group sizes
242
- row_group_size = 50_000
243
- table = pa.Table.from_pandas(combined_df, preserve_index=False)
244
- writer = pq.ParquetWriter(output_file, table.schema)
245
- for i in range(0, total_rows, row_group_size):
246
- chunk = table.slice(i, min(row_group_size, total_rows - i))
247
- writer.write_table(chunk)
248
- writer.close()
 
 
 
 
 
 
 
 
 
249
 
250
  return total_rows
251
 
252
 
253
- async def create_parquet_files(skip_upload=False):
254
  start_time = time.time()
255
  endpoints = [
256
  "daily_papers",
@@ -307,6 +329,8 @@ async def create_parquet_files(skip_upload=False):
307
  params = {}
308
 
309
  page += 1
 
 
310
 
311
  except Exception as e:
312
  print(f"Error on page {page} for {endpoint}: {e}")
@@ -375,8 +399,22 @@ def upload_to_hub(file_path, repo_id):
375
  return False
376
 
377
 
378
- def main(skip_upload=False):
379
- created_files, elapsed = asyncio.run(create_parquet_files(skip_upload=skip_upload))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
380
 
381
  print(f"\nCompleted in {elapsed:.2f} seconds")
382
  print(f"Created {len(created_files)} parquet files:")
@@ -387,16 +425,20 @@ def main(skip_upload=False):
387
  rows = pf.metadata.num_rows
388
  print(f" {os.path.basename(file)}: {rows:,} rows, {size:,} bytes")
389
 
 
 
390
  if skip_upload:
391
  print(f"\nRaw JSONL files saved to {CACHE_DIR}/ for recreation")
392
  print("Use 'python app.py --recreate' to recreate parquet files from JSONL")
393
 
394
 
395
  if __name__ == "__main__":
396
- import sys
397
-
398
  if "--recreate" in sys.argv:
399
  recreate_from_jsonl()
 
400
  else:
401
  skip_upload = "--skip-upload" in sys.argv
402
- main(skip_upload=skip_upload)
 
 
 
 
14
  import json
15
  import os
16
  import asyncio
17
+ import sys
18
  import time
19
 
20
  import pandas as pd
 
203
  return await response.json(), response.headers.get("Link")
204
 
205
 
206
+ ROWS_PER_CHUNK = 50_000
207
+
 
 
208
 
209
+ def iter_chunk_dfs(endpoint, jsonl_file, rows_per_chunk=ROWS_PER_CHUNK):
210
+ """Stream the raw JSONL as processed DataFrames of ~rows_per_chunk rows."""
211
+ items = []
212
  with open(jsonl_file, "r") as f:
213
  for line in f:
214
  line = line.strip()
 
216
  continue
217
  data = json.loads(line)
218
  if endpoint == "posts":
219
+ page_items = data.get("socialPosts", [])
220
  else:
221
+ page_items = data
222
+ if not page_items:
 
223
  continue
224
 
225
+ items.extend(page_items)
226
+ if len(items) >= rows_per_chunk:
227
+ df = process_dataframe(pd.DataFrame(items), endpoint)
228
+ items = []
229
+ if not df.empty:
230
+ yield df
231
+
232
+ if items:
233
+ df = process_dataframe(pd.DataFrame(items), endpoint)
234
+ if not df.empty:
235
+ yield df
236
 
 
 
237
 
238
+ def jsonl_to_parquet(endpoint, jsonl_file, output_file):
239
+ if not os.path.exists(jsonl_file):
240
+ print(f"✗ {jsonl_file} not found")
241
+ return 0
242
+
243
+ # Pass 1: infer a unified schema one chunk at a time, never holding all rows
244
+ schemas = []
245
+ for df in iter_chunk_dfs(endpoint, jsonl_file):
246
+ schemas.append(pa.Table.from_pandas(df, preserve_index=False).schema)
247
+
248
+ if not schemas:
249
  print(f" No data found for {endpoint}")
250
  return 0
251
 
252
+ unified_schema = pa.unify_schemas(schemas, promote_options="permissive")
 
 
253
 
254
+ # Pass 2: convert chunk-by-chunk and stream row groups straight to disk
255
+ total_rows = 0
256
+ writer = pq.ParquetWriter(output_file, unified_schema)
257
+ try:
258
+ for df in iter_chunk_dfs(endpoint, jsonl_file):
259
+ for name in unified_schema.names:
260
+ if name not in df.columns:
261
+ df[name] = None
262
+ table = pa.Table.from_pandas(
263
+ df[list(unified_schema.names)],
264
+ schema=unified_schema,
265
+ preserve_index=False,
266
+ )
267
+ writer.write_table(table)
268
+ total_rows += len(df)
269
+ finally:
270
+ writer.close()
271
 
272
  return total_rows
273
 
274
 
275
+ async def create_parquet_files(skip_upload=False, max_pages=None):
276
  start_time = time.time()
277
  endpoints = [
278
  "daily_papers",
 
329
  params = {}
330
 
331
  page += 1
332
+ if max_pages is not None and page >= max_pages:
333
+ url = None
334
 
335
  except Exception as e:
336
  print(f"Error on page {page} for {endpoint}: {e}")
 
399
  return False
400
 
401
 
402
+ def print_peak_memory():
403
+ try:
404
+ import resource
405
+
406
+ peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
407
+ # ru_maxrss is bytes on macOS, kilobytes on Linux
408
+ peak_mb = peak / (1024 * 1024) if sys.platform == "darwin" else peak / 1024
409
+ print(f"Peak memory: {peak_mb:,.0f} MB")
410
+ except Exception:
411
+ pass
412
+
413
+
414
+ def main(skip_upload=False, max_pages=None):
415
+ created_files, elapsed = asyncio.run(
416
+ create_parquet_files(skip_upload=skip_upload, max_pages=max_pages)
417
+ )
418
 
419
  print(f"\nCompleted in {elapsed:.2f} seconds")
420
  print(f"Created {len(created_files)} parquet files:")
 
425
  rows = pf.metadata.num_rows
426
  print(f" {os.path.basename(file)}: {rows:,} rows, {size:,} bytes")
427
 
428
+ print_peak_memory()
429
+
430
  if skip_upload:
431
  print(f"\nRaw JSONL files saved to {CACHE_DIR}/ for recreation")
432
  print("Use 'python app.py --recreate' to recreate parquet files from JSONL")
433
 
434
 
435
  if __name__ == "__main__":
 
 
436
  if "--recreate" in sys.argv:
437
  recreate_from_jsonl()
438
+ print_peak_memory()
439
  else:
440
  skip_upload = "--skip-upload" in sys.argv
441
+ max_pages = None
442
+ if "--max-pages" in sys.argv:
443
+ max_pages = int(sys.argv[sys.argv.index("--max-pages") + 1])
444
+ main(skip_upload=skip_upload, max_pages=max_pages)