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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.10"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "datasets",
|
| 5 |
+
# "huggingface-hub[hf_transfer]",
|
| 6 |
+
# "polars",
|
| 7 |
+
# "torch",
|
| 8 |
+
# "transformers",
|
| 9 |
+
# "toolz",
|
| 10 |
+
# "tqdm",
|
| 11 |
+
# "pyarrow",
|
| 12 |
+
# ]
|
| 13 |
+
# ///
|
| 14 |
+
"""
|
| 15 |
+
Incremental batch text classification for ArXiv papers.
|
| 16 |
+
|
| 17 |
+
This script processes new papers from the arxiv-metadata-snapshot dataset
|
| 18 |
+
and updates the existing classified dataset. It only processes papers newer
|
| 19 |
+
than the last classification run, making it efficient for daily updates.
|
| 20 |
+
|
| 21 |
+
Example usage:
|
| 22 |
+
# Daily incremental update (only new papers)
|
| 23 |
+
uv run batch_classify_arxiv_incremental.py
|
| 24 |
+
|
| 25 |
+
# Monthly full refresh (reprocess everything)
|
| 26 |
+
uv run batch_classify_arxiv_incremental.py --full-refresh
|
| 27 |
+
|
| 28 |
+
# Test with small sample
|
| 29 |
+
uv run batch_classify_arxiv_incremental.py --limit 100
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
import argparse
|
| 33 |
+
import json
|
| 34 |
+
import logging
|
| 35 |
+
import os
|
| 36 |
+
import shutil
|
| 37 |
+
import sys
|
| 38 |
+
import tempfile
|
| 39 |
+
from datetime import datetime
|
| 40 |
+
from pathlib import Path
|
| 41 |
+
from typing import Dict, List, Optional, Tuple
|
| 42 |
+
|
| 43 |
+
import polars as pl
|
| 44 |
+
import torch
|
| 45 |
+
from datasets import Dataset, load_dataset
|
| 46 |
+
from huggingface_hub import HfFolder, login
|
| 47 |
+
from toolz import partition_all
|
| 48 |
+
from tqdm.auto import tqdm
|
| 49 |
+
from transformers import pipeline
|
| 50 |
+
|
| 51 |
+
# Try to import vLLM - it may not be available in all environments
|
| 52 |
+
try:
|
| 53 |
+
import vllm
|
| 54 |
+
from vllm import LLM
|
| 55 |
+
VLLM_AVAILABLE = True
|
| 56 |
+
except ImportError:
|
| 57 |
+
VLLM_AVAILABLE = False
|
| 58 |
+
|
| 59 |
+
logging.basicConfig(
|
| 60 |
+
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
|
| 61 |
+
)
|
| 62 |
+
logger = logging.getLogger(__name__)
|
| 63 |
+
|
| 64 |
+
# Constants
|
| 65 |
+
DEFAULT_OUTPUT_DATASET = "davanstrien/my-classified-papers"
|
| 66 |
+
DEFAULT_INPUT_DATASET = "librarian-bots/arxiv-metadata-snapshot"
|
| 67 |
+
DEFAULT_MODEL = "davanstrien/ModernBERT-base-is-new-arxiv-dataset"
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def check_backend() -> Tuple[str, int]:
|
| 71 |
+
"""
|
| 72 |
+
Check available backend and return (backend_name, recommended_batch_size).
|
| 73 |
+
|
| 74 |
+
Returns:
|
| 75 |
+
Tuple of (backend_name, batch_size) where backend is 'vllm', 'cuda', 'mps', or 'cpu'
|
| 76 |
+
"""
|
| 77 |
+
if torch.cuda.is_available() and VLLM_AVAILABLE:
|
| 78 |
+
gpu_name = torch.cuda.get_device_name(0)
|
| 79 |
+
gpu_memory = torch.cuda.get_device_properties(0).total_memory / 1024**3
|
| 80 |
+
logger.info(f"GPU detected: {gpu_name} with {gpu_memory:.1f} GB memory")
|
| 81 |
+
logger.info(f"vLLM version: {vllm.__version__}")
|
| 82 |
+
return "vllm", 100_000
|
| 83 |
+
elif torch.cuda.is_available():
|
| 84 |
+
logger.info("CUDA available but vLLM not installed. Using transformers with GPU.")
|
| 85 |
+
return "cuda", 10_000
|
| 86 |
+
elif torch.backends.mps.is_available():
|
| 87 |
+
logger.info("Using Apple Silicon MPS device with transformers")
|
| 88 |
+
return "mps", 1_000
|
| 89 |
+
else:
|
| 90 |
+
logger.info("Using CPU device with transformers")
|
| 91 |
+
return "cpu", 100
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def get_last_update_date(output_dataset: str, hf_token: Optional[str] = None) -> Optional[str]:
|
| 95 |
+
"""
|
| 96 |
+
Get the maximum update_date from the existing classified dataset.
|
| 97 |
+
|
| 98 |
+
Args:
|
| 99 |
+
output_dataset: HuggingFace dataset ID
|
| 100 |
+
hf_token: Optional HuggingFace token
|
| 101 |
+
|
| 102 |
+
Returns:
|
| 103 |
+
ISO format date string of the last update, or None if dataset doesn't exist
|
| 104 |
+
"""
|
| 105 |
+
try:
|
| 106 |
+
logger.info(f"Checking for existing dataset: {output_dataset}")
|
| 107 |
+
|
| 108 |
+
# Try to load dataset metadata
|
| 109 |
+
from huggingface_hub import hf_hub_download, list_repo_files
|
| 110 |
+
|
| 111 |
+
# Check if dataset exists
|
| 112 |
+
try:
|
| 113 |
+
files = list_repo_files(output_dataset, repo_type="dataset", token=hf_token)
|
| 114 |
+
parquet_files = [f for f in files if f.endswith('.parquet')]
|
| 115 |
+
|
| 116 |
+
if not parquet_files:
|
| 117 |
+
logger.info("No parquet files found in existing dataset")
|
| 118 |
+
return None
|
| 119 |
+
|
| 120 |
+
except Exception as e:
|
| 121 |
+
logger.info(f"Dataset {output_dataset} not found or inaccessible: {e}")
|
| 122 |
+
return None
|
| 123 |
+
|
| 124 |
+
# Download and scan parquet files to find max update_date
|
| 125 |
+
temp_dir = Path(tempfile.mkdtemp(prefix="arxiv_incremental_check_"))
|
| 126 |
+
|
| 127 |
+
try:
|
| 128 |
+
from huggingface_hub import snapshot_download
|
| 129 |
+
local_dir = snapshot_download(
|
| 130 |
+
output_dataset,
|
| 131 |
+
local_dir=str(temp_dir),
|
| 132 |
+
allow_patterns=["*.parquet"],
|
| 133 |
+
repo_type="dataset",
|
| 134 |
+
token=hf_token
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
# Use Polars to efficiently find max update_date
|
| 138 |
+
lf = pl.scan_parquet(Path(local_dir).rglob("*.parquet"))
|
| 139 |
+
max_date_df = lf.select(pl.col("update_date").max()).collect()
|
| 140 |
+
|
| 141 |
+
if max_date_df.height > 0 and max_date_df.width > 0:
|
| 142 |
+
max_date = max_date_df[0, 0]
|
| 143 |
+
logger.info(f"Found last update date in existing dataset: {max_date}")
|
| 144 |
+
return max_date
|
| 145 |
+
else:
|
| 146 |
+
logger.info("No update_date found in existing dataset")
|
| 147 |
+
return None
|
| 148 |
+
|
| 149 |
+
finally:
|
| 150 |
+
# Cleanup temp directory
|
| 151 |
+
if temp_dir.exists():
|
| 152 |
+
shutil.rmtree(temp_dir)
|
| 153 |
+
|
| 154 |
+
except Exception as e:
|
| 155 |
+
logger.warning(f"Error checking existing dataset: {e}")
|
| 156 |
+
return None
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def prepare_incremental_data(
|
| 160 |
+
input_dataset: str,
|
| 161 |
+
temp_dir: Path,
|
| 162 |
+
last_update_date: Optional[str] = None,
|
| 163 |
+
limit: Optional[int] = None,
|
| 164 |
+
full_refresh: bool = False
|
| 165 |
+
) -> Optional[Path]:
|
| 166 |
+
"""
|
| 167 |
+
Prepare data for incremental classification.
|
| 168 |
+
|
| 169 |
+
Args:
|
| 170 |
+
input_dataset: Source dataset ID
|
| 171 |
+
temp_dir: Directory for temporary files
|
| 172 |
+
last_update_date: Date of last classification run
|
| 173 |
+
limit: Optional limit for testing
|
| 174 |
+
full_refresh: If True, process all papers regardless of date
|
| 175 |
+
|
| 176 |
+
Returns:
|
| 177 |
+
Path to filtered parquet file, or None if no new papers
|
| 178 |
+
"""
|
| 179 |
+
output_path = temp_dir / "papers_to_classify.parquet"
|
| 180 |
+
|
| 181 |
+
logger.info(f"Loading source dataset: {input_dataset}")
|
| 182 |
+
|
| 183 |
+
# Download dataset
|
| 184 |
+
from huggingface_hub import snapshot_download
|
| 185 |
+
local_dir = temp_dir / "raw_data"
|
| 186 |
+
snapshot_download(
|
| 187 |
+
input_dataset,
|
| 188 |
+
local_dir=str(local_dir),
|
| 189 |
+
allow_patterns=["*.parquet"],
|
| 190 |
+
repo_type="dataset",
|
| 191 |
+
)
|
| 192 |
+
parquet_files = list(local_dir.rglob("*.parquet"))
|
| 193 |
+
|
| 194 |
+
logger.info(f"Found {len(parquet_files)} parquet files")
|
| 195 |
+
|
| 196 |
+
# Create lazy frame
|
| 197 |
+
lf = pl.scan_parquet(parquet_files)
|
| 198 |
+
|
| 199 |
+
# Filter to CS papers
|
| 200 |
+
logger.info("Filtering to CS papers...")
|
| 201 |
+
lf_cs = lf.filter(pl.col("categories").str.contains("cs."))
|
| 202 |
+
|
| 203 |
+
# Apply incremental filter if not full refresh
|
| 204 |
+
if not full_refresh and last_update_date:
|
| 205 |
+
logger.info(f"Filtering for papers newer than {last_update_date}")
|
| 206 |
+
lf_cs = lf_cs.filter(pl.col("update_date") > last_update_date)
|
| 207 |
+
elif full_refresh:
|
| 208 |
+
logger.info("Full refresh mode - processing all CS papers")
|
| 209 |
+
else:
|
| 210 |
+
logger.info("No existing dataset found - processing all CS papers")
|
| 211 |
+
|
| 212 |
+
# Apply limit if specified (for testing)
|
| 213 |
+
if limit:
|
| 214 |
+
logger.info(f"Limiting to {limit} papers for testing")
|
| 215 |
+
lf_cs = lf_cs.head(limit)
|
| 216 |
+
|
| 217 |
+
# Add formatted text column
|
| 218 |
+
logger.info("Formatting text for classification...")
|
| 219 |
+
lf_formatted = lf_cs.with_columns(
|
| 220 |
+
pl.concat_str([
|
| 221 |
+
pl.lit("TITLE: "),
|
| 222 |
+
pl.col("title"),
|
| 223 |
+
pl.lit(" \n\nABSTRACT: "),
|
| 224 |
+
pl.col("abstract")
|
| 225 |
+
]).alias("text_for_classification")
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
# Collect to check if we have any papers to process
|
| 229 |
+
df_to_classify = lf_formatted.collect(streaming=True)
|
| 230 |
+
|
| 231 |
+
if df_to_classify.height == 0:
|
| 232 |
+
logger.info("No new papers to classify")
|
| 233 |
+
return None
|
| 234 |
+
|
| 235 |
+
logger.info(f"Found {df_to_classify.height:,} papers to classify")
|
| 236 |
+
|
| 237 |
+
# Write to parquet
|
| 238 |
+
df_to_classify.write_parquet(output_path)
|
| 239 |
+
return output_path
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def classify_with_vllm(
|
| 243 |
+
dataset: Dataset,
|
| 244 |
+
model_id: str,
|
| 245 |
+
batch_size: int = 100_000
|
| 246 |
+
) -> List[Dict]:
|
| 247 |
+
"""
|
| 248 |
+
Classify papers using vLLM for efficient GPU inference.
|
| 249 |
+
"""
|
| 250 |
+
logger.info(f"Initializing vLLM with model: {model_id}")
|
| 251 |
+
llm = LLM(model=model_id, task="classify")
|
| 252 |
+
|
| 253 |
+
texts = dataset["text_for_classification"]
|
| 254 |
+
total_papers = len(texts)
|
| 255 |
+
|
| 256 |
+
logger.info(f"Starting vLLM classification of {total_papers:,} papers")
|
| 257 |
+
all_results = []
|
| 258 |
+
|
| 259 |
+
for batch in tqdm(
|
| 260 |
+
list(partition_all(batch_size, texts)),
|
| 261 |
+
desc="Processing batches",
|
| 262 |
+
unit="batch"
|
| 263 |
+
):
|
| 264 |
+
batch_results = llm.classify(batch)
|
| 265 |
+
|
| 266 |
+
for result in batch_results:
|
| 267 |
+
logits = torch.tensor(result.outputs.probs)
|
| 268 |
+
probs = torch.nn.functional.softmax(logits, dim=0)
|
| 269 |
+
top_idx = torch.argmax(probs).item()
|
| 270 |
+
top_prob = probs[top_idx].item()
|
| 271 |
+
|
| 272 |
+
label = "new_dataset" if top_idx == 1 else "no_new_dataset"
|
| 273 |
+
|
| 274 |
+
all_results.append({
|
| 275 |
+
"classification_label": label,
|
| 276 |
+
"is_new_dataset": label == "new_dataset",
|
| 277 |
+
"confidence_score": float(top_prob)
|
| 278 |
+
})
|
| 279 |
+
|
| 280 |
+
return all_results
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def classify_with_transformers(
|
| 284 |
+
dataset: Dataset,
|
| 285 |
+
model_id: str,
|
| 286 |
+
batch_size: int = 1_000,
|
| 287 |
+
device: str = "cpu"
|
| 288 |
+
) -> List[Dict]:
|
| 289 |
+
"""
|
| 290 |
+
Classify papers using transformers pipeline.
|
| 291 |
+
"""
|
| 292 |
+
logger.info(f"Initializing transformers pipeline with model: {model_id}")
|
| 293 |
+
|
| 294 |
+
if device == "cuda":
|
| 295 |
+
device_map = 0
|
| 296 |
+
elif device == "mps":
|
| 297 |
+
device_map = "mps"
|
| 298 |
+
else:
|
| 299 |
+
device_map = None
|
| 300 |
+
|
| 301 |
+
pipe = pipeline(
|
| 302 |
+
"text-classification",
|
| 303 |
+
model=model_id,
|
| 304 |
+
device=device_map,
|
| 305 |
+
batch_size=batch_size
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
texts = dataset["text_for_classification"]
|
| 309 |
+
total_papers = len(texts)
|
| 310 |
+
|
| 311 |
+
logger.info(f"Starting transformers classification of {total_papers:,} papers")
|
| 312 |
+
all_results = []
|
| 313 |
+
|
| 314 |
+
with tqdm(total=total_papers, desc="Classifying papers", unit="papers") as pbar:
|
| 315 |
+
for batch in partition_all(batch_size, texts):
|
| 316 |
+
batch_list = list(batch)
|
| 317 |
+
predictions = pipe(batch_list)
|
| 318 |
+
|
| 319 |
+
for pred in predictions:
|
| 320 |
+
label = pred["label"]
|
| 321 |
+
all_results.append({
|
| 322 |
+
"classification_label": label,
|
| 323 |
+
"is_new_dataset": label == "new_dataset",
|
| 324 |
+
"confidence_score": float(pred["score"])
|
| 325 |
+
})
|
| 326 |
+
|
| 327 |
+
pbar.update(len(batch_list))
|
| 328 |
+
|
| 329 |
+
return all_results
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def merge_with_existing(
|
| 333 |
+
new_dataset: Dataset,
|
| 334 |
+
output_dataset: str,
|
| 335 |
+
temp_dir: Path,
|
| 336 |
+
hf_token: Optional[str] = None
|
| 337 |
+
) -> Dataset:
|
| 338 |
+
"""
|
| 339 |
+
Merge newly classified papers with existing dataset.
|
| 340 |
+
|
| 341 |
+
Args:
|
| 342 |
+
new_dataset: Newly classified papers
|
| 343 |
+
output_dataset: Target dataset ID
|
| 344 |
+
temp_dir: Temporary directory
|
| 345 |
+
hf_token: HuggingFace token
|
| 346 |
+
|
| 347 |
+
Returns:
|
| 348 |
+
Merged dataset
|
| 349 |
+
"""
|
| 350 |
+
try:
|
| 351 |
+
logger.info(f"Loading existing dataset from {output_dataset}")
|
| 352 |
+
|
| 353 |
+
# Download existing dataset
|
| 354 |
+
from huggingface_hub import snapshot_download
|
| 355 |
+
existing_dir = temp_dir / "existing_data"
|
| 356 |
+
snapshot_download(
|
| 357 |
+
output_dataset,
|
| 358 |
+
local_dir=str(existing_dir),
|
| 359 |
+
allow_patterns=["*.parquet"],
|
| 360 |
+
repo_type="dataset",
|
| 361 |
+
token=hf_token
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
# Load with Polars for efficient merging
|
| 365 |
+
existing_files = list(existing_dir.rglob("*.parquet"))
|
| 366 |
+
|
| 367 |
+
if existing_files:
|
| 368 |
+
# Convert new dataset to Polars
|
| 369 |
+
new_df = pl.from_arrow(new_dataset.data.table)
|
| 370 |
+
|
| 371 |
+
# Load existing data
|
| 372 |
+
existing_df = pl.read_parquet(existing_files)
|
| 373 |
+
|
| 374 |
+
# Combine datasets
|
| 375 |
+
logger.info(f"Merging {new_df.height:,} new papers with {existing_df.height:,} existing papers")
|
| 376 |
+
combined_df = pl.concat([existing_df, new_df], how="vertical")
|
| 377 |
+
|
| 378 |
+
# Deduplicate by paper ID, keeping the most recent
|
| 379 |
+
logger.info("Deduplicating by paper ID...")
|
| 380 |
+
final_df = combined_df.unique(subset=["id"], keep="last")
|
| 381 |
+
|
| 382 |
+
logger.info(f"Final dataset has {final_df.height:,} papers after deduplication")
|
| 383 |
+
|
| 384 |
+
# Convert back to HuggingFace Dataset
|
| 385 |
+
final_dataset = Dataset.from_pandas(final_df.to_pandas())
|
| 386 |
+
|
| 387 |
+
return final_dataset
|
| 388 |
+
else:
|
| 389 |
+
logger.info("No existing data found, returning new dataset")
|
| 390 |
+
return new_dataset
|
| 391 |
+
|
| 392 |
+
except Exception as e:
|
| 393 |
+
logger.warning(f"Could not load existing dataset: {e}")
|
| 394 |
+
logger.info("Returning new dataset only")
|
| 395 |
+
return new_dataset
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def main(
|
| 399 |
+
input_dataset: str = DEFAULT_INPUT_DATASET,
|
| 400 |
+
output_dataset: str = DEFAULT_OUTPUT_DATASET,
|
| 401 |
+
model_id: str = DEFAULT_MODEL,
|
| 402 |
+
batch_size: Optional[int] = None,
|
| 403 |
+
limit: Optional[int] = None,
|
| 404 |
+
full_refresh: bool = False,
|
| 405 |
+
temp_dir: Optional[str] = None,
|
| 406 |
+
hf_token: Optional[str] = None
|
| 407 |
+
):
|
| 408 |
+
"""
|
| 409 |
+
Main incremental classification pipeline.
|
| 410 |
+
"""
|
| 411 |
+
# Authentication
|
| 412 |
+
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
|
| 413 |
+
if HF_TOKEN:
|
| 414 |
+
login(token=HF_TOKEN)
|
| 415 |
+
else:
|
| 416 |
+
logger.warning("No HF_TOKEN found. You may need to login for private datasets.")
|
| 417 |
+
|
| 418 |
+
# Setup temp directory
|
| 419 |
+
if temp_dir:
|
| 420 |
+
temp_path = Path(temp_dir)
|
| 421 |
+
temp_path.mkdir(parents=True, exist_ok=True)
|
| 422 |
+
else:
|
| 423 |
+
temp_path = Path(tempfile.mkdtemp(prefix="arxiv_incremental_"))
|
| 424 |
+
|
| 425 |
+
logger.info(f"Using temp directory: {temp_path}")
|
| 426 |
+
|
| 427 |
+
# Check backend and set batch size
|
| 428 |
+
backend, default_batch_size = check_backend()
|
| 429 |
+
if batch_size is None:
|
| 430 |
+
batch_size = default_batch_size
|
| 431 |
+
logger.info(f"Using batch size: {batch_size:,}")
|
| 432 |
+
|
| 433 |
+
# Step 1: Check for existing dataset and get last update date
|
| 434 |
+
last_update_date = None
|
| 435 |
+
if not full_refresh:
|
| 436 |
+
last_update_date = get_last_update_date(output_dataset, HF_TOKEN)
|
| 437 |
+
if last_update_date:
|
| 438 |
+
logger.info(f"Will process papers newer than: {last_update_date}")
|
| 439 |
+
else:
|
| 440 |
+
logger.info("No existing dataset found - will process all papers")
|
| 441 |
+
else:
|
| 442 |
+
logger.info("Full refresh mode - will process all papers")
|
| 443 |
+
|
| 444 |
+
# Step 2: Prepare incremental data
|
| 445 |
+
papers_to_classify = prepare_incremental_data(
|
| 446 |
+
input_dataset,
|
| 447 |
+
temp_path,
|
| 448 |
+
last_update_date,
|
| 449 |
+
limit,
|
| 450 |
+
full_refresh
|
| 451 |
+
)
|
| 452 |
+
|
| 453 |
+
if papers_to_classify is None:
|
| 454 |
+
logger.info("No new papers to classify. Dataset is up to date!")
|
| 455 |
+
# Cleanup temp directory
|
| 456 |
+
if not temp_dir and temp_path.exists():
|
| 457 |
+
shutil.rmtree(temp_path)
|
| 458 |
+
return
|
| 459 |
+
|
| 460 |
+
# Step 3: Load as HuggingFace Dataset
|
| 461 |
+
logger.info("Loading papers to classify as HuggingFace Dataset...")
|
| 462 |
+
dataset = load_dataset(
|
| 463 |
+
"parquet",
|
| 464 |
+
data_files=str(papers_to_classify),
|
| 465 |
+
split="train"
|
| 466 |
+
)
|
| 467 |
+
logger.info(f"Dataset loaded with {len(dataset):,} papers to classify")
|
| 468 |
+
|
| 469 |
+
# Step 4: Classify papers
|
| 470 |
+
if backend == "vllm":
|
| 471 |
+
results = classify_with_vllm(dataset, model_id, batch_size)
|
| 472 |
+
else:
|
| 473 |
+
results = classify_with_transformers(
|
| 474 |
+
dataset, model_id, batch_size, backend
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
# Step 5: Add results to dataset
|
| 478 |
+
logger.info("Adding classification results to dataset...")
|
| 479 |
+
|
| 480 |
+
dataset = dataset.add_column("classification_label", [r["classification_label"] for r in results])
|
| 481 |
+
dataset = dataset.add_column("is_new_dataset", [r["is_new_dataset"] for r in results])
|
| 482 |
+
dataset = dataset.add_column("confidence_score", [r["confidence_score"] for r in results])
|
| 483 |
+
|
| 484 |
+
# Add metadata
|
| 485 |
+
dataset = dataset.add_column("classification_date", [datetime.now().isoformat()] * len(dataset))
|
| 486 |
+
dataset = dataset.add_column("model_version", [model_id] * len(dataset))
|
| 487 |
+
|
| 488 |
+
# Remove temporary columns and problematic nested columns
|
| 489 |
+
columns_to_remove = ["text_for_classification"]
|
| 490 |
+
if "versions" in dataset.column_names:
|
| 491 |
+
columns_to_remove.append("versions")
|
| 492 |
+
if "authors_parsed" in dataset.column_names:
|
| 493 |
+
columns_to_remove.append("authors_parsed")
|
| 494 |
+
|
| 495 |
+
dataset = dataset.remove_columns(columns_to_remove)
|
| 496 |
+
|
| 497 |
+
# Step 6: Merge with existing dataset (if not full refresh)
|
| 498 |
+
if not full_refresh and last_update_date:
|
| 499 |
+
dataset = merge_with_existing(dataset, output_dataset, temp_path, HF_TOKEN)
|
| 500 |
+
|
| 501 |
+
# Step 7: Push to Hub or save locally
|
| 502 |
+
if HF_TOKEN:
|
| 503 |
+
logger.info(f"Pushing results to: {output_dataset}")
|
| 504 |
+
dataset.push_to_hub(output_dataset, token=HF_TOKEN)
|
| 505 |
+
else:
|
| 506 |
+
local_path = temp_path / "classified_dataset"
|
| 507 |
+
logger.info(f"No HF_TOKEN, saving results locally to: {local_path}")
|
| 508 |
+
dataset.save_to_disk(str(local_path))
|
| 509 |
+
|
| 510 |
+
# Print statistics
|
| 511 |
+
num_new_datasets = sum(1 for i in range(len(dataset)) if dataset[i]["is_new_dataset"])
|
| 512 |
+
avg_confidence = sum(dataset[i]["confidence_score"] for i in range(len(dataset))) / len(dataset)
|
| 513 |
+
|
| 514 |
+
logger.info("="*60)
|
| 515 |
+
logger.info("Incremental Classification Complete!")
|
| 516 |
+
logger.info(f"Total papers in dataset: {len(dataset):,}")
|
| 517 |
+
logger.info(f"Papers with new datasets: {num_new_datasets:,} ({num_new_datasets/len(dataset)*100:.1f}%)")
|
| 518 |
+
logger.info(f"Average confidence score: {avg_confidence:.3f}")
|
| 519 |
+
logger.info(f"Results saved to: {output_dataset}")
|
| 520 |
+
if not full_refresh and last_update_date:
|
| 521 |
+
logger.info(f"Processed papers newer than: {last_update_date}")
|
| 522 |
+
logger.info("="*60)
|
| 523 |
+
|
| 524 |
+
# Cleanup temp directory if not explicitly specified
|
| 525 |
+
if not temp_dir and temp_path.exists():
|
| 526 |
+
logger.info(f"Cleaning up temp directory: {temp_path}")
|
| 527 |
+
shutil.rmtree(temp_path)
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
if __name__ == "__main__":
|
| 531 |
+
parser = argparse.ArgumentParser(
|
| 532 |
+
description="Incremental classification of ArXiv papers for new datasets",
|
| 533 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 534 |
+
epilog="""
|
| 535 |
+
Examples:
|
| 536 |
+
# Daily incremental update (only new papers)
|
| 537 |
+
uv run batch_classify_arxiv_incremental.py
|
| 538 |
+
|
| 539 |
+
# Monthly full refresh (reprocess everything)
|
| 540 |
+
uv run batch_classify_arxiv_incremental.py --full-refresh
|
| 541 |
+
|
| 542 |
+
# Test with small sample
|
| 543 |
+
uv run batch_classify_arxiv_incremental.py --limit 100
|
| 544 |
+
|
| 545 |
+
# Custom datasets
|
| 546 |
+
uv run batch_classify_arxiv_incremental.py \\
|
| 547 |
+
--input-dataset librarian-bots/arxiv-metadata-snapshot \\
|
| 548 |
+
--output-dataset my-custom-classification
|
| 549 |
+
"""
|
| 550 |
+
)
|
| 551 |
+
|
| 552 |
+
parser.add_argument(
|
| 553 |
+
"--input-dataset",
|
| 554 |
+
type=str,
|
| 555 |
+
default=DEFAULT_INPUT_DATASET,
|
| 556 |
+
help=f"Input dataset on HuggingFace Hub (default: {DEFAULT_INPUT_DATASET})"
|
| 557 |
+
)
|
| 558 |
+
parser.add_argument(
|
| 559 |
+
"--output-dataset",
|
| 560 |
+
type=str,
|
| 561 |
+
default=DEFAULT_OUTPUT_DATASET,
|
| 562 |
+
help=f"Output dataset on HuggingFace Hub (default: {DEFAULT_OUTPUT_DATASET})"
|
| 563 |
+
)
|
| 564 |
+
parser.add_argument(
|
| 565 |
+
"--model",
|
| 566 |
+
type=str,
|
| 567 |
+
default=DEFAULT_MODEL,
|
| 568 |
+
help=f"Model ID for classification (default: {DEFAULT_MODEL})"
|
| 569 |
+
)
|
| 570 |
+
parser.add_argument(
|
| 571 |
+
"--batch-size",
|
| 572 |
+
type=int,
|
| 573 |
+
help="Batch size for inference (auto-detected if not specified)"
|
| 574 |
+
)
|
| 575 |
+
parser.add_argument(
|
| 576 |
+
"--limit",
|
| 577 |
+
type=int,
|
| 578 |
+
help="Limit number of papers for testing"
|
| 579 |
+
)
|
| 580 |
+
parser.add_argument(
|
| 581 |
+
"--full-refresh",
|
| 582 |
+
action="store_true",
|
| 583 |
+
help="Process all papers regardless of update date (monthly refresh)"
|
| 584 |
+
)
|
| 585 |
+
parser.add_argument(
|
| 586 |
+
"--temp-dir",
|
| 587 |
+
type=str,
|
| 588 |
+
help="Directory for temporary files (auto-created if not specified)"
|
| 589 |
+
)
|
| 590 |
+
parser.add_argument(
|
| 591 |
+
"--hf-token",
|
| 592 |
+
type=str,
|
| 593 |
+
help="HuggingFace token (can also use HF_TOKEN env var)"
|
| 594 |
+
)
|
| 595 |
+
|
| 596 |
+
args = parser.parse_args()
|
| 597 |
+
|
| 598 |
+
main(
|
| 599 |
+
input_dataset=args.input_dataset,
|
| 600 |
+
output_dataset=args.output_dataset,
|
| 601 |
+
model_id=args.model,
|
| 602 |
+
batch_size=args.batch_size,
|
| 603 |
+
limit=args.limit,
|
| 604 |
+
full_refresh=args.full_refresh,
|
| 605 |
+
temp_dir=args.temp_dir,
|
| 606 |
+
hf_token=args.hf_token
|
| 607 |
+
)
|