cfahlgren1 HF Staff commited on
Commit
00e7557
·
verified ·
1 Parent(s): b64c51c

use live paper api for cron selection

Browse files
Files changed (1) hide show
  1. daily_papers_sync.py +59 -33
daily_papers_sync.py CHANGED
@@ -5,8 +5,6 @@
5
  # "datasets",
6
  # "requests",
7
  # "huggingface-hub",
8
- # "pandas",
9
- # "pyarrow",
10
  # ]
11
  # ///
12
  """
@@ -28,14 +26,10 @@ from datetime import datetime, timezone
28
  from typing import Any, Optional
29
  from urllib.parse import urlparse
30
 
31
- import pandas as pd
32
  import requests
33
  from datasets import load_dataset
34
- from huggingface_hub import hf_hub_download
35
 
36
  REPO_ID = "huggingface/trending-papers-x"
37
- INDEXED_PAPERS_REPO_ID = "cfahlgren1/hub-stats"
38
- INDEXED_PAPERS_FILENAME = "arxiv_papers.parquet"
39
  API_BASE = "https://huggingface.co/api"
40
  DEFAULT_LIMIT = 150
41
  DEFAULT_SLEEP_AFTER_INDEX_SECONDS = 30
@@ -56,6 +50,13 @@ class Candidate:
56
  source: Optional[str]
57
 
58
 
 
 
 
 
 
 
 
59
  def normalize_arxiv_id(value: Any) -> Optional[str]:
60
  """Extract and validate arXiv ID from various formats."""
61
  if not value:
@@ -179,26 +180,29 @@ def get_token() -> str:
179
  return ""
180
 
181
 
182
- def load_indexed_paper_ids(token: str) -> set[str]:
183
- """Load indexed paper IDs from the latest hub-stats parquet snapshot."""
184
- parquet_path = hf_hub_download(
185
- repo_id=INDEXED_PAPERS_REPO_ID,
186
- filename=INDEXED_PAPERS_FILENAME,
187
- repo_type="dataset",
188
- token=token,
189
- )
190
- indexed = pd.read_parquet(parquet_path, columns=["id"])
191
- return {
192
- arxiv_id
193
- for value in indexed["id"].dropna()
194
- if (arxiv_id := normalize_arxiv_id(value))
195
- }
196
 
 
 
 
 
 
197
 
198
- def iter_candidates(indexed_paper_ids: set[str], limit: int) -> list[Candidate]:
199
- """Select missing trending papers that have link metadata."""
 
 
 
200
  dataset = load_dataset(REPO_ID, split="train", streaming=True)
201
  candidates: list[Candidate] = []
 
202
  seen: set[str] = set()
203
 
204
  for row in dataset:
@@ -206,7 +210,7 @@ def iter_candidates(indexed_paper_ids: set[str], limit: int) -> list[Candidate]:
206
  break
207
 
208
  arxiv_id = normalize_arxiv_id(row.get("arxiv_id") or row.get("paper_id"))
209
- if not arxiv_id or arxiv_id in indexed_paper_ids or arxiv_id in seen:
210
  continue
211
 
212
  github_repo = normalize_github_repo(row.get("github") or row.get("github_url"))
@@ -217,6 +221,19 @@ def iter_candidates(indexed_paper_ids: set[str], limit: int) -> list[Candidate]:
217
  continue
218
 
219
  seen.add(arxiv_id)
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  candidates.append(
221
  Candidate(
222
  arxiv_id=arxiv_id,
@@ -227,7 +244,7 @@ def iter_candidates(indexed_paper_ids: set[str], limit: int) -> list[Candidate]:
227
  )
228
  )
229
 
230
- return candidates
231
 
232
 
233
  def index_paper(
@@ -298,13 +315,11 @@ def main() -> None:
298
  )
299
 
300
  print(f"Dataset: {REPO_ID}")
301
- print(f"Indexed snapshot: {INDEXED_PAPERS_REPO_ID}/{INDEXED_PAPERS_FILENAME}")
302
- print(f"Limit: {args.limit} missing link-bearing papers")
303
  print(f"Mode: {'dry-run' if args.dry_run else 'apply'}")
304
  print("-" * 50)
305
 
306
- indexed_paper_ids = load_indexed_paper_ids(token)
307
- candidates = iter_candidates(indexed_paper_ids, args.limit)
308
  if candidates:
309
  first_added_at = (
310
  candidates[0].added_at.isoformat() if candidates[0].added_at else "unknown"
@@ -319,7 +334,14 @@ def main() -> None:
319
  print("Candidates: 0")
320
  print("-" * 50)
321
 
322
- stats = {"indexed": 0, "already_indexed": 0, "links": 0, "dry_run": 0, "errors": 0}
 
 
 
 
 
 
 
323
 
324
  for candidate in candidates:
325
  pieces = [
@@ -349,7 +371,7 @@ def main() -> None:
349
  stats["already_indexed"] += 1
350
  print(f"ALREADY INDEXED: {' | '.join(pieces)}")
351
  else:
352
- stats["errors"] += 1
353
  print(
354
  f"ERROR: {candidate.arxiv_id} - failed to index"
355
  f" (status={index_http_status}, error={index_error})"
@@ -366,21 +388,25 @@ def main() -> None:
366
  stats["links"] += 1
367
  print(f"LINKS {links_status.upper()}: {candidate.arxiv_id}")
368
  else:
369
- stats["errors"] += 1
370
  print(
371
  f"ERROR: {candidate.arxiv_id} - failed to update links"
372
  f" (status={links_http_status}, error={links_error})"
373
  )
374
 
375
  print("-" * 50)
 
 
 
376
  print(f"Candidates: {len(candidates)}")
377
  print(f"Indexed: {stats['indexed']}")
378
  print(f"Already indexed: {stats['already_indexed']}")
379
  print(f"Links updated: {stats['links']}")
380
  print(f"Dry run: {stats['dry_run']}")
381
- print(f"Errors: {stats['errors']}")
 
382
 
383
- if stats["errors"]:
384
  exit(1)
385
 
386
 
 
5
  # "datasets",
6
  # "requests",
7
  # "huggingface-hub",
 
 
8
  # ]
9
  # ///
10
  """
 
