davanstrien HF Staff commited on
Commit
3d2c5a0
·
verified ·
1 Parent(s): ec0535b

Upload classify_arxiv_to_lance.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. classify_arxiv_to_lance.py +193 -9
classify_arxiv_to_lance.py CHANGED
@@ -54,7 +54,6 @@ from pathlib import Path
54
  from typing import TYPE_CHECKING
55
 
56
  import polars as pl
57
- import pyarrow as pa
58
  import torch
59
  from huggingface_hub import HfApi, login
60
  from toolz import partition_all
@@ -153,8 +152,8 @@ def get_last_update_date(
153
  """
154
  Get the maximum update_date from the existing Lance dataset on HF Hub.
155
 
156
- Uses the hf:// protocol to query the remote Lance dataset directly,
157
- avoiding the need to download the entire dataset.
158
 
159
  Args:
160
  output_dataset: HuggingFace dataset ID (e.g., "davanstrien/arxiv-cs-papers-lance")
@@ -163,7 +162,10 @@ def get_last_update_date(
163
  Returns:
164
  ISO format date string of the last update, or None if dataset doesn't exist
165
  """
166
- raise NotImplementedError("Sub-task 3.3: Implement Lance remote query for max date")
 
 
 
167
 
168
 
169
  # =============================================================================
@@ -194,7 +196,69 @@ def prepare_incremental_data(
194
  Returns:
195
  Polars DataFrame ready for classification, or None if no new papers
196
  """
197
- raise NotImplementedError("Sub-task 3.4: Implement Polars filtering and formatting")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
 
199
 
200
  # =============================================================================
@@ -221,7 +285,41 @@ def classify_with_vllm(
221
  Returns:
222
  List of dicts with keys: classification_label, is_new_dataset, confidence_score
223
  """
224
- raise NotImplementedError("Sub-task 3.5: Implement vLLM classification")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225
 
226
 
227
  def classify_with_transformers(
@@ -244,7 +342,49 @@ def classify_with_transformers(
244
  Returns:
245
  List of dicts with keys: classification_label, is_new_dataset, confidence_score
246
  """
247
- raise NotImplementedError("Sub-task 3.5: Implement transformers fallback")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
248
 
249
 
250
  # =============================================================================
@@ -265,7 +405,26 @@ def save_to_lance(
265
  output_path: Local path for Lance dataset
266
  mode: 'overwrite' for full refresh, 'append' for incremental
267
  """
268
- raise NotImplementedError("Sub-task 3.6: Implement Lance output")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
269
 
270
 
271
  def upload_to_hub(
@@ -281,7 +440,32 @@ def upload_to_hub(
281
  output_dataset: Target dataset ID on HF Hub
282
  hf_token: HuggingFace token for authentication
283
  """
284
- raise NotImplementedError("Sub-task 3.6: Implement HF Hub upload")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
285
 
286
 
287
  # =============================================================================
 
54
  from typing import TYPE_CHECKING
55
 
56
  import polars as pl
 
57
  import torch
58
  from huggingface_hub import HfApi, login
59
  from toolz import partition_all
 
152
  """
153
  Get the maximum update_date from the existing Lance dataset on HF Hub.
154
 
155
+ For now, returns None to trigger full refresh mode.
156
+ TODO: Implement incremental mode by querying existing Lance dataset.
157
 
158
  Args:
159
  output_dataset: HuggingFace dataset ID (e.g., "davanstrien/arxiv-cs-papers-lance")
 
162
  Returns:
163
  ISO format date string of the last update, or None if dataset doesn't exist
164
  """
165
+ # TODO: Implement incremental mode
166
+ # For now, always return None to trigger full refresh
167
+ logger.info("Incremental mode not yet implemented - will do full refresh")
168
+ return None
169
 
170
 
171
  # =============================================================================
 
196
  Returns:
197
  Polars DataFrame ready for classification, or None if no new papers
198
  """
199
+ from huggingface_hub import snapshot_download
200
+
201
+ logger.info(f"Loading source dataset: {input_dataset}")
202
+
203
+ # Download dataset
204
+ local_dir = temp_dir / "raw_data"
205
+ snapshot_download(
206
+ input_dataset,
207
+ local_dir=str(local_dir),
208
+ allow_patterns=["*.parquet"],
209
+ repo_type="dataset",
210
+ )
211
+ parquet_files = list(local_dir.rglob("*.parquet"))
212
+ logger.info(f"Found {len(parquet_files)} parquet files")
213
+
214
+ # Create lazy frame
215
+ lf = pl.scan_parquet(parquet_files)
216
+
217
+ # Filter to CS papers
218
+ logger.info("Filtering to CS papers...")
219
+ lf_cs = lf.filter(pl.col("categories").str.contains("cs."))
220
+
221
+ # Apply incremental filter if not full refresh
222
+ if not full_refresh and last_update_date:
223
+ logger.info(f"Filtering for papers newer than {last_update_date}")
224
+ lf_cs = lf_cs.filter(pl.col("update_date") > last_update_date)
225
+ elif full_refresh:
226
+ logger.info("Full refresh mode - processing all CS papers")
227
+ else:
228
+ logger.info("No existing dataset found - processing all CS papers")
229
+
230
+ # Apply limit if specified (for testing) - AFTER filtering to CS
231
+ if limit:
232
+ logger.info(f"Limiting to {limit} papers for testing")
233
+ lf_cs = lf_cs.head(limit)
234
+
235
+ # Select only the columns we need (drop nested columns that cause issues)
236
+ columns_to_keep = ["id", "title", "abstract", "categories", "update_date", "authors"]
237
+ lf_selected = lf_cs.select([col for col in columns_to_keep if col in lf_cs.columns])
238
+
239
+ # Add formatted text column for classification
240
+ logger.info("Formatting text for classification...")
241
+ lf_formatted = lf_selected.with_columns(
242
+ pl.concat_str(
243
+ [
244
+ pl.lit("TITLE: "),
245
+ pl.col("title"),
246
+ pl.lit(" \n\nABSTRACT: "),
247
+ pl.col("abstract"),
248
+ ]
249
+ ).alias("text_for_classification")
250
+ )
251
+
252
+ # Collect the data
253
+ logger.info("Collecting data...")
254
+ df = lf_formatted.collect(streaming=True)
255
+
256
+ if df.height == 0:
257
+ logger.info("No papers to classify")
258
+ return None
259
+
260
+ logger.info(f"Prepared {df.height:,} papers for classification")
261
+ return df
262
 
263
 
264
  # =============================================================================
 
285
  Returns:
286
  List of dicts with keys: classification_label, is_new_dataset, confidence_score
287
  """
288
+ logger.info(f"Initializing vLLM with model: {model_id}")
289
+ llm = LLM(model=model_id, runner="pooling")
290
+
291
+ texts = df["text_for_classification"].to_list()
292
+ total_papers = len(texts)
293
+
294
+ logger.info(f"Starting vLLM classification of {total_papers:,} papers")
295
+ all_results = []
296
+
297
+ for batch in tqdm(
298
+ list(partition_all(batch_size, texts)),
299
+ desc="Processing batches",
300
+ unit="batch",
301
+ ):
302
+ batch_results = llm.classify(list(batch))
303
+
304
+ for result in batch_results:
305
+ logits = torch.tensor(result.outputs.probs)
306
+ probs = torch.nn.functional.softmax(logits, dim=0)
307
+ top_idx = torch.argmax(probs).item()
308
+ top_prob = probs[top_idx].item()
309
+
310
+ # Model config: 0 -> new_dataset, 1 -> no_new_dataset
311
+ label = "new_dataset" if top_idx == 0 else "no_new_dataset"
312
+
313
+ all_results.append(
314
+ {
315
+ "classification_label": label,
316
+ "is_new_dataset": label == "new_dataset",
317
+ "confidence_score": float(top_prob),
318
+ }
319
+ )
320
+
321
+ logger.info(f"Classified {len(all_results):,} papers with vLLM")
322
+ return all_results
323
 
324
 
325
  def classify_with_transformers(
 
342
  Returns:
343
  List of dicts with keys: classification_label, is_new_dataset, confidence_score
344
  """
345
+ from transformers import pipeline
346
+
347
+ logger.info(f"Initializing transformers pipeline with model: {model_id}")
348
+
349
+ if device == "cuda":
350
+ device_map = 0
351
+ elif device == "mps":
352
+ device_map = "mps"
353
+ else:
354
+ device_map = None
355
+
356
+ pipe = pipeline(
357
+ "text-classification",
358
+ model=model_id,
359
+ device=device_map,
360
+ batch_size=batch_size,
361
+ )
362
+
363
+ texts = df["text_for_classification"].to_list()
364
+ total_papers = len(texts)
365
+
366
+ logger.info(f"Starting transformers classification of {total_papers:,} papers")
367
+ all_results = []
368
+
369
+ with tqdm(total=total_papers, desc="Classifying papers", unit="papers") as pbar:
370
+ for batch in partition_all(batch_size, texts):
371
+ batch_list = list(batch)
372
+ predictions = pipe(batch_list)
373
+
374
+ for pred in predictions:
375
+ label = pred["label"]
376
+ all_results.append(
377
+ {
378
+ "classification_label": label,
379
+ "is_new_dataset": label == "new_dataset",
380
+ "confidence_score": float(pred["score"]),
381
+ }
382
+ )
383
+
384
+ pbar.update(len(batch_list))
385
+
386
+ logger.info(f"Classified {len(all_results):,} papers with transformers")
387
+ return all_results
388
 
389
 
390
  # =============================================================================
 
405
  output_path: Local path for Lance dataset
406
  mode: 'overwrite' for full refresh, 'append' for incremental
407
  """
408
+ if not LANCE_AVAILABLE:
409
+ raise ImportError("Lance library not available. Install with: pip install pylance")
410
+
411
+ logger.info(f"Saving {df.height:,} papers to Lance format at {output_path}")
412
+
413
+ # Convert Polars DataFrame to PyArrow Table
414
+ arrow_table = df.to_arrow()
415
+
416
+ # Write to Lance format
417
+ if mode == "overwrite" or not output_path.exists():
418
+ lance.write_dataset(arrow_table, str(output_path), mode="overwrite")
419
+ logger.info(f"Created new Lance dataset at {output_path}")
420
+ else:
421
+ # Append mode for incremental updates
422
+ lance.write_dataset(arrow_table, str(output_path), mode="append")
423
+ logger.info(f"Appended to existing Lance dataset at {output_path}")
424
+
425
+ # Verify the write
426
+ ds = lance.dataset(str(output_path))
427
+ logger.info(f"Lance dataset now has {ds.count_rows():,} total rows")
428
 
429
 
430
  def upload_to_hub(
 
440
  output_dataset: Target dataset ID on HF Hub
441
  hf_token: HuggingFace token for authentication
442
  """
443
+ api = HfApi()
444
+
445
+ # Create the dataset repo if it doesn't exist
446
+ try:
447
+ api.create_repo(
448
+ repo_id=output_dataset,
449
+ repo_type="dataset",
450
+ exist_ok=True,
451
+ token=hf_token,
452
+ )
453
+ logger.info(f"Dataset repo ready: {output_dataset}")
454
+ except Exception as e:
455
+ logger.warning(f"Could not create repo (may already exist): {e}")
456
+
457
+ # Upload the Lance directory
458
+ logger.info(f"Uploading Lance dataset to {output_dataset}...")
459
+ api.upload_folder(
460
+ folder_path=str(lance_path),
461
+ path_in_repo=LANCE_DATA_PATH,
462
+ repo_id=output_dataset,
463
+ repo_type="dataset",
464
+ token=hf_token,
465
+ commit_message=f"Update Lance dataset - {datetime.now().isoformat()}",
466
+ )
467
+
468
+ logger.info(f"Successfully uploaded to https://huggingface.co/datasets/{output_dataset}")
469
 
470
 
471
  # =============================================================================