File size: 23,089 Bytes
ec0535b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d2c5a0
 
ec0535b
 
 
 
 
 
 
 
3d2c5a0
 
 
 
ec0535b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d2c5a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fedc701
 
3d2c5a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fedc701
3d2c5a0
 
 
 
 
 
 
ec0535b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d2c5a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec0535b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d2c5a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec0535b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d2c5a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec0535b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d2c5a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec0535b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
# /// script
# requires-python = ">=3.10"
# dependencies = [
#     "huggingface-hub[hf_transfer]>=0.20",
#     "polars>=1.0",
#     "torch>=2.0",
#     "transformers>=4.40",
#     "vllm",
#     "pylance>=0.20",
#     "pyarrow>=15.0",
#     "tqdm",
#     "toolz",
# ]
# [[tool.uv.index]]
# url = "https://wheels.vllm.ai/nightly"
# ///
"""
Classify arXiv CS papers to identify which ones introduce new datasets.

This script processes papers from the arxiv-metadata-snapshot dataset,
classifies them using a fine-tuned ModernBERT model, and outputs results
to Lance format for efficient vector search on the HF Hub.

Output supports direct remote queries via the hf:// protocol, enabling
semantic search without downloading the full dataset.

Example usage:
    # Incremental update (only new papers since last run)
    uv run classify_arxiv_to_lance.py

    # Full refresh (reprocess everything)
    uv run classify_arxiv_to_lance.py --full-refresh

    # Test with small sample
    uv run classify_arxiv_to_lance.py --limit 100

    # Run on HF Jobs (A100)
    hf jobs uv run \\
      --flavor a100-large \\
      --image vllm/vllm-openai \\
      --secrets HF_TOKEN \\
      classify_arxiv_to_lance.py
"""

from __future__ import annotations

import argparse
import logging
import os
import shutil
import tempfile
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING

import polars as pl
import torch
from huggingface_hub import HfApi, login
from toolz import partition_all
from tqdm.auto import tqdm

# Conditional imports for type checking
if TYPE_CHECKING:
    from typing import Optional

# Try to import vLLM - may not be available in all environments
try:
    import vllm
    from vllm import LLM

    VLLM_AVAILABLE = True
except ImportError:
    VLLM_AVAILABLE = False

# Try to import lance
try:
    import lance

    LANCE_AVAILABLE = True
except ImportError:
    LANCE_AVAILABLE = False

# Logging setup
logging.basicConfig(
    level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)

# =============================================================================
# Constants
# =============================================================================

DEFAULT_INPUT_DATASET = "librarian-bots/arxiv-metadata-snapshot"
DEFAULT_OUTPUT_DATASET = "davanstrien/arxiv-cs-papers-lance"
DEFAULT_MODEL = "davanstrien/ModernBERT-base-is-new-arxiv-dataset"

# Batch sizes tuned for different backends
BATCH_SIZES = {
    "vllm": 500_000,  # vLLM on A100 can handle large batches
    "cuda": 256,  # transformers on CUDA needs smaller batches
    "mps": 1_000,  # Apple Silicon
    "cpu": 100,  # CPU fallback
}

# Lance output path within the dataset repo
LANCE_DATA_PATH = "data/train.lance"


# =============================================================================
# Backend Detection
# =============================================================================


def check_backend() -> tuple[str, int]:
    """
    Check available backend and return (backend_name, recommended_batch_size).

    Priority: vLLM (CUDA) > CUDA (transformers) > MPS > CPU

    Returns:
        Tuple of (backend_name, batch_size) where backend is
        'vllm', 'cuda', 'mps', or 'cpu'
    """
    if torch.cuda.is_available() and VLLM_AVAILABLE:
        gpu_name = torch.cuda.get_device_name(0)
        gpu_memory = torch.cuda.get_device_properties(0).total_memory / 1024**3
        logger.info(f"GPU detected: {gpu_name} with {gpu_memory:.1f} GB memory")
        logger.info(f"vLLM version: {vllm.__version__}")
        return "vllm", BATCH_SIZES["vllm"]
    elif torch.cuda.is_available():
        gpu_name = torch.cuda.get_device_name(0)
        gpu_memory = torch.cuda.get_device_properties(0).total_memory / 1024**3
        logger.info(f"GPU detected: {gpu_name} with {gpu_memory:.1f} GB memory")
        logger.info("vLLM not available, using transformers with CUDA")
        return "cuda", BATCH_SIZES["cuda"]
    elif torch.backends.mps.is_available():
        logger.info("Using Apple Silicon MPS device with transformers")
        return "mps", BATCH_SIZES["mps"]
    else:
        logger.info("Using CPU device with transformers")
        return "cpu", BATCH_SIZES["cpu"]


