Download krita_plugins/ai_reference_board/board.py from cowpuncher/Krita_AI_Helper_Addons: direct link, hf CLI and curl.
- Browser
- Download file 52 kB
-
https://huggingface.co/datasets/cowpuncher/Krita_AI_Helper_Addons/resolve/main/krita_plugins/ai_reference_board/board.py
- Command line
-
hf download hf://datasets/cowpuncher/Krita_AI_Helper_Addons/krita_plugins/ai_reference_board/board.py
-
curl -L -o board.py https://huggingface.co/datasets/cowpuncher/Krita_AI_Helper_Addons/resolve/main/krita_plugins/ai_reference_board/board.py
52 kB
"""AI Reference Board: a Krita docker that turns images from a folder into AI Image Diffusion reference
control layers - the whole picture or just the part you drag out - without loading anything onto the canvas
by hand. Each image lives on a hidden layer in an "[AI References]" group and is linked as a control layer of
the AI plugin (so it also shows, and can be fine-tuned, in the AI docker). Off unlinks it but keeps the image;
Remove deletes the layer, and the AI plugin drops the control layer with it."""
from __future__ import annotations
import random
import time
from pathlib import Path
from types import SimpleNamespace
from krita import DockWidget, Krita # type: ignore
try:
from PyQt5.QtCore import QPoint, QRect, QSize, Qt, QThread, QTimer, QUrl, pyqtSignal
from PyQt5.QtGui import QColor, QDesktopServices, QIcon, QImage, QImageReader, QPainter, QPen, QPixmap
from PyQt5.QtWidgets import (
QApplication, QCheckBox, QComboBox, QDialog, QDialogButtonBox, QDoubleSpinBox, QFileDialog, QFormLayout, QHBoxLayout, QLabel,
QLineEdit, QListView, QListWidget, QListWidgetItem, QMessageBox, QPlainTextEdit, QPushButton, QSlider, QSpinBox,
QSplitter, QVBoxLayout, QWidget,
)
except ImportError: # Krita 6
from PyQt6.QtCore import QPoint, QRect, QSize, Qt, QThread, QTimer, QUrl, pyqtSignal
from PyQt6.QtGui import QColor, QDesktopServices, QIcon, QImage, QImageReader, QPainter, QPen, QPixmap
from PyQt6.QtWidgets import (
QApplication, QCheckBox, QComboBox, QDialog, QDialogButtonBox, QDoubleSpinBox, QFileDialog, QFormLayout, QHBoxLayout, QLabel,
QLineEdit, QListView, QListWidget, QListWidgetItem, QMessageBox, QPlainTextEdit, QPushButton, QSlider, QSpinBox,
QSplitter, QVBoxLayout, QWidget,
)
from . import grab as G
SETTINGS = "ai_reference_board"
GROUP_NAME = "[AI References]"
PREFIX = "[Ref] "
IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif", ".tif", ".tiff"}
THUMB = 96
# The AI plugin's image-reference (IP-Adapter) modes, plus a pose pulled out of the picture (works on Anima too)
MODES = ("reference", "style", "composition", "face", "pose")
RATING_CHOICES = (("General only", "general"), ("General + sensitive", "sensitive"),
("Any rating (adult included)", "any"), ("Adult only (questionable + explicit)", "adult"))
SOURCE_CHOICES = (("Danbooru", "danbooru"), ("Gelbooru (needs your login)", "gelbooru"))
ROLE = Qt.ItemDataRole.UserRole
PRESET_STEPS = 4 # the AI plugin's strength slider has positions 0 .. 4
# What each use does, per model family. "Anima" needs the Anima Reference add-on.
MODE_TIPS = {
"reference": "The picture as an image prompt (SDXL / Illustrious, edit styles).\n"
"Anima: the character in the picture. Two Reference pictures are the left and the right character.",
"style": "The picture's style (SDXL / Illustrious).\n"
"Anima: the character AND the art style of the picture.",
"composition": "The picture's layout (SDXL / Illustrious). Not available with Anima.",
"face": "The face in the picture (SDXL / Illustrious).\n"
"Anima: one more picture of the same character as the Reference or Style picture, up to 5 in total.",
"pose": "Finds the pose in the picture and adds it as a Pose control layer (a stick figure you can move). "
"Works on Anima too.",
}
def _plugin():
"""The AI Image Diffusion pieces this docker drives, or None when that plugin isn't loaded."""
try:
from ai_diffusion.backend.resources import ControlMode # type: ignore
from ai_diffusion.image import Bounds, Image # type: ignore
from ai_diffusion.layer import RestoreActiveLayer # type: ignore
from ai_diffusion.model.control import ControlPresets # type: ignore
from ai_diffusion.model.root import root # type: ignore
except Exception:
return None
return SimpleNamespace(root=root, ControlMode=ControlMode, ControlPresets=ControlPresets, Image=Image,
Bounds=Bounds, RestoreActiveLayer=RestoreActiveLayer)
def _pose_tools():
"""The AI plugin's own pose-detection path (what the control layer's generate button runs), fed our picture
instead of the canvas. Internal API of the plugin, so None if this version doesn't have it."""
try:
from ai_diffusion import eventloop # type: ignore
from ai_diffusion.backend import workflow # type: ignore
from ai_diffusion.model.model import _report_errors # type: ignore
except Exception:
return None
if not hasattr(workflow, "prepare_create_control_image"):
return None
return SimpleNamespace(eventloop=eventloop, workflow=workflow, report=_report_errors)
def _tag_files():
"""Danbooru's tag list as shipped with the AI plugin (used for aliases, tag kinds and post counts)."""
try:
import ai_diffusion # type: ignore
folder = Path(ai_diffusion.__file__).parent / "tags"
return [p for p in (folder / "Danbooru.csv", folder / "Danbooru NSFW.csv") if p.exists()]
except Exception:
return []
def _gelbooru_tag_files():
"""Gelbooru tag lists, if they are in the AI plugin's own tags folder (they are not shipped with it)."""
try:
from ai_diffusion.util import user_data_dir # type: ignore
folder = Path(user_data_dir) / "tags"
return [p for p in (folder / "Gelbooru.csv", folder / "Gelbooru NSFW.csv") if p.exists()]
except Exception:
return []
def parse_gelbooru_login(text: str):
"""(user id, api key) out of what Gelbooru shows as "API Access Credentials": &api_key=...&user_id=..."""
import re
key = re.search(r"api_key=([0-9A-Za-z]+)", text or "")
user = re.search(r"user_id=(\d+)", text or "")
return (user.group(1) if user else ""), (key.group(1) if key else "")
class GelbooruLoginDialog(QDialog):
"""Gelbooru's API only answers with an account's User ID and API key. Both are kept in Krita's settings."""
def __init__(self, user_id="", api_key="", parent=None):
super().__init__(parent)
self.setWindowTitle("Gelbooru login")
lay = QVBoxLayout(self)
info = QLabel(
"Gelbooru only answers searches that come with an account's User ID and API key (a free account will do).\n\n"
"1. Log in on gelbooru.com and open your account's Options page (button below).\n"
"2. Near the bottom is \"API Access Credentials\", a line like &api_key=...&user_id=...\n"
"3. Copy that whole line and paste it into the first box.\n\n"
"Both values are stored as plain text in Krita's settings on this computer and are sent to gelbooru.com only.")
info.setWordWrap(True)
lay.addWidget(info)
open_btn = QPushButton("Open my Gelbooru Options page")
open_btn.clicked.connect(lambda: QDesktopServices.openUrl(QUrl(G.GELBOORU_ACCOUNT_PAGE)))
lay.addWidget(open_btn)
form = QFormLayout()
self.paste_edit = QLineEdit()
self.paste_edit.setPlaceholderText("&api_key=...&user_id=...")
self.paste_edit.textChanged.connect(self._pasted)
self.user_edit = QLineEdit(user_id)
self.key_edit = QLineEdit(api_key)
self.key_edit.setEchoMode(QLineEdit.EchoMode.Password)
form.addRow("Paste the line here", self.paste_edit)
form.addRow("User ID", self.user_edit)
form.addRow("API key", self.key_edit)
lay.addLayout(form)
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
lay.addWidget(buttons)
def _pasted(self, text):
user_id, api_key = parse_gelbooru_login(text)
if user_id:
self.user_edit.setText(user_id)
if api_key:
self.key_edit.setText(api_key)
def values(self):
return self.user_edit.text().strip(), self.key_edit.text().strip()
def _grab_root() -> Path:
saved = _setting("grab_root")
return Path(saved) if saved else Path.home() / "Pictures" / "AI Reference Board"
class GrabWorker(QThread):
progress = pyqtSignal(str)
done = pyqtSignal(dict)
def __init__(self, text, rating, count, root, holder, source="danbooru", credentials=None, parent=None):
super().__init__(parent)
self.text, self.rating, self.count, self.root, self.holder = text, rating, count, root, holder
self.source, self.credentials = source, credentials
def run(self):
try:
# Danbooru searches keep using Danbooru's own list (its aliases, its spellings); Gelbooru searches
# use both lists, so Gelbooru spellings are known and its flat tag strings can be sorted by kind.
which = "taglist_all" if self.source == "gelbooru" else "taglist"
if self.holder.get(which) is None:
self.progress.emit("Loading the tag list ...")
files = list(self.holder.get("files", []))
if which == "taglist_all":
files += list(self.holder.get("gelbooru_files", []))
self.holder[which] = G.TagList(files)
result = G.grab(self.text, self.rating, self.count, self.root, self.holder[which], self.progress.emit,
source=self.source, credentials=self.credentials)
except Exception as e: # never leave the button dead
result = {"error": f"{type(e).__name__}: {e}"}
self.done.emit(result)
def _setting(name, default=""):
try:
return Krita.instance().readSetting(SETTINGS, name, default)
except Exception:
return default
def _save_setting(name, value):
try:
Krita.instance().writeSetting(SETTINGS, name, str(value))
except Exception:
pass
def _event_pos(e) -> QPoint:
return e.position().toPoint() if hasattr(e, "position") else e.pos()
class CropView(QWidget):
"""Shows the picked image. Drag a box to use only that part; double-click for the whole image again."""
def __init__(self, on_change, parent=None):
super().__init__(parent)
self.setMinimumHeight(160)
self._image: QImage | None = None
self._pix: QPixmap | None = None
self._crop: QRect | None = None # in image pixels; None = the whole image
self._drag_from: QPoint | None = None # in view pixels
self._before: QRect | None = None
self._on_change = on_change
def image(self):
return self._image
def crop(self):
return self._crop
def set_image(self, img: QImage | None):
self._image = img if img is not None and not img.isNull() else None
self._pix, self._crop = None, None
self.update()
self._on_change()
def reset_crop(self):
self._crop = None
self.update()
self._on_change()
def _target(self) -> QRect:
iw, ih = self._image.width(), self._image.height()
s = min(self.width() / iw, self.height() / ih)
w, h = max(1, int(iw * s)), max(1, int(ih * s))
return QRect((self.width() - w) // 2, (self.height() - h) // 2, w, h)
def _to_image(self, p: QPoint) -> QPoint:
t = self._target()
x = min(max(p.x(), t.left()), t.left() + t.width())
y = min(max(p.y(), t.top()), t.top() + t.height())
return QPoint(round((x - t.left()) * self._image.width() / t.width()),
round((y - t.top()) * self._image.height() / t.height()))
def _to_view(self, r: QRect) -> QRect:
t = self._target()
sx, sy = t.width() / self._image.width(), t.height() / self._image.height()
return QRect(t.left() + round(r.x() * sx), t.top() + round(r.y() * sy),
max(1, round(r.width() * sx)), max(1, round(r.height() * sy)))
def paintEvent(self, _event):
p = QPainter(self)
if self._image is None:
p.setPen(self.palette().mid().color())
p.drawText(self.rect(), Qt.AlignmentFlag.AlignCenter, "Click an image above")
return
t = self._target()
if self._pix is None or self._pix.size() != t.size():
self._pix = QPixmap.fromImage(self._image.scaled(
t.size(), Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation))
p.drawPixmap(t.topLeft(), self._pix)
if self._crop is not None:
v = self._to_view(self._crop)
shade = QColor(0, 0, 0, 150)
p.fillRect(QRect(t.left(), t.top(), t.width(), v.top() - t.top()), shade)
p.fillRect(QRect(t.left(), v.top() + v.height(), t.width(), t.top() + t.height() - v.top() - v.height()), shade)
p.fillRect(QRect(t.left(), v.top(), v.left() - t.left(), v.height()), shade)
p.fillRect(QRect(v.left() + v.width(), v.top(), t.left() + t.width() - v.left() - v.width(), v.height()), shade)
p.setPen(QPen(QColor(255, 255, 255), 1, Qt.PenStyle.DashLine))
p.drawRect(v.adjusted(0, 0, -1, -1))
def mousePressEvent(self, e):
if self._image is not None and e.button() == Qt.MouseButton.LeftButton:
self._drag_from = _event_pos(e)
self._before = self._crop
def mouseMoveEvent(self, e):
if self._drag_from is None:
return
pos = _event_pos(e)
box = QRect(self._drag_from, pos).normalized()
if box.width() >= 6 and box.height() >= 6:
self._crop = QRect(self._to_image(self._drag_from), self._to_image(pos)).normalized()
else: # too small to be a box yet: a click or a shaky hand keeps the box as it was
self._crop = self._before
self.update()
def mouseReleaseEvent(self, _e):
if self._drag_from is None:
return
self._drag_from = None
if self._crop is not None:
self._crop = self._crop.intersected(QRect(0, 0, self._image.width(), self._image.height()))
if self._crop.isEmpty():
self._crop = None
self.update()
self._on_change()
def mouseDoubleClickEvent(self, _e):
self.reset_crop()
class ReferenceBoardDocker(DockWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("AI Reference Board")
self._path: str | None = None
self._thumb_queue: list[int] = []
self._used_signature = None
self._parked: dict[str, tuple] = {} # settings of references switched off, to restore on On
self._hidden_by_off: set[str] = set() # visible layers (a pose) hidden while off, shown again on On
self._pending_pose: dict[str, tuple] = {} # source layer key -> (control, source layer, name, started)
self._tag_holder = {"files": _tag_files(), "gelbooru_files": _gelbooru_tag_files(), "taglist": None, "taglist_all": None}
self._worker: GrabWorker | None = None
self._tags_text = ""
body = QWidget()
self.setWidget(body)
lay = QVBoxLayout(body)
lay.setContentsMargins(4, 4, 4, 4)
row = QHBoxLayout()
self.folder_edit = QLineEdit(_setting("folder"))
self.folder_edit.setPlaceholderText("Folder with reference images")
self.folder_edit.editingFinished.connect(self.scan)
browse = QPushButton("Folder ...")
browse.clicked.connect(self.browse)
refresh = QPushButton("Reload")
refresh.clicked.connect(self.scan)
row.addWidget(self.folder_edit, 1)
row.addWidget(browse)
row.addWidget(refresh)
lay.addLayout(row)
self.sub_check = QCheckBox("Include subfolders")
self.sub_check.setChecked(_setting("subfolders", "false") == "true")
self.sub_check.toggled.connect(self.scan)
lay.addWidget(self.sub_check)
grab_row = QHBoxLayout()
self.grab_edit = QLineEdit(_setting("grab_tags"))
self.grab_edit.setPlaceholderText("Grab by tags, e.g. index finger raised")
self.grab_edit.setToolTip("Comma-separated tags, written like in a prompt. -tag leaves a tag out.")
self.grab_edit.returnPressed.connect(self.grab)
self.grab_btn = QPushButton("Grab")
self.grab_btn.setToolTip(f"Saves into {_grab_root()}\\<tags>, each picture with a .txt of its tags")
self.grab_btn.clicked.connect(self.grab)
grab_row.addWidget(self.grab_edit, 1)
grab_row.addWidget(self.grab_btn)
lay.addLayout(grab_row)
grab_opts = QHBoxLayout()
self.rating_combo = QComboBox()
for label, key in RATING_CHOICES:
self.rating_combo.addItem(label, key)
self.rating_combo.setCurrentIndex(max(0, self.rating_combo.findData(_setting("grab_rating", "general"))))
self.rating_combo.currentIndexChanged.connect(lambda *_: _save_setting("grab_rating", self.rating_combo.currentData()))
self.count_spin = QSpinBox()
self.count_spin.setRange(2, 60)
self.count_spin.setSuffix(" pictures")
self.count_spin.setValue(int(_setting("grab_count", "12") or 12))
self.count_spin.valueChanged.connect(lambda v: _save_setting("grab_count", v))
grab_opts.addWidget(self.rating_combo, 1)
grab_opts.addWidget(self.count_spin)
lay.addLayout(grab_opts)
source_row = QHBoxLayout()
self.source_combo = QComboBox()
for label, key in SOURCE_CHOICES:
self.source_combo.addItem(label, key)
self.source_combo.setToolTip("Danbooru: no login needed; Safebooru steps in when it is down.\n"
"Gelbooru: the site Anima's tags follow. Its search only answers with your account's "
"User ID and API key.")
self.source_combo.setCurrentIndex(max(0, self.source_combo.findData(_setting("grab_source", "danbooru"))))
self.login_btn = QPushButton("Gelbooru login ...")
self.login_btn.clicked.connect(self.gelbooru_login)
self.source_combo.currentIndexChanged.connect(self.source_changed)
source_row.addWidget(QLabel("From"))
source_row.addWidget(self.source_combo, 1)
source_row.addWidget(self.login_btn)
lay.addLayout(source_row)
self.login_btn.setEnabled(self.source_combo.currentData() == "gelbooru")
self.thumbs = QListWidget()
self.thumbs.setViewMode(QListView.ViewMode.IconMode)
self.thumbs.setIconSize(QSize(THUMB, THUMB))
self.thumbs.setGridSize(QSize(THUMB + 14, THUMB + 30))
self.thumbs.setResizeMode(QListView.ResizeMode.Adjust)
self.thumbs.setMovement(QListView.Movement.Static)
self.thumbs.setUniformItemSizes(True)
self.thumbs.setWordWrap(True)
self.thumbs.currentItemChanged.connect(self.pick)
self.crop_view = CropView(self.crop_changed)
self.tags_widget = QWidget() # the picked picture's tags, when it has a .txt next to it
tags_lay = QHBoxLayout(self.tags_widget)
tags_lay.setContentsMargins(0, 0, 0, 0)
self.tags_box = QPlainTextEdit()
self.tags_box.setReadOnly(True)
self.tags_box.setMinimumHeight(40)
copy_tags = QPushButton("Copy\ntags")
copy_tags.setToolTip("Copies the picture's tags, ready to paste into a prompt")
copy_tags.clicked.connect(self.copy_tags)
tags_lay.addWidget(self.tags_box, 1)
tags_lay.addWidget(copy_tags)
self.tags_widget.hide()
split = QSplitter(Qt.Orientation.Vertical)
split.addWidget(self.thumbs)
split.addWidget(self.crop_view)
split.addWidget(self.tags_widget)
split.setStretchFactor(0, 3)
split.setStretchFactor(1, 2)
split.setStretchFactor(2, 0)
split.setSizes([260, 200, 90])
lay.addWidget(split, 1)
crop_row = QHBoxLayout()
self.crop_label = QLabel("")
self.crop_label.setWordWrap(True)
whole = QPushButton("Whole image")
whole.clicked.connect(self.crop_view.reset_crop)
crop_row.addWidget(self.crop_label, 1)
crop_row.addWidget(whole)
lay.addLayout(crop_row)
form = QFormLayout()
self.mode_combo = QComboBox()
# Strength: the same five-position slider the AI docker has. A reference added this way keeps a
# live slider there. "Exact values" is the other way: a typed strength and range, which the AI docker
# shows as "Use custom values" (its slider is then switched off until that box is unticked).
self.preset = QSlider(Qt.Orientation.Horizontal)
self.preset.setRange(0, PRESET_STEPS)
self.preset.setPageStep(1)
self.preset.setTickPosition(QSlider.TickPosition.TicksBelow)
self.preset.setTickInterval(1)
self.preset.setToolTip("Same as the slider on the control layer in the AI docker; you can still move that one afterwards.")
self.preset_label = QLabel("")
preset_row = QHBoxLayout()
preset_row.addWidget(self.preset, 1)
preset_row.addWidget(self.preset_label)
self.exact_check = QCheckBox("Exact values")
self.exact_check.setToolTip("Type the strength and range yourself. The AI docker then shows the control layer with "
"'Use custom values' ticked, and its own slider is off until you untick that.")
self.strength = QDoubleSpinBox()
self.strength.setRange(0.0, 2.0)
self.strength.setSingleStep(0.02) # the AI plugin stores strength in steps of 0.02
self.start = QDoubleSpinBox()
self.end = QDoubleSpinBox()
for spin in (self.start, self.end):
spin.setRange(0.0, 1.0)
spin.setSingleStep(0.05)
self.exact_widget = QWidget()
exact_row = QHBoxLayout(self.exact_widget)
exact_row.setContentsMargins(0, 0, 0, 0)
exact_row.addWidget(self.strength)
exact_row.addWidget(QLabel("range"))
exact_row.addWidget(self.start)
exact_row.addWidget(QLabel("to"))
exact_row.addWidget(self.end)
form.addRow("Use as", self.mode_combo)
form.addRow("Strength", preset_row)
form.addRow(self.exact_check, self.exact_widget)
lay.addLayout(form)
self.add_btn = QPushButton("Add as reference")
self.add_btn.clicked.connect(self.add_reference)
lay.addWidget(self.add_btn)
lay.addWidget(QLabel("References in this document:"))
self.used = QListWidget()
self.used.setMaximumHeight(130)
self.used.currentItemChanged.connect(self.load_selected)
lay.addWidget(self.used)
used_btns = QHBoxLayout()
b_apply = QPushButton("Apply")
b_apply.setToolTip("Give the selected reference the Use as / Strength set above")
b_toggle = QPushButton("On / Off")
b_toggle.setToolTip("Off unlinks it from the AI plugin but keeps the image; On links it again with the settings it had")
b_remove = QPushButton("Remove")
b_clear = QPushButton("Remove all")
b_apply.clicked.connect(self.apply_selected)
b_toggle.clicked.connect(self.toggle_selected)
b_remove.clicked.connect(self.remove_selected)
b_clear.clicked.connect(self.remove_all)
for b in (b_apply, b_toggle, b_remove, b_clear):
used_btns.addWidget(b)
lay.addLayout(used_btns)
self.status = QLabel("")
self.status.setWordWrap(True)
lay.addWidget(self.status)
self._fill_modes()
self.strength.setValue(float(_setting("strength", "0.6") or 0.6))
self.start.setValue(float(_setting("start", "0.0") or 0.0))
self.end.setValue(float(_setting("end", "1.0") or 1.0))
self.preset.setValue(min(PRESET_STEPS, max(0, int(_setting("preset", "2") or 2))))
self.exact_check.setChecked(_setting("exact", "false") == "true")
self.exact_widget.setEnabled(self.exact_check.isChecked())
self.preset.setEnabled(not self.exact_check.isChecked())
self.mode_combo.currentIndexChanged.connect(self.mode_changed)
self.preset.valueChanged.connect(self.preset_changed)
self.exact_check.toggled.connect(self.exact_toggled)
for spin, key in ((self.strength, "strength"), (self.start, "start"), (self.end, "end")):
spin.valueChanged.connect(lambda v, k=key: _save_setting(k, f"{v:.2f}"))
self._show_preset_values()
self._thumb_timer = QTimer(self)
self._thumb_timer.timeout.connect(self._load_some_thumbs)
self._used_timer = QTimer(self)
self._used_timer.timeout.connect(self.refresh_used)
self._used_timer.start(1000)
self.crop_changed()
if self.folder_edit.text().strip():
QTimer.singleShot(0, self.scan)
if _plugin() is None:
self.status.setText("AI Image Diffusion isn't loaded; this board only works alongside it.")
self.add_btn.setEnabled(False)
# ---- Krita
def canvasChanged(self, canvas):
self._used_signature = None
self.refresh_used()
# ---- folder and thumbnails
def browse(self):
folder = QFileDialog.getExistingDirectory(self, "Reference folder", self.folder_edit.text())
if folder:
self.folder_edit.setText(folder)
self.scan()
def scan(self, *_args):
text = self.folder_edit.text().strip()
_save_setting("folder", text)
_save_setting("subfolders", "true" if self.sub_check.isChecked() else "false")
self._thumb_timer.stop()
self.thumbs.clear()
self._thumb_queue = []
self._path = None
self.crop_view.set_image(None)
self.show_tags(None)
folder = Path(text)
if not text or not folder.is_dir():
self.status.setText("Pick a folder with images.")
return
files = folder.rglob("*") if self.sub_check.isChecked() else folder.iterdir()
paths = sorted((p for p in files if p.is_file() and p.suffix.lower() in IMAGE_EXTS), key=lambda p: str(p).lower())
for p in paths:
label = str(p.relative_to(folder)) if self.sub_check.isChecked() else p.name
item = QListWidgetItem(label if len(label) <= 18 else label[:16] + "...")
item.setData(ROLE, str(p))
item.setToolTip(str(p))
item.setSizeHint(QSize(THUMB + 12, THUMB + 28)) # room for the thumbnail, which loads a moment later
self.thumbs.addItem(item)
self._thumb_queue = list(range(len(paths)))
self._thumb_timer.start(0)
self.status.setText(f"{len(paths)} image(s).")
def _load_some_thumbs(self):
for _ in range(6):
if not self._thumb_queue:
self._thumb_timer.stop()
return
item = self.thumbs.item(self._thumb_queue.pop(0))
if item is None:
continue
reader = QImageReader(item.data(ROLE))
reader.setAutoTransform(True)
size = reader.size()
if size.isValid():
size.scale(THUMB, THUMB, Qt.AspectRatioMode.KeepAspectRatio)
reader.setScaledSize(size)
img = reader.read()
if not img.isNull():
item.setIcon(QIcon(QPixmap.fromImage(img)))
def pick(self, item, _previous=None):
if item is None:
return
self._path = item.data(ROLE)
reader = QImageReader(self._path)
reader.setAutoTransform(True)
img = reader.read()
if img.isNull():
self.status.setText(f"Couldn't read {Path(self._path).name}: {reader.errorString()}")
self.crop_view.set_image(img)
self.show_tags(G.read_sidecar(self._path))
def show_tags(self, info):
self._tags_text = (info or {}).get("tags", "")
if not self._tags_text:
self.tags_widget.hide()
return
lines = [self._tags_text] + [f"{k}: {info[k]}" for k in ("character", "copyright", "artist") if info.get(k)]
self.tags_box.setPlainText("\n".join(lines))
self.tags_widget.show()
QTimer.singleShot(0, lambda: self.tags_box.verticalScrollBar().setValue(0)) # start at the searched tags
def copy_tags(self):
if self._tags_text:
QApplication.clipboard().setText(self._tags_text)
self.status.setText("Tags copied. Paste them into the prompt, then cut what you don't want.")
# ---- grabbing pictures for a tag
def grab(self):
if self._worker is not None:
return
text = self.grab_edit.text().strip()
if not text:
self.status.setText("Type a tag to grab, e.g. index finger raised.")
return
_save_setting("grab_tags", text)
source, credentials = self.source_combo.currentData(), None
if source == "gelbooru":
credentials = self._gelbooru_credentials()
if not all(credentials) and not self.gelbooru_login():
self.status.setText("Gelbooru needs your User ID and API key first (button 'Gelbooru login ...').")
return
credentials = self._gelbooru_credentials()
self.grab_btn.setEnabled(False)
self._worker = GrabWorker(text, self.rating_combo.currentData(), self.count_spin.value(), _grab_root(),
self._tag_holder, source, credentials, self)
self._worker.progress.connect(self.status.setText)
self._worker.done.connect(self.grab_done)
self._worker.start()
def source_changed(self, *_args):
_save_setting("grab_source", self.source_combo.currentData())
self.login_btn.setEnabled(self.source_combo.currentData() == "gelbooru")
@staticmethod
def _gelbooru_credentials():
return _setting("gelbooru_user_id", "").strip(), _setting("gelbooru_api_key", "").strip()
def gelbooru_login(self) -> bool:
"""Ask for the Gelbooru User ID and API key. True when both are filled in afterwards."""
dialog = GelbooruLoginDialog(*self._gelbooru_credentials(), parent=self)
run = getattr(dialog, "exec", None) or dialog.exec_
if not run():
return False
user_id, api_key = dialog.values()
_save_setting("gelbooru_user_id", user_id)
_save_setting("gelbooru_api_key", api_key)
return bool(user_id and api_key)
def grab_done(self, r: dict):
if self._worker is not None:
self._worker.wait(2000)
self._worker = None
self.grab_btn.setEnabled(True)
if r.get("error"):
self.status.setText(r["error"])
return
notes = []
if r.get("notes"):
notes.append("Read as: " + "; ".join(r["notes"]) + ".")
if r.get("down"):
notes.append("Danbooru didn't answer, so these come from Safebooru (safe pictures only).")
if r.get("source") == "Gelbooru" and not self._tag_holder.get("gelbooru_files"):
notes.append("No Gelbooru tag list is installed, so character and artist tags may be listed among the plain tags.")
rare = [f"{t.replace('_', ' ')} ({n} posts)" for t, n in r.get("counts", {}).items() if n < 1000]
if rare:
notes.append("Rare tag: " + ", ".join(rare) + ". Models barely learned it, so a picture beats the tag.")
if r.get("failed"):
notes.append(f"{r['failed']} download(s) failed.")
if r.get("saved"):
self.folder_edit.setText(r["folder"])
self.scan()
self.status.setText((f"Grabbed {r['saved']} from {r['source']}. " + " ".join(notes)).strip())
return
tried = ", ".join(t.replace("_", " ") for t in r.get("tags", []))
close = []
for lst in (r.get("suggestions") or {}).values():
close += [s for s in lst if s not in close]
hint = (" Real tags close to it: " + ", ".join(s.replace("_", " ") for s in close[:6]) + ".") if close else ""
self.status.setText((f"Nothing found for {tried} on {r.get('source', 'Danbooru')}.{hint} " + " ".join(notes)).strip())
def crop_changed(self):
img, crop = self.crop_view.image(), self.crop_view.crop()
if img is None:
self.crop_label.setText("")
elif crop is None:
self.crop_label.setText(f"Using the whole image ({img.width()}x{img.height()}). Drag on it to use only a part.")
else:
self.crop_label.setText(f"Using a {crop.width()}x{crop.height()} part. Double-click for the whole image.")
# ---- modes and their defaults
def _fill_modes(self):
P = _plugin()
saved = _setting("mode", "reference")
self.mode_combo.blockSignals(True)
for name in MODES:
label = name.title()
if P is not None:
try:
label = getattr(P.ControlMode, name).text
except Exception:
pass
if name == "pose":
label += " (from picture)"
self.mode_combo.addItem(label, name)
for index, name in enumerate(MODES):
self.mode_combo.setItemData(index, MODE_TIPS[name], Qt.ItemDataRole.ToolTipRole)
idx = self.mode_combo.findData(saved)
self.mode_combo.setCurrentIndex(idx if idx >= 0 else 0)
self.mode_combo.blockSignals(False)
def _preset_values(self, mode: str, position: int):
"""(strength, start, end) the AI plugin gives this use at this slider position with the current style."""
P = _plugin()
try:
params = P.ControlPresets.instance().interpolate(getattr(P.ControlMode, mode), P.root.active_model.arch,
position / PRESET_STEPS)
return float(params.strength), float(params.range[0]), float(params.range[1])
except Exception:
return None
def _show_preset_values(self):
values = self._preset_values(self.mode_combo.currentData(), self.preset.value())
text = f"{self.preset.value() + 1} of {PRESET_STEPS + 1}"
if values is not None:
text += f" ({values[0]:.2f}, {values[1]:.2f}-{values[2]:.2f})"
self.preset_label.setText(text)
def preset_changed(self, value):
_save_setting("preset", value)
self._show_preset_values()
def exact_toggled(self, on):
_save_setting("exact", "true" if on else "false")
self.exact_widget.setEnabled(on)
self.preset.setEnabled(not on)
if on: # start typing from what the slider stood for
values = self._preset_values(self.mode_combo.currentData(), self.preset.value())
if values is not None:
self.strength.setValue(values[0])
self.start.setValue(values[1])
self.end.setValue(values[2])
def mode_changed(self, *_args):
name = self.mode_combo.currentData()
_save_setting("mode", name)
self._show_preset_values()
if not self.exact_check.isChecked():
return
values = self._preset_values(name, 2) # exact values start from the AI plugin's own default for this use
if values is not None:
self.strength.setValue(values[0])
self.start.setValue(values[1])
self.end.setValue(values[2])
# ---- the document side
def _context(self):
P = _plugin()
if P is None or Krita.instance().activeDocument() is None:
return None, None
return P, P.root.active_model
def _group(self, P, model, create=False):
for layer in model.layers.all:
if layer.type.name == "group" and layer.name == GROUP_NAME:
return layer
if not create:
return None
with P.RestoreActiveLayer(model.layers):
group = model.layers.create_group(GROUP_NAME)
group.hide()
return group
def _control_lists(self, model):
lists = [model.regions.control]
if getattr(model, "edit_regions", None) is not None:
lists.append(model.edit_regions.control)
return lists
def _control_for(self, model, layer):
for controls in self._control_lists(model):
for c in controls:
if c.layer_id == layer.id:
return controls, c
return None, None
@staticmethod
def _key(layer) -> str:
return layer.id.toString() if hasattr(layer.id, "toString") else str(layer.id)
@staticmethod
def _settings_of(control):
"""(use, exact values?, slider position, strength, range start, range end) of a linked reference."""
return (control.mode.name, bool(control.use_custom_strength), int(control.preset_value),
control.strength / control.strength_multiplier, control.start, control.end)
def _panel_settings(self):
return (self.mode_combo.currentData(), self.exact_check.isChecked(), self.preset.value(),
self.strength.value(), self.start.value(), self.end.value())
def _show_settings(self, settings):
mode, exact, preset, strength, start, end = settings
idx = self.mode_combo.findData(mode)
if idx >= 0:
self.mode_combo.blockSignals(True) # keep these values, not the mode's defaults
self.mode_combo.setCurrentIndex(idx)
self.mode_combo.blockSignals(False)
_save_setting("mode", mode)
self.exact_check.blockSignals(True) # show the reference as it is; ticking the box by hand loads defaults
self.exact_check.setChecked(exact)
self.exact_check.blockSignals(False)
self.exact_widget.setEnabled(exact)
self.preset.setEnabled(not exact)
self.preset.setValue(min(PRESET_STEPS, max(0, preset)))
self.strength.setValue(strength)
self.start.setValue(start)
self.end.setValue(end)
self._show_preset_values()
def _apply(self, P, control, settings):
mode, exact, preset, strength, start, end = settings
if exact:
control.use_custom_strength = True # first, so the mode change doesn't load the preset over it
control.mode = getattr(P.ControlMode, mode)
control.strength = int(round(strength * control.strength_multiplier))
control.start = start
control.end = max(end, start)
else:
# The AI plugin's own way: a slider position. Its slider on the control layer stays live, so the
# strength can be changed there without unticking anything.
control.use_custom_strength = False
control.mode = getattr(P.ControlMode, mode)
control.preset_value = min(control.max_preset_value, max(0, int(preset)))
values = self._preset_values(mode, control.preset_value)
if values is not None: # also when neither the use nor the position changed (a new control layer)
control.strength = int(values[0] * control.strength_multiplier)
control.start, control.end = values[1], values[2]
if not control.is_supported:
self.status.setText(f"Linked, but the current style can't use it: {control.error_text}. Reference images need "
"an SDXL/Illustrious style, an edit style, or for Anima the Anima Reference add-on.")
def _attach(self, P, model, layer, settings=None):
"""Link the layer to the AI plugin as a control layer, with the given (mode, strength, start, end)
or else the settings in the panel."""
control = model.active_regions.control.emplace()
control.layer_id = layer.id
self._apply(P, control, settings or self._panel_settings())
return control
def add_reference(self):
P, model = self._context()
if model is None:
self.status.setText("Open a document first.")
return
img = self.crop_view.image()
if img is None or not self._path:
self.status.setText("Click an image first.")
return
ok, msg = model.document.check_color_mode()
if not ok:
self.status.setText(msg or "This document's color mode isn't supported.")
return
crop = self.crop_view.crop()
part = img.copy(crop) if crop is not None else img
if self.mode_combo.currentData() == "pose":
self._add_pose(P, model, part, Path(self._path).name + (" (part)" if crop is not None else ""))
return
ext = model.document.extent
if part.width() > ext.width or part.height() > ext.height: # layers are cut at the canvas edge
part = part.scaled(ext.width, ext.height, Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation)
part = part.convertToFormat(QImage.Format.Format_ARGB32)
group = self._group(P, model, create=True)
name = PREFIX + Path(self._path).name + (" (part)" if crop is not None else "")
layer = model.layers.create(name, P.Image(part), P.Bounds(0, 0, part.width(), part.height()),
make_active=False, parent=group)
layer.hide()
control = self._attach(P, model, layer)
if control.is_supported:
self.status.setText(f"Added {name[len(PREFIX):]} as {self.mode_combo.currentText()}.")
self._used_signature = None
self.refresh_used()
# ---- a pose pulled out of the picture
def _add_pose(self, P, model, part: QImage, label: str):
tools = _pose_tools()
client = P.root.connection.client_if_connected
if tools is None:
self.status.setText("This version of the AI plugin doesn't let the board run pose detection.")
return
if client is None:
self.status.setText("Connect to the server first (AI Image Generation docker).")
return
ext = model.document.extent
canvas = QImage(ext.width, ext.height, QImage.Format.Format_ARGB32)
canvas.fill(QColor(255, 255, 255))
fit = part.scaled(ext.width, ext.height, Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation)
painter = QPainter(canvas)
painter.drawImage((ext.width - fit.width()) // 2, (ext.height - fit.height()) // 2, fit)
painter.end()
# never the exact same picture twice: a cached run gives the plugin no result to make a layer from
canvas.setPixelColor(0, 0, QColor(255, 255, random.randint(235, 254)))
group = self._group(P, model, create=True)
bounds = P.Bounds(0, 0, ext.width, ext.height)
src = model.layers.create(PREFIX + label + " (finding pose)", P.Image(canvas), bounds, make_active=False,
parent=group)
src.hide()
control = self._attach(P, model, src)
try:
inp = tools.workflow.prepare_create_control_image(P.Image(canvas), control.mode,
model._performance_settings(client), None)
job = model.jobs.add_control(control, bounds)
control._generate_job = job
control.has_active_job = True
tools.eventloop.run(tools.report(model, model._enqueue_job(job, inp)))
except Exception as e:
self._remove(P, model, src)
self._drop_empty_group(P, model)
self.status.setText(f"Couldn't start pose detection: {e}")
return
self._pending_pose[self._key(src)] = (control, src, PREFIX + label + " (pose)", time.time())
if control.is_supported:
self.status.setText("Finding the pose ...")
self._used_signature = None
self.refresh_used()
def _check_pending(self, P, model):
"""When the plugin has made the pose layer: name it, drop the source picture."""
for key, (control, src, name, started) in list(self._pending_pose.items()):
alive = any(c is control for lst in self._control_lists(model) for c in lst)
if not alive: # removed meanwhile
self._pending_pose.pop(key)
continue
if control.layer_id != src.id:
layer = model.layers.find(control.layer_id)
if layer is None:
continue
self._pending_pose.pop(key)
if layer.name.startswith("[Control]"):
layer.name = name
src.remove()
self._drop_empty_group(P, model)
self.status.setText("Pose ready. It's an editable stick figure: move it or its joints to place "
"the character. It isn't painted into the picture.")
else: # not the layer we asked for (a cached run links the active layer): undo
control.layer_id = src.id
self._remove(P, model, src)
self._drop_empty_group(P, model)
self.status.setText("Pose detection gave nothing back. Try again.")
self._used_signature = None
elif (not control.has_active_job and time.time() - started > 3) or time.time() - started > 180:
self._pending_pose.pop(key)
self._remove(P, model, src)
self._drop_empty_group(P, model)
self.status.setText("Pose detection didn't finish. The AI docker shows the error.")
self._used_signature = None
# ---- references already in the document
def _ref_layers(self, model, P):
"""Everything the board added: the hidden pictures in its group, and pose layers wherever they are."""
return [l for l in model.layers.all if l.name.startswith(PREFIX)]
def refresh_used(self):
P, model = self._context()
self._show_preset_values() # the numbers behind a slider position depend on the style in use
rows = []
if model is not None:
if self._pending_pose:
self._check_pending(P, model)
for layer in self._ref_layers(model, P):
_, c = self._control_for(model, layer)
rows.append((self._key(layer), layer.name, None if c is None else
(c.mode.text, c.strength / c.strength_multiplier, c.start, c.end, c.is_supported,
bool(c.use_custom_strength))))
signature = tuple(rows)
if signature == self._used_signature:
return
self._used_signature = signature
keep = self.used.currentItem().data(ROLE) if self.used.currentItem() else None
self.used.blockSignals(True) # a rebuild isn't the user picking a row
self.used.clear()
for key, name, info in rows:
text = name[len(PREFIX):] if name.startswith(PREFIX) else name
if info is None:
text += " (off)"
else:
mode, strength, start, end, supported, exact = info
text += (f" {mode} {strength:.2f}, {start:.2f}-{end:.2f}" + (" (exact)" if exact else "")
+ ("" if supported else " (not usable with this style)"))
item = QListWidgetItem(text)
item.setData(ROLE, key)
item.setToolTip(text)
self.used.addItem(item)
if keep is not None and key == keep:
self.used.setCurrentItem(item)
self.used.blockSignals(False)
def _selected_layer(self):
P, model = self._context()
item = self.used.currentItem()
if model is None or item is None:
return P, model, None
key = item.data(ROLE)
layer = next((l for l in self._ref_layers(model, P) if self._key(l) == key), None)
return P, model, layer
def load_selected(self, item, _previous=None):
"""Picking a reference in the list shows its settings above, ready to change and Apply."""
if item is None:
return
P, model, layer = self._selected_layer()
if layer is None:
return
_, control = self._control_for(model, layer)
settings = self._settings_of(control) if control is not None else self._parked.get(self._key(layer))
if settings is not None:
self._show_settings(settings)
def apply_selected(self):
P, model, layer = self._selected_layer()
if layer is None:
self.status.setText("Select a reference in the list first.")
return
_, control = self._control_for(model, layer)
if control is None: # it was off: this switches it on with the new settings
self._parked.pop(self._key(layer), None)
control = self._attach(P, model, layer)
else:
self._apply(P, control, self._panel_settings())
if control.is_supported:
self.status.setText("Applied to the selected reference.")
self._used_signature = None
self.refresh_used()
def toggle_selected(self):
P, model, layer = self._selected_layer()
if layer is None:
self.status.setText("Select a reference in the list first.")
return
controls, control = self._control_for(model, layer)
key = self._key(layer)
if control is not None:
self._parked[key] = self._settings_of(control)
controls.remove(control)
if layer.is_visible: # a pose layer: unlinked it would be painted into the picture, so hide it
layer.hide()
self._hidden_by_off.add(key)
self.status.setText("Off: the image stays in the document, unused.")
else:
parked = self._parked.pop(key, None) # back on with the settings it had, else the ones above
if key in self._hidden_by_off:
self._hidden_by_off.discard(key)
layer.show()
control = self._attach(P, model, layer, parked)
if control.is_supported:
self.status.setText("On again" + (" with its previous settings." if parked else ", with the settings above."))
self._used_signature = None
self.refresh_used()
def _remove(self, P, model, layer):
controls, control = self._control_for(model, layer)
if control is not None:
controls.remove(control)
layer.remove()
def _drop_empty_group(self, P, model):
group = self._group(P, model)
if group is not None and not group.child_layers:
group.remove()
def remove_selected(self):
P, model, layer = self._selected_layer()
if layer is None:
self.status.setText("Select a reference in the list first.")
return
self._remove(P, model, layer)
self._drop_empty_group(P, model)
self._used_signature = None
self.refresh_used()
def remove_all(self):
P, model = self._context()
if model is None:
return
layers = self._ref_layers(model, P)
if not layers:
return
answer = QMessageBox.question(self, "Remove all references",
f"Remove all {len(layers)} reference image(s) from this document?")
if answer != QMessageBox.StandardButton.Yes:
return
for layer in layers:
self._remove(P, model, layer)
self._drop_empty_group(P, model)
self._used_signature = None
self.refresh_used()
"""AI Reference Board: a Krita docker that turns images from a folder into AI Image Diffusion reference
control layers - the whole picture or just the part you drag out - without loading anything onto the canvas
by hand. Each image lives on a hidden layer in an "[AI References]" group and is linked as a control layer of
the AI plugin (so it also shows, and can be fine-tuned, in the AI docker). Off unlinks it but keeps the image;
Remove deletes the layer, and the AI plugin drops the control layer with it."""
from __future__ import annotations
import random
import time
from pathlib import Path
from types import SimpleNamespace
from krita import DockWidget, Krita # type: ignore
try:
from PyQt5.QtCore import QPoint, QRect, QSize, Qt, QThread, QTimer, QUrl, pyqtSignal
from PyQt5.QtGui import QColor, QDesktopServices, QIcon, QImage, QImageReader, QPainter, QPen, QPixmap
from PyQt5.QtWidgets import (
QApplication, QCheckBox, QComboBox, QDialog, QDialogButtonBox, QDoubleSpinBox, QFileDialog, QFormLayout, QHBoxLayout, QLabel,
QLineEdit, QListView, QListWidget, QListWidgetItem, QMessageBox, QPlainTextEdit, QPushButton, QSlider, QSpinBox,
QSplitter, QVBoxLayout, QWidget,
)
except ImportError: # Krita 6
from PyQt6.QtCore import QPoint, QRect, QSize, Qt, QThread, QTimer, QUrl, pyqtSignal
from PyQt6.QtGui import QColor, QDesktopServices, QIcon, QImage, QImageReader, QPainter, QPen, QPixmap
from PyQt6.QtWidgets import (
QApplication, QCheckBox, QComboBox, QDialog, QDialogButtonBox, QDoubleSpinBox, QFileDialog, QFormLayout, QHBoxLayout, QLabel,
QLineEdit, QListView, QListWidget, QListWidgetItem, QMessageBox, QPlainTextEdit, QPushButton, QSlider, QSpinBox,
QSplitter, QVBoxLayout, QWidget,
)
from . import grab as G
SETTINGS = "ai_reference_board"
GROUP_NAME = "[AI References]"
PREFIX = "[Ref] "
IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif", ".tif", ".tiff"}
THUMB = 96
# The AI plugin's image-reference (IP-Adapter) modes, plus a pose pulled out of the picture (works on Anima too)
MODES = ("reference", "style", "composition", "face", "pose")
RATING_CHOICES = (("General only", "general"), ("General + sensitive", "sensitive"),
("Any rating (adult included)", "any"), ("Adult only (questionable + explicit)", "adult"))
SOURCE_CHOICES = (("Danbooru", "danbooru"), ("Gelbooru (needs your login)", "gelbooru"))
ROLE = Qt.ItemDataRole.UserRole
PRESET_STEPS = 4 # the AI plugin's strength slider has positions 0 .. 4
# What each use does, per model family. "Anima" needs the Anima Reference add-on.
MODE_TIPS = {
"reference": "The picture as an image prompt (SDXL / Illustrious, edit styles).\n"
"Anima: the character in the picture. Two Reference pictures are the left and the right character.",
"style": "The picture's style (SDXL / Illustrious).\n"
"Anima: the character AND the art style of the picture.",
"composition": "The picture's layout (SDXL / Illustrious). Not available with Anima.",
"face": "The face in the picture (SDXL / Illustrious).\n"
"Anima: one more picture of the same character as the Reference or Style picture, up to 5 in total.",
"pose": "Finds the pose in the picture and adds it as a Pose control layer (a stick figure you can move). "
"Works on Anima too.",
}
def _plugin():
"""The AI Image Diffusion pieces this docker drives, or None when that plugin isn't loaded."""
try:
from ai_diffusion.backend.resources import ControlMode # type: ignore
from ai_diffusion.image import Bounds, Image # type: ignore
from ai_diffusion.layer import RestoreActiveLayer # type: ignore
from ai_diffusion.model.control import ControlPresets # type: ignore
from ai_diffusion.model.root import root # type: ignore
except Exception:
return None
return SimpleNamespace(root=root, ControlMode=ControlMode, ControlPresets=ControlPresets, Image=Image,
Bounds=Bounds, RestoreActiveLayer=RestoreActiveLayer)
def _pose_tools():
"""The AI plugin's own pose-detection path (what the control layer's generate button runs), fed our picture
instead of the canvas. Internal API of the plugin, so None if this version doesn't have it."""
try:
from ai_diffusion import eventloop # type: ignore
from ai_diffusion.backend import workflow # type: ignore
from ai_diffusion.model.model import _report_errors # type: ignore
except Exception:
return None
if not hasattr(workflow, "prepare_create_control_image"):
return None
return SimpleNamespace(eventloop=eventloop, workflow=workflow, report=_report_errors)
def _tag_files():
"""Danbooru's tag list as shipped with the AI plugin (used for aliases, tag kinds and post counts)."""
try:
import ai_diffusion # type: ignore
folder = Path(ai_diffusion.__file__).parent / "tags"
return [p for p in (folder / "Danbooru.csv", folder / "Danbooru NSFW.csv") if p.exists()]
except Exception:
return []
def _gelbooru_tag_files():
"""Gelbooru tag lists, if they are in the AI plugin's own tags folder (they are not shipped with it)."""
try: