File size: 12,241 Bytes
65552fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b64c51c
65552fd
 
ee9fff1
b64c51c
 
65552fd
 
 
 
 
 
 
 
b64c51c
 
65552fd
 
b64c51c
 
 
65552fd
 
 
b64c51c
 
 
 
 
 
 
 
 
00e7557
 
 
 
 
 
 
65552fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b64c51c
 
 
 
 
 
 
65552fd
 
 
 
 
 
 
 
b64c51c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65552fd
 
 
 
 
 
b64c51c
65552fd
 
 
 
 
00e7557
 
 
 
 
 
 
 
b64c51c
00e7557
 
 
 
 
b64c51c
00e7557
 
 
 
 
b64c51c
 
00e7557
b64c51c
65552fd
b64c51c
 
 
65552fd
b64c51c
00e7557
b64c51c
 
 
 
 
 
 
 
 
 
00e7557
 
 
 
 
 
 
 
 
 
 
 
 
b64c51c
 
 
 
 
 
 
 
 
 
00e7557
b64c51c
 
 
 
 
 
65552fd
b64c51c
 
 
 
 
 
 
 
 
 
 
65552fd
 
 
 
 
 
 
b64c51c
65552fd
 
 
 
 
 
 
 
b64c51c
65552fd
 
b64c51c
 
 
 
 
 
 
 
 
 
 
65552fd
 
 
b64c51c
 
 
 
 
65552fd
 
 
 
 
 
b64c51c
 
 
 
 
 
65552fd
 
00e7557
b64c51c
65552fd
 
00e7557
b64c51c
 
 
 
 
 
 
 
 
 
 
 
 
65552fd
00e7557
 
 
 
 
 
 
 
b64c51c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65552fd
 
b64c51c
 
 
 
 
 
 
 
 
 
 
 
00e7557
b64c51c
 
 
 
65552fd
 
b64c51c
 
 
 
 
 
 
 
 
65552fd
00e7557
b64c51c
 
 
 
65552fd
 
00e7557
 
 
b64c51c
65552fd
b64c51c
 
 
00e7557
 
b64c51c
00e7557
b64c51c
65552fd
 
 
 
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
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.10"
# dependencies = [
#     "datasets",
#     "requests",
#     "huggingface-hub",
# ]
# ///
"""
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

# Regex patterns for arXiv ID validation
_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()

    # Extract from URL if present
    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:]

    # Remove version suffix
    s = re.sub(r"v\d+$", "", s)

    # Validate new-style arXiv ID format
    if not _ARXIV_NEW_RE.fullmatch(s):
        return None

    # Validate month (positions 2-3)
    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()