| |
| |
| |
| |
| |
| |
| |
| |
| |
| """ |
| Daily sync for huggingface/trending-papers-x dataset. |
| Indexes new papers and updates GitHub/project URLs via HF Papers API. |
| |
| Run locally: uv run daily_papers_sync.py |
| Run as HF Job: hf jobs uv run daily_papers_sync.py --secrets HF_TOKEN |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import os |
| import re |
| import time |
| from dataclasses import dataclass |
| from datetime import datetime, timezone |
| from typing import Any, Optional |
| from urllib.parse import urlparse |
|
|
| import requests |
| from datasets import load_dataset |
|
|
| REPO_ID = "huggingface/trending-papers-x" |
| API_BASE = "https://huggingface.co/api" |
| DEFAULT_LIMIT = 150 |
| DEFAULT_SLEEP_AFTER_INDEX_SECONDS = 30 |
|
|
| |
| _ARXIV_URL_RE = re.compile( |
| r"https?://(?:www\.)?arxiv\.org/(?:abs|pdf)/(?P<id>[^?#]+)", re.I |
| ) |
| _ARXIV_NEW_RE = re.compile(r"^\d{4}\.\d{4,5}$") |
|
|
|
|
| @dataclass |
| class Candidate: |
| arxiv_id: str |
| github_repo: Optional[str] |
| project_page: Optional[str] |
| added_at: Optional[datetime] |
| source: Optional[str] |
|
|
|
|
| @dataclass |
| class CandidateStats: |
| link_rows_checked: int = 0 |
| already_indexed: int = 0 |
| status_errors: int = 0 |
|
|
|
|
| def normalize_arxiv_id(value: Any) -> Optional[str]: |
| """Extract and validate arXiv ID from various formats.""" |
| if not value: |
| return None |
| s = str(value).strip() |
|
|
| |
| if m := _ARXIV_URL_RE.search(s): |
| s = m.group("id") |
|
|
| s = s.strip().rstrip("/") |
| if s.lower().endswith(".pdf"): |
| s = s[:-4] |
| if s.lower().startswith("arxiv:"): |
| s = s[6:] |
|
|
| |
| s = re.sub(r"v\d+$", "", s) |
|
|
| |
| if not _ARXIV_NEW_RE.fullmatch(s): |
| return None |
|
|
| |
| month = int(s[2:4]) |
| return s if 1 <= month <= 12 else None |
|
|
|
|
| def normalize_github_repo(value: Any) -> Optional[str]: |
| """Extract and normalize GitHub repo URL.""" |
| if not value: |
| return None |
| s = str(value).strip() |
|
|
| if s.startswith("git@github.com:"): |
| s = f"https://github.com/{s[15:]}" |
| elif s.startswith("github.com/"): |
| s = f"https://{s}" |
|
|
| p = urlparse(s) |
| if p.scheme not in ("http", "https"): |
| return None |
|
|
| host = (p.netloc or "").lower().removeprefix("www.") |
| if host != "github.com": |
| return None |
|
|
| parts = [x for x in p.path.split("/") if x] |
| if len(parts) < 2: |
| return None |
|
|
| owner, repo = parts[0], parts[1].removesuffix(".git") |
| return f"https://github.com/{owner}/{repo}" |
|
|
|
|
| def normalize_url(value: Any) -> Optional[str]: |
| """Validate and normalize a URL.""" |
| if not value: |
| return None |
| s = str(value).strip() |
| p = urlparse(s) |
| return s if p.scheme in ("http", "https") and p.netloc else None |
|
|
|
|
| def parse_date(value: Any) -> Optional[datetime]: |
| """Parse date string into datetime.""" |
| if isinstance(value, datetime): |
| return value.replace(tzinfo=timezone.utc) if value.tzinfo is None else value |
| if not value: |
| return None |
|
|
| for fmt in [ |
| "%Y-%m-%dT%H:%M:%S.%fZ", |
| "%Y-%m-%dT%H:%M:%SZ", |
| "%Y-%m-%dT%H:%M:%S.%f", |
| "%Y-%m-%dT%H:%M:%S", |
| "%Y-%m-%d", |
| ]: |
| try: |
| dt = datetime.strptime(str(value).strip(), fmt) |
| return dt.replace(tzinfo=timezone.utc) |
| except ValueError: |
| continue |
| return None |
|
|
|
|
| def parse_args() -> argparse.Namespace: |
| """Parse CLI args; scheduled jobs use mutating defaults.""" |
| parser = argparse.ArgumentParser( |
| description="Index missing trending-papers-x rows with extracted links." |
| ) |
| parser.add_argument( |
| "--dry-run", |
| action="store_true", |
| help="Preview candidates without calling write endpoints.", |
| ) |
| parser.add_argument( |
| "--limit", |
| type=int, |
| default=DEFAULT_LIMIT, |
| help=f"Maximum missing link-bearing rows to process. Defaults to {DEFAULT_LIMIT}.", |
| ) |
| parser.add_argument( |
| "--sleep-after-index", |
| type=float, |
| default=DEFAULT_SLEEP_AFTER_INDEX_SECONDS, |
| help="Seconds to wait after successful indexing before updating links.", |
| ) |
| return parser.parse_args() |
|
|
|
|
| def get_token() -> str: |
| """Get HF token from environment or huggingface-cli.""" |
| if token := os.environ.get("HF_TOKEN", "").strip(): |
| return token |
| try: |
| from huggingface_hub import HfFolder |
|
|
| return (HfFolder.get_token() or "").strip() |
| except Exception: |
| return "" |
|
|
|
|
| def get_paper_status( |
| session: requests.Session, arxiv_id: str |
| ) -> tuple[str, Optional[int], Optional[str]]: |
| """Check whether a paper is already indexed.""" |
| try: |
| r = session.get(f"{API_BASE}/papers/{arxiv_id}", timeout=30) |
| except requests.RequestException as e: |
| return "error", None, str(e) |
|
|
| if r.status_code == 200: |
| return "indexed", r.status_code, None |
| if r.status_code == 404: |
| return "missing", r.status_code, None |
| return "error", r.status_code, r.text[:500] |
|
|
|
|
| def iter_candidates( |
| session: requests.Session, limit: int |
| ) -> tuple[list[Candidate], CandidateStats]: |
| """Select live-missing trending papers that have link metadata.""" |
| dataset = load_dataset(REPO_ID, split="train", streaming=True) |
| candidates: list[Candidate] = [] |
| stats = CandidateStats() |
| seen: set[str] = set() |
|
|
| for row in dataset: |
| if len(candidates) >= limit: |
| break |
|
|
| arxiv_id = normalize_arxiv_id(row.get("arxiv_id") or row.get("paper_id")) |
| if not arxiv_id or arxiv_id in seen: |
| continue |
|
|
| github_repo = normalize_github_repo(row.get("github") or row.get("github_url")) |
| project_page = normalize_url( |
| row.get("project_page_url") or row.get("project_page") |
| ) |
| if not github_repo and not project_page: |
| continue |
|
|
| seen.add(arxiv_id) |
| stats.link_rows_checked += 1 |
| status, http_status, error = get_paper_status(session, arxiv_id) |
| if status == "indexed": |
| stats.already_indexed += 1 |
| continue |
| if status == "error": |
| stats.status_errors += 1 |
| print( |
| f"ERROR: {arxiv_id} - failed to check paper status" |
| f" (status={http_status}, error={error})" |
| ) |
| continue |
|
|
| candidates.append( |
| Candidate( |
| arxiv_id=arxiv_id, |
| github_repo=github_repo, |
| project_page=project_page, |
| added_at=parse_date(row.get("added_at")), |
| source=row.get("source"), |
| ) |
| ) |
|
|
| return candidates, stats |
|
|
|
|
| def index_paper( |
| session: requests.Session, arxiv_id: str |
| ) -> tuple[str, Optional[int], Optional[str]]: |
| """Index a paper by arXiv ID.""" |
| try: |
| r = session.post( |
| f"{API_BASE}/papers/index", json={"arxivId": arxiv_id}, timeout=30 |
| ) |
| except requests.RequestException as e: |
| return "error", None, str(e) |
|
|
| if r.status_code == 200: |
| return "indexed", r.status_code, None |
| if r.status_code == 409: |
| return "already-indexed", r.status_code, None |
| return "error", r.status_code, r.text[:500] |
|
|
|
|
| def update_paper_links( |
| session: requests.Session, |
| arxiv_id: str, |
| github_repo: Optional[str] = None, |
| project_page: Optional[str] = None, |
| ) -> tuple[str, Optional[int], Optional[str]]: |
| """Update GitHub repo and/or project page for a paper.""" |
| payload = {} |
| if github_repo: |
| payload["githubRepo"] = github_repo |
| if project_page: |
| payload["projectPage"] = project_page |
|
|
| if not payload: |
| return "skipped", None, "no links to update" |
|
|
| try: |
| r = session.post( |
| f"{API_BASE}/papers/{arxiv_id}/links", json=payload, timeout=30 |
| ) |
| except requests.RequestException as e: |
| return "error", None, str(e) |
|
|
| if r.status_code == 200: |
| return "updated", r.status_code, None |
| if r.status_code == 409: |
| return "already-updated", r.status_code, None |
| return "error", r.status_code, r.text[:500] |
|
|
|
|
| def main() -> None: |
| args = parse_args() |
| if args.limit < 1: |
| print("ERROR: --limit must be greater than 0") |
| exit(1) |
|
|
| token = get_token() |
| if not token: |
| print("ERROR: HF token not found. Set HF_TOKEN or run `huggingface-cli login`.") |
| exit(1) |
|
|
| session = requests.Session() |
| session.headers.update( |
| { |
| "Content-Type": "application/json", |
| "Authorization": f"Bearer {token}", |
| } |
| ) |
|
|
| print(f"Dataset: {REPO_ID}") |
| print(f"Limit: {args.limit} live-missing link-bearing papers") |
| print(f"Mode: {'dry-run' if args.dry_run else 'apply'}") |
| print("-" * 50) |
|
|
| candidates, candidate_stats = iter_candidates(session, args.limit) |
| if candidates: |
| first_added_at = ( |
| candidates[0].added_at.isoformat() if candidates[0].added_at else "unknown" |
| ) |
| last_added_at = ( |
| candidates[-1].added_at.isoformat() |
| if candidates[-1].added_at |
| else "unknown" |
| ) |
| print(f"Candidates: {len(candidates)} ({first_added_at} -> {last_added_at})") |
| else: |
| print("Candidates: 0") |
| print("-" * 50) |
|
|
| stats = { |
| "indexed": 0, |
| "already_indexed": 0, |
| "links": 0, |
| "dry_run": 0, |
| "index_errors": 0, |
| "link_errors": 0, |
| } |
|
|
| for candidate in candidates: |
| pieces = [ |
| candidate.arxiv_id, |
| f"added_at={candidate.added_at.isoformat() if candidate.added_at else 'unknown'}", |
| f"source={candidate.source or 'unknown'}", |
| ] |
| if candidate.github_repo: |
| pieces.append(f"github={candidate.github_repo}") |
| if candidate.project_page: |
| pieces.append(f"project={candidate.project_page}") |
|
|
| if args.dry_run: |
| stats["dry_run"] += 1 |
| print("DRY RUN: " + " | ".join(pieces)) |
| continue |
|
|
| index_status, index_http_status, index_error = index_paper( |
| session, candidate.arxiv_id |
| ) |
| if index_status == "indexed": |
| stats["indexed"] += 1 |
| print(f"INDEXED: {' | '.join(pieces)}") |
| if args.sleep_after_index > 0: |
| time.sleep(args.sleep_after_index) |
| elif index_status == "already-indexed": |
| stats["already_indexed"] += 1 |
| print(f"ALREADY INDEXED: {' | '.join(pieces)}") |
| else: |
| stats["index_errors"] += 1 |
| print( |
| f"ERROR: {candidate.arxiv_id} - failed to index" |
| f" (status={index_http_status}, error={index_error})" |
| ) |
| continue |
|
|
| links_status, links_http_status, links_error = update_paper_links( |
| session, |
| candidate.arxiv_id, |
| candidate.github_repo, |
| candidate.project_page, |
| ) |
| if links_status in {"updated", "already-updated"}: |
| stats["links"] += 1 |
| print(f"LINKS {links_status.upper()}: {candidate.arxiv_id}") |
| else: |
| stats["link_errors"] += 1 |
| print( |
| f"ERROR: {candidate.arxiv_id} - failed to update links" |
| f" (status={links_http_status}, error={links_error})" |
| ) |
|
|
| print("-" * 50) |
| print(f"Link-bearing rows checked: {candidate_stats.link_rows_checked}") |
| print(f"Already indexed while selecting: {candidate_stats.already_indexed}") |
| print(f"Status check errors: {candidate_stats.status_errors}") |
| print(f"Candidates: {len(candidates)}") |
| print(f"Indexed: {stats['indexed']}") |
| print(f"Already indexed: {stats['already_indexed']}") |
| print(f"Links updated: {stats['links']}") |
| print(f"Dry run: {stats['dry_run']}") |
| print(f"Index errors: {stats['index_errors']}") |
| print(f"Link errors: {stats['link_errors']}") |
|
|
| if stats["index_errors"] or candidate_stats.status_errors: |
| exit(1) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|