Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
mikf
GitHub Repository: mikf/gallery-dl
Path: blob/master/gallery_dl/extractor/danbooru.py
5399 views
1
# -*- coding: utf-8 -*-
2
3
# Copyright 2014-2025 Mike Fährmann
4
#
5
# This program is free software; you can redistribute it and/or modify
6
# it under the terms of the GNU General Public License version 2 as
7
# published by the Free Software Foundation.
8
9
"""Extractors for https://danbooru.donmai.us/ and other Danbooru instances"""
10
11
from .common import BaseExtractor, Message
12
from .. import text, util
13
import datetime
14
15
16
class DanbooruExtractor(BaseExtractor):
17
"""Base class for danbooru extractors"""
18
basecategory = "Danbooru"
19
filename_fmt = "{category}_{id}_{filename}.{extension}"
20
page_limit = 1000
21
page_start = None
22
per_page = 200
23
useragent = util.USERAGENT
24
request_interval = (0.5, 1.5)
25
26
def _init(self):
27
self.ugoira = self.config("ugoira", False)
28
self.external = self.config("external", False)
29
self.includes = False
30
31
threshold = self.config("threshold")
32
if isinstance(threshold, int):
33
self.threshold = 1 if threshold < 1 else threshold
34
else:
35
self.threshold = self.per_page - 20
36
37
username, api_key = self._get_auth_info()
38
if username:
39
self.log.debug("Using HTTP Basic Auth for user '%s'", username)
40
self.session.auth = util.HTTPBasicAuth(username, api_key)
41
42
def skip(self, num):
43
pages = num // self.per_page
44
if pages >= self.page_limit:
45
pages = self.page_limit - 1
46
self.page_start = pages + 1
47
return pages * self.per_page
48
49
def items(self):
50
# 'includes' initialization must be done here and not in '_init()'
51
# or it'll cause an exception with e621 when 'metadata' is enabled
52
if includes := self.config("metadata"):
53
if isinstance(includes, (list, tuple)):
54
includes = ",".join(includes)
55
elif not isinstance(includes, str):
56
includes = "artist_commentary,children,notes,parent,uploader"
57
self.includes = includes + ",id"
58
59
data = self.metadata()
60
for post in self.posts():
61
62
try:
63
url = post["file_url"]
64
except KeyError:
65
if self.external and post["source"]:
66
post.update(data)
67
yield Message.Directory, post
68
yield Message.Queue, post["source"], post
69
continue
70
71
text.nameext_from_url(url, post)
72
post["date"] = text.parse_datetime(
73
post["created_at"], "%Y-%m-%dT%H:%M:%S.%f%z")
74
75
post["tags"] = (
76
post["tag_string"].split(" ")
77
if post["tag_string"] else ())
78
post["tags_artist"] = (
79
post["tag_string_artist"].split(" ")
80
if post["tag_string_artist"] else ())
81
post["tags_character"] = (
82
post["tag_string_character"].split(" ")
83
if post["tag_string_character"] else ())
84
post["tags_copyright"] = (
85
post["tag_string_copyright"].split(" ")
86
if post["tag_string_copyright"] else ())
87
post["tags_general"] = (
88
post["tag_string_general"].split(" ")
89
if post["tag_string_general"] else ())
90
post["tags_meta"] = (
91
post["tag_string_meta"].split(" ")
92
if post["tag_string_meta"] else ())
93
94
if post["extension"] == "zip":
95
if self.ugoira:
96
post["_ugoira_original"] = False
97
post["_ugoira_frame_data"] = post["frames"] = \
98
self._ugoira_frames(post)
99
post["_http_adjust_extension"] = False
100
else:
101
url = post["large_file_url"]
102
post["extension"] = "webm"
103
104
if url[0] == "/":
105
url = self.root + url
106
107
post.update(data)
108
yield Message.Directory, post
109
yield Message.Url, url, post
110
111
def items_artists(self):
112
for artist in self.artists():
113
artist["_extractor"] = DanbooruTagExtractor
114
url = f"{self.root}/posts?tags={text.quote(artist['name'])}"
115
yield Message.Queue, url, artist
116
117
def metadata(self):
118
return ()
119
120
def posts(self):
121
return ()
122
123
def _pagination(self, endpoint, params, prefix=None):
124
url = self.root + endpoint
125
params["limit"] = self.per_page
126
params["page"] = self.page_start
127
128
first = True
129
while True:
130
posts = self.request_json(url, params=params)
131
if isinstance(posts, dict):
132
posts = posts["posts"]
133
134
if posts:
135
if self.includes:
136
params_meta = {
137
"only" : self.includes,
138
"limit": len(posts),
139
"tags" : "id:" + ",".join(str(p["id"]) for p in posts),
140
}
141
data = {
142
meta["id"]: meta
143
for meta in self.request_json(url, params=params_meta)
144
}
145
for post in posts:
146
post.update(data[post["id"]])
147
148
if prefix == "a" and not first:
149
posts.reverse()
150
151
yield from posts
152
153
if len(posts) < self.threshold:
154
return
155
156
if prefix:
157
params["page"] = f"{prefix}{posts[-1]['id']}"
158
elif params["page"]:
159
params["page"] += 1
160
else:
161
params["page"] = 2
162
first = False
163
164
def _ugoira_frames(self, post):
165
data = self.request_json(
166
f"{self.root}/posts/{post['id']}.json?only=media_metadata"
167
)["media_metadata"]["metadata"]
168
169
if "Ugoira:FrameMimeType" in data:
170
ext = data["Ugoira:FrameMimeType"].rpartition("/")[2]
171
if ext == "jpeg":
172
ext = "jpg"
173
else:
174
ext = data["ZIP:ZipFileName"].rpartition(".")[2]
175
176
fmt = ("{:>06}." + ext).format
177
delays = data["Ugoira:FrameDelays"]
178
return [{"file": fmt(index), "delay": delay}
179
for index, delay in enumerate(delays)]
180
181
def _collection_posts(self, cid, ctype):
182
reverse = prefix = None
183
184
order = self.config("order-posts")
185
if not order or order in {"asc", "pool", "pool_asc", "asc_pool"}:
186
params = {"tags": f"ord{ctype}:{cid}"}
187
elif order in {"id", "desc_id", "id_desc"}:
188
params = {"tags": f"{ctype}:{cid}"}
189
prefix = "b"
190
elif order in {"desc", "desc_pool", "pool_desc"}:
191
params = {"tags": f"ord{ctype}:{cid}"}
192
reverse = True
193
elif order in {"asc_id", "id_asc"}:
194
params = {"tags": f"{ctype}:{cid}"}
195
reverse = True
196
197
posts = self._pagination("/posts.json", params, prefix)
198
if reverse:
199
self.log.info("Collecting posts of %s %s", ctype, cid)
200
return self._collection_enumerate_reverse(posts)
201
else:
202
return self._collection_enumerate(posts)
203
204
def _collection_metadata(self, cid, ctype, cname=None):
205
url = f"{self.root}/{cname or ctype}s/{cid}.json"
206
collection = self.request_json(url)
207
collection["name"] = collection["name"].replace("_", " ")
208
self.post_ids = collection.pop("post_ids", ())
209
return {ctype: collection}
210
211
def _collection_enumerate(self, posts):
212
pid_to_num = {pid: num for num, pid in enumerate(self.post_ids, 1)}
213
for post in posts:
214
post["num"] = pid_to_num[post["id"]]
215
yield post
216
217
def _collection_enumerate_reverse(self, posts):
218
posts = list(posts)
219
posts.reverse()
220
221
pid_to_num = {pid: num for num, pid in enumerate(self.post_ids, 1)}
222
for post in posts:
223
post["num"] = pid_to_num[post["id"]]
224
return posts
225
226
227
BASE_PATTERN = DanbooruExtractor.update({
228
"danbooru": {
229
"root": None,
230
"pattern": r"(?:(?:danbooru|hijiribe|sonohara|safebooru)\.donmai\.us"
231
r"|donmai\.moe)",
232
},
233
"atfbooru": {
234
"root": "https://booru.allthefallen.moe",
235
"pattern": r"booru\.allthefallen\.moe",
236
},
237
"aibooru": {
238
"root": None,
239
"pattern": r"(?:safe\.|general\.)?aibooru\.(?:online|download)",
240
},
241
"booruvar": {
242
"root": "https://booru.borvar.art",
243
"pattern": r"booru\.borvar\.art",
244
},
245
})
246
247
248
class DanbooruTagExtractor(DanbooruExtractor):
249
"""Extractor for danbooru posts from tag searches"""
250
subcategory = "tag"
251
directory_fmt = ("{category}", "{search_tags}")
252
archive_fmt = "t_{search_tags}_{id}"
253
pattern = BASE_PATTERN + r"/posts\?(?:[^&#]*&)*tags=([^&#]*)"
254
example = "https://danbooru.donmai.us/posts?tags=TAG"
255
256
def metadata(self):
257
self.tags = text.unquote(self.groups[-1].replace("+", " "))
258
return {"search_tags": self.tags}
259
260
def posts(self):
261
prefix = "b"
262
for tag in self.tags.split():
263
if tag.startswith("order:"):
264
if tag == "order:id" or tag == "order:id_asc":
265
prefix = "a"
266
elif tag == "order:id_desc":
267
prefix = "b"
268
else:
269
prefix = None
270
elif tag.startswith(
271
("id:", "md5:", "ordfav:", "ordfavgroup:", "ordpool:")):
272
prefix = None
273
break
274
275
return self._pagination("/posts.json", {"tags": self.tags}, prefix)
276
277
278
class DanbooruPoolExtractor(DanbooruExtractor):
279
"""Extractor for Danbooru pools"""
280
subcategory = "pool"
281
directory_fmt = ("{category}", "pool", "{pool[id]} {pool[name]}")
282
filename_fmt = "{num:>04}_{id}_{filename}.{extension}"
283
archive_fmt = "p_{pool[id]}_{id}"
284
pattern = BASE_PATTERN + r"/pool(?:s|/show)/(\d+)"
285
example = "https://danbooru.donmai.us/pools/12345"
286
287
def metadata(self):
288
self.pool_id = self.groups[-1]
289
return self._collection_metadata(self.pool_id, "pool")
290
291
def posts(self):
292
return self._collection_posts(self.pool_id, "pool")
293
294
295
class DanbooruFavgroupExtractor(DanbooruExtractor):
296
"""Extractor for Danbooru favorite groups"""
297
subcategory = "favgroup"
298
directory_fmt = ("{category}", "Favorite Groups",
299
"{favgroup[id]} {favgroup[name]}")
300
filename_fmt = "{num:>04}_{id}_{filename}.{extension}"
301
archive_fmt = "fg_{favgroup[id]}_{id}"
302
pattern = BASE_PATTERN + r"/favorite_group(?:s|/show)/(\d+)"
303
example = "https://danbooru.donmai.us/favorite_groups/12345"
304
305
def metadata(self):
306
return self._collection_metadata(
307
self.groups[-1], "favgroup", "favorite_group")
308
309
def posts(self):
310
return self._collection_posts(self.groups[-1], "favgroup")
311
312
313
class DanbooruPostExtractor(DanbooruExtractor):
314
"""Extractor for single danbooru posts"""
315
subcategory = "post"
316
archive_fmt = "{id}"
317
pattern = BASE_PATTERN + r"/post(?:s|/show)/(\d+)"
318
example = "https://danbooru.donmai.us/posts/12345"
319
320
def posts(self):
321
url = f"{self.root}/posts/{self.groups[-1]}.json"
322
post = self.request_json(url)
323
if self.includes:
324
params = {"only": self.includes}
325
post.update(self.request_json(url, params=params))
326
return (post,)
327
328
329
class DanbooruPopularExtractor(DanbooruExtractor):
330
"""Extractor for popular images from danbooru"""
331
subcategory = "popular"
332
directory_fmt = ("{category}", "popular", "{scale}", "{date}")
333
archive_fmt = "P_{scale[0]}_{date}_{id}"
334
pattern = BASE_PATTERN + r"/(?:explore/posts/)?popular(?:\?([^#]*))?"
335
example = "https://danbooru.donmai.us/explore/posts/popular"
336
337
def metadata(self):
338
self.params = params = text.parse_query(self.groups[-1])
339
scale = params.get("scale", "day")
340
date = params.get("date") or datetime.date.today().isoformat()
341
342
if scale == "week":
343
date = datetime.date.fromisoformat(date)
344
date = (date - datetime.timedelta(days=date.weekday())).isoformat()
345
elif scale == "month":
346
date = date[:-3]
347
348
return {"date": date, "scale": scale}
349
350
def posts(self):
351
return self._pagination("/explore/posts/popular.json", self.params)
352
353
354
class DanbooruArtistExtractor(DanbooruExtractor):
355
"""Extractor for danbooru artists"""
356
subcategory = "artist"
357
pattern = BASE_PATTERN + r"/artists/(\d+)"
358
example = "https://danbooru.donmai.us/artists/12345"
359
360
items = DanbooruExtractor.items_artists
361
362
def artists(self):
363
url = f"{self.root}/artists/{self.groups[-1]}.json"
364
return (self.request_json(url),)
365
366
367
class DanbooruArtistSearchExtractor(DanbooruExtractor):
368
"""Extractor for danbooru artist searches"""
369
subcategory = "artist-search"
370
pattern = BASE_PATTERN + r"/artists/?\?([^#]+)"
371
example = "https://danbooru.donmai.us/artists?QUERY"
372
373
items = DanbooruExtractor.items_artists
374
375
def artists(self):
376
url = self.root + "/artists.json"
377
params = text.parse_query(self.groups[-1])
378
params["page"] = text.parse_int(params.get("page"), 1)
379
380
while True:
381
artists = self.request_json(url, params=params)
382
383
yield from artists
384
385
if len(artists) < 20:
386
return
387
params["page"] += 1
388
389