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