Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
mikf
GitHub Repository: mikf/gallery-dl
Path: blob/master/gallery_dl/extractor/e621.py
8901 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://e621.net/ and other e621 instances"""
10
11
from .common import Extractor, Message
12
from . import danbooru
13
from ..cache import memcache
14
from .. import text, util
15
16
17
class E621Extractor(danbooru.DanbooruExtractor):
18
"""Base class for e621 extractors"""
19
basecategory = "E621"
20
page_limit = 750
21
page_start = None
22
per_page = 320
23
useragent = util.USERAGENT_GALLERYDL + " (by mikf)"
24
request_interval_min = 1.0
25
26
def items(self):
27
if includes := self.config("metadata") or ():
28
if isinstance(includes, str):
29
includes = includes.split(",")
30
elif not isinstance(includes, (list, tuple)):
31
includes = ("notes", "pools")
32
33
notes = ("notes" in includes)
34
pools = ("pools" in includes)
35
36
data = self.metadata()
37
for post in self.posts():
38
file = post["file"]
39
40
if not file["url"]:
41
md5 = file["md5"]
42
file["url"] = (f"https://static1.{self.root[8:]}/data"
43
f"/{md5[0:2]}/{md5[2:4]}/{md5}.{file['ext']}")
44
45
if notes and post.get("has_notes"):
46
post["notes"] = self._get_notes(post["id"])
47
48
if pools and post["pools"]:
49
post["pools"] = self._get_pools(
50
",".join(map(str, post["pools"])))
51
52
post["filename"] = file["md5"]
53
post["extension"] = file["ext"]
54
post["date"] = self.parse_datetime_iso(post["created_at"])
55
56
post.update(data)
57
yield Message.Directory, "", post
58
yield Message.Url, file["url"], post
59
60
def items_artists(self):
61
for artist in self.artists():
62
artist["_extractor"] = E621TagExtractor
63
url = f"{self.root}/posts?tags={text.quote(artist['name'])}"
64
yield Message.Queue, url, artist
65
66
def _get_notes(self, id):
67
return self.request_json(
68
f"{self.root}/notes.json?search[post_id]={id}")
69
70
@memcache(keyarg=1)
71
def _get_pools(self, ids):
72
pools = self.request_json(
73
f"{self.root}/pools.json?search[id]={ids}")
74
for pool in pools:
75
pool["name"] = pool["name"].replace("_", " ")
76
return pools
77
78
79
BASE_PATTERN = E621Extractor.update({
80
"e621": {
81
"root": "https://e621.net",
82
"pattern": r"e621\.(?:net|cc)",
83
},
84
"e926": {
85
"root": "https://e926.net",
86
"pattern": r"e926\.net",
87
},
88
"e6ai": {
89
"root": "https://e6ai.net",
90
"pattern": r"e6ai\.net",
91
},
92
})
93
94
95
class E621TagExtractor(E621Extractor, danbooru.DanbooruTagExtractor):
96
"""Extractor for e621 posts from tag searches"""
97
pattern = BASE_PATTERN + r"/posts?(?:\?[^#]*?tags=|/index/\d+/)([^&#]*)"
98
example = "https://e621.net/posts?tags=TAG"
99
100
101
class E621PoolExtractor(E621Extractor, danbooru.DanbooruPoolExtractor):
102
"""Extractor for e621 pools"""
103
pattern = BASE_PATTERN + r"/pool(?:s|/show)/(\d+)"
104
example = "https://e621.net/pools/12345"
105
106
def posts(self):
107
self.log.info("Collecting posts of pool %s", self.pool_id)
108
109
id_to_post = {
110
post["id"]: post
111
for post in self._pagination(
112
"/posts.json", {"tags": "pool:" + self.pool_id})
113
}
114
115
posts = []
116
for num, pid in enumerate(self.post_ids, 1):
117
if pid in id_to_post:
118
post = id_to_post[pid]
119
post["num"] = num
120
posts.append(post)
121
else:
122
self.log.warning("Post %s is unavailable", pid)
123
return posts
124
125
126
class E621PostExtractor(E621Extractor, danbooru.DanbooruPostExtractor):
127
"""Extractor for single e621 posts"""
128
pattern = BASE_PATTERN + r"/post(?:s|/show)/(\d+)"
129
example = "https://e621.net/posts/12345"
130
131
def posts(self):
132
url = f"{self.root}/posts/{self.groups[-1]}.json"
133
return (self.request_json(url)["post"],)
134
135
136
class E621PopularExtractor(E621Extractor, danbooru.DanbooruPopularExtractor):
137
"""Extractor for popular images from e621"""
138
pattern = BASE_PATTERN + r"/explore/posts/popular(?:\?([^#]*))?"
139
example = "https://e621.net/explore/posts/popular"
140
141
def posts(self):
142
return self._pagination("/popular.json", self.params)
143
144
145
class E621ArtistExtractor(E621Extractor, danbooru.DanbooruArtistExtractor):
146
"""Extractor for e621 artists"""
147
subcategory = "artist"
148
pattern = BASE_PATTERN + r"/artists/(\d+)"
149
example = "https://e621.net/artists/12345"
150
151
items = E621Extractor.items_artists
152
153
154
class E621ArtistSearchExtractor(E621Extractor,
155
danbooru.DanbooruArtistSearchExtractor):
156
"""Extractor for e621 artist searches"""
157
subcategory = "artist-search"
158
pattern = BASE_PATTERN + r"/artists/?\?([^#]+)"
159
example = "https://e621.net/artists?QUERY"
160
161
items = E621Extractor.items_artists
162
163
164
class E621FavoriteExtractor(E621Extractor):
165
"""Extractor for e621 favorites"""
166
subcategory = "favorite"
167
directory_fmt = ("{category}", "Favorites", "{user_id}")
168
archive_fmt = "f_{user_id}_{id}"
169
pattern = BASE_PATTERN + r"/favorites(?:\?([^#]*))?"
170
example = "https://e621.net/favorites"
171
172
def metadata(self):
173
self.query = text.parse_query(self.groups[-1])
174
return {"user_id": self.query.get("user_id", "")}
175
176
def posts(self):
177
return self._pagination("/favorites.json", self.query)
178
179
180
class E621FrontendExtractor(Extractor):
181
"""Extractor for alternative e621 frontends"""
182
basecategory = "E621"
183
category = "e621"
184
subcategory = "frontend"
185
pattern = r"(?:https?://)?e621\.(?:cc/\?tags|anthro\.fr/\?q)=([^&#]*)"
186
example = "https://e621.cc/?tags=TAG"
187
188
def initialize(self):
189
pass
190
191
def items(self):
192
url = "https://e621.net/posts?tags=" + self.groups[0]
193
data = {"_extractor": E621TagExtractor}
194
yield Message.Queue, url, data
195
196