# =============================================================================
# Incremental Processing Support
# =============================================================================


def get_last_update_date(
    output_dataset: str, hf_token: Optional[str] = None
) -> Optional[str]:
    """
    Get the maximum update_date from the existing Lance dataset on HF Hub.

    For now, returns None to trigger full refresh mode.
    TODO: Implement incremental mode by querying existing Lance dataset.

    Args:
        output_dataset: HuggingFace dataset ID (e.g., "davanstrien/arxiv-cs-papers-lance")
        hf_token: Optional HuggingFace token for private datasets

    Returns:
        ISO format date string of the last update, or None if dataset doesn't exist
    """
    # TODO: Implement incremental mode
    # For now, always return None to trigger full refresh
    logger.info("Incremental mode not yet implemented - will do full refresh")
    return None


# =============================================================================
# Data Preparation
# =============================================================================


def prepare_incremental_data(
    input_dataset: str,
    temp_dir: Path,
    last_update_date: Optional[str] = None,
    limit: Optional[int] = None,
    full_refresh: bool = False,
) -> Optional[pl.DataFrame]:
    """
    Prepare data for incremental classification.

    Downloads source dataset, filters to CS papers, applies incremental
    filtering based on last_update_date, and formats text for classification.

    Args:
        input_dataset: Source dataset ID on HF Hub
        temp_dir: Directory for temporary files
        last_update_date: Date of last classification run (for incremental mode)
        limit: Optional limit for testing
        full_refresh: If True, process all papers regardless of date

    Returns:
        Polars DataFrame ready for classification, or None if no new papers
    """
    from huggingface_hub import snapshot_download

    logger.info(f"Loading source dataset: {input_dataset}")

    # Download dataset
    local_dir = temp_dir / "raw_data"
    snapshot_download(
        input_dataset,
        local_dir=str(local_dir),
        allow_patterns=["*.parquet"],
        repo_type="dataset",
    )
    parquet_files = list(local_dir.rglob("*.parquet"))
    logger.info(f"Found {len(parquet_files)} parquet files")

    # Create lazy frame
    lf = pl.scan_parquet(parquet_files)

    # Filter to CS papers
    logger.info("Filtering to CS papers...")
    lf_cs = lf.filter(pl.col("categories").str.contains("cs."))

    # Apply incremental filter if not full refresh
    if not full_refresh and last_update_date:
        logger.info(f"Filtering for papers newer than {last_update_date}")
        lf_cs = lf_cs.filter(pl.col("update_date") > last_update_date)
    elif full_refresh:
        logger.info("Full refresh mode - processing all CS papers")
    else:
        logger.info("No existing dataset found - processing all CS papers")

    # Apply limit if specified (for testing) - AFTER filtering to CS
    if limit:
        logger.info(f"Limiting to {limit} papers for testing")
        lf_cs = lf_cs.head(limit)

    # Select only the columns we need (drop nested columns that cause issues)
    columns_to_keep = ["id", "title", "abstract", "categories", "update_date", "authors"]
    available_columns = lf_cs.collect_schema().names()
    lf_selected = lf_cs.select([col for col in columns_to_keep if col in available_columns])

    # Add formatted text column for classification
    logger.info("Formatting text for classification...")
    lf_formatted = lf_selected.with_columns(
        pl.concat_str(
            [
                pl.lit("TITLE: "),
                pl.col("title"),
                pl.lit(" \n\nABSTRACT: "),
                pl.col("abstract"),
            ]
        ).alias("text_for_classification")
    )

    # Collect the data
    logger.info("Collecting data...")
    df = lf_formatted.collect(engine="streaming")

    if df.height == 0:
        logger.info("No papers to classify")
        return None

    logger.info(f"Prepared {df.height:,} papers for classification")
    return df


# =============================================================================
# Classification Functions
# =============================================================================


