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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
var acConfig = null;
|
| 2 |
+
var acActive = true;
|
| 3 |
+
|
| 4 |
+
// Style for new elements. Gets appended to the Gradio root.
|
| 5 |
+
let autocompleteCSS_dark = `
|
| 6 |
+
.autocompleteResults {
|
| 7 |
+
position: absolute;
|
| 8 |
+
z-index: 999;
|
| 9 |
+
margin: 5px 0 0 0;
|
| 10 |
+
background-color: #0b0f19 !important;
|
| 11 |
+
border: 1px solid #4b5563 !important;
|
| 12 |
+
border-radius: 12px !important;
|
| 13 |
+
overflow-y: auto;
|
| 14 |
+
}
|
| 15 |
+
.autocompleteResultsList > li:nth-child(odd) {
|
| 16 |
+
background-color: #111827;
|
| 17 |
+
}
|
| 18 |
+
.autocompleteResultsList > li {
|
| 19 |
+
list-style-type: none;
|
| 20 |
+
padding: 10px;
|
| 21 |
+
cursor: pointer;
|
| 22 |
+
}
|
| 23 |
+
.autocompleteResultsList > li:hover {
|
| 24 |
+
background-color: #1f2937;
|
| 25 |
+
}
|
| 26 |
+
.autocompleteResultsList > li.selected {
|
| 27 |
+
background-color: #374151;
|
| 28 |
+
}
|
| 29 |
+
`;
|
| 30 |
+
let autocompleteCSS_light = `
|
| 31 |
+
.autocompleteResults {
|
| 32 |
+
position: absolute;
|
| 33 |
+
z-index: 999;
|
| 34 |
+
margin: 5px 0 0 0;
|
| 35 |
+
background-color: #ffffff !important;
|
| 36 |
+
border: 1.5px solid #e5e7eb !important;
|
| 37 |
+
border-radius: 12px !important;
|
| 38 |
+
overflow-y: auto;
|
| 39 |
+
}
|
| 40 |
+
.autocompleteResultsList > li:nth-child(odd) {
|
| 41 |
+
background-color: #f9fafb;
|
| 42 |
+
}
|
| 43 |
+
.autocompleteResultsList > li {
|
| 44 |
+
list-style-type: none;
|
| 45 |
+
padding: 10px;
|
| 46 |
+
cursor: pointer;
|
| 47 |
+
}
|
| 48 |
+
.autocompleteResultsList > li:hover {
|
| 49 |
+
background-color: #f5f6f8;
|
| 50 |
+
}
|
| 51 |
+
.autocompleteResultsList > li.selected {
|
| 52 |
+
background-color: #e5e7eb;
|
| 53 |
+
}
|
| 54 |
+
`;
|
| 55 |
+
|
| 56 |
+
// Parse the CSV file into a 2D array. Doesn't use regex, so it is very lightweight.
|
| 57 |
+
function parseCSV(str) {
|
| 58 |
+
var arr = [];
|
| 59 |
+
var quote = false; // 'true' means we're inside a quoted field
|
| 60 |
+
|
| 61 |
+
// Iterate over each character, keep track of current row and column (of the returned array)
|
| 62 |
+
for (var row = 0, col = 0, c = 0; c < str.length; c++) {
|
| 63 |
+
var cc = str[c], nc = str[c + 1]; // Current character, next character
|
| 64 |
+
arr[row] = arr[row] || []; // Create a new row if necessary
|
| 65 |
+
arr[row][col] = arr[row][col] || ''; // Create a new column (start with empty string) if necessary
|
| 66 |
+
|
| 67 |
+
// If the current character is a quotation mark, and we're inside a
|
| 68 |
+
// quoted field, and the next character is also a quotation mark,
|
| 69 |
+
// add a quotation mark to the current column and skip the next character
|
| 70 |
+
if (cc == '"' && quote && nc == '"') { arr[row][col] += cc; ++c; continue; }
|
| 71 |
+
|
| 72 |
+
// If it's just one quotation mark, begin/end quoted field
|
| 73 |
+
if (cc == '"') { quote = !quote; continue; }
|
| 74 |
+
|
| 75 |
+
// If it's a comma and we're not in a quoted field, move on to the next column
|
| 76 |
+
if (cc == ',' && !quote) { ++col; continue; }
|
| 77 |
+
|
| 78 |
+
// If it's a newline (CRLF) and we're not in a quoted field, skip the next character
|
| 79 |
+
// and move on to the next row and move to column 0 of that new row
|
| 80 |
+
if (cc == '\r' && nc == '\n' && !quote) { ++row; col = 0; ++c; continue; }
|
| 81 |
+
|
| 82 |
+
// If it's a newline (LF or CR) and we're not in a quoted field,
|
| 83 |
+
// move on to the next row and move to column 0 of that new row
|
| 84 |
+
if (cc == '\n' && !quote) { ++row; col = 0; continue; }
|
| 85 |
+
if (cc == '\r' && !quote) { ++row; col = 0; continue; }
|
| 86 |
+
|
| 87 |
+
// Otherwise, append the current character to the current column
|
| 88 |
+
arr[row][col] += cc;
|
| 89 |
+
}
|
| 90 |
+
return arr;
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
// Load file
|
| 94 |
+
function readFile(filePath) {
|
| 95 |
+
let request = new XMLHttpRequest();
|
| 96 |
+
request.open("GET", filePath, false);
|
| 97 |
+
request.send(null);
|
| 98 |
+
return request.responseText;
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
// Load CSV
|
| 102 |
+
function loadCSV(path) {
|
| 103 |
+
let text = readFile(path);
|
| 104 |
+
return parseCSV(text);
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
// Debounce function to prevent spamming the autocomplete function
|
| 108 |
+
var dbTimeOut;
|
| 109 |
+
const debounce = (func, wait = 300) => {
|
| 110 |
+
return function (...args) {
|
| 111 |
+
if (dbTimeOut) {
|
| 112 |
+
clearTimeout(dbTimeOut);
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
dbTimeOut = setTimeout(() => {
|
| 116 |
+
func.apply(this, args);
|
| 117 |
+
}, wait);
|
| 118 |
+
}
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
// Difference function to fix duplicates not being seen as changes in normal filter
|
| 122 |
+
function difference(a, b) {
|
| 123 |
+
if (a.length == 0) {
|
| 124 |
+
return b;
|
| 125 |
+
}
|
| 126 |
+
if (b.length == 0) {
|
| 127 |
+
return a;
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
return [...b.reduce((acc, v) => acc.set(v, (acc.get(v) || 0) - 1),
|
| 131 |
+
a.reduce((acc, v) => acc.set(v, (acc.get(v) || 0) + 1), new Map())
|
| 132 |
+
)].reduce((acc, [v, count]) => acc.concat(Array(Math.abs(count)).fill(v)), []);
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
// Get the identifier for the text area to differentiate between positive and negative
|
| 136 |
+
function getTextAreaIdentifier(textArea) {
|
| 137 |
+
let txt2img_p = gradioApp().querySelector('#txt2img_prompt > label > textarea');
|
| 138 |
+
let txt2img_n = gradioApp().querySelector('#txt2img_neg_prompt > label > textarea');
|
| 139 |
+
let img2img_p = gradioApp().querySelector('#img2img_prompt > label > textarea');
|
| 140 |
+
let img2img_n = gradioApp().querySelector('#img2img_neg_prompt > label > textarea');
|
| 141 |
+
|
| 142 |
+
let modifier = "";
|
| 143 |
+
switch (textArea) {
|
| 144 |
+
case txt2img_p:
|
| 145 |
+
modifier = ".txt2img.p";
|
| 146 |
+
break;
|
| 147 |
+
case txt2img_n:
|
| 148 |
+
modifier = ".txt2img.n";
|
| 149 |
+
break;
|
| 150 |
+
case img2img_p:
|
| 151 |
+
modifier = ".img2img.p";
|
| 152 |
+
break;
|
| 153 |
+
case img2img_n:
|
| 154 |
+
modifier = ".img2img.n";
|
| 155 |
+
break;
|
| 156 |
+
default:
|
| 157 |
+
break;
|
| 158 |
+
}
|
| 159 |
+
return modifier;
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
// Create the result list div and necessary styling
|
| 163 |
+
function createResultsDiv(textArea) {
|
| 164 |
+
let resultsDiv = document.createElement("div");
|
| 165 |
+
let resultsList = document.createElement('ul');
|
| 166 |
+
|
| 167 |
+
let textAreaId = getTextAreaIdentifier(textArea);
|
| 168 |
+
let typeClass = textAreaId.replaceAll(".", " ");
|
| 169 |
+
|
| 170 |
+
resultsDiv.style.setProperty("max-height", acConfig.maxResults * 50 + "px");
|
| 171 |
+
resultsDiv.setAttribute('class', `autocompleteResults ${typeClass}`);
|
| 172 |
+
resultsList.setAttribute('class', 'autocompleteResultsList');
|
| 173 |
+
resultsDiv.appendChild(resultsList);
|
| 174 |
+
|
| 175 |
+
return resultsDiv;
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
// Create the checkbox to enable/disable autocomplete
|
| 179 |
+
function createCheckbox() {
|
| 180 |
+
let label = document.createElement("label");
|
| 181 |
+
let input = document.createElement("input");
|
| 182 |
+
let span = document.createElement("span");
|
| 183 |
+
|
| 184 |
+
label.setAttribute('id', 'acActiveCheckbox');
|
| 185 |
+
label.setAttribute('class', '"flex items-center text-gray-700 text-sm rounded-lg cursor-pointer dark:bg-transparent');
|
| 186 |
+
input.setAttribute('type', 'checkbox');
|
| 187 |
+
input.setAttribute('class', 'gr-check-radio gr-checkbox')
|
| 188 |
+
span.setAttribute('class', 'ml-2');
|
| 189 |
+
|
| 190 |
+
span.textContent = "Enable Autocomplete";
|
| 191 |
+
|
| 192 |
+
label.appendChild(input);
|
| 193 |
+
label.appendChild(span);
|
| 194 |
+
return label;
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
// The selected tag index. Needs to be up here so hide can access it.
|
| 198 |
+
var selectedTag = null;
|
| 199 |
+
var previousTags = [];
|
| 200 |
+
|
| 201 |
+
// Show or hide the results div
|
| 202 |
+
function isVisible(textArea) {
|
| 203 |
+
let textAreaId = getTextAreaIdentifier(textArea);
|
| 204 |
+
let resultsDiv = gradioApp().querySelector('.autocompleteResults' + textAreaId);
|
| 205 |
+
return resultsDiv.style.display === "block";
|
| 206 |
+
}
|
| 207 |
+
function showResults(textArea) {
|
| 208 |
+
let textAreaId = getTextAreaIdentifier(textArea);
|
| 209 |
+
let resultsDiv = gradioApp().querySelector('.autocompleteResults' + textAreaId);
|
| 210 |
+
resultsDiv.style.display = "block";
|
| 211 |
+
}
|
| 212 |
+
function hideResults(textArea) {
|
| 213 |
+
let textAreaId = getTextAreaIdentifier(textArea);
|
| 214 |
+
let resultsDiv = gradioApp().querySelector('.autocompleteResults' + textAreaId);
|
| 215 |
+
resultsDiv.style.display = "none";
|
| 216 |
+
selectedTag = null;
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
function escapeRegExp(string) {
|
| 220 |
+
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
let hideBlocked = false;
|
| 224 |
+
|
| 225 |
+
// On click, insert the tag into the prompt textbox with respect to the cursor position
|
| 226 |
+
function insertTextAtCursor(textArea, result, tagword) {
|
| 227 |
+
let text = result[0];
|
| 228 |
+
let tagType = result[1];
|
| 229 |
+
|
| 230 |
+
let cursorPos = textArea.selectionStart;
|
| 231 |
+
var sanitizedText = text
|
| 232 |
+
|
| 233 |
+
// Replace differently depending on if it's a tag or wildcard
|
| 234 |
+
if (tagType === "wildcardFile") {
|
| 235 |
+
sanitizedText = "__" + text.replace("Wildcards: ", "") + "__";
|
| 236 |
+
} else if (tagType === "wildcardTag") {
|
| 237 |
+
sanitizedText = text.replace(/^.*?: /g, "");
|
| 238 |
+
} else if (tagType === "embedding") {
|
| 239 |
+
sanitizedText = `<${text.replace(/^.*?: /g, "")}>`;
|
| 240 |
+
} else {
|
| 241 |
+
sanitizedText = acConfig.replaceUnderscores ? text.replaceAll("_", " ") : text;
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
if (acConfig.escapeParentheses) {
|
| 245 |
+
sanitizedText = sanitizedText
|
| 246 |
+
.replaceAll("(", "\\(")
|
| 247 |
+
.replaceAll(")", "\\)")
|
| 248 |
+
.replaceAll("[", "\\[")
|
| 249 |
+
.replaceAll("]", "\\]");
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
var prompt = textArea.value;
|
| 253 |
+
|
| 254 |
+
// Edit prompt text
|
| 255 |
+
let editStart = Math.max(cursorPos - tagword.length, 0);
|
| 256 |
+
let editEnd = Math.min(cursorPos + tagword.length, prompt.length);
|
| 257 |
+
let surrounding = prompt.substring(editStart, editEnd);
|
| 258 |
+
let match = surrounding.match(new RegExp(escapeRegExp(`${tagword}`)));
|
| 259 |
+
let afterInsertCursorPos = editStart + match.index + sanitizedText.length;
|
| 260 |
+
|
| 261 |
+
var optionalComma = "";
|
| 262 |
+
if (tagType !== "wildcardFile") {
|
| 263 |
+
optionalComma = surrounding.match(new RegExp(escapeRegExp(`${tagword},`))) !== null ? "" : ", ";
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
// Replace partial tag word with new text, add comma if needed
|
| 267 |
+
let insert = surrounding.replace(tagword, sanitizedText + optionalComma);
|
| 268 |
+
|
| 269 |
+
// Add back start
|
| 270 |
+
var newPrompt = prompt.substring(0, editStart) + insert + prompt.substring(editEnd);
|
| 271 |
+
textArea.value = newPrompt;
|
| 272 |
+
textArea.selectionStart = afterInsertCursorPos + optionalComma.length;
|
| 273 |
+
textArea.selectionEnd = textArea.selectionStart
|
| 274 |
+
|
| 275 |
+
// Since we've modified a Gradio Textbox component manually, we need to simulate an `input` DOM event to ensure its
|
| 276 |
+
// internal Svelte data binding remains in sync.
|
| 277 |
+
textArea.dispatchEvent(new Event("input", { bubbles: true }));
|
| 278 |
+
|
| 279 |
+
// Update previous tags with the edited prompt to prevent re-searching the same term
|
| 280 |
+
let tags = newPrompt.match(/[^, ]+/g);
|
| 281 |
+
previousTags = tags;
|
| 282 |
+
|
| 283 |
+
// Hide results after inserting
|
| 284 |
+
if (tagType === "wildcardFile") {
|
| 285 |
+
// If it's a wildcard, we want to keep the results open so the user can select another wildcard
|
| 286 |
+
hideBlocked = true;
|
| 287 |
+
autocomplete(textArea, prompt, sanitizedText);
|
| 288 |
+
setTimeout(() => { hideBlocked = false; }, 100);
|
| 289 |
+
} else {
|
| 290 |
+
hideResults(textArea);
|
| 291 |
+
}
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
function addResultsToList(textArea, results, tagword, resetList) {
|
| 295 |
+
let textAreaId = getTextAreaIdentifier(textArea);
|
| 296 |
+
let resultDiv = gradioApp().querySelector('.autocompleteResults' + textAreaId);
|
| 297 |
+
let resultsList = resultDiv.querySelector('ul');
|
| 298 |
+
|
| 299 |
+
// Reset list, selection and scrollTop since the list changed
|
| 300 |
+
if (resetList) {
|
| 301 |
+
resultsList.innerHTML = "";
|
| 302 |
+
selectedTag = null;
|
| 303 |
+
resultDiv.scrollTop = 0;
|
| 304 |
+
resultCount = 0;
|
| 305 |
+
}
|
| 306 |
+
|
| 307 |
+
// Find right colors from config
|
| 308 |
+
let tagFileName = acConfig.tagFile.split(".")[0];
|
| 309 |
+
let tagColors = acConfig.colors;
|
| 310 |
+
let mode = gradioApp().querySelector('.dark') ? 0 : 1;
|
| 311 |
+
let nextLength = Math.min(results.length, resultCount + acConfig.resultStepLength);
|
| 312 |
+
|
| 313 |
+
for (let i = resultCount; i < nextLength; i++) {
|
| 314 |
+
let result = results[i];
|
| 315 |
+
let li = document.createElement("li");
|
| 316 |
+
|
| 317 |
+
//suppost only show the translation to result
|
| 318 |
+
if (result[2]) {
|
| 319 |
+
li.textContent = result[2];
|
| 320 |
+
if (!acConfig.translation.onlyShowTranslation) {
|
| 321 |
+
li.textContent += " >> " + result[0];
|
| 322 |
+
}
|
| 323 |
+
} else {
|
| 324 |
+
li.textContent = result[0];
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
// Wildcards & Embeds have no tag type
|
| 328 |
+
if (!result[1].startsWith("wildcard") && result[1] !== "embedding") {
|
| 329 |
+
// Set the color of the tag
|
| 330 |
+
let tagType = result[1];
|
| 331 |
+
let colorGroup = tagColors[tagFileName];
|
| 332 |
+
// Default to danbooru scheme if no matching one is found
|
| 333 |
+
if (colorGroup === undefined) colorGroup = tagColors["danbooru"];
|
| 334 |
+
|
| 335 |
+
li.style = `color: ${colorGroup[tagType][mode]};`;
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
// Add listener
|
| 339 |
+
li.addEventListener("click", function () { insertTextAtCursor(textArea, result, tagword); });
|
| 340 |
+
// Add element to list
|
| 341 |
+
resultsList.appendChild(li);
|
| 342 |
+
}
|
| 343 |
+
resultCount = nextLength;
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
function updateSelectionStyle(textArea, newIndex, oldIndex) {
|
| 347 |
+
let textAreaId = getTextAreaIdentifier(textArea);
|
| 348 |
+
let resultDiv = gradioApp().querySelector('.autocompleteResults' + textAreaId);
|
| 349 |
+
let resultsList = resultDiv.querySelector('ul');
|
| 350 |
+
let items = resultsList.getElementsByTagName('li');
|
| 351 |
+
|
| 352 |
+
if (oldIndex != null) {
|
| 353 |
+
items[oldIndex].classList.remove('selected');
|
| 354 |
+
}
|
| 355 |
+
|
| 356 |
+
// make it safer
|
| 357 |
+
if (newIndex !== null) {
|
| 358 |
+
items[newIndex].classList.add('selected');
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
// Set scrolltop to selected item if we are showing more than max results
|
| 362 |
+
if (items.length > acConfig.maxResults) {
|
| 363 |
+
let selected = items[newIndex];
|
| 364 |
+
resultDiv.scrollTop = selected.offsetTop - resultDiv.offsetTop;
|
| 365 |
+
}
|
| 366 |
+
}
|
| 367 |
+
|
| 368 |
+
var wildcardFiles = [];
|
| 369 |
+
var wildcards = {};
|
| 370 |
+
var embeddings = [];
|
| 371 |
+
var allTags = [];
|
| 372 |
+
var results = [];
|
| 373 |
+
var tagword = "";
|
| 374 |
+
var resultCount = 0;
|
| 375 |
+
function autocomplete(textArea, prompt, fixedTag = null) {
|
| 376 |
+
// Return if the function is deactivated in the UI
|
| 377 |
+
if (!acActive) return;
|
| 378 |
+
|
| 379 |
+
// Guard for empty prompt
|
| 380 |
+
if (prompt.length === 0) {
|
| 381 |
+
hideResults(textArea);
|
| 382 |
+
return;
|
| 383 |
+
}
|
| 384 |
+
|
| 385 |
+
if (fixedTag === null) {
|
| 386 |
+
// Match tags with RegEx to get the last edited one
|
| 387 |
+
let tags = prompt.match(/[^, ]+/g);
|
| 388 |
+
let diff = difference(tags, previousTags)
|
| 389 |
+
previousTags = tags;
|
| 390 |
+
|
| 391 |
+
// Guard for no difference / only whitespace remaining
|
| 392 |
+
if (diff === null || diff.length === 0) {
|
| 393 |
+
if (!hideBlocked) hideResults(textArea);
|
| 394 |
+
return;
|
| 395 |
+
}
|
| 396 |
+
|
| 397 |
+
tagword = diff[0]
|
| 398 |
+
|
| 399 |
+
// Guard for empty tagword
|
| 400 |
+
if (tagword === null || tagword.length === 0) {
|
| 401 |
+
hideResults(textArea);
|
| 402 |
+
return;
|
| 403 |
+
}
|
| 404 |
+
} else {
|
| 405 |
+
tagword = fixedTag;
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
tagword = tagword.toLowerCase();
|
| 409 |
+
|
| 410 |
+
if (acConfig.useWildcards && [...tagword.matchAll(/\b__([^,_ ]+)__([^, ]*)\b/g)].length > 0) {
|
| 411 |
+
// Show wildcards from a file with that name
|
| 412 |
+
wcMatch = [...tagword.matchAll(/\b__([^,_ ]+)__([^, ]*)\b/g)]
|
| 413 |
+
let wcFile = wcMatch[0][1];
|
| 414 |
+
let wcWord = wcMatch[0][2];
|
| 415 |
+
results = wildcards[wcFile].filter(x => (wcWord !== null) ? x.toLowerCase().includes(wcWord) : x) // Filter by tagword
|
| 416 |
+
.map(x => [wcFile + ": " + x.trim(), "wildcardTag"]); // Mark as wildcard
|
| 417 |
+
} else if (acConfig.useWildcards && (tagword.startsWith("__") && !tagword.endsWith("__") || tagword === "__")) {
|
| 418 |
+
// Show available wildcard files
|
| 419 |
+
let tempResults = [];
|
| 420 |
+
if (tagword !== "__") {
|
| 421 |
+
tempResults = wildcardFiles.filter(x => x.toLowerCase().includes(tagword.replace("__", ""))) // Filter by tagword
|
| 422 |
+
} else {
|
| 423 |
+
tempResults = wildcardFiles;
|
| 424 |
+
}
|
| 425 |
+
results = tempResults.map(x => ["Wildcards: " + x.trim(), "wildcardFile"]); // Mark as wildcard
|
| 426 |
+
} else if (acConfig.useEmbeddings && tagword.match(/<[^,> ]*>?/g)) {
|
| 427 |
+
// Show embeddings
|
| 428 |
+
let tempResults = [];
|
| 429 |
+
if (tagword !== "<") {
|
| 430 |
+
tempResults = embeddings.filter(x => x.toLowerCase().includes(tagword.replace("<", ""))) // Filter by tagword
|
| 431 |
+
} else {
|
| 432 |
+
tempResults = embeddings;
|
| 433 |
+
}
|
| 434 |
+
// Since some tags are kaomoji, we have to still get the normal results first.
|
| 435 |
+
genericResults = allTags.filter(x => x[0].toLowerCase().includes(tagword)).slice(0, acConfig.maxResults);
|
| 436 |
+
results = genericResults.concat(tempResults.map(x => ["Embeddings: " + x.trim(), "embedding"])); // Mark as embedding
|
| 437 |
+
} else {
|
| 438 |
+
if (acConfig.translation.searchByTranslation) {
|
| 439 |
+
results = allTags.filter(x => x[2] && x[2].toLowerCase().includes(tagword)); // check have translation
|
| 440 |
+
// if search by [a~z],first list the translations, and then search English if it is not enough
|
| 441 |
+
// if only show translation,it is unnecessary to list English results
|
| 442 |
+
if (!acConfig.translation.onlyShowTranslation) {
|
| 443 |
+
results = results.concat(allTags.filter(x => x[0].toLowerCase().includes(tagword) && !results.includes(x)));
|
| 444 |
+
}
|
| 445 |
+
} else {
|
| 446 |
+
results = allTags.filter(x => x[0].toLowerCase().includes(tagword));
|
| 447 |
+
}
|
| 448 |
+
// it's good to show all results
|
| 449 |
+
if (!acConfig.showAllResults) {
|
| 450 |
+
results = results.slice(0, acConfig.maxResults);
|
| 451 |
+
}
|
| 452 |
+
}
|
| 453 |
+
|
| 454 |
+
// Guard for empty results
|
| 455 |
+
if (!results.length) {
|
| 456 |
+
hideResults(textArea);
|
| 457 |
+
return;
|
| 458 |
+
}
|
| 459 |
+
|
| 460 |
+
showResults(textArea);
|
| 461 |
+
addResultsToList(textArea, results, tagword, true);
|
| 462 |
+
}
|
| 463 |
+
|
| 464 |
+
function navigateInList(textArea, event) {
|
| 465 |
+
// Return if the function is deactivated in the UI
|
| 466 |
+
if (!acActive) return;
|
| 467 |
+
|
| 468 |
+
validKeys = ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Enter", "Tab", "Escape"];
|
| 469 |
+
|
| 470 |
+
if (!validKeys.includes(event.key)) return;
|
| 471 |
+
if (!isVisible(textArea)) return
|
| 472 |
+
// Return if ctrl key is pressed to not interfere with weight editing shortcut
|
| 473 |
+
if (event.ctrlKey || event.altKey) return;
|
| 474 |
+
|
| 475 |
+
oldSelectedTag = selectedTag;
|
| 476 |
+
|
| 477 |
+
switch (event.key) {
|
| 478 |
+
case "ArrowUp":
|
| 479 |
+
if (selectedTag === null) {
|
| 480 |
+
selectedTag = resultCount - 1;
|
| 481 |
+
} else {
|
| 482 |
+
selectedTag = (selectedTag - 1 + resultCount) % resultCount;
|
| 483 |
+
}
|
| 484 |
+
break;
|
| 485 |
+
case "ArrowDown":
|
| 486 |
+
if (selectedTag === null) {
|
| 487 |
+
selectedTag = 0;
|
| 488 |
+
} else {
|
| 489 |
+
selectedTag = (selectedTag + 1) % resultCount;
|
| 490 |
+
}
|
| 491 |
+
break;
|
| 492 |
+
case "ArrowLeft":
|
| 493 |
+
selectedTag = 0;
|
| 494 |
+
break;
|
| 495 |
+
case "ArrowRight":
|
| 496 |
+
selectedTag = resultCount - 1;
|
| 497 |
+
break;
|
| 498 |
+
case "Enter":
|
| 499 |
+
if (selectedTag !== null) {
|
| 500 |
+
insertTextAtCursor(textArea, results[selectedTag], tagword);
|
| 501 |
+
}
|
| 502 |
+
break;
|
| 503 |
+
case "Tab":
|
| 504 |
+
if (selectedTag === null) {
|
| 505 |
+
selectedTag = 0;
|
| 506 |
+
}
|
| 507 |
+
insertTextAtCursor(textArea, results[selectedTag], tagword);
|
| 508 |
+
break;
|
| 509 |
+
case "Escape":
|
| 510 |
+
hideResults(textArea);
|
| 511 |
+
break;
|
| 512 |
+
}
|
| 513 |
+
if (selectedTag === resultCount - 1
|
| 514 |
+
&& (event.key === "ArrowUp" || event.key === "ArrowDown" || event.key === "ArrowLeft" || event.key === "ArrowRight")) {
|
| 515 |
+
addResultsToList(textArea, results, tagword, false);
|
| 516 |
+
}
|
| 517 |
+
// Update highlighting
|
| 518 |
+
if (selectedTag !== null)
|
| 519 |
+
updateSelectionStyle(textArea, selectedTag, oldSelectedTag);
|
| 520 |
+
|
| 521 |
+
// Prevent default behavior
|
| 522 |
+
event.preventDefault();
|
| 523 |
+
event.stopPropagation();
|
| 524 |
+
}
|
| 525 |
+
|
| 526 |
+
var styleAdded = false;
|
| 527 |
+
onUiUpdate(function () {
|
| 528 |
+
// Load config
|
| 529 |
+
if (acConfig === null) {
|
| 530 |
+
try {
|
| 531 |
+
acConfig = JSON.parse(readFile("file/tags/config.json"));
|
| 532 |
+
if (acConfig.translation.onlyShowTranslation) {
|
| 533 |
+
acConfig.translation.searchByTranslation = true; // if only show translation, enable search by translation is necessary
|
| 534 |
+
}
|
| 535 |
+
} catch (e) {
|
| 536 |
+
console.error("Error loading config.json: " + e);
|
| 537 |
+
return;
|
| 538 |
+
}
|
| 539 |
+
}
|
| 540 |
+
// Load main tags and translations
|
| 541 |
+
if (allTags.length === 0) {
|
| 542 |
+
try {
|
| 543 |
+
allTags = loadCSV(`file/tags/${acConfig.tagFile}`);
|
| 544 |
+
} catch (e) {
|
| 545 |
+
console.error("Error loading tags file: " + e);
|
| 546 |
+
return;
|
| 547 |
+
}
|
| 548 |
+
if (acConfig.extra.extraFile) {
|
| 549 |
+
try {
|
| 550 |
+
extras = loadCSV(`file/tags/${acConfig.extra.extraFile}`);
|
| 551 |
+
if (acConfig.extra.onlyTranslationExtraFile) {
|
| 552 |
+
// This works purely on index, so it's not very robust. But a lot faster.
|
| 553 |
+
for (let i = 0, n = extras.length; i < n; i++) {
|
| 554 |
+
if (extras[i][0]) {
|
| 555 |
+
allTags[i][2] = extras[i][0];
|
| 556 |
+
}
|
| 557 |
+
}
|
| 558 |
+
} else {
|
| 559 |
+
extras.forEach(e => {
|
| 560 |
+
// Check if a tag in allTags has the same name as the extra tag
|
| 561 |
+
if (tag = allTags.find(t => t[0] === e[0] && t[1] == e[1])) {
|
| 562 |
+
if (e[2]) // If the extra tag has a translation, add it to the tag
|
| 563 |
+
tag[2] = e[2];
|
| 564 |
+
} else {
|
| 565 |
+
// If the tag doesn't exist, add it to allTags
|
| 566 |
+
allTags.push(e);
|
| 567 |
+
}
|
| 568 |
+
});
|
| 569 |
+
}
|
| 570 |
+
} catch (e) {
|
| 571 |
+
console.error("Error loading extra translation file: " + e);
|
| 572 |
+
return;
|
| 573 |
+
}
|
| 574 |
+
}
|
| 575 |
+
}
|
| 576 |
+
// Load wildcards
|
| 577 |
+
if (wildcardFiles.length === 0 && acConfig.useWildcards) {
|
| 578 |
+
try {
|
| 579 |
+
wildcardFiles = readFile("file/tags/temp/wc.txt").split("\n")
|
| 580 |
+
.filter(x => x.trim().length > 0) // Remove empty lines
|
| 581 |
+
.map(x => x.trim().replace(".txt", "")); // Remove file extension & newlines
|
| 582 |
+
|
| 583 |
+
wildcardFiles.forEach(fName => {
|
| 584 |
+
try {
|
| 585 |
+
wildcards[fName] = readFile(`file/scripts/wildcards/${fName}.txt`).split("\n")
|
| 586 |
+
.filter(x => x.trim().length > 0); // Remove empty lines
|
| 587 |
+
} catch (e) {
|
| 588 |
+
console.log(`Could not load wildcards for ${fName}`);
|
| 589 |
+
}
|
| 590 |
+
});
|
| 591 |
+
} catch (e) {
|
| 592 |
+
console.error("Error loading wildcardNames.txt: " + e);
|
| 593 |
+
}
|
| 594 |
+
}
|
| 595 |
+
// Load embeddings
|
| 596 |
+
if (embeddings.length === 0 && acConfig.useEmbeddings) {
|
| 597 |
+
try {
|
| 598 |
+
embeddings = readFile("file/tags/temp/emb.txt").split("\n")
|
| 599 |
+
.filter(x => x.trim().length > 0) // Remove empty lines
|
| 600 |
+
.map(x => x.replace(".bin", "").replace(".pt", "")); // Remove file extensions
|
| 601 |
+
} catch (e) {
|
| 602 |
+
console.error("Error loading embeddings.txt: " + e);
|
| 603 |
+
}
|
| 604 |
+
}
|
| 605 |
+
|
| 606 |
+
// Find all textareas
|
| 607 |
+
let txt2imgTextArea = gradioApp().querySelector('#txt2img_prompt > label > textarea');
|
| 608 |
+
let img2imgTextArea = gradioApp().querySelector('#img2img_prompt > label > textarea');
|
| 609 |
+
let txt2imgTextArea_n = gradioApp().querySelector('#txt2img_neg_prompt > label > textarea');
|
| 610 |
+
let img2imgTextArea_n = gradioApp().querySelector('#img2img_neg_prompt > label > textarea');
|
| 611 |
+
let textAreas = [txt2imgTextArea, img2imgTextArea, txt2imgTextArea_n, img2imgTextArea_n];
|
| 612 |
+
|
| 613 |
+
let quicksettings = gradioApp().querySelector('#quicksettings');
|
| 614 |
+
|
| 615 |
+
// Not found, we're on a page without prompt textareas
|
| 616 |
+
if (textAreas.every(v => v === null || v === undefined)) return;
|
| 617 |
+
// Already added or unnecessary to add
|
| 618 |
+
if (gradioApp().querySelector('.autocompleteResults.p')) {
|
| 619 |
+
if (gradioApp().querySelector('.autocompleteResults.n') || !acConfig.activeIn.negativePrompts) {
|
| 620 |
+
return;
|
| 621 |
+
}
|
| 622 |
+
} else if (!acConfig.activeIn.txt2img && !acConfig.activeIn.img2img) {
|
| 623 |
+
return;
|
| 624 |
+
}
|
| 625 |
+
|
| 626 |
+
textAreas.forEach(area => {
|
| 627 |
+
|
| 628 |
+
// Return if autocomplete is disabled for the current area type in config
|
| 629 |
+
let textAreaId = getTextAreaIdentifier(area);
|
| 630 |
+
if ((!acConfig.activeIn.img2img && textAreaId.includes("img2img"))
|
| 631 |
+
|| (!acConfig.activeIn.txt2img && textAreaId.includes("txt2img"))
|
| 632 |
+
|| (!acConfig.activeIn.negativePrompts && textAreaId.includes("n"))) {
|
| 633 |
+
return;
|
| 634 |
+
}
|
| 635 |
+
|
| 636 |
+
// Only add listeners once
|
| 637 |
+
if (!area.classList.contains('autocomplete')) {
|
| 638 |
+
// Add our new element
|
| 639 |
+
var resultsDiv = createResultsDiv(area);
|
| 640 |
+
area.parentNode.insertBefore(resultsDiv, area.nextSibling);
|
| 641 |
+
// Hide by default so it doesn't show up on page load
|
| 642 |
+
hideResults(area);
|
| 643 |
+
|
| 644 |
+
// Add autocomplete event listener
|
| 645 |
+
area.addEventListener('input', debounce(() => autocomplete(area, area.value), 100));
|
| 646 |
+
// Add focusout event listener
|
| 647 |
+
area.addEventListener('focusout', debounce(() => hideResults(area), 400));
|
| 648 |
+
// Add up and down arrow event listener
|
| 649 |
+
area.addEventListener('keydown', (e) => navigateInList(area, e));
|
| 650 |
+
|
| 651 |
+
// Add class so we know we've already added the listeners
|
| 652 |
+
area.classList.add('autocomplete');
|
| 653 |
+
}
|
| 654 |
+
});
|
| 655 |
+
|
| 656 |
+
if (gradioApp().querySelector("#acActiveCheckbox") === null) {
|
| 657 |
+
// Add toggle switch
|
| 658 |
+
let cb = createCheckbox();
|
| 659 |
+
cb.querySelector("input").checked = acActive;
|
| 660 |
+
cb.querySelector("input").addEventListener("change", (e) => {
|
| 661 |
+
acActive = e.target.checked;
|
| 662 |
+
});
|
| 663 |
+
quicksettings.parentNode.insertBefore(cb, quicksettings.nextSibling);
|
| 664 |
+
}
|
| 665 |
+
|
| 666 |
+
if (styleAdded) return;
|
| 667 |
+
|
| 668 |
+
// Add style to dom
|
| 669 |
+
let acStyle = document.createElement('style');
|
| 670 |
+
let css = gradioApp().querySelector('.dark') ? autocompleteCSS_dark : autocompleteCSS_light;
|
| 671 |
+
if (acStyle.styleSheet) {
|
| 672 |
+
acStyle.styleSheet.cssText = css;
|
| 673 |
+
} else {
|
| 674 |
+
acStyle.appendChild(document.createTextNode(css));
|
| 675 |
+
}
|
| 676 |
+
gradioApp().appendChild(acStyle);
|
| 677 |
+
styleAdded = true;
|
| 678 |
+
});
|