search_arxiv.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. #!/usr/bin/env python3
  2. """Search arXiv and display results in a clean format.
  3. Usage:
  4. python search_arxiv.py "GRPO reinforcement learning"
  5. python search_arxiv.py "GRPO reinforcement learning" --max 10
  6. python search_arxiv.py "GRPO reinforcement learning" --sort date
  7. python search_arxiv.py --author "Yann LeCun" --max 5
  8. python search_arxiv.py --category cs.AI --sort date --max 10
  9. python search_arxiv.py --id 2402.03300
  10. python search_arxiv.py --id 2402.03300,2401.12345
  11. """
  12. import sys
  13. import urllib.request
  14. import urllib.parse
  15. import xml.etree.ElementTree as ET
  16. NS = {'a': 'http://www.w3.org/2005/Atom'}
  17. def search(query=None, author=None, category=None, ids=None, max_results=5, sort="relevance"):
  18. params = {}
  19. if ids:
  20. params['id_list'] = ids
  21. else:
  22. parts = []
  23. if query:
  24. parts.append(f'all:{urllib.parse.quote(query)}')
  25. if author:
  26. parts.append(f'au:{urllib.parse.quote(author)}')
  27. if category:
  28. parts.append(f'cat:{category}')
  29. if not parts:
  30. print("Error: provide a query, --author, --category, or --id")
  31. sys.exit(1)
  32. params['search_query'] = '+AND+'.join(parts)
  33. params['max_results'] = str(max_results)
  34. sort_map = {"relevance": "relevance", "date": "submittedDate", "updated": "lastUpdatedDate"}
  35. params['sortBy'] = sort_map.get(sort, sort)
  36. params['sortOrder'] = 'descending'
  37. url = "https://export.arxiv.org/api/query?" + "&".join(f"{k}={v}" for k, v in params.items())
  38. req = urllib.request.Request(url, headers={'User-Agent': 'HermesAgent/1.0'})
  39. with urllib.request.urlopen(req, timeout=15) as resp:
  40. data = resp.read()
  41. root = ET.fromstring(data)
  42. entries = root.findall('a:entry', NS)
  43. if not entries:
  44. print("No results found.")
  45. return
  46. total = root.find('{http://a9.com/-/spec/opensearch/1.1/}totalResults')
  47. if total is not None:
  48. print(f"Found {total.text} results (showing {len(entries)})\n")
  49. for i, entry in enumerate(entries):
  50. title = entry.find('a:title', NS).text.strip().replace('\n', ' ')
  51. raw_id = entry.find('a:id', NS).text.strip()
  52. full_id = raw_id.split('/abs/')[-1] if '/abs/' in raw_id else raw_id
  53. arxiv_id = full_id.split('v')[0] # base ID for links
  54. published = entry.find('a:published', NS).text[:10]
  55. updated = entry.find('a:updated', NS).text[:10]
  56. authors = ', '.join(a.find('a:name', NS).text for a in entry.findall('a:author', NS))
  57. summary = entry.find('a:summary', NS).text.strip().replace('\n', ' ')
  58. cats = ', '.join(c.get('term') for c in entry.findall('a:category', NS))
  59. version = full_id[len(arxiv_id):] if full_id != arxiv_id else ""
  60. print(f"{i+1}. {title}")
  61. print(f" ID: {arxiv_id}{version} | Published: {published} | Updated: {updated}")
  62. print(f" Authors: {authors}")
  63. print(f" Categories: {cats}")
  64. print(f" Abstract: {summary[:300]}{'...' if len(summary) > 300 else ''}")
  65. print(f" Links: https://arxiv.org/abs/{arxiv_id} | https://arxiv.org/pdf/{arxiv_id}")
  66. print()
  67. if __name__ == "__main__":
  68. args = sys.argv[1:]
  69. if not args or args[0] in {"-h", "--help"}:
  70. print(__doc__)
  71. sys.exit(0)
  72. query = None
  73. author = None
  74. category = None
  75. ids = None
  76. max_results = 5
  77. sort = "relevance"
  78. i = 0
  79. positional = []
  80. while i < len(args):
  81. if args[i] == "--max" and i + 1 < len(args):
  82. max_results = int(args[i + 1]); i += 2
  83. elif args[i] == "--sort" and i + 1 < len(args):
  84. sort = args[i + 1]; i += 2
  85. elif args[i] == "--author" and i + 1 < len(args):
  86. author = args[i + 1]; i += 2
  87. elif args[i] == "--category" and i + 1 < len(args):
  88. category = args[i + 1]; i += 2
  89. elif args[i] == "--id" and i + 1 < len(args):
  90. ids = args[i + 1]; i += 2
  91. else:
  92. positional.append(args[i]); i += 1
  93. if positional:
  94. query = " ".join(positional)
  95. search(query=query, author=author, category=category, ids=ids, max_results=max_results, sort=sort)