-
Notifications
You must be signed in to change notification settings - Fork 29
/
thingiverse_crawler.py
executable file
·269 lines (226 loc) · 9.1 KB
/
thingiverse_crawler.py
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
#!//usr/bin/env python
import argparse
import datetime
import os
import os.path
import requests
import re
import time
import urllib
import urlparse
from subprocess import check_call
def utc_mktime(utc_tuple):
"""Returns number of seconds elapsed since epoch
Note that no timezone are taken into consideration.
utc tuple must be: (year, month, day, hour, minute, second)
"""
if len(utc_tuple) == 6:
utc_tuple += (0, 0, 0)
return time.mktime(utc_tuple) - time.mktime((1970, 1, 1, 0, 0, 0, 0, 0, 0))
def datetime_to_timestamp(dt):
"""Converts a datetime object to UTC timestamp"""
return int(utc_mktime(dt.timetuple()))
def parse_thing_ids(text):
pattern = "thing:(\d{5,7})"
matched = re.findall(pattern, text)
return [int(val) for val in matched]
def parse_file_ids(text):
pattern = "download:(\d{5,7})"
matched = re.findall(pattern, text)
return [int(val) for val in matched]
known_licenses = [
("Creative Commons - Attribution",
re.compile("http://creativecommons.org/licenses/by/\d(.\d)?/")),
("Creative Commons - Attribution - Share Alike",
re.compile("http://creativecommons.org/licenses/by-sa/\d(.\d)?/")),
("Creative Commons - Attribution - No Derivatives",
re.compile("http://creativecommons.org/licenses/by-nd/\d(.\d)?/")),
("Creative Commons - Attribution - Non-Commercial",
re.compile("http://creativecommons.org/licenses/by-nc/\d(.\d)?/")),
("Attribution - Non-Commercial - Share Alike",
re.compile("http://creativecommons.org/licenses/by-nc-sa/\d(.\d)?/")),
("Attribution - Non-Commercial - No Derivatives",
re.compile("http://creativecommons.org/licenses/by-nc-nd/\d(.\d)?/")),
("Creative Commons - Public Domain Dedication",
re.compile("http://creativecommons.org/publicdomain/zero/\d(.\d)?/")),
("GNU - GPL",
re.compile("http://creativecommons.org/licenses/GPL/\d(.\d)?/")),
("GNU - LGPL",
re.compile("http://creativecommons.org/licenses/LGPL/\d(.\d)?/")),
("BSD License",
re.compile("http://creativecommons.org/licenses/BSD/")),
("Nokia",
re.compile("http://www.developer.nokia.com/Terms_and_conditions/3d-printing.xhtml")),
("Public Domain",
re.compile("http://creativecommons.org/licenses/publicdomain/")),
]
def parse_license(text):
for name, pattern in known_licenses:
if pattern.search(text):
return name
return "unknown_license"
def crawl_thing_ids(N, end_date=None):
""" This method extract N things that were uploaded to thingiverse.com
before end_date. If end_date is None, use today's date.
"""
baseurl = "http://www.thingiverse.com/search/recent/things/page:{}?q=&start_date=&stop_date={}&search_mode=advanced&description=&username=&tags=&license="
end_date = datetime_to_timestamp(end_date)
thing_ids = set()
for i in range(N/12 + 1):
url = baseurl.format(i, end_date)
r = requests.get(url)
assert(r.status_code==200)
thing_ids.update(parse_thing_ids(r.text))
if len(thing_ids) > N:
break
# Sleep a bit to avoid being mistaken as DoS.
time.sleep(0.5)
return thing_ids
def crawl_things(N, output_dir, term=None, category=None, source=None, organize=False):
#baseurl = "http://www.thingiverse.com/newest/page:{}"
#baseurl = "http://www.thingiverse.com/explore/popular/page:{}"
key = None
if term is None:
assert(source is not None);
url_prefix= "http://www.thingiverse.com/explore/{}/".format(source);
if category is None:
baseurl = url_prefix + "page:{}"
else:
baseurl = url_prefix + urllib.quote_plus(category) + "/page:{}"
key = category
else:
baseurl = "http://www.thingiverse.com/search/page:{}?type=things&q=" + urllib.quote_plus(term)
key = term
thing_ids = set()
file_ids = set()
records = []
num_files = 0
page = 0
previous_path = ''
while True:
url = baseurl.format(page+1)
contents = get_url(url)
page += 1
# If the previous url ends up being the same as the old one, we should stop as there are no more pages
current_path = urlparse.urlparse(contents.url).path
if previous_path == current_path:
return records
else:
previous_path = current_path
for thing_id in parse_thing_ids(contents.text):
if thing_id in thing_ids:
continue
print("thing id: {}".format(thing_id))
thing_ids.add(thing_id)
license, thing_files = get_thing(thing_id)
for file_id in thing_files:
if file_id in file_ids:
continue
file_ids.add(file_id)
print(" file id: {}".format(file_id))
result = download_file(file_id, thing_id, output_dir, organize)
if result is None: continue
filename, link = result
if filename is not None:
records.append((thing_id, file_id, filename, license, link))
if N is not None and len(records) >= N:
return records
# Sleep a bit to avoid being mistaken as DoS.
time.sleep(0.5)
save_records(records, key)
def get_thing(thing_id):
base_url = "http://www.thingiverse.com/{}:{}"
file_ids = []
url = base_url.format("thing", thing_id)
contents = get_url(url).text
license = parse_license(contents)
return license, parse_file_ids(contents)
def get_url(url, time_out=600):
r = requests.get(url)
sleep_time = 1.0
while r.status_code != 200:
print("sleep {}s".format(sleep_time))
print(url)
time.sleep(sleep_time)
r = requests.get(url)
sleep_time += 2
if (sleep_time > time_out):
# We have sleeped for over 10 minutes, the page probably does
# not exist.
break
if r.status_code != 200:
print("failed to retrieve {}".format(url))
else:
return r
# return r.text
def get_download_link(file_id):
base_url = "https://www.thingiverse.com/{}:{}"
url = base_url.format("download", file_id)
r = requests.head(url)
link = r.headers.get("Location", None)
if link is not None:
__, ext = os.path.splitext(link)
if ext.lower() not in [".stl", ".obj", ".ply", ".off"]:
return None
return link
def download_file(file_id, thing_id, output_dir, organize):
link = get_download_link(file_id)
if link is None:
return None
__, ext = os.path.splitext(link)
output_file = "{}{}".format(file_id, ext.lower())
if organize:
output_file = os.path.join(str(thing_id), output_file)
output_file = os.path.join(output_dir, output_file)
command = "wget -q --tries=20 --waitretry 20 -O {} {}".format(output_file, link)
#check_call(command.split())
return output_file, link
def save_records(records, key=None):
# Enforce kebab case file name
output_name = re.sub('(\w) (\w)', r'\1-\2', key).lower()+"-" if key else ""
output_name += "summary"
with open(output_name+".csv", 'w') as fout:
fout.write("thing_id, file_id, file, license, link\n")
for entry in records:
fout.write(",".join([str(val) for val in entry]) + "\n")
def parse_args():
parser = argparse.ArgumentParser(
description="Crawl data from thingiverse",
epilog="Written by Qingnan Zhou <qnzhou at gmail dot com> Modified by Mike Gleason")
parser.add_argument("--output-dir", "-o", help="output directories",
default=".")
parser.add_argument("--number", "-n", type=int,
help="how many files to crawl", default=None)
group = parser.add_mutually_exclusive_group()
group.add_argument("--search-term", "-s", type=str, default=None,
help="term to search for")
group.add_argument("--category", "-c", type=str, default=None,
help="catergory to search for")
parser.add_argument('--organize', dest='organized', default=False, action='store_true',
help="organize files by their main category")
parser.add_argument("--source", choices=("newest", "featured", "popular",
"verified", "made-things", "derivatives", "customizable",
"random-things", "firehose"), default="featured");
return parser
def main():
parser = parse_args()
args = parser.parse_args()
if args.number is None and (args.search_term is None and args.category is None):
parser.error('Number or Search/Category Term required')
output_dir = args.output_dir
number = args.number
records = crawl_things(
args.number,
output_dir,
args.search_term,
args.category,
args.source,
args.organized)
if args.search_term:
save_records(records, args.search_term)
elif args.category:
save_records(records, args.category)
else:
save_records(records)
if __name__ == "__main__":
main()