26
  from typing import Any, Optional
27
  from urllib.parse import urlparse
28
 
 
29
  import requests
30
  from datasets import load_dataset
 
31
 
32
  REPO_ID = "huggingface/trending-papers-x"
 
 
33
  API_BASE = "https://huggingface.co/api"
34
  DEFAULT_LIMIT = 150
35
  DEFAULT_SLEEP_AFTER_INDEX_SECONDS = 30
 
50
  source: Optional[str]
51
 
52
 
53
+ @dataclass
54
+ class CandidateStats:
55
+ link_rows_checked: int = 0
56
+ already_indexed: int = 0
57
+ status_errors: int = 0
58
+
59
+
60
  def normalize_arxiv_id(value: Any) -> Optional[str]:
61
  """Extract and validate arXiv ID from various formats."""
62
  if not value:
 
180
  return ""
181
 
182
 
183
+ def get_paper_status(
184
+ session: requests.Session, arxiv_id: str
185
+ ) -> tuple[str, Optional[int], Optional[str]]:
186
+ """Check whether a paper is already indexed."""
187
+ try:
188
+ r = session.get(f"{API_BASE}/papers/{arxiv_id}", timeout=30)
189
+ except requests.RequestException as e:
190
+ return "error", None, str(e)
 
 
 
 
 
 
191
 
192
+ if r.status_code == 200:
193
+ return "indexed", r.status_code, None
194
+ if r.status_code == 404:
195
+ return "missing", r.status_code, None
196
+ return "error", r.status_code, r.text[:500]
197
 
