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