cowpuncher's picture
Initial Files. You will Need all of them.
c5be659 verified
Raw History Blame Contribute Delete
18.9 kB
"""Grab example pictures for a tag from Danbooru (Safebooru when Danbooru is down) or from Gelbooru into a
folder, each with a .txt of its tags. No Krita here, so it can be tested on its own."""
from __future__ import annotations
import csv
import json
import re
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
UA = "krita-ai-reference-board/1.3"
IMAGE_EXTS = {"jpg", "jpeg", "png", "webp"}
RATING_NAMES = {"g": "general", "s": "sensitive", "q": "questionable", "e": "explicit"}
# rating choice -> (Danbooru metatag value, ratings kept)
RATINGS = {"general": ("g", {"g"}), "sensitive": ("g,s", {"g", "s"}), "any": ("", {"g", "s", "q", "e"}),
"adult": ("q,e", {"q", "e"})}
SOURCES = ("danbooru", "gelbooru")
GELBOORU_API = "https://gelbooru.com/index.php"
GELBOORU_ACCOUNT_PAGE = "https://gelbooru.com/index.php?page=account&s=options"
# Gelbooru's rating words -> the letters used here; rating choice -> what is added to the search
GELBOORU_RATING = {"general": "g", "safe": "g", "sensitive": "s", "questionable": "q", "explicit": "e"}
GELBOORU_FILTER = {"general": ["rating:general"], "sensitive": ["-rating:questionable", "-rating:explicit"], "any": [],
"adult": ["-rating:general", "-rating:sensitive"]}
DANBOORU_FREE_TAGS = 2 # tags an account-less search may use; order: counts as one, rating: doesn't
# A picture rated above general is never kept when it has one of these: they mean the subject is a child.
MINOR_TAGS = {"loli", "shota", "child", "children", "female_child", "male_child", "toddler", "baby", "infant", "aged_down",
"younger", "oppai_loli", "kindergarten_uniform", "kindergarten", "kindergartener", "preschooler", "randoseru",
"elementary_school", "elementary_schooler", "little_girl", "little_boy", "toddlercon", "lolidom", "shotadom",
"onee-shota", "onee-loli", "child_on_child"}
KAOMOJI = {"0_0", "(o)_(o)", "+_+", "+_-", "._.", "<o>_<o>", "<|>_<|>", "=_=", ">_<", "3_3", "6_9",
">_o", "@_@", "^_^", "o_o", "u_u", "x_x", "|_|", "||_||"}
class SourceDown(Exception):
"""The site didn't answer with posts (maintenance page, outage, timeout)."""
class NeedsLogin(Exception):
"""Gelbooru only answers API requests that carry an account's User ID and API key."""
def _request(url: str, timeout=30) -> bytes:
req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "application/json, image/*, */*"})
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.read()
METATAGS = {"rating", "order", "sort", "limit", "score", "status", "user", "fav", "ordfav", "pool", "id", "md5"}
def parse_tags(text: str) -> list[str]:
"""'index finger raised, -from side' -> ['index_finger_raised', '-from_side'] (booru spelling). Ratings and
sort orders come from the board's own boxes, so typed ones are dropped."""
out = []
for piece in (text or "").replace("\\(", "(").replace("\\)", ")").split(","):
tag = re.sub(r"\s+", "_", piece.strip().lower())
if ":" in tag and tag.lstrip("-").split(":", 1)[0] in METATAGS:
continue
if tag and tag != "-" and tag not in out:
out.append(tag)
return out
def _has(tags: set, wanted: list[str]) -> bool:
return all((t[1:] not in tags) if t.startswith("-") else (t in tags) for t in wanted)
def positive(tags: list[str]) -> list[str]:
return [t for t in tags if not t.startswith("-")]
def prompt_name(tag: str) -> str:
"""Booru tag -> how it goes in a Krita prompt: spaces, kaomoji kept, brackets escaped."""
name = tag if tag in KAOMOJI else tag.replace("_", " ")
return name.replace("(", "\\(").replace(")", "\\)")
def folder_name(tags: list[str]) -> str:
name = " + ".join(t.replace("_", " ") for t in tags) or "grab"
return re.sub(r'[<>:"/\\|?*]', "_", name).strip(" .")[:80] or "grab"
class TagList:
"""Danbooru's tag list as the AI plugin ships it (tag,type,count,aliases): types 0 general, 1 artist,
3 copyright, 4 character, 5 meta."""
def __init__(self, paths=()):
self.info: dict[str, tuple[int, int]] = {}
self.alias: dict[str, str] = {}
for path in paths:
try:
with open(path, encoding="utf-8", newline="") as f:
for row in csv.reader(f):
if len(row) < 3 or not row[2].isdigit():
continue
tag, kind, count = row[0], int(row[1]) if row[1].isdigit() else 0, int(row[2])
if tag not in self.info or self.info[tag][1] < count:
self.info[tag] = (kind, count)
for a in (row[3].split(",") if len(row) > 3 and row[3] else []):
self.alias.setdefault(a.strip(), tag)
except OSError:
pass
def __bool__(self):
return bool(self.info)
def category(self, tag: str):
return self.info.get(tag, (None, 0))[0]
def resolve(self, tags: list[str]) -> tuple[list[str], list[str]]:
"""Aliases to the real tag ('finger raised' -> 'index finger raised')."""
out, notes = [], []
for t in tags:
neg, bare = ("-", t[1:]) if t.startswith("-") else ("", t)
if bare not in self.info and bare in self.alias:
notes.append(f"{bare.replace('_', ' ')} -> {self.alias[bare].replace('_', ' ')}")
bare = self.alias[bare]
if neg + bare not in out:
out.append(neg + bare)
return out, notes
def unknown(self, tags: list[str]) -> list[str]:
return [t for t in (x.lstrip("-") for x in tags) if self and t not in self.info]
def count(self, tag: str) -> int | None:
return self.info[tag][1] if tag in self.info else None
def suggest(self, tag: str, n=5) -> list[str]:
"""Real tags close to one that found nothing: most words shared ('wag' counts for 'wagging'), whole
words before word starts, then the most used."""
words = {w for w in tag.lstrip("-").split("_") if len(w) > 2}
if not words:
return []
scored = []
for t, (kind, count) in self.info.items():
if kind != 0 or t == tag:
continue
tw = t.split("_")
exact = sum(1 for w in words if w in tw)
hits = exact + sum(1 for w in words if w not in tw and any(x.startswith(w) for x in tw))
if hits:
scored.append((-hits, -exact, -count, t))
scored.sort()
return [s[-1] for s in scored[:n]]
def _url_ext(url: str) -> str:
return urllib.parse.urlparse(url).path.rsplit(".", 1)[-1].lower()
def allowed(post: dict) -> bool:
"""Nothing above general rating that shows a child."""
if post["rating"] == "g":
return True
return not ((set(post["general"]) | set(post["character"]) | set(post.get("all_tags", ()))) & MINOR_TAGS)
def danbooru_search(tags: list[str], rating: str, want: int) -> list[dict]:
meta, keep = RATINGS[rating]
sent = tags[:DANBOORU_FREE_TAGS]
query = list(sent) + ([f"rating:{meta}"] if meta else []) + (["order:score"] if len(sent) == 1 else [])
limit = min(100, max(40, want * 4))
url = "https://danbooru.donmai.us/posts.json?" + urllib.parse.urlencode({"tags": " ".join(query), "limit": limit})
try:
data = json.loads(_request(url))
except urllib.error.HTTPError as e:
if 400 <= e.code < 500 and e.code != 429: # the search itself was refused: try the plain tags
url = "https://danbooru.donmai.us/posts.json?" + urllib.parse.urlencode({"tags": " ".join(sent), "limit": 100})
try:
data = json.loads(_request(url))
except Exception as e2:
raise SourceDown(f"Danbooru: {e2}") from e2
else:
raise SourceDown(f"Danbooru: HTTP {e.code}") from e
except (urllib.error.URLError, TimeoutError, ValueError, OSError) as e: # ValueError: a maintenance page, not JSON
raise SourceDown(f"Danbooru: {getattr(e, 'reason', e)}") from e
if not isinstance(data, list):
raise SourceDown(f"Danbooru: {data.get('message') if isinstance(data, dict) else 'unexpected answer'}")
posts = []
for p in data:
if p.get("is_deleted") or p.get("is_banned"):
continue
url = p.get("large_file_url") or p.get("file_url")
if not url or _url_ext(url) not in IMAGE_EXTS or p.get("rating") not in keep:
continue
post = {
"source": "danbooru", "id": p.get("id"), "url": url, "rating": p.get("rating"), "score": p.get("score") or 0,
"general": (p.get("tag_string_general") or "").split(),
"character": (p.get("tag_string_character") or "").split(),
"copyright": (p.get("tag_string_copyright") or "").split(),
"artist": (p.get("tag_string_artist") or "").split(),
"page": f"https://danbooru.donmai.us/posts/{p.get('id')}",
}
everything = set(post["general"]) | set(post["character"]) | set(post["copyright"]) | set(post["artist"])
if _has(everything, tags): # tags past the free two are checked here
posts.append(post)
posts.sort(key=lambda p: -p["score"])
return posts
def safebooru_search(tags: list[str], want: int, taglist: TagList) -> list[dict]:
query = " ".join(tags + ["sort:score:desc"])
url = ("https://safebooru.org/index.php?page=dapi&s=post&q=index&json=1&"
+ urllib.parse.urlencode({"limit": min(100, max(40, want * 3)), "tags": query}))
try:
body = _request(url).strip()
data = json.loads(body) if body else []
except urllib.error.HTTPError as e:
raise SourceDown(f"Safebooru: HTTP {e.code}") from e
except (urllib.error.URLError, TimeoutError, ValueError, OSError) as e:
raise SourceDown(f"Safebooru: {getattr(e, 'reason', e)}") from e
if not isinstance(data, list):
raise SourceDown("Safebooru: unexpected answer")
posts = []
for p in data:
url = p.get("sample_url") if p.get("sample") else p.get("file_url")
url = url or p.get("file_url")
if not url or _url_ext(url) not in IMAGE_EXTS:
continue
split = {"general": [], "character": [], "copyright": [], "artist": []}
for t in (p.get("tags") or "").split():
kind = taglist.category(t)
if kind == 5 or (kind is None and taglist):
continue # meta (highres, commentary ...), or not a Danbooru tag at all (Safebooru mixes in others)
split[{1: "artist", 3: "copyright", 4: "character"}.get(kind, "general")].append(t)
posts.append({
"source": "safebooru", "id": p.get("id"), "url": url,
"rating": "g" if p.get("rating") in ("safe", "general") else "s", "score": p.get("score") or 0,
**split, "page": f"https://safebooru.org/index.php?page=post&s=view&id={p.get('id')}",
})
return posts
def gelbooru_search(tags: list[str], rating: str, want: int, taglist: TagList, credentials) -> list[dict]:
"""credentials: (user id, api key) of a Gelbooru account. Posts come back with one flat tag string, so the
tag list on disk is what sorts them into general / character / copyright / artist."""
user_id, api_key = (str(c or "").strip() for c in (credentials or ("", "")))
if not user_id or not api_key:
raise NeedsLogin("Gelbooru needs your User ID and API key (button 'Gelbooru login ...').")
_, keep = RATINGS[rating]
query = list(tags) + GELBOORU_FILTER[rating]
if rating != "general":
query += ["-loli", "-shota"] # not even asked for; allowed() below is the rule that decides
query.append("sort:score:desc")
url = GELBOORU_API + "?" + urllib.parse.urlencode({
"page": "dapi", "s": "post", "q": "index", "json": "1", "limit": min(100, max(40, want * 3)), "pid": 0,
"tags": " ".join(query), "api_key": api_key, "user_id": user_id})
try:
body = _request(url).strip()
data = json.loads(body) if body else {}
except urllib.error.HTTPError as e:
if e.code in (401, 403):
raise NeedsLogin("Gelbooru did not accept the User ID and API key. Check them under 'Gelbooru login ...'.") from e
raise SourceDown(f"Gelbooru: HTTP {e.code}") from e
except (urllib.error.URLError, TimeoutError, ValueError, OSError) as e:
raise SourceDown(f"Gelbooru: {getattr(e, 'reason', e)}") from e
found = data.get("post", []) if isinstance(data, dict) else data # no "post" entry at all = nothing found
if isinstance(found, dict):
found = [found]
if not isinstance(found, list):
raise SourceDown("Gelbooru: unexpected answer")
posts = []
for p in found:
if not isinstance(p, dict):
continue
url = p.get("sample_url") if str(p.get("sample") or "0") not in ("0", "False", "false", "") else None
url = url or p.get("file_url")
rating_letter = GELBOORU_RATING.get(str(p.get("rating") or "").lower())
if not url or _url_ext(url) not in IMAGE_EXTS or rating_letter not in keep:
continue
every = (p.get("tags") or "").split()
split = {"general": [], "character": [], "copyright": [], "artist": []}
for t in every:
kind = taglist.category(t)
if kind == 5:
continue # meta: highres, commentary ...
split[{1: "artist", 3: "copyright", 4: "character"}.get(kind, "general")].append(t)
try:
score = int(p.get("score") or 0)
except (TypeError, ValueError):
score = 0
post = {"source": "gelbooru", "id": p.get("id"), "url": url, "rating": rating_letter, "score": score, **split,
"all_tags": every, "page": f"https://gelbooru.com/index.php?page=post&s=view&id={p.get('id')}"}
if _has(set(every), tags):
posts.append(post)
posts.sort(key=lambda p: -p["score"])
return posts
def sidecar_text(post: dict, searched: list[str]) -> str:
"""Prompt-ready tags, the searched ones first."""
searched = positive(searched)
general = [t for t in searched if t in post["general"]] + [t for t in post["general"] if t not in searched]
lines = [f"tags: {', '.join(prompt_name(t) for t in general)}"]
for key in ("character", "copyright", "artist"):
if post[key]:
lines.append(f"{key}: {', '.join(prompt_name(t) for t in post[key])}")
lines += [f"rating: {RATING_NAMES.get(post['rating'], post['rating'])}", f"score: {post['score']}",
f"post: {post['page']}"]
return "\n".join(lines) + "\n"
def read_sidecar(image_path) -> dict | None:
"""The .txt next to a picture: grabbed ones have 'key: value' lines; anything else (a LoRA caption file,
say) counts as its tags."""
path = Path(image_path).with_suffix(".txt")
try:
text = path.read_text(encoding="utf-8", errors="replace")[:6000]
except OSError:
return None
info = {}
for line in text.splitlines():
m = re.match(r"^(tags|character|copyright|artist|rating|score|post):\s*(.*)$", line.strip())
if m:
info[m.group(1)] = m.group(2)
if "tags" not in info:
info = {"tags": " ".join(text.split())}
return info
def grab(text: str, rating: str, count: int, root, taglist: TagList | None = None, progress=lambda s: None,
source: str = "danbooru", credentials=None) -> dict:
"""Search, then download up to `count` pictures into root/<tags>. Returns a summary dict.
source: "danbooru" (Safebooru when it is down) or "gelbooru" (needs credentials = (user id, api key))."""
taglist = taglist or TagList()
if rating not in RATINGS:
rating = "general"
tags = parse_tags(text)
if not tags:
return {"error": "Type a tag to grab, e.g. index finger raised."}
tags, notes = taglist.resolve(tags)
if not positive(tags):
return {"error": "Add at least one tag to look for (not only -excluded ones)."}
if rating != "general" and set(positive(tags)) & MINOR_TAGS:
return {"error": "Tags for children are only searched with the General rating."}
unknown = taglist.unknown(tags)
posts, down = [], ""
if source == "gelbooru":
source = "Gelbooru"
progress("Asking Gelbooru ...")
try:
posts = gelbooru_search(tags, rating, count, taglist, credentials)
except NeedsLogin as e:
return {"error": str(e), "needs_login": True, "notes": notes}
except SourceDown as e:
return {"error": f"Gelbooru did not answer ({e}).", "notes": notes}
else:
source = "Danbooru"
progress("Asking Danbooru ...")
try:
posts = danbooru_search(tags, rating, count)
except SourceDown as e:
down = str(e)
if rating == "adult":
return {"error": f"Danbooru did not answer ({down}), and Safebooru only has safe pictures.", "notes": notes}
source = "Safebooru"
progress("Danbooru isn't answering, asking Safebooru ...")
try:
posts = safebooru_search(tags, count, taglist)
except SourceDown as e2:
return {"error": f"Neither site answered ({down}; {e2}).", "notes": notes}
posts = [p for p in posts if allowed(p)][:count]
result = {"source": source, "tags": tags, "notes": notes, "down": down, "saved": 0, "folder": "", "found": len(posts),
# how often Danbooru uses each tag: a rare one is a tag the models barely learned
"counts": {t: taglist.count(t) for t in positive(tags) if taglist.count(t) is not None}}
if not posts:
result["suggestions"] = {t: taglist.suggest(t) for t in (unknown or positive(tags))}
return result
folder = Path(root) / folder_name(tags)
folder.mkdir(parents=True, exist_ok=True)
result["folder"] = str(folder)
failed = 0
for i, post in enumerate(posts, 1):
progress(f"Downloading {i}/{len(posts)} from {source} ...")
stem = folder / f"{post['source']}_{post['id']}"
target = stem.with_suffix("." + _url_ext(post["url"]).replace("jpeg", "jpg"))
try:
if not target.exists():
data = _request(post["url"], timeout=60)
if len(data) < 100:
raise ValueError("empty file")
target.write_bytes(data)
time.sleep(0.25) # be polite
stem.with_suffix(".txt").write_text(sidecar_text(post, tags), encoding="utf-8")
result["saved"] += 1
except Exception:
failed += 1
result["failed"] = failed
return result