def classify_with_vllm(
    df: pl.DataFrame,
    model_id: str,
    batch_size: int = 500_000,
) -> list[dict]:
    """
    Classify papers using vLLM for efficient GPU inference.

    Uses vLLM's pooling runner for sequence classification, which provides
    significant speedup over transformers pipeline on large batches.

    Args:
        df: DataFrame with 'text_for_classification' column
        model_id: HuggingFace model ID for classification
        batch_size: Number of texts to process per batch

    Returns:
        List of dicts with keys: classification_label, is_new_dataset, confidence_score
    """
    logger.info(f"Initializing vLLM with model: {model_id}")
    llm = LLM(model=model_id, runner="pooling")

    texts = df["text_for_classification"].to_list()
    total_papers = len(texts)

    logger.info(f"Starting vLLM classification of {total_papers:,} papers")
    all_results = []

    for batch in tqdm(
        list(partition_all(batch_size, texts)),
        desc="Processing batches",
        unit="batch",
    ):
        batch_results = llm.classify(list(batch))

        for result in batch_results:
            logits = torch.tensor(result.outputs.probs)
            probs = torch.nn.functional.softmax(logits, dim=0)
            top_idx = torch.argmax(probs).item()
            top_prob = probs[top_idx].item()

            # Model config: 0 -> new_dataset, 1 -> no_new_dataset
            label = "new_dataset" if top_idx == 0 else "no_new_dataset"

            all_results.append(
                {
                    "classification_label": label,
                    "is_new_dataset": label == "new_dataset",
                    "confidence_score": float(top_prob),
                }
            )

    logger.info(f"Classified {len(all_results):,} papers with vLLM")
    return all_results


def classify_with_transformers(
    df: pl.DataFrame,
    model_id: str,
    batch_size: int = 1_000,
    device: str = "cpu",
) -> list[dict]:
    """
    Classify papers using transformers pipeline.

    Fallback for environments without vLLM or for smaller datasets.

    Args:
        df: DataFrame with 'text_for_classification' column
        model_id: HuggingFace model ID for classification
        batch_size: Number of texts to process per batch
        device: Device to use ('cuda', 'mps', or 'cpu')

    Returns:
        List of dicts with keys: classification_label, is_new_dataset, confidence_score
    """
    from transformers import pipeline

    logger.info(f"Initializing transformers pipeline with model: {model_id}")

    if device == "cuda":
        device_map = 0
    elif device == "mps":
        device_map = "mps"
    else:
        device_map = None

    pipe = pipeline(
        "text-classification",
        model=model_id,
        device=device_map,
        batch_size=batch_size,
    )

    texts = df["text_for_classification"].to_list()
    total_papers = len(texts)

    logger.info(f"Starting transformers classification of {total_papers:,} papers")
    all_results = []

    with tqdm(total=total_papers, desc="Classifying papers", unit="papers") as pbar:
        for batch in partition_all(batch_size, texts):
            batch_list = list(batch)
            predictions = pipe(batch_list)

            for pred in predictions:
                label = pred["label"]
                all_results.append(
                    {
                        "classification_label": label,
                        "is_new_dataset": label == "new_dataset",
                        "confidence_score": float(pred["score"]),
                    }
                )

            pbar.update(len(batch_list))

    logger.info(f"Classified {len(all_results):,} papers with transformers")
    return all_results


# =============================================================================
# Output to Lance
# =============================================================================


def save_to_lance(
    df: pl.DataFrame,
    output_path: Path,
    mode: str = "overwrite",
) -> None:
    """
    Save classified DataFrame to Lance format.

    Args:
        df: Classified DataFrame with all columns
        output_path: Local path for Lance dataset
        mode: 'overwrite' for full refresh, 'append' for incremental
    """
    if not LANCE_AVAILABLE:
        raise ImportError("Lance library not available. Install with: pip install pylance")

    logger.info(f"Saving {df.height:,} papers to Lance format at {output_path}")

    # Convert Polars DataFrame to PyArrow Table
    arrow_table = df.to_arrow()

    # Write to Lance format
    if mode == "overwrite" or not output_path.exists():
        lance.write_dataset(arrow_table, str(output_path), mode="overwrite")
        logger.info(f"Created new Lance dataset at {output_path}")
    else:
        # Append mode for incremental updates
        lance.write_dataset(arrow_table, str(output_path), mode="append")
        logger.info(f"Appended to existing Lance dataset at {output_path}")

    # Verify the write
    ds = lance.dataset(str(output_path))
    logger.info(f"Lance dataset now has {ds.count_rows():,} total rows")


