Buckets:
| """LoRA Trigger Picker: a Krita extension that reads AI Image Diffusion's LoRA list, looks each file up | |
| on Civitai by hash, and writes the trigger words you tick straight into the plugin's LoRA database | |
| (through the plugin's own API, so the change shows up in its style settings immediately). | |
| The Checkpoints tab does the same lookup for checkpoints / diffusion models (Civitai + Hugging Face), mines the | |
| recommended positive / negative prompts and settings from the pages, and can save them as a new style. | |
| 1.2: folder dropdown and search over the LoRA list; ticking words adds to what is already set instead of | |
| replacing it; Undo for the last write; automatic snapshots of every LoRA's trigger words with a Restore button; | |
| Clear asks first; failed lookups are retried instead of remembered as "not found"; the style page's trigger box | |
| is refreshed after a write.""" | |
| import re | |
| import time | |
| from pathlib import Path | |
| from krita import Extension # type: ignore | |
| try: | |
| from PyQt5.QtCore import Qt, QThread, QUrl, pyqtSignal | |
| from PyQt5.QtGui import QDesktopServices | |
| from PyQt5.QtWidgets import ( | |
| QApplication, QCheckBox, QComboBox, QDialog, QGroupBox, QHBoxLayout, QInputDialog, QLabel, QLineEdit, | |
| QListWidget, QListWidgetItem, QMessageBox, QPlainTextEdit, QPushButton, QScrollArea, QTabWidget, | |
| QVBoxLayout, QWidget, | |
| ) | |
| except ImportError: # Krita 6 | |
| from PyQt6.QtCore import Qt, QThread, QUrl, pyqtSignal | |
| from PyQt6.QtGui import QDesktopServices | |
| from PyQt6.QtWidgets import ( | |
| QApplication, QCheckBox, QComboBox, QDialog, QGroupBox, QHBoxLayout, QInputDialog, QLabel, QLineEdit, | |
| QListWidget, QListWidgetItem, QMessageBox, QPlainTextEdit, QPushButton, QScrollArea, QTabWidget, | |
| QVBoxLayout, QWidget, | |
| ) | |
| from . import core | |
| from .checkpoints import CheckpointsPanel | |
| ID_ROLE = Qt.ItemDataRole.UserRole | |
| ALL_FOLDERS = "All folders" | |
| SNAPSHOTS_KEPT = 10 | |
| HISTORY_KEPT = 20 | |
| def _ai_plugin(): | |
| """The AI Image Diffusion plugin's live objects, or None if it isn't loaded.""" | |
| try: | |
| from ai_diffusion.model.root import root # type: ignore | |
| from ai_diffusion.settings import settings # type: ignore | |
| from ai_diffusion.util import user_data_dir # type: ignore | |
| return root, settings, user_data_dir | |
| except Exception: | |
| return None | |
| def _norm_id(file_id: str) -> str: | |
| return file_id.replace("\\", "/") | |
| def _folders_of(file_id: str): | |
| parts = [p for p in re.split(r"[\\/]", file_id) if p] | |
| return ["/".join(parts[:i]) for i in range(1, len(parts))] | |
| class LookupWorker(QThread): | |
| progress = pyqtSignal(str) | |
| result = pyqtSignal(str, dict) # file id, entry | |
| finished_all = pyqtSignal() | |
| def __init__(self, jobs, hash_cache, civ_cache, cache_paths, parent=None): | |
| super().__init__(parent) | |
| self.jobs = jobs # list of (file_id, Path) | |
| self.hash_cache, self.civ_cache = hash_cache, civ_cache | |
| self.hash_cache_path, self.civ_cache_path = cache_paths | |
| def run(self): | |
| for file_id, path in self.jobs: | |
| self.progress.emit(f"hashing {path.name} ...") | |
| try: | |
| digest = core.sha256_of(path, self.hash_cache) | |
| core.save_json(self.hash_cache_path, self.hash_cache) | |
| self.progress.emit(f"asking Civitai about {path.name} ...") | |
| found, status, definitive = core.civitai_lookup_lora(digest) | |
| entry = {"status": status, "sha256": digest, "definitive": definitive, **(found or {})} | |
| except Exception as e: | |
| entry = {"status": f"{type(e).__name__}: {e}", "definitive": False} | |
| if entry.get("definitive"): # errors are shown but not remembered, so the next click retries | |
| self.civ_cache[str(path)] = entry | |
| core.save_json(self.civ_cache_path, self.civ_cache) | |
| self.result.emit(file_id, entry) | |
| if len(self.jobs) > 1: | |
| time.sleep(0.6) | |
| self.finished_all.emit() | |
| class PickerDialog(QDialog): | |
| def __init__(self, parent=None): | |
| super().__init__(parent) | |
| self.setWindowTitle("LoRA Trigger Picker") | |
| self.resize(1280, 800) | |
| self.ckpt = None | |
| self._worker = None | |
| self._vars = [] # (tag, QCheckBox) | |
| self._current_id = None | |
| self._syncing = False | |
| self._names = {} | |
| self._url = "" | |
| plugin = _ai_plugin() | |
| if plugin is None: | |
| lay = QVBoxLayout(self) | |
| lay.addWidget(QLabel("AI Image Diffusion is not loaded, nothing to edit.")) | |
| return | |
| self.root, self.settings, user_dir = plugin | |
| self.cache_dir = Path(user_dir) / "lora_trigger_picker" | |
| self.hash_cache_path = self.cache_dir / "hashes.json" | |
| self.civ_cache_path = self.cache_dir / "civitai.json" | |
| self.history_path = self.cache_dir / "trigger_history.json" | |
| self.prefs_path = self.cache_dir / "lora_prefs.json" | |
| self.snap_dir = self.cache_dir / "trigger_snapshots" | |
| self.hash_cache = core.load_json(self.hash_cache_path, {}) | |
| self.civ_cache = core.load_json(self.civ_cache_path, {}) | |
| self.history = core.load_json(self.history_path, {}) | |
| self.prefs = core.load_json(self.prefs_path, {}) | |
| outer = QVBoxLayout(self) | |
| self.tabs = QTabWidget() | |
| outer.addWidget(self.tabs) | |
| lora_tab = QWidget() | |
| main = QHBoxLayout(lora_tab) | |
| left = QVBoxLayout() | |
| right = QVBoxLayout() | |
| main.addLayout(left, 2) | |
| main.addLayout(right, 3) | |
| self.tabs.addTab(lora_tab, "LoRA trigger words") | |
| self.ckpt = CheckpointsPanel(self.root, self.settings, self.cache_dir, self.hash_cache, self.hash_cache_path, self) | |
| self.tabs.addTab(self.ckpt, "Checkpoints: prompts && settings") | |
| # ---- left: folder, filter, list | |
| left.addWidget(QLabel("LoRA folder (where the files live):")) | |
| default_root = str(Path(self.settings.server_path) / "models" / "loras") | |
| self.root_edit = QLineEdit(self.prefs.get("lora_root") or default_root) | |
| self.root_edit.editingFinished.connect(self.save_prefs) | |
| left.addWidget(self.root_edit) | |
| left.addWidget(QLabel("LoRAs known to AI Image Diffusion:")) | |
| filters = QHBoxLayout() | |
| self.folder_combo = QComboBox() | |
| self.folder_combo.setMinimumWidth(220) | |
| self.folder_combo.setMaxVisibleItems(25) | |
| self.folder_combo.currentIndexChanged.connect(self.apply_filter) | |
| filters.addWidget(self.folder_combo, 3) | |
| self.search_edit = QLineEdit() | |
| self.search_edit.setPlaceholderText("Search file or Civitai name ...") | |
| self.search_edit.setClearButtonEnabled(True) | |
| self.search_edit.textChanged.connect(self.apply_filter) | |
| filters.addWidget(self.search_edit, 2) | |
| left.addLayout(filters) | |
| self.list = QListWidget() | |
| self.list.currentItemChanged.connect(self.on_item_changed) | |
| left.addWidget(self.list, 1) | |
| self.count_label = QLabel("") | |
| left.addWidget(self.count_label) | |
| self.status = QLabel("Select a LoRA, or press Fetch all.") | |
| self.status.setWordWrap(True) | |
| left.addWidget(self.status) | |
| # ---- right: what Civitai knows, the words, the text to write | |
| self.info = QLabel("") | |
| self.info.setWordWrap(True) | |
| right.addWidget(self.info) | |
| links = QHBoxLayout() | |
| self.link_btn = QPushButton("Open Civitai page") | |
| self.link_btn.setEnabled(False) | |
| self.link_btn.clicked.connect(self.open_link) | |
| self.relookup_btn = QPushButton("Look up again") | |
| self.relookup_btn.setEnabled(False) | |
| self.relookup_btn.clicked.connect(self.relookup) | |
| links.addWidget(self.link_btn) | |
| links.addWidget(self.relookup_btn) | |
| links.addStretch() | |
| right.addLayout(links) | |
| right.addWidget(QLabel("Trained words from Civitai. Ticked = in the trigger words below; " | |
| "ticking adds, unticking removes, your own words stay:")) | |
| self.scroll = QScrollArea() | |
| self.scroll.setWidgetResizable(True) | |
| self.words_widget = QWidget() | |
| self.words_layout = QVBoxLayout(self.words_widget) | |
| self.scroll.setWidget(self.words_widget) | |
| right.addWidget(self.scroll, 1) | |
| right.addWidget(QLabel("Trigger words to write (edit freely; nothing is saved until you press Write):")) | |
| self.trig = QPlainTextEdit() | |
| self.trig.setMaximumHeight(90) | |
| self.trig.textChanged.connect(self.on_text_changed) | |
| right.addWidget(self.trig) | |
| self.cur = QLabel("") | |
| self.cur.setWordWrap(True) | |
| right.addWidget(self.cur) | |
| btns = QHBoxLayout() | |
| b_name = QPushButton("Name only (first word)") | |
| b_write = QPushButton("Write to AI Image Diffusion") | |
| b_undo = QPushButton("Undo last write") | |
| b_clear = QPushButton("Clear trigger ...") | |
| for b in (b_name, b_write, b_undo, b_clear): | |
| btns.addWidget(b) | |
| right.addLayout(btns) | |
| btns2 = QHBoxLayout() | |
| b_all = QPushButton("Fetch all") | |
| b_report = QPushButton("Write report") | |
| b_restore = QPushButton("Restore triggers from a snapshot ...") | |
| for b in (b_all, b_report, b_restore): | |
| btns2.addWidget(b) | |
| btns2.addStretch() | |
| right.addLayout(btns2) | |
| b_name.clicked.connect(self.name_only) | |
| b_write.clicked.connect(self.write_trigger) | |
| b_undo.clicked.connect(self.undo_write) | |
| b_clear.clicked.connect(self.clear_trigger) | |
| b_all.clicked.connect(self.fetch_all) | |
| b_report.clicked.connect(self.write_report) | |
| b_restore.clicked.connect(self.restore_snapshot) | |
| self.reload_list() | |
| self.take_snapshot() | |
| # ---- data access through the AI plugin | |
| def files(self): | |
| return [f for f in self.root.files.loras] | |
| def file_by_id(self, file_id): | |
| return self.root.files.loras.find(file_id) if file_id else None | |
| def current_trigger(self, file_id): | |
| f = self.file_by_id(file_id) | |
| return (f.meta("lora_triggers", "") if f else "") or "" | |
| def path_for(self, f): | |
| roots = [self.root_edit.text().strip(), str(Path(self.settings.server_path) / "ComfyUI" / "models" / "loras")] | |
| return core.resolve_path(f.id, f.path, roots) | |
| def cached(self, f): | |
| p = self.path_for(f) | |
| e = self.civ_cache.get(str(p)) if p else None | |
| return p, (e if core.lookup_is_final(e) else None) | |
| def save_prefs(self): | |
| self.prefs["lora_root"] = self.root_edit.text().strip() | |
| folder = self.folder_combo.currentData() | |
| self.prefs["folder"] = folder or "" | |
| core.save_json(self.prefs_path, self.prefs) | |
| # ---- list, folder dropdown, search | |
| def _index_names(self): | |
| """File id -> Civitai model name, so the search box also finds a LoRA by the name on its page.""" | |
| self._names = {} | |
| for f in self.files(): | |
| _, e = self.cached(f) | |
| if e and e.get("model_name"): | |
| self._names[f.id] = e["model_name"] | |
| def reload_list(self): | |
| keep = self._current_id | |
| self._index_names() | |
| folders = {} | |
| for f in self.files(): | |
| for folder in _folders_of(f.id): | |
| folders[folder] = folders.get(folder, 0) + 1 | |
| wanted = self.folder_combo.currentData() if self.folder_combo.count() else self.prefs.get("folder", "") | |
| self.folder_combo.blockSignals(True) | |
| self.folder_combo.clear() | |
| self.folder_combo.addItem(f"{ALL_FOLDERS} ({len(self.files())})", "") | |
| for folder in sorted(folders, key=str.lower): | |
| depth = folder.count("/") | |
| self.folder_combo.addItem(f"{' ' * depth}{folder.split('/')[-1]} ({folders[folder]})", folder) | |
| idx = self.folder_combo.findData(wanted or "") | |
| self.folder_combo.setCurrentIndex(idx if idx >= 0 else 0) | |
| self.folder_combo.blockSignals(False) | |
| self.apply_filter(keep_id=keep) | |
| if self.ckpt is not None: | |
| self.ckpt.reload_list() | |
| def apply_filter(self, *_args, keep_id=None): | |
| keep_id = keep_id or self._current_id | |
| folder = self.folder_combo.currentData() or "" | |
| prefix = folder + "/" if folder else "" | |
| needle = self.search_edit.text().strip().lower() | |
| self.list.blockSignals(True) | |
| self.list.clear() | |
| shown, total, selected = 0, 0, None | |
| for f in sorted(self.files(), key=lambda f: f.id.lower()): | |
| total += 1 | |
| nid = _norm_id(f.id) | |
| if prefix and not nid.startswith(prefix): | |
| continue | |
| if needle and needle not in f"{nid} {self._names.get(f.id, '')}".lower(): | |
| continue | |
| label = nid[len(prefix):] if prefix else nid | |
| if (f.meta("lora_triggers", "") or "").strip(): | |
| label += " ✓" | |
| item = QListWidgetItem(label) | |
| item.setData(ID_ROLE, f.id) | |
| item.setToolTip(f.id) | |
| self.list.addItem(item) | |
| shown += 1 | |
| if f.id == keep_id: | |
| selected = item | |
| if selected is not None: | |
| self.list.setCurrentItem(selected) | |
| self.list.scrollToItem(selected) | |
| self.list.blockSignals(False) | |
| self.count_label.setText(f"{shown} of {total} shown (✓ = trigger words set)") | |
| if self.sender() is self.folder_combo: | |
| self.save_prefs() | |
| def refresh_item(self, file_id): | |
| for i in range(self.list.count()): | |
| item = self.list.item(i) | |
| if item.data(ID_ROLE) == file_id: | |
| label = item.text().replace(" ✓", "") | |
| if self.current_trigger(file_id).strip(): | |
| label += " ✓" | |
| item.setText(label) | |
| return | |
| def on_item_changed(self, item, _previous=None): | |
| if item is not None: | |
| self.show_file(item.data(ID_ROLE)) | |
| # ---- display | |
| def show_file(self, file_id, force=False): | |
| if not file_id: | |
| return | |
| self._current_id = file_id | |
| f = self.file_by_id(file_id) | |
| text = self.current_trigger(file_id) | |
| self.cur.setText(f"Currently set: {text or '(empty)'}") | |
| self._set_text(text) | |
| self.relookup_btn.setEnabled(f is not None) | |
| path = self.path_for(f) if f else None | |
| if path is None: | |
| self.info.setText(f"{file_id}\nFile not found under the LoRA folder above.") | |
| self.link_btn.setEnabled(False) | |
| self.rebuild_words(None) | |
| return | |
| _, entry = self.cached(f) | |
| if entry is None or force: | |
| self.rebuild_words(None) | |
| self.info.setText(f"{file_id}\nlooking up ...") | |
| self.start_worker([(file_id, path)]) | |
| return | |
| self.render_entry(file_id, entry) | |
| def render_entry(self, file_id, entry): | |
| if entry.get("model_name"): | |
| self.info.setText( | |
| f"{entry['model_name']} [{entry.get('version_name', '')}]\n" | |
| f"type: {entry.get('type')} base: {entry.get('base_model')} nsfw: {entry.get('nsfw')}\n" | |
| f"file: {file_id}" | |
| ) | |
| self._url = entry.get("url", "") | |
| self.link_btn.setEnabled(bool(self._url)) | |
| else: | |
| self.info.setText(f"{file_id}\n{entry.get('status', '?')}\nSHA256 {str(entry.get('sha256', '?'))[:12]}...") | |
| self.link_btn.setEnabled(False) | |
| self.rebuild_words(entry) | |
| def open_link(self): | |
| if getattr(self, "_url", ""): | |
| QDesktopServices.openUrl(QUrl(self._url)) | |
| def relookup(self): | |
| if self._current_id: | |
| self.show_file(self._current_id, force=True) | |
| def rebuild_words(self, entry): | |
| while self.words_layout.count(): | |
| item = self.words_layout.takeAt(0) | |
| if item.widget(): | |
| item.widget().deleteLater() | |
| self._vars = [] | |
| words = (entry or {}).get("trained_words") or [] | |
| if not words: | |
| self.words_layout.addWidget(QLabel("(no trained words on Civitai, or not looked up yet)")) | |
| self.words_layout.addStretch() | |
| return | |
| have = {t.lower() for t in core.split_tags(self.trig.toPlainText())} | |
| for i, s in enumerate(words): | |
| box = QGroupBox(f"set {i + 1}: {s[:100]}") | |
| row = QHBoxLayout(box) | |
| for tag in core.split_tags(s): | |
| cb = QCheckBox(tag) | |
| cb.setChecked(tag.lower() in have) | |
| cb.toggled.connect(lambda checked, t=tag: self.on_box_toggled(t, checked)) | |
| row.addWidget(cb) | |
| self._vars.append((tag, cb)) | |
| row.addStretch() | |
| self.words_layout.addWidget(box) | |
| self.words_layout.addStretch() | |
| # ---- ticking and the text box stay in step | |
| def _set_text(self, text): | |
| self._syncing = True | |
| self.trig.setPlainText(text) | |
| self._syncing = False | |
| self.on_text_changed() | |
| def on_box_toggled(self, tag, checked): | |
| if self._syncing: | |
| return | |
| self._syncing = True | |
| for t, cb in self._vars: # the same word in several sets ticks together | |
| if t.lower() == tag.lower() and cb.isChecked() != checked: | |
| cb.setChecked(checked) | |
| self._syncing = False | |
| self.compose() | |
| def compose(self): | |
| """Your words stay where they are; unticked trained words go; newly ticked ones are added at the end.""" | |
| current = core.split_tags(self.trig.toPlainText()) | |
| box_tags = {t.lower() for t, _ in self._vars} | |
| chosen = [] | |
| for t, cb in self._vars: | |
| if cb.isChecked() and t.lower() not in {c.lower() for c in chosen}: | |
| chosen.append(t) | |
| chosen_low = {c.lower() for c in chosen} | |
| kept = [t for t in current if t.lower() not in box_tags or t.lower() in chosen_low] | |
| kept_low = {t.lower() for t in kept} | |
| result = kept + [c for c in chosen if c.lower() not in kept_low] | |
| self._syncing = True | |
| self.trig.setPlainText(", ".join(result)) | |
| self._syncing = False | |
| def on_text_changed(self): | |
| if self._syncing: | |
| return | |
| have = {t.lower() for t in core.split_tags(self.trig.toPlainText())} | |
| self._syncing = True | |
| for t, cb in self._vars: | |
| cb.setChecked(t.lower() in have) | |
| self._syncing = False | |
| def name_only(self): | |
| if self._vars: | |
| self._set_text(self._vars[0][0]) | |
| # ---- writing, undo, clear | |
| def _write(self, f, text, record=True): | |
| old = (f.meta("lora_triggers", "") or "") | |
| if record and old != text: | |
| hist = self.history.setdefault(f.id, []) | |
| hist.append({"time": time.strftime("%Y-%m-%d %H:%M:%S"), "old": old, "new": text}) | |
| del hist[:-HISTORY_KEPT] | |
| core.save_json(self.history_path, self.history) | |
| self.root.files.loras.set_meta(f, "lora_triggers", text) | |
| self._sync_style_pages(f.id, text) | |
| self.refresh_item(f.id) | |
| def _sync_style_pages(self, file_id, text): | |
| """The style settings keep a trigger box per LoRA slot that never re-reads the database; show the new | |
| words there too (signals blocked, so this only changes what's displayed, it saves nothing).""" | |
| try: | |
| for w in QApplication.allWidgets(): | |
| if type(w).__name__ != "LoraItem": | |
| continue | |
| cur = getattr(w, "_current", None) | |
| edit = getattr(w, "_trigger_edit", None) | |
| if cur is None or edit is None or getattr(cur, "id", None) != file_id: | |
| continue | |
| if cur is not self.file_by_id(file_id) and isinstance(getattr(cur, "metadata", None), dict): | |
| cur.metadata["lora_triggers"] = text | |
| edit.blockSignals(True) | |
| edit.setText(text) | |
| edit.blockSignals(False) | |
| except Exception: | |
| pass | |
| def write_trigger(self): | |
| f = self.file_by_id(self._current_id) | |
| if not f: | |
| self.status.setText("Select a LoRA first.") | |
| return | |
| text = ", ".join(core.split_tags(self.trig.toPlainText())) | |
| self._write(f, text) | |
| self.cur.setText(f"Currently set: {text or '(empty)'}") | |
| self.status.setText(f"Saved for {Path(_norm_id(f.id)).name}.") | |
| def undo_write(self): | |
| f = self.file_by_id(self._current_id) | |
| hist = self.history.get(f.id, []) if f else [] | |
| if not f or not hist: | |
| self.status.setText("Nothing to undo for this LoRA.") | |
| return | |
| last = hist.pop() | |
| core.save_json(self.history_path, self.history) | |
| self._write(f, last["old"], record=False) | |
| self.show_file(f.id) | |
| self.status.setText(f"Undone: back to what was set before {last['time']}.") | |
| def clear_trigger(self): | |
| f = self.file_by_id(self._current_id) | |
| if not f: | |
| return | |
| name = Path(_norm_id(f.id)).name | |
| answer = QMessageBox.question(self, "Clear trigger words", f"Remove all trigger words from {name}?\n" | |
| "(Undo last write brings them back.)") | |
| if answer != QMessageBox.StandardButton.Yes: | |
| return | |
| self._write(f, "") | |
| self.show_file(f.id) | |
| self.status.setText(f"Cleared {name}.") | |
| # ---- snapshots of every trigger, so a wipe can be undone | |
| def _all_triggers(self): | |
| return {f.id: (f.meta("lora_triggers", "") or "") for f in self.files() if (f.meta("lora_triggers", "") or "").strip()} | |
| def _snapshots(self): | |
| return sorted(self.snap_dir.glob("triggers_*.json"), reverse=True) if self.snap_dir.exists() else [] | |
| def take_snapshot(self): | |
| current = self._all_triggers() | |
| snaps = self._snapshots() | |
| if not current or (snaps and core.load_json(snaps[0], {}) == current): | |
| return | |
| core.save_json(self.snap_dir / time.strftime("triggers_%Y%m%d_%H%M%S.json"), current) | |
| for old in self._snapshots()[SNAPSHOTS_KEPT:]: | |
| try: | |
| old.unlink() | |
| except OSError: | |
| pass | |
| def restore_snapshot(self): | |
| snaps = self._snapshots() | |
| if not snaps: | |
| self.status.setText("No snapshots yet (one is taken each time the picker opens).") | |
| return | |
| labels = [] | |
| for p in snaps: | |
| stamp = p.stem.replace("triggers_", "") | |
| labels.append(f"{stamp[:4]}-{stamp[4:6]}-{stamp[6:8]} {stamp[9:11]}:{stamp[11:13]} " | |
| f"({len(core.load_json(p, {}))} LoRAs with trigger words)") | |
| choice, ok = QInputDialog.getItem(self, "Restore trigger words", "Snapshot:", labels, 0, False) | |
| if not ok: | |
| return | |
| snap = core.load_json(snaps[labels.index(choice)], {}) | |
| box = QMessageBox(self) | |
| box.setWindowTitle("Restore trigger words") | |
| box.setText("Restore only LoRAs whose trigger words are empty now, or put every LoRA back to the snapshot?") | |
| empty_btn = box.addButton("Only empty ones", QMessageBox.ButtonRole.AcceptRole) | |
| all_btn = box.addButton("All of them", QMessageBox.ButtonRole.DestructiveRole) | |
| box.addButton(QMessageBox.StandardButton.Cancel) | |
| box.exec() | |
| if box.clickedButton() not in (empty_btn, all_btn): | |
| return | |
| only_empty = box.clickedButton() is empty_btn | |
| changed = 0 | |
| for fid, text in snap.items(): | |
| f = self.file_by_id(fid) | |
| if f is None: | |
| continue | |
| now = (f.meta("lora_triggers", "") or "") | |
| if now == text or (only_empty and now.strip()): | |
| continue | |
| self._write(f, text) | |
| changed += 1 | |
| self.apply_filter() | |
| if self._current_id: | |
| self.show_file(self._current_id) | |
| self.status.setText(f"Restored trigger words for {changed} LoRA(s) (each one can be undone).") | |
| # ---- background lookups | |
| def start_worker(self, jobs): | |
| if self._worker and self._worker.isRunning(): | |
| self.status.setText("A lookup is already running; wait for it to finish.") | |
| return | |
| self._worker = LookupWorker(jobs, self.hash_cache, self.civ_cache, (self.hash_cache_path, self.civ_cache_path), self) | |
| self._worker.progress.connect(self.status.setText) | |
| self._worker.result.connect(self.on_result) | |
| self._worker.finished_all.connect(lambda: self.status.setText("Lookup finished.")) | |
| self._worker.start() | |
| def on_result(self, file_id, entry): | |
| if entry.get("model_name"): | |
| self._names[file_id] = entry["model_name"] | |
| if file_id == self._current_id: | |
| self.render_entry(file_id, entry) | |
| def fetch_all(self): | |
| jobs = [] | |
| for f in self.files(): | |
| p, entry = self.cached(f) | |
| if p is not None and entry is None: | |
| jobs.append((f.id, p)) | |
| if not jobs: | |
| self.status.setText("Everything is already looked up.") | |
| return | |
| self.status.setText(f"Looking up {len(jobs)} LoRAs in the background ...") | |
| self.start_worker(jobs) | |
| def write_report(self): | |
| lines = [] | |
| for f in sorted(self.files(), key=lambda f: f.id.lower()): | |
| _, e = self.cached(f) | |
| e = e or {} | |
| lines.append( | |
| f"{f.id}\n civitai: {e.get('model_name') or e.get('status', 'not looked up')} base: {e.get('base_model', '')} type: {e.get('type', '')}\n" | |
| f" url: {e.get('url', '')}\n trained words: {' | '.join(e.get('trained_words') or [])}\n" | |
| f" trigger set in Krita: {self.current_trigger(f.id)}\n" | |
| ) | |
| out = self.cache_dir / "lora_trigger_report.txt" | |
| out.parent.mkdir(parents=True, exist_ok=True) | |
| out.write_text("\n".join(lines), encoding="utf-8") | |
| self.status.setText(f"Report written: {out}") | |
| def hideEvent(self, event): | |
| if self.ckpt is not None: | |
| self.ckpt.stash() | |
| super().hideEvent(event) | |
| class LoraTriggerPickerExtension(Extension): | |
| def __init__(self, parent): | |
| super().__init__(parent) | |
| self._dialog = None | |
| def setup(self): | |
| pass | |
| def createActions(self, window): | |
| action = window.createAction("lora_trigger_picker_open", "LoRA Trigger Picker", "tools/scripts") | |
| action.triggered.connect(self.open) | |
| def open(self): | |
| from krita import Krita # type: ignore | |
| win = Krita.instance().activeWindow() | |
| parent = win.qwindow() if win else None | |
| if self._dialog is None: | |
| self._dialog = PickerDialog(parent) | |
| elif hasattr(self._dialog, "list"): | |
| self._dialog.reload_list() | |
| self._dialog.take_snapshot() | |
| self._dialog.show() | |
| self._dialog.raise_() | |
Xet Storage Details
- Size:
- 27.1 kB
- Xet hash:
- 6f385d672be37d56bdd48a2d48ee4170657d9d621b5d0da93961595f7231de1a
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.