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
|
import os
import requests
import time
import random
from util import *
class AuthorStub(object):
def __init__(self, **kwargs):
self.authorId = kwargs["authorId"]
self.name = kwargs.get("name", None)
self.url = kwargs.get("url", None)
def __str__(self):
return self.authorId
def __eq__(self, other):
return isinstance(other, AuthorStub) and self.authorId == other.authorId
def __hash__(self):
return hash(self.authorId)
def json(self):
return {
"authorId" : self.authorId,
"name" : self.name,
"url" : self.url
}
def full(self, **kwargs):
return SemanticScholarAPI.author(self.authorId, **kwargs)
class Author(object):
def __init__(self, **kwargs):
self._kwargs = kwargs
self.authorId = kwargs["authorId"]
self.name = kwargs.get("name", None)
self.aliases = kwargs.get("aliases", [])
self.citationVelocity = kwargs.get("citationVelocity", None)
self.influentialCitationCount = kwargs.get("influentialCitationCount", None)
self.url = kwargs.get("url", None)
def __str__(self):
return self.authorId
def __eq__(self, other):
return isinstance(other, Author) and self.authorId == other.authorId
def __hash__(self):
return hash(self.authorId)
def papers(self):
for elem in self._kwargs.get("papers", []):
yield SemanticScholarAPI.paper(elem["paperId"])
def json(self):
return self._kwargs
class PaperStub(object):
def __init__(self, **kwargs):
self.paperId = kwargs["paperId"]
self.isInfluential = kwargs.get("isInfluential", False)
self.title = kwargs.get("title", None)
self.venue = kwargs.get("venue", None)
self.year = kwargs.get("year", None)
def __str__(self):
return self.paperId
def __eq__(self, other):
return isinstance(other, PaperStub) and self.paperId == other.paperId
def __hash__(self):
return hash(self.paperId)
def json(self):
return {
"paperId" : self.paperId,
"isInfluential" : self.isInfluential,
"title" : self.title,
"venue" : self.venue,
"year" : self.year,
}
def full(self, **kwargs):
return SemanticScholarAPI.paper(self.paperId, **kwargs)
class Paper(object):
def __init__(self, **kwargs):
self.doi = kwargs.get("doi", None)
self.citationVelocity = kwargs.get("citationVelocity", None)
self.influentialCitationCount = kwargs.get("influentialCitationCount", None)
self.url = kwargs.get("url", None)
self.authors = [AuthorStub(**elem) for elem in kwargs.get("authors", [])]
self.citations = [PaperStub(**elem) for elem in kwargs.get("citations", [])]
self.references = [PaperStub(**elem) for elem in kwargs.get("references", [])]
self.venue = kwargs.get("venue", None)
self.references = kwargs.get("references", [])
self.title = kwargs.get("title", None)
self.year = kwargs.get("year", None)
def __str__(self):
return self.paperId
def __eq__(self, other):
return isinstance(other, Paper) and self.paperId == other.paperId
def __hash__(self):
return hash(self.paperId)
def json(self):
return self._kwargs
class SemanticScholarAPI(object):
BASE_URL = "http://api.semanticscholar.org/v1"
AUTHOR_ENDPOINT = "{}/{}".format(BASE_URL, "author")
PAPER_ENDPOINT = "{}/{}".format(BASE_URL, "paper")
SEARCH_ENDPOINT = "https://www.semanticscholar.org/api/1/search"
RAW_PAPER_ENDPOINT = "https://www.semanticscholar.org/api/1/paper"
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36',
}
@staticmethod
def fetch_file(url, fn, **kwargs):
try:
resp = requests.get(url, params=kwargs, headers=SemanticScholarAPI.headers, verify=False)
if resp.status_code != 200:
return None
except:
return None
size = 0
with open(fn, 'wb') as f:
for chunk in resp.iter_content(chunk_size=1024):
if chunk:
size += len(chunk)
f.write(chunk)
return size
@staticmethod
def fetch_doi(url, fn, **kwargs):
try:
resp = requests.get(url, params=kwargs, headers=SemanticScholarAPI.headers, verify=False)
if resp.status_code != 200:
return None, None
except:
return None, None
size = 0
with open(fn, 'wb') as f:
for chunk in resp.iter_content(chunk_size=1024):
if chunk:
size += len(chunk)
f.write(chunk)
return size, resp.url
@staticmethod
def paper(paper_id, **kwargs):
url = "{}/{}".format(SemanticScholarAPI.PAPER_ENDPOINT, paper_id)
resp = requests.get(url, params=kwargs, headers=SemanticScholarAPI.headers)
return None if resp.status_code != 200 else resp.json() # Paper(**resp.json())
@staticmethod
def author(author_id, **kwargs):
url = "{}/{}".format(SemanticScholarAPI.AUTHOR_ENDPOINT, author_id)
resp = requests.get(url, params=kwargs, headers=SemanticScholarAPI.headers)
return None if resp.status_code != 200 else resp.json() # Author(**resp.json())
@staticmethod
def pdf_url(paper_id):
return "http://pdfs.semanticscholar.org/{}/{}.pdf".format(paper_id[:4], paper_id[4:])
@staticmethod
def raw_paper(paper_id, **kwargs):
url = "{}/{}".format(SemanticScholarAPI.RAW_PAPER_ENDPOINT, paper_id)
resp = requests.get(url, params=kwargs, headers=SemanticScholarAPI.headers)
return None if resp.status_code != 200 else resp.json() # Paper(**resp.json())
@staticmethod
def search(q):
resp = requests.post(SemanticScholarAPI.SEARCH_ENDPOINT, json={
'authors': [],
'coAuthors': [],
'facets': {},
'page': 1,
'pageSize': 10,
'publicationTypes': [],
'queryString': q,
'requireViewablePdf': False,
'sort': "relevance",
'venues': [],
'yearFilter': None,
}, headers=SemanticScholarAPI.headers)
# print(resp.status_code)
return None if resp.status_code != 200 else resp.json()
def fetch_paper(s2, paper_id):
os.makedirs('./datasets/s2/papers/{}/{}'.format(paper_id[0:2], paper_id), exist_ok=True)
paper_fn = './datasets/s2/papers/{}/{}/paper.json'.format(paper_id[0:2], paper_id)
if os.path.exists(paper_fn):
return read_json(paper_fn)
print(paper_id)
paper = s2.paper(paper_id)
if paper is None:
print("Got none paper??")
time.sleep(random.randint(1, 2))
paper = s2.paper(paper_id)
if paper is None:
print("Paper not found")
return None
write_json(paper_fn, paper)
time.sleep(random.randint(1, 2))
return paper
|