198
+
199
+ def iter_candidates(
200
+ session: requests.Session, limit: int
201
+ ) -> tuple[list[Candidate], CandidateStats]:
202
+ """Select live-missing trending papers that have link metadata."""
203
  dataset = load_dataset(REPO_ID, split="train", streaming=True)
204
  candidates: list[Candidate] = []
205
+ stats = CandidateStats()
206
  seen: set[str] = set()
207
 
208
  for row in dataset:
 
210
  break
211
 
212
  arxiv_id = normalize_arxiv_id(row.get("arxiv_id") or row.get("paper_id"))
213
+ if not arxiv_id or arxiv_id in seen:
214
  continue
215
 
216
  github_repo = normalize_github_repo(row.get("github") or row.get("github_url"))
 
221
  continue
222
 
223
  seen.add(arxiv_id)
224
+ stats.link_rows_checked += 1
225
+ status, http_status, error = get_paper_status(session, arxiv_id)
226
+ if status == "indexed":
227
+ stats.already_indexed += 1
228
+ continue
229
+ if status == "error":
230
+ stats.status_errors += 1
231
+ print(
232
+ f"ERROR: {arxiv_id} - failed to check paper status"
233
+ f" (status={http_status}, error={error})"
234
+ )
235
+ continue
236
+
237
  candidates.append(
238
  Candidate(
239
  arxiv_id=arxiv_id,
 
244
  )
245
  )
246
 
247
+ return candidates, stats
248
 
249
 
250
  def index_paper(
 
315
  )
316
 
317
  print(f"Dataset: {REPO_ID}")
318
+ print(f"Limit: {args.limit} live-missing link-bearing papers")
 
319
  print(f"Mode: {'dry-run' if args.dry_run else 'apply'}")
320
  print("-" * 50)
321
 
322
+ candidates, candidate_stats = iter_candidates(session, args.limit)
 
323
  if candidates:
324
  first_added_at = (
325
  candidates[0].added_at.isoformat() if candidates[0].added_at else "unknown"
 
334
  print("Candidates: 0")
335
  print("-" * 50)
336
 
337
+ stats = {
338
+ "indexed": 0,
339
+ "already_indexed": 0,
340
+ "links": 0,
341
+ "dry_run": 0,
342
+ "index_errors": 0,
343
+ "link_errors": 0,
344
+ }
345
 
346
  for candidate in candidates:
347
  pieces = [
 
371
  stats["already_indexed"] += 1
372
  print(f"ALREADY INDEXED: {' | '.join(pieces)}")
373
  else:
374
+ stats["index_errors"] += 1
375
  print(
376
  f"ERROR: {candidate.arxiv_id} - failed to index"
377
  f" (status={index_http_status}, error={index_error})"
 
388
  stats["links"] += 1
389
  print(f"LINKS {links_status.upper()}: {candidate.arxiv_id}")
390
  else:
391
+ stats["link_errors"] += 1
392
  print(
393
  f"ERROR: {candidate.arxiv_id} - failed to update links"
394
  f" (status={links_http_status}, error={links_error})"
395
  )
396
 
397
  print("-" * 50)
398
+ print(f"Link-bearing rows checked: {candidate_stats.link_rows_checked}")
399
+ print(f"Already indexed while selecting: {candidate_stats.already_indexed}")
400
+ print(f"Status check errors: {candidate_stats.status_errors}")
401
  print(f"Candidates: {len(candidates)}")
402
  print(f"Indexed: {stats['indexed']}")
403
  print(f"Already indexed: {stats['already_indexed']}")
404
  print(f"Links updated: {stats['links']}")
405
  print(f"Dry run: {stats['dry_run']}")
406
+ print(f"Index errors: {stats['index_errors']}")
407
+ print(f"Link errors: {stats['link_errors']}")
408
 
409
+ if stats["index_errors"] or candidate_stats.status_errors:
410
  exit(1)
411
 
412