def upload_to_hub(
    lance_path: Path,
    output_dataset: str,
    hf_token: Optional[str] = None,
) -> None:
    """
    Upload Lance dataset to HuggingFace Hub.

    Args:
        lance_path: Local path to Lance dataset
        output_dataset: Target dataset ID on HF Hub
        hf_token: HuggingFace token for authentication
    """
    api = HfApi()

    # Create the dataset repo if it doesn't exist
    try:
        api.create_repo(
            repo_id=output_dataset,
            repo_type="dataset",
            exist_ok=True,
            token=hf_token,
        )
        logger.info(f"Dataset repo ready: {output_dataset}")
    except Exception as e:
        logger.warning(f"Could not create repo (may already exist): {e}")

    # Upload the Lance directory
    logger.info(f"Uploading Lance dataset to {output_dataset}...")
    api.upload_folder(
        folder_path=str(lance_path),
        path_in_repo=LANCE_DATA_PATH,
        repo_id=output_dataset,
        repo_type="dataset",
        token=hf_token,
        commit_message=f"Update Lance dataset - {datetime.now().isoformat()}",
    )

    logger.info(f"Successfully uploaded to https://huggingface.co/datasets/{output_dataset}")


# =============================================================================
# Main Pipeline
# =============================================================================


def main(
    input_dataset: str = DEFAULT_INPUT_DATASET,
    output_dataset: str = DEFAULT_OUTPUT_DATASET,
    model_id: str = DEFAULT_MODEL,
    batch_size: Optional[int] = None,
    limit: Optional[int] = None,
    full_refresh: bool = False,
    temp_dir: Optional[str] = None,
    hf_token: Optional[str] = None,
) -> None:
    """
    Main classification pipeline.

    Flow:
        1. Authenticate with HF Hub
        2. Detect backend (vLLM/CUDA/MPS/CPU)
        3. Check for existing Lance dataset, get last update date
        4. Download and filter source data (incremental or full)
        5. Classify papers using appropriate backend
        6. Save results to Lance format
        7. Upload to HF Hub
        8. Print statistics

    Args:
        input_dataset: Source arxiv metadata dataset
        output_dataset: Target Lance dataset on HF Hub
        model_id: Classification model ID
        batch_size: Override auto-detected batch size
        limit: Limit papers for testing
        full_refresh: Process all papers (ignore existing data)
        temp_dir: Custom temp directory (auto-created if not specified)
        hf_token: HF token (falls back to HF_TOKEN env var)
    """
    # === Step 0: Setup ===
    logger.info("=" * 60)
    logger.info("ArXiv CS Papers Classification Pipeline (Lance Output)")
    logger.info("=" * 60)

    # Authentication
    HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
    if HF_TOKEN:
        login(token=HF_TOKEN)
        logger.info("Authenticated with HuggingFace Hub")
    else:
        logger.warning("No HF_TOKEN found. May fail for private datasets or uploads.")

    # Setup temp directory
    if temp_dir:
        temp_path = Path(temp_dir)
        temp_path.mkdir(parents=True, exist_ok=True)
    else:
        temp_path = Path(tempfile.mkdtemp(prefix="arxiv_lance_"))
    logger.info(f"Using temp directory: {temp_path}")

    # === Step 1: Detect backend ===
    backend, default_batch_size = check_backend()
    if batch_size is None:
        batch_size = default_batch_size
    logger.info(f"Backend: {backend}, Batch size: {batch_size:,}")

    # === Step 2: Check existing dataset for incremental mode ===
    last_update_date = None
    if not full_refresh:
        last_update_date = get_last_update_date(output_dataset, HF_TOKEN)
        if last_update_date:
            logger.info(f"Incremental mode: processing papers after {last_update_date}")
        else:
            logger.info("No existing dataset found - processing all papers")
    else:
        logger.info("Full refresh mode - processing all papers")

    # === Step 3: Prepare data ===
    df = prepare_incremental_data(
        input_dataset,
        temp_path,
        last_update_date,
        limit,
        full_refresh,
    )

    if df is None or df.height == 0:
        logger.info("No new papers to classify. Dataset is up to date!")
        # Cleanup
        if not temp_dir and temp_path.exists():
            shutil.rmtree(temp_path)
        return

    logger.info(f"Prepared {df.height:,} papers for classification")

    # === Step 4: Classify papers ===
    if backend == "vllm":
        results = classify_with_vllm(df, model_id, batch_size)
    else:
        results = classify_with_transformers(df, model_id, batch_size, backend)

    # === Step 5: Add classification results to DataFrame ===
    logger.info("Adding classification results...")
    df = df.with_columns(
        [
            pl.Series("classification_label", [r["classification_label"] for r in results]),
            pl.Series("is_new_dataset", [r["is_new_dataset"] for r in results]),
            pl.Series("confidence_score", [r["confidence_score"] for r in results]),
            pl.lit(datetime.now().isoformat()).alias("classification_date"),
            pl.lit(model_id).alias("model_version"),
            # Placeholder for embeddings (filled by embed_arxiv_lance.py)
            pl.lit(None).cast(pl.List(pl.Float32)).alias("embedding"),
            pl.lit(None).cast(pl.Utf8).alias("embedding_model"),
        ]
    )

    # Remove temporary columns
    if "text_for_classification" in df.columns:
        df = df.drop("text_for_classification")

    # === Step 6: Save to Lance ===
    lance_output_path = temp_path / "output.lance"
    mode = "overwrite" if full_refresh or last_update_date is None else "append"
    save_to_lance(df, lance_output_path, mode)

    # === Step 7: Upload to Hub ===
    if HF_TOKEN:
        upload_to_hub(lance_output_path, output_dataset, HF_TOKEN)
    else:
        logger.warning(f"No HF_TOKEN - results saved locally at {lance_output_path}")

    # === Step 8: Print statistics ===
    num_new_datasets = df.filter(pl.col("is_new_dataset")).height
    avg_confidence = df["confidence_score"].mean()

    logger.info("=" * 60)
    logger.info("Classification Complete!")
    logger.info(f"Total papers classified: {df.height:,}")
    logger.info(
        f"Papers with new datasets: {num_new_datasets:,} ({num_new_datasets/df.height*100:.1f}%)"
    )
    logger.info(f"Average confidence score: {avg_confidence:.3f}")
    logger.info(f"Output dataset: {output_dataset}")
    logger.info("=" * 60)

    # Cleanup
    if not temp_dir and temp_path.exists():
        logger.info(f"Cleaning up temp directory: {temp_path}")
        shutil.rmtree(temp_path)


# =============================================================================
# CLI Entry Point
# =============================================================================

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Classify arXiv CS papers for new datasets (Lance output)",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # Incremental update (only new papers since last run)
  uv run classify_arxiv_to_lance.py

  # Full refresh (reprocess all papers)
  uv run classify_arxiv_to_lance.py --full-refresh

  # Test with small sample
  uv run classify_arxiv_to_lance.py --limit 100

  # Run on HF Jobs with A100
  hf jobs uv run \\
    --flavor a100-large \\
    --image vllm/vllm-openai \\
    --secrets HF_TOKEN \\
    classify_arxiv_to_lance.py --full-refresh
        """,
    )

    parser.add_argument(
        "--input-dataset",
        type=str,
        default=DEFAULT_INPUT_DATASET,
        help=f"Input dataset on HuggingFace Hub (default: {DEFAULT_INPUT_DATASET})",
    )
    parser.add_argument(
        "--output-dataset",
        type=str,
        default=DEFAULT_OUTPUT_DATASET,
        help=f"Output Lance dataset on HuggingFace Hub (default: {DEFAULT_OUTPUT_DATASET})",
    )
    parser.add_argument(
        "--model",
        type=str,
        default=DEFAULT_MODEL,
        help=f"Model ID for classification (default: {DEFAULT_MODEL})",
    )
    parser.add_argument(
        "--batch-size",
        type=int,
        help="Batch size for inference (auto-detected based on backend if not specified)",
    )
    parser.add_argument(
        "--limit",
        type=int,
        help="Limit number of papers for testing",
    )
    parser.add_argument(
        "--full-refresh",
        action="store_true",
        help="Process all papers regardless of update date (monthly refresh)",
    )
    parser.add_argument(
        "--temp-dir",
        type=str,
        help="Directory for temporary files (auto-created if not specified)",
    )
    parser.add_argument(
        "--hf-token",
        type=str,
        help="HuggingFace token (can also use HF_TOKEN env var)",
    )

    args = parser.parse_args()

    main(
        input_dataset=args.input_dataset,
        output_dataset=args.output_dataset,
        model_id=args.model,
        batch_size=args.batch_size,
        limit=args.limit,
        full_refresh=args.full_refresh,
        temp_dir=args.temp_dir,
        hf_token=args.hf_token,
    )