Skip to content
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
__pycache__
pysssss.json
user/autocomplete.txt
user/url.txt
web/js/assets/favicon.user.ico
web/js/assets/favicon-active.user.ico
web/js/assets/favicon-active.user.ico
40 changes: 35 additions & 5 deletions py/autocomplete.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,39 @@
from server import PromptServer
from aiohttp import web
from aiohttp import web, ClientSession
import os
import folder_paths

dir = os.path.abspath(os.path.join(__file__, "../../user"))
if not os.path.exists(dir):
os.mkdir(dir)
file = os.path.join(dir, "autocomplete.txt")
tag_file = os.path.join(dir, "autocomplete.txt")
url_file = os.path.join(dir, "url.txt")


@PromptServer.instance.routes.get("/pysssss/autocomplete")
async def get_autocomplete(request):
if os.path.isfile(file):
return web.FileResponse(file)
if os.path.isfile(tag_file):
return web.FileResponse(tag_file)
return web.Response(status=404)


@PromptServer.instance.routes.post("/pysssss/autocomplete")
async def update_autocomplete(request):
with open(file, "w", encoding="utf-8") as f:
with open(tag_file, "w", encoding="utf-8") as f:
f.write(await request.text())
return web.Response(status=200)


@PromptServer.instance.routes.get("/pysssss/cwlUrl")
async def get_url(request):
if os.path.isfile(url_file):
return web.FileResponse(url_file)
return web.Response(status=404)


@PromptServer.instance.routes.post("/pysssss/cwlUrl")
async def update_url(request):
with open(url_file, "w", encoding="utf-8") as f:
f.write(await request.text())
return web.Response(status=200)

Expand All @@ -27,3 +42,18 @@ async def update_autocomplete(request):
async def get_loras(request):
loras = folder_paths.get_filename_list("loras")
return web.json_response(list(map(lambda a: os.path.splitext(a)[0], loras)))


@PromptServer.instance.routes.post("/pysssss/getWordList")
async def get_word_list(request):
proxies = await request.text()
if proxies:
session = ClientSession(proxy=proxies)
else:
session = ClientSession()
with open(url_file, "r", encoding="utf-8") as f:
url = f.read().strip()
async with session.get(url) as resp:
text = await resp.text()
await session.close()
return web.Response(text=text, status=200)
69 changes: 57 additions & 12 deletions web/js/autocompleter.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ import { TextAreaAutoComplete } from "./common/autocomplete.js";
import { ModelInfoDialog } from "./common/modelInfoDialog.js";
import { LoraInfoDialog } from "./modelInfo.js";

const DEFAULT_CWL_URL = "https://gist.githubusercontent.com/pythongosssss/" +
"1d3efa6050356a08cea975183088159a/raw/" +
"a18fb2f94f9156cf4476b0c24a09544d6c0baec6/danbooru-tags.txt";

function parseCSV(csvText) {
const rows = [];
const delimiter = ",";
Expand Down Expand Up @@ -85,6 +89,30 @@ async function getCustomWords() {
return undefined;
}

/**
* 获取自定义词的URL
* @returns {string}
*/
async function getCWLUrl() {
const resp = await api.fetchApi("/pysssss/cwlUrl", { cache: "no-store" });
if (resp.status === 200) {
/** @type {string} */
let url = await resp.text();
return url;
}

return DEFAULT_CWL_URL;
}

/**
* 将自定义词的URL保存到服务器
* @param {string} url
*/
async function saveCWLUrl(url) {
const resp = await api.fetchApi("/pysssss/cwlUrl", { method: "POST", body: url });
return resp.status === 200;
}

async function addCustomWords(text) {
if (!text) {
text = await getCustomWords();
Expand Down Expand Up @@ -177,12 +205,13 @@ class CustomWordsDialog extends ComfyDialog {
},
});

const input = $el("input", {
this.cwlUrl = await getCWLUrl();

this.input = $el("input", {
style: {
flex: "auto",
},
value:
"https://gist.githubusercontent.com/pythongosssss/1d3efa6050356a08cea975183088159a/raw/a18fb2f94f9156cf4476b0c24a09544d6c0baec6/danbooru-tags.txt",
value: this.cwlUrl,
});

super.show(
Expand Down Expand Up @@ -219,17 +248,21 @@ class CustomWordsDialog extends ComfyDialog {
},
[
$el("label", { textContent: "Load Custom List: " }),
input,
this.input,
$el("button", {
textContent: "Load",
onclick: async () => {
try {
const res = await fetch(input.value);
if (res.status !== 200) {
throw new Error("Error loading: " + res.status + " " + res.statusText);
this.cwlUrl = this.input.value || DEFAULT_CWL_URL;
if (!await saveCWLUrl(this.cwlUrl)) {
throw new Error("Error saving URL!");
}
const res = await api.fetchApi("/pysssss/getWordList", {
method: "POST", cache: "no-store", body: app.extensionManager.setting.get(`${id}.Proxies`)
});
this.words.value = await res.text();
} catch (error) {
console.error(error);
alert("Error loading custom list, try manually copy + pasting the list");
}
},
Expand All @@ -249,6 +282,10 @@ class CustomWordsDialog extends ComfyDialog {
textContent: "Save",
onclick: async (e) => {
try {
this.cwlUrl = this.input.value;
if (!await saveCWLUrl(this.cwlUrl)) {
throw new Error("Error saving URL!");
}
const res = await api.fetchApi("/pysssss/autocomplete", { method: "POST", body: this.words.value });
if (res.status !== 200) {
throw new Error("Error saving: " + res.status + " " + res.statusText);
Expand All @@ -259,7 +296,6 @@ class CustomWordsDialog extends ComfyDialog {
save.textContent = "Save";
}, 500);
} catch (error) {
alert("Error saving word list!");
console.error(error);
}
},
Expand All @@ -274,6 +310,15 @@ const id = "pysssss.AutoCompleter";

app.registerExtension({
name: id,
settings: [
{
id: `${id}.Proxies`,
name: "Proxies",
type: "text",
defaultValue: "",
tooltip: "http://<addr>:<port>"
}
],
init() {
const STRING = ComfyWidgets.STRING;
const SKIP_WIDGETS = new Set(["ttN xyPlot.x_values", "ttN xyPlot.y_values"]);
Expand Down Expand Up @@ -494,9 +539,9 @@ app.registerExtension({
onclick: () => {
try {
// Try closing old settings window
if (typeof app.ui.settings.element?.close === "function") {
if (typeof app.ui.settings.element?.close === "function") {
app.ui.settings.element.close();
}
}
} catch (error) {
}
try {
Expand All @@ -506,7 +551,7 @@ app.registerExtension({
// Fallback to just hiding the element
app.ui.settings.element.style.display = "none";
}

new CustomWordsDialog().show();
},
style: {
Expand Down Expand Up @@ -549,7 +594,7 @@ app.registerExtension({
let loras;
try {
loras = LiteGraph.registered_node_types["LoraLoader"]?.nodeData.input.required.lora_name[0];
} catch (error) {}
} catch (error) { }

if (!loras?.length) {
loras = await api.fetchApi("/pysssss/loras", { cache: "no-store" }).then((res) => res.json());
Expand Down
76 changes: 39 additions & 37 deletions web/js/common/autocomplete.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,16 @@ import { addStylesheet } from "./utils.js";
addStylesheet(import.meta.url);

/*
https://github.com/component/textarea-caret-position
The MIT License (MIT)
https://github.com/component/textarea-caret-position
The MIT License (MIT)

Copyright (c) 2015 Jonathan Ong me@jongleberry.com
Copyright (c) 2015 Jonathan Ong me@jongleberry.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
const getCaretCoordinates = (function () {
// We'll copy the properties below into the mirror div.
Expand Down Expand Up @@ -140,10 +140,12 @@ const getCaretCoordinates = (function () {
span.textContent = element.value.substring(position) || "."; // || because a completely empty faux span doesn't render at all
div.appendChild(span);

const lineHeight = Math.ceil(parseFloat(computed["lineHeight"]));

var coordinates = {
top: span.offsetTop + parseInt(computed["borderTopWidth"]),
left: span.offsetLeft + parseInt(computed["borderLeftWidth"]),
height: parseInt(computed["lineHeight"]),
height: lineHeight,
};

if (debug) {
Expand All @@ -157,19 +159,19 @@ const getCaretCoordinates = (function () {
})();

/*
Key functions from:
https://github.com/yuku/textcomplete
© Yuku Takahashi - This software is licensed under the MIT license.
Key functions from:
https://github.com/yuku/textcomplete
© Yuku Takahashi - This software is licensed under the MIT license.

The MIT License (MIT)
The MIT License (MIT)

Copyright (c) 2015 Jonathan Ong me@jongleberry.com
Copyright (c) 2015 Jonathan Ong me@jongleberry.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
const CHAR_CODE_ZERO = "0".charCodeAt(0);
const CHAR_CODE_NINE = "9".charCodeAt(0);
Expand Down Expand Up @@ -613,29 +615,29 @@ export class TextAreaAutoComplete {
const item = $el(
"div.pysssss-autocomplete-item",
{
onclick: () => {
this.el.focus();
let value = wordInfo.value ?? wordInfo.text;
const use_replacer = wordInfo.use_replacer ?? true;
if (TextAreaAutoComplete.replacer && use_replacer) {
value = TextAreaAutoComplete.replacer(value);
}
value = this.#escapeParentheses(value);
const afterCursor = this.helper.getAfterCursor();
const shouldAddSeparator = !afterCursor.trim().startsWith(this.separator.trim());
this.helper.insertAtCursor(
value + (shouldAddSeparator ? this.separator : ''),
-before.length,
wordInfo.caretOffset
);
setTimeout(() => {
this.#update();
}, 150);
},
onclick: () => {
this.el.focus();
let value = wordInfo.value ?? wordInfo.text;
const use_replacer = wordInfo.use_replacer ?? true;
if (TextAreaAutoComplete.replacer && use_replacer) {
value = TextAreaAutoComplete.replacer(value);
}
value = this.#escapeParentheses(value);

const afterCursor = this.helper.getAfterCursor();
const shouldAddSeparator = !afterCursor.trim().startsWith(this.separator.trim());
this.helper.insertAtCursor(
value + (shouldAddSeparator ? this.separator : ''),
-before.length,
wordInfo.caretOffset
);
setTimeout(() => {
this.#update();
}, 150);
},
},
parts
);
);

if (wordInfo === this.selected) {
hasSelected = true;
Expand All @@ -662,7 +664,7 @@ export class TextAreaAutoComplete {

#escapeParentheses(text) {
return text.replace(/\(/g, '\\(').replace(/\)/g, '\\)');
}
}

#hide() {
this.selected = null;
Expand Down