semantic_scholar.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Semantic Scholar (Science)"""
  3. from json import dumps
  4. from datetime import datetime
  5. from lxml import html
  6. from flask_babel import gettext
  7. from searx.network import get
  8. from searx.utils import eval_xpath_getindex, html_to_text
  9. about = {
  10. "website": 'https://www.semanticscholar.org/',
  11. "wikidata_id": 'Q22908627',
  12. "official_api_documentation": 'https://api.semanticscholar.org/',
  13. "use_official_api": True,
  14. "require_api_key": False,
  15. "results": 'JSON',
  16. }
  17. categories = ['science', 'scientific publications']
  18. paging = True
  19. search_url = 'https://www.semanticscholar.org/api/1/search'
  20. base_url = 'https://www.semanticscholar.org'
  21. def _get_ui_version():
  22. resp = get(base_url)
  23. if not resp.ok:
  24. raise RuntimeError("Can't determine Semantic Scholar UI version")
  25. doc = html.fromstring(resp.text)
  26. ui_version = eval_xpath_getindex(doc, "//meta[@name='s2-ui-version']/@content", 0)
  27. if not ui_version:
  28. raise RuntimeError("Can't determine Semantic Scholar UI version")
  29. return ui_version
  30. def request(query, params):
  31. params['url'] = search_url
  32. params['method'] = 'POST'
  33. params['headers'].update(
  34. {
  35. 'Content-Type': 'application/json',
  36. 'X-S2-UI-Version': _get_ui_version(),
  37. 'X-S2-Client': "webapp-browser",
  38. }
  39. )
  40. params['data'] = dumps(
  41. {
  42. "queryString": query,
  43. "page": params['pageno'],
  44. "pageSize": 10,
  45. "sort": "relevance",
  46. "getQuerySuggestions": False,
  47. "authors": [],
  48. "coAuthors": [],
  49. "venues": [],
  50. "performTitleMatch": True,
  51. }
  52. )
  53. return params
  54. def response(resp):
  55. res = resp.json()
  56. results = []
  57. for result in res['results']:
  58. url = result.get('primaryPaperLink', {}).get('url')
  59. if not url and result.get('links'):
  60. url = result.get('links')[0]
  61. if not url:
  62. alternatePaperLinks = result.get('alternatePaperLinks')
  63. if alternatePaperLinks:
  64. url = alternatePaperLinks[0].get('url')
  65. if not url:
  66. url = base_url + '/paper/%s' % result['id']
  67. # publishedDate
  68. if 'pubDate' in result:
  69. publishedDate = datetime.strptime(result['pubDate'], "%Y-%m-%d")
  70. else:
  71. publishedDate = None
  72. # authors
  73. authors = [author[0]['name'] for author in result.get('authors', [])]
  74. # pick for the first alternate link, but not from the crawler
  75. pdf_url = None
  76. for doc in result.get('alternatePaperLinks', []):
  77. if doc['linkType'] not in ('crawler', 'doi'):
  78. pdf_url = doc['url']
  79. break
  80. # comments
  81. comments = None
  82. if 'citationStats' in result:
  83. comments = gettext(
  84. '{numCitations} citations from the year {firstCitationVelocityYear} to {lastCitationVelocityYear}'
  85. ).format(
  86. numCitations=result['citationStats']['numCitations'],
  87. firstCitationVelocityYear=result['citationStats']['firstCitationVelocityYear'],
  88. lastCitationVelocityYear=result['citationStats']['lastCitationVelocityYear'],
  89. )
  90. results.append(
  91. {
  92. 'template': 'paper.html',
  93. 'url': url,
  94. 'title': result['title']['text'],
  95. 'content': html_to_text(result['paperAbstract']['text']),
  96. 'journal': result.get('venue', {}).get('text') or result.get('journal', {}).get('name'),
  97. 'doi': result.get('doiInfo', {}).get('doi'),
  98. 'tags': result.get('fieldsOfStudy'),
  99. 'authors': authors,
  100. 'pdf_url': pdf_url,
  101. 'publishedDate': publishedDate,
  102. 'comments': comments,
  103. }
  104. )
  105. return results