| var acConfig = null; |
| var acActive = true; |
|
|
| |
| let autocompleteCSS_dark = ` |
| .autocompleteResults { |
| position: absolute; |
| z-index: 999; |
| margin: 5px 0 0 0; |
| background-color: #0b0f19 !important; |
| border: 1px solid #4b5563 !important; |
| border-radius: 12px !important; |
| overflow-y: auto; |
| } |
| .autocompleteResultsList > li:nth-child(odd) { |
| background-color: #111827; |
| } |
| .autocompleteResultsList > li { |
| list-style-type: none; |
| padding: 10px; |
| cursor: pointer; |
| } |
| .autocompleteResultsList > li:hover { |
| background-color: #1f2937; |
| } |
| .autocompleteResultsList > li.selected { |
| background-color: #374151; |
| } |
| `; |
| let autocompleteCSS_light = ` |
| .autocompleteResults { |
| position: absolute; |
| z-index: 999; |
| margin: 5px 0 0 0; |
| background-color: #ffffff !important; |
| border: 1.5px solid #e5e7eb !important; |
| border-radius: 12px !important; |
| overflow-y: auto; |
| } |
| .autocompleteResultsList > li:nth-child(odd) { |
| background-color: #f9fafb; |
| } |
| .autocompleteResultsList > li { |
| list-style-type: none; |
| padding: 10px; |
| cursor: pointer; |
| } |
| .autocompleteResultsList > li:hover { |
| background-color: #f5f6f8; |
| } |
| .autocompleteResultsList > li.selected { |
| background-color: #e5e7eb; |
| } |
| `; |
|
|
| |
| function parseCSV(str) { |
| var arr = []; |
| var quote = false; |
|
|
| |
| for (var row = 0, col = 0, c = 0; c < str.length; c++) { |
| var cc = str[c], nc = str[c + 1]; |
| arr[row] = arr[row] || []; |
| arr[row][col] = arr[row][col] || ''; |
|
|
| |
| |
| |
| if (cc == '"' && quote && nc == '"') { arr[row][col] += cc; ++c; continue; } |
|
|
| |
| if (cc == '"') { quote = !quote; continue; } |
|
|
| |
| if (cc == ',' && !quote) { ++col; continue; } |
|
|
| |
| |
| if (cc == '\r' && nc == '\n' && !quote) { ++row; col = 0; ++c; continue; } |
|
|
| |
| |
| if (cc == '\n' && !quote) { ++row; col = 0; continue; } |
| if (cc == '\r' && !quote) { ++row; col = 0; continue; } |
|
|
| |
| arr[row][col] += cc; |
| } |
| return arr; |
| } |
|
|
| |
| function readFile(filePath) { |
| let request = new XMLHttpRequest(); |
| request.open("GET", filePath, false); |
| request.send(null); |
| return request.responseText; |
| } |
|
|
| |
| function loadCSV(path) { |
| let text = readFile(path); |
| return parseCSV(text); |
| } |
|
|
| |
| var dbTimeOut; |
| const debounce = (func, wait = 300) => { |
| return function (...args) { |
| if (dbTimeOut) { |
| clearTimeout(dbTimeOut); |
| } |
|
|
| dbTimeOut = setTimeout(() => { |
| func.apply(this, args); |
| }, wait); |
| } |
| } |
|
|
| |
| function difference(a, b) { |
| if (a.length == 0) { |
| return b; |
| } |
| if (b.length == 0) { |
| return a; |
| } |
|
|
| return [...b.reduce((acc, v) => acc.set(v, (acc.get(v) || 0) - 1), |
| a.reduce((acc, v) => acc.set(v, (acc.get(v) || 0) + 1), new Map()) |
| )].reduce((acc, [v, count]) => acc.concat(Array(Math.abs(count)).fill(v)), []); |
| } |
|
|
| |
| function getTextAreaIdentifier(textArea) { |
| let txt2img_p = gradioApp().querySelector('#txt2img_prompt > label > textarea'); |
| let txt2img_n = gradioApp().querySelector('#txt2img_neg_prompt > label > textarea'); |
| let img2img_p = gradioApp().querySelector('#img2img_prompt > label > textarea'); |
| let img2img_n = gradioApp().querySelector('#img2img_neg_prompt > label > textarea'); |
|
|
| let modifier = ""; |
| switch (textArea) { |
| case txt2img_p: |
| modifier = ".txt2img.p"; |
| break; |
| case txt2img_n: |
| modifier = ".txt2img.n"; |
| break; |
| case img2img_p: |
| modifier = ".img2img.p"; |
| break; |
| case img2img_n: |
| modifier = ".img2img.n"; |
| break; |
| default: |
| break; |
| } |
| return modifier; |
| } |
|
|
| |
| function createResultsDiv(textArea) { |
| let resultsDiv = document.createElement("div"); |
| let resultsList = document.createElement('ul'); |
|
|
| let textAreaId = getTextAreaIdentifier(textArea); |
| let typeClass = textAreaId.replaceAll(".", " "); |
|
|
| resultsDiv.style.setProperty("max-height", acConfig.maxResults * 50 + "px"); |
| resultsDiv.setAttribute('class', `autocompleteResults ${typeClass}`); |
| resultsList.setAttribute('class', 'autocompleteResultsList'); |
| resultsDiv.appendChild(resultsList); |
|
|
| return resultsDiv; |
| } |
|
|
| |
| function createCheckbox() { |
| let label = document.createElement("label"); |
| let input = document.createElement("input"); |
| let span = document.createElement("span"); |
|
|
| label.setAttribute('id', 'acActiveCheckbox'); |
| label.setAttribute('class', '"flex items-center text-gray-700 text-sm rounded-lg cursor-pointer dark:bg-transparent'); |
| input.setAttribute('type', 'checkbox'); |
| input.setAttribute('class', 'gr-check-radio gr-checkbox') |
| span.setAttribute('class', 'ml-2'); |
|
|
| span.textContent = "Enable Autocomplete"; |
|
|
| label.appendChild(input); |
| label.appendChild(span); |
| return label; |
| } |
|
|
| |
| var selectedTag = null; |
| var previousTags = []; |
|
|
| |
| function isVisible(textArea) { |
| let textAreaId = getTextAreaIdentifier(textArea); |
| let resultsDiv = gradioApp().querySelector('.autocompleteResults' + textAreaId); |
| return resultsDiv.style.display === "block"; |
| } |
| function showResults(textArea) { |
| let textAreaId = getTextAreaIdentifier(textArea); |
| let resultsDiv = gradioApp().querySelector('.autocompleteResults' + textAreaId); |
| resultsDiv.style.display = "block"; |
| } |
| function hideResults(textArea) { |
| let textAreaId = getTextAreaIdentifier(textArea); |
| let resultsDiv = gradioApp().querySelector('.autocompleteResults' + textAreaId); |
| resultsDiv.style.display = "none"; |
| selectedTag = null; |
| } |
|
|
| function escapeRegExp(string) { |
| return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); |
| } |
|
|
| let hideBlocked = false; |
|
|
| |
| function insertTextAtCursor(textArea, result, tagword) { |
| let text = result[0]; |
| let tagType = result[1]; |
|
|
| let cursorPos = textArea.selectionStart; |
| var sanitizedText = text |
|
|
| |
| if (tagType === "wildcardFile") { |
| sanitizedText = "__" + text.replace("Wildcards: ", "") + "__"; |
| } else if (tagType === "wildcardTag") { |
| sanitizedText = text.replace(/^.*?: /g, ""); |
| } else if (tagType === "embedding") { |
| sanitizedText = `<${text.replace(/^.*?: /g, "")}>`; |
| } else { |
| sanitizedText = acConfig.replaceUnderscores ? text.replaceAll("_", " ") : text; |
| } |
|
|
| if (acConfig.escapeParentheses) { |
| sanitizedText = sanitizedText |
| .replaceAll("(", "\\(") |
| .replaceAll(")", "\\)") |
| .replaceAll("[", "\\[") |
| .replaceAll("]", "\\]"); |
| } |
|
|
| var prompt = textArea.value; |
|
|
| |
| let editStart = Math.max(cursorPos - tagword.length, 0); |
| let editEnd = Math.min(cursorPos + tagword.length, prompt.length); |
| let surrounding = prompt.substring(editStart, editEnd); |
| let match = surrounding.match(new RegExp(escapeRegExp(`${tagword}`))); |
| let afterInsertCursorPos = editStart + match.index + sanitizedText.length; |
|
|
| var optionalComma = ""; |
| if (tagType !== "wildcardFile") { |
| optionalComma = surrounding.match(new RegExp(escapeRegExp(`${tagword},`))) !== null ? "" : ", "; |
| } |
|
|
| |
| let insert = surrounding.replace(tagword, sanitizedText + optionalComma); |
|
|
| |
| var newPrompt = prompt.substring(0, editStart) + insert + prompt.substring(editEnd); |
| textArea.value = newPrompt; |
| textArea.selectionStart = afterInsertCursorPos + optionalComma.length; |
| textArea.selectionEnd = textArea.selectionStart |
|
|
| |
| |
| textArea.dispatchEvent(new Event("input", { bubbles: true })); |
|
|
| |
| let tags = newPrompt.match(/[^, ]+/g); |
| previousTags = tags; |
|
|
| |
| if (tagType === "wildcardFile") { |
| |
| hideBlocked = true; |
| autocomplete(textArea, prompt, sanitizedText); |
| setTimeout(() => { hideBlocked = false; }, 100); |
| } else { |
| hideResults(textArea); |
| } |
| } |
|
|
| function addResultsToList(textArea, results, tagword, resetList) { |
| let textAreaId = getTextAreaIdentifier(textArea); |
| let resultDiv = gradioApp().querySelector('.autocompleteResults' + textAreaId); |
| let resultsList = resultDiv.querySelector('ul'); |
|
|
| |
| if (resetList) { |
| resultsList.innerHTML = ""; |
| selectedTag = null; |
| resultDiv.scrollTop = 0; |
| resultCount = 0; |
| } |
|
|
| |
| let tagFileName = acConfig.tagFile.split(".")[0]; |
| let tagColors = acConfig.colors; |
| let mode = gradioApp().querySelector('.dark') ? 0 : 1; |
| let nextLength = Math.min(results.length, resultCount + acConfig.resultStepLength); |
|
|
| for (let i = resultCount; i < nextLength; i++) { |
| let result = results[i]; |
| let li = document.createElement("li"); |
|
|
| |
| if (result[2]) { |
| li.textContent = result[2]; |
| if (!acConfig.translation.onlyShowTranslation) { |
| li.textContent += " >> " + result[0]; |
| } |
| } else { |
| li.textContent = result[0]; |
| } |
|
|
| |
| if (!result[1].startsWith("wildcard") && result[1] !== "embedding") { |
| |
| let tagType = result[1]; |
| let colorGroup = tagColors[tagFileName]; |
| |
| if (colorGroup === undefined) colorGroup = tagColors["danbooru"]; |
|
|
| li.style = `color: ${colorGroup[tagType][mode]};`; |
| } |
|
|
| |
| li.addEventListener("click", function () { insertTextAtCursor(textArea, result, tagword); }); |
| |
| resultsList.appendChild(li); |
| } |
| resultCount = nextLength; |
| } |
|
|
| function updateSelectionStyle(textArea, newIndex, oldIndex) { |
| let textAreaId = getTextAreaIdentifier(textArea); |
| let resultDiv = gradioApp().querySelector('.autocompleteResults' + textAreaId); |
| let resultsList = resultDiv.querySelector('ul'); |
| let items = resultsList.getElementsByTagName('li'); |
|
|
| if (oldIndex != null) { |
| items[oldIndex].classList.remove('selected'); |
| } |
|
|
| |
| if (newIndex !== null) { |
| items[newIndex].classList.add('selected'); |
| } |
|
|
| |
| if (items.length > acConfig.maxResults) { |
| let selected = items[newIndex]; |
| resultDiv.scrollTop = selected.offsetTop - resultDiv.offsetTop; |
| } |
| } |
|
|
| var wildcardFiles = []; |
| var wildcards = {}; |
| var embeddings = []; |
| var allTags = []; |
| var results = []; |
| var tagword = ""; |
| var resultCount = 0; |
| function autocomplete(textArea, prompt, fixedTag = null) { |
| |
| if (!acActive) return; |
|
|
| |
| if (prompt.length === 0) { |
| hideResults(textArea); |
| return; |
| } |
|
|
| if (fixedTag === null) { |
| |
| let tags = prompt.match(/[^, ]+/g); |
| let diff = difference(tags, previousTags) |
| previousTags = tags; |
|
|
| |
| if (diff === null || diff.length === 0) { |
| if (!hideBlocked) hideResults(textArea); |
| return; |
| } |
|
|
| tagword = diff[0] |
|
|
| |
| if (tagword === null || tagword.length === 0) { |
| hideResults(textArea); |
| return; |
| } |
| } else { |
| tagword = fixedTag; |
| } |
|
|
| tagword = tagword.toLowerCase(); |
|
|
| if (acConfig.useWildcards && [...tagword.matchAll(/\b__([^,_ ]+)__([^, ]*)\b/g)].length > 0) { |
| |
| wcMatch = [...tagword.matchAll(/\b__([^,_ ]+)__([^, ]*)\b/g)] |
| let wcFile = wcMatch[0][1]; |
| let wcWord = wcMatch[0][2]; |
| results = wildcards[wcFile].filter(x => (wcWord !== null) ? x.toLowerCase().includes(wcWord) : x) |
| .map(x => [wcFile + ": " + x.trim(), "wildcardTag"]); |
| } else if (acConfig.useWildcards && (tagword.startsWith("__") && !tagword.endsWith("__") || tagword === "__")) { |
| |
| let tempResults = []; |
| if (tagword !== "__") { |
| tempResults = wildcardFiles.filter(x => x.toLowerCase().includes(tagword.replace("__", ""))) |
| } else { |
| tempResults = wildcardFiles; |
| } |
| results = tempResults.map(x => ["Wildcards: " + x.trim(), "wildcardFile"]); |
| } else if (acConfig.useEmbeddings && tagword.match(/<[^,> ]*>?/g)) { |
| |
| let tempResults = []; |
| if (tagword !== "<") { |
| tempResults = embeddings.filter(x => x.toLowerCase().includes(tagword.replace("<", ""))) |
| } else { |
| tempResults = embeddings; |
| } |
| |
| genericResults = allTags.filter(x => x[0].toLowerCase().includes(tagword)).slice(0, acConfig.maxResults); |
| results = genericResults.concat(tempResults.map(x => ["Embeddings: " + x.trim(), "embedding"])); |
| } else { |
| if (acConfig.translation.searchByTranslation) { |
| results = allTags.filter(x => x[2] && x[2].toLowerCase().includes(tagword)); |
| |
| |
| if (!acConfig.translation.onlyShowTranslation) { |
| results = results.concat(allTags.filter(x => x[0].toLowerCase().includes(tagword) && !results.includes(x))); |
| } |
| } else { |
| results = allTags.filter(x => x[0].toLowerCase().includes(tagword)); |
| } |
| |
| if (!acConfig.showAllResults) { |
| results = results.slice(0, acConfig.maxResults); |
| } |
| } |
|
|
| |
| if (!results.length) { |
| hideResults(textArea); |
| return; |
| } |
|
|
| showResults(textArea); |
| addResultsToList(textArea, results, tagword, true); |
| } |
|
|
| function navigateInList(textArea, event) { |
| |
| if (!acActive) return; |
|
|
| validKeys = ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Enter", "Tab", "Escape"]; |
|
|
| if (!validKeys.includes(event.key)) return; |
| if (!isVisible(textArea)) return |
| |
| if (event.ctrlKey || event.altKey) return; |
|
|
| oldSelectedTag = selectedTag; |
|
|
| switch (event.key) { |
| case "ArrowUp": |
| if (selectedTag === null) { |
| selectedTag = resultCount - 1; |
| } else { |
| selectedTag = (selectedTag - 1 + resultCount) % resultCount; |
| } |
| break; |
| case "ArrowDown": |
| if (selectedTag === null) { |
| selectedTag = 0; |
| } else { |
| selectedTag = (selectedTag + 1) % resultCount; |
| } |
| break; |
| case "ArrowLeft": |
| selectedTag = 0; |
| break; |
| case "ArrowRight": |
| selectedTag = resultCount - 1; |
| break; |
| case "Enter": |
| if (selectedTag !== null) { |
| insertTextAtCursor(textArea, results[selectedTag], tagword); |
| } |
| break; |
| case "Tab": |
| if (selectedTag === null) { |
| selectedTag = 0; |
| } |
| insertTextAtCursor(textArea, results[selectedTag], tagword); |
| break; |
| case "Escape": |
| hideResults(textArea); |
| break; |
| } |
| if (selectedTag === resultCount - 1 |
| && (event.key === "ArrowUp" || event.key === "ArrowDown" || event.key === "ArrowLeft" || event.key === "ArrowRight")) { |
| addResultsToList(textArea, results, tagword, false); |
| } |
| |
| if (selectedTag !== null) |
| updateSelectionStyle(textArea, selectedTag, oldSelectedTag); |
|
|
| |
| event.preventDefault(); |
| event.stopPropagation(); |
| } |
|
|
| var styleAdded = false; |
| onUiUpdate(function () { |
| |
| if (acConfig === null) { |
| try { |
| acConfig = JSON.parse(readFile("file/tags/config.json")); |
| if (acConfig.translation.onlyShowTranslation) { |
| acConfig.translation.searchByTranslation = true; |
| } |
| } catch (e) { |
| console.error("Error loading config.json: " + e); |
| return; |
| } |
| } |
| |
| if (allTags.length === 0) { |
| try { |
| allTags = loadCSV(`file/tags/${acConfig.tagFile}`); |
| } catch (e) { |
| console.error("Error loading tags file: " + e); |
| return; |
| } |
| if (acConfig.extra.extraFile) { |
| try { |
| extras = loadCSV(`file/tags/${acConfig.extra.extraFile}`); |
| if (acConfig.extra.onlyTranslationExtraFile) { |
| |
| for (let i = 0, n = extras.length; i < n; i++) { |
| if (extras[i][0]) { |
| allTags[i][2] = extras[i][0]; |
| } |
| } |
| } else { |
| extras.forEach(e => { |
| |
| if (tag = allTags.find(t => t[0] === e[0] && t[1] == e[1])) { |
| if (e[2]) |
| tag[2] = e[2]; |
| } else { |
| |
| allTags.push(e); |
| } |
| }); |
| } |
| } catch (e) { |
| console.error("Error loading extra translation file: " + e); |
| return; |
| } |
| } |
| } |
| |
| if (wildcardFiles.length === 0 && acConfig.useWildcards) { |
| try { |
| wildcardFiles = readFile("file/tags/temp/wc.txt").split("\n") |
| .filter(x => x.trim().length > 0) |
| .map(x => x.trim().replace(".txt", "")); |
|
|
| wildcardFiles.forEach(fName => { |
| try { |
| wildcards[fName] = readFile(`file/scripts/wildcards/${fName}.txt`).split("\n") |
| .filter(x => x.trim().length > 0); |
| } catch (e) { |
| console.log(`Could not load wildcards for ${fName}`); |
| } |
| }); |
| } catch (e) { |
| console.error("Error loading wildcardNames.txt: " + e); |
| } |
| } |
| |
| if (embeddings.length === 0 && acConfig.useEmbeddings) { |
| try { |
| embeddings = readFile("file/tags/temp/emb.txt").split("\n") |
| .filter(x => x.trim().length > 0) |
| .map(x => x.replace(".bin", "").replace(".pt", "")); |
| } catch (e) { |
| console.error("Error loading embeddings.txt: " + e); |
| } |
| } |
|
|
| |
| let txt2imgTextArea = gradioApp().querySelector('#txt2img_prompt > label > textarea'); |
| let img2imgTextArea = gradioApp().querySelector('#img2img_prompt > label > textarea'); |
| let txt2imgTextArea_n = gradioApp().querySelector('#txt2img_neg_prompt > label > textarea'); |
| let img2imgTextArea_n = gradioApp().querySelector('#img2img_neg_prompt > label > textarea'); |
| let textAreas = [txt2imgTextArea, img2imgTextArea, txt2imgTextArea_n, img2imgTextArea_n]; |
|
|
| let quicksettings = gradioApp().querySelector('#quicksettings'); |
|
|
| |
| if (textAreas.every(v => v === null || v === undefined)) return; |
| |
| if (gradioApp().querySelector('.autocompleteResults.p')) { |
| if (gradioApp().querySelector('.autocompleteResults.n') || !acConfig.activeIn.negativePrompts) { |
| return; |
| } |
| } else if (!acConfig.activeIn.txt2img && !acConfig.activeIn.img2img) { |
| return; |
| } |
|
|
| textAreas.forEach(area => { |
|
|
| |
| let textAreaId = getTextAreaIdentifier(area); |
| if ((!acConfig.activeIn.img2img && textAreaId.includes("img2img")) |
| || (!acConfig.activeIn.txt2img && textAreaId.includes("txt2img")) |
| || (!acConfig.activeIn.negativePrompts && textAreaId.includes("n"))) { |
| return; |
| } |
|
|
| |
| if (!area.classList.contains('autocomplete')) { |
| |
| var resultsDiv = createResultsDiv(area); |
| area.parentNode.insertBefore(resultsDiv, area.nextSibling); |
| |
| hideResults(area); |
|
|
| |
| area.addEventListener('input', debounce(() => autocomplete(area, area.value), 100)); |
| |
| area.addEventListener('focusout', debounce(() => hideResults(area), 400)); |
| |
| area.addEventListener('keydown', (e) => navigateInList(area, e)); |
|
|
| |
| area.classList.add('autocomplete'); |
| } |
| }); |
|
|
| if (gradioApp().querySelector("#acActiveCheckbox") === null) { |
| |
| let cb = createCheckbox(); |
| cb.querySelector("input").checked = acActive; |
| cb.querySelector("input").addEventListener("change", (e) => { |
| acActive = e.target.checked; |
| }); |
| quicksettings.parentNode.insertBefore(cb, quicksettings.nextSibling); |
| } |
|
|
| if (styleAdded) return; |
|
|
| |
| let acStyle = document.createElement('style'); |
| let css = gradioApp().querySelector('.dark') ? autocompleteCSS_dark : autocompleteCSS_light; |
| if (acStyle.styleSheet) { |
| acStyle.styleSheet.cssText = css; |
| } else { |
| acStyle.appendChild(document.createTextNode(css)); |
| } |
| gradioApp().appendChild(acStyle); |
| styleAdded = true; |
| }); |