new extension manager

This commit is contained in:
Vladimir Mandic
2023-05-10 15:12:02 -04:00
parent aad2a53379
commit c5df80197e
27 changed files with 2959 additions and 2996 deletions
+106 -107
View File
@@ -1,107 +1,106 @@
let currentWidth = null;
let currentHeight = null;
let arFrameTimeout = setTimeout(() => {}, 0);
function dimensionChange(e, is_width, is_height) {
if (is_width) {
currentWidth = e.target.value * 1.0;
}
if (is_height) {
currentHeight = e.target.value * 1.0;
}
const inImg2img = gradioApp().querySelector('#tab_img2img').style.display == 'block';
if (!inImg2img) {
return;
}
let targetElement = null;
const tabIndex = get_tab_index('mode_img2img');
if (tabIndex == 0) { // img2img
targetElement = gradioApp().querySelector('#img2img_image div[data-testid=image] img');
} else if (tabIndex == 1) { // Sketch
targetElement = gradioApp().querySelector('#img2img_sketch div[data-testid=image] img');
} else if (tabIndex == 2) { // Inpaint
targetElement = gradioApp().querySelector('#img2maskimg div[data-testid=image] img');
} else if (tabIndex == 3) { // Inpaint sketch
targetElement = gradioApp().querySelector('#inpaint_sketch div[data-testid=image] img');
}
if (targetElement) {
let arPreviewRect = gradioApp().querySelector('#imageARPreview');
if (!arPreviewRect) {
arPreviewRect = document.createElement('div');
arPreviewRect.id = 'imageARPreview';
gradioApp().appendChild(arPreviewRect);
}
const viewportOffset = targetElement.getBoundingClientRect();
viewportscale = Math.min(targetElement.clientWidth / targetElement.naturalWidth, targetElement.clientHeight / targetElement.naturalHeight);
scaledx = targetElement.naturalWidth * viewportscale;
scaledy = targetElement.naturalHeight * viewportscale;
cleintRectTop = (viewportOffset.top + window.scrollY);
cleintRectLeft = (viewportOffset.left + window.scrollX);
cleintRectCentreY = cleintRectTop + (targetElement.clientHeight / 2);
cleintRectCentreX = cleintRectLeft + (targetElement.clientWidth / 2);
viewRectTop = cleintRectCentreY - (scaledy / 2);
viewRectLeft = cleintRectCentreX - (scaledx / 2);
arRectWidth = scaledx;
arRectHeight = scaledy;
arscale = Math.min(arRectWidth / currentWidth, arRectHeight / currentHeight);
arscaledx = currentWidth * arscale;
arscaledy = currentHeight * arscale;
arRectTop = cleintRectCentreY - (arscaledy / 2);
arRectLeft = cleintRectCentreX - (arscaledx / 2);
arRectWidth = arscaledx;
arRectHeight = arscaledy;
arPreviewRect.style.top = `${arRectTop}px`;
arPreviewRect.style.left = `${arRectLeft}px`;
arPreviewRect.style.width = `${arRectWidth}px`;
arPreviewRect.style.height = `${arRectHeight}px`;
clearTimeout(arFrameTimeout);
arFrameTimeout = setTimeout(() => {
arPreviewRect.style.display = 'none';
}, 2000);
arPreviewRect.style.display = 'block';
}
}
onUiUpdate(() => {
const arPreviewRect = gradioApp().querySelector('#imageARPreview');
if (arPreviewRect) {
arPreviewRect.style.display = 'none';
}
const tabImg2img = gradioApp().querySelector('#tab_img2img');
if (tabImg2img) {
const inImg2img = tabImg2img.style.display == 'block';
if (inImg2img) {
const inputs = gradioApp().querySelectorAll('input');
inputs.forEach((e) => {
const is_width = e.parentElement.id == 'img2img_width';
const is_height = e.parentElement.id == 'img2img_height';
if ((is_width || is_height) && !e.classList.contains('scrollwatch')) {
e.addEventListener('input', (e) => { dimensionChange(e, is_width, is_height); });
e.classList.add('scrollwatch');
}
if (is_width) {
currentWidth = e.value * 1.0;
}
if (is_height) {
currentHeight = e.value * 1.0;
}
});
}
}
});
let currentWidth = null;
let currentHeight = null;
let arFrameTimeout = setTimeout(() => {}, 0);
function dimensionChange(e, is_width, is_height) {
if (is_width) {
currentWidth = e.target.value * 1.0;
}
if (is_height) {
currentHeight = e.target.value * 1.0;
}
const inImg2img = gradioApp().querySelector('#tab_img2img').style.display === 'block';
if (!inImg2img) {
return;
}
let targetElement = null;
const tabIndex = get_tab_index('mode_img2img');
if (tabIndex === 0) { // img2img
targetElement = gradioApp().querySelector('#img2img_image div[data-testid=image] img');
} else if (tabIndex === 1) { // Sketch
targetElement = gradioApp().querySelector('#img2img_sketch div[data-testid=image] img');
} else if (tabIndex === 2) { // Inpaint
targetElement = gradioApp().querySelector('#img2maskimg div[data-testid=image] img');
} else if (tabIndex === 3) { // Inpaint sketch
targetElement = gradioApp().querySelector('#inpaint_sketch div[data-testid=image] img');
}
if (targetElement) {
let arPreviewRect = gradioApp().querySelector('#imageARPreview');
if (!arPreviewRect) {
arPreviewRect = document.createElement('div');
arPreviewRect.id = 'imageARPreview';
gradioApp().appendChild(arPreviewRect);
}
const viewportOffset = targetElement.getBoundingClientRect();
viewportscale = Math.min(targetElement.clientWidth / targetElement.naturalWidth, targetElement.clientHeight / targetElement.naturalHeight);
scaledx = targetElement.naturalWidth * viewportscale;
scaledy = targetElement.naturalHeight * viewportscale;
cleintRectTop = (viewportOffset.top + window.scrollY);
cleintRectLeft = (viewportOffset.left + window.scrollX);
cleintRectCentreY = cleintRectTop + (targetElement.clientHeight / 2);
cleintRectCentreX = cleintRectLeft + (targetElement.clientWidth / 2);
viewRectTop = cleintRectCentreY - (scaledy / 2);
viewRectLeft = cleintRectCentreX - (scaledx / 2);
arRectWidth = scaledx;
arRectHeight = scaledy;
arscale = Math.min(arRectWidth / currentWidth, arRectHeight / currentHeight);
arscaledx = currentWidth * arscale;
arscaledy = currentHeight * arscale;
arRectTop = cleintRectCentreY - (arscaledy / 2);
arRectLeft = cleintRectCentreX - (arscaledx / 2);
arRectWidth = arscaledx;
arRectHeight = arscaledy;
arPreviewRect.style.top = `${arRectTop}px`;
arPreviewRect.style.left = `${arRectLeft}px`;
arPreviewRect.style.width = `${arRectWidth}px`;
arPreviewRect.style.height = `${arRectHeight}px`;
clearTimeout(arFrameTimeout);
arFrameTimeout = setTimeout(() => {
arPreviewRect.style.display = 'none';
}, 2000);
arPreviewRect.style.display = 'block';
}
}
onUiUpdate(() => {
const arPreviewRect = gradioApp().querySelector('#imageARPreview');
if (arPreviewRect) {
arPreviewRect.style.display = 'none';
}
const tabImg2img = gradioApp().querySelector('#tab_img2img');
if (tabImg2img) {
const inImg2img = tabImg2img.style.display === 'block';
if (inImg2img) {
const inputs = gradioApp().querySelectorAll('input');
inputs.forEach((e) => {
const is_width = e.parentElement.id === 'img2img_width';
const is_height = e.parentElement.id === 'img2img_height';
if ((is_width || is_height) && !e.classList.contains('scrollwatch')) {
e.addEventListener('input', (e) => { dimensionChange(e, is_width, is_height); });
e.classList.add('scrollwatch');
}
if (is_width) {
currentWidth = e.value * 1.0;
}
if (is_height) {
currentHeight = e.value * 1.0;
}
});
}
}
});
+176 -176
View File
@@ -1,176 +1,176 @@
contextMenuInit = function () {
let eventListenerApplied = false;
const menuSpecs = new Map();
const uid = function () {
return Date.now().toString(36) + Math.random().toString(36).substr(2);
};
function showContextMenu(event, element, menuEntries) {
const posx = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
const posy = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
const oldMenu = gradioApp().querySelector('#context-menu');
if (oldMenu) {
oldMenu.remove();
}
const tabButton = uiCurrentTab;
const baseStyle = window.getComputedStyle(tabButton);
const contextMenu = document.createElement('nav');
contextMenu.id = 'context-menu';
contextMenu.style.background = baseStyle.background;
contextMenu.style.color = baseStyle.color;
contextMenu.style.fontFamily = baseStyle.fontFamily;
contextMenu.style.top = `${posy}px`;
contextMenu.style.left = `${posx}px`;
const contextMenuList = document.createElement('ul');
contextMenuList.className = 'context-menu-items';
contextMenu.append(contextMenuList);
menuEntries.forEach((entry) => {
const contextMenuEntry = document.createElement('a');
contextMenuEntry.innerHTML = entry.name;
contextMenuEntry.addEventListener('click', (e) => {
entry.func();
});
contextMenuList.append(contextMenuEntry);
});
gradioApp().appendChild(contextMenu);
const menuWidth = contextMenu.offsetWidth + 4;
const menuHeight = contextMenu.offsetHeight + 4;
const windowWidth = window.innerWidth;
const windowHeight = window.innerHeight;
if ((windowWidth - posx) < menuWidth) {
contextMenu.style.left = `${windowWidth - menuWidth}px`;
}
if ((windowHeight - posy) < menuHeight) {
contextMenu.style.top = `${windowHeight - menuHeight}px`;
}
}
function appendContextMenuOption(targetElementSelector, entryName, entryFunction) {
currentItems = menuSpecs.get(targetElementSelector);
if (!currentItems) {
currentItems = [];
menuSpecs.set(targetElementSelector, currentItems);
}
const newItem = {
id: `${targetElementSelector}_${uid()}`,
name: entryName,
func: entryFunction,
isNew: true,
};
currentItems.push(newItem);
return newItem.id;
}
function removeContextMenuOption(uid) {
menuSpecs.forEach((v, k) => {
let index = -1;
v.forEach((e, ei) => { if (e.id == uid) { index = ei; } });
if (index >= 0) {
v.splice(index, 1);
}
});
}
function addContextMenuEventListener() {
if (eventListenerApplied) {
return;
}
gradioApp().addEventListener('click', (e) => {
const source = e.composedPath()[0];
if (source.id && source.id.indexOf('check_progress') > -1) {
return;
}
const oldMenu = gradioApp().querySelector('#context-menu');
if (oldMenu) {
oldMenu.remove();
}
});
gradioApp().addEventListener('contextmenu', (e) => {
const oldMenu = gradioApp().querySelector('#context-menu');
if (oldMenu) {
oldMenu.remove();
}
menuSpecs.forEach((v, k) => {
if (e.composedPath()[0].matches(k)) {
showContextMenu(e, e.composedPath()[0], v);
e.preventDefault();
}
});
});
eventListenerApplied = true;
}
return [appendContextMenuOption, removeContextMenuOption, addContextMenuEventListener];
};
initResponse = contextMenuInit();
appendContextMenuOption = initResponse[0];
removeContextMenuOption = initResponse[1];
addContextMenuEventListener = initResponse[2];
(function () {
// Start example Context Menu Items
const generateOnRepeat = function (genbuttonid, interruptbuttonid) {
const genbutton = gradioApp().querySelector(genbuttonid);
const busy = document.getElementById('progressbar')?.style.display == 'block';
if (!busy) {
genbutton.click();
}
clearInterval(window.generateOnRepeatInterval);
window.generateOnRepeatInterval = setInterval(
() => {
const busy = document.getElementById('progressbar')?.style.display == 'block';
if (!busy) {
genbutton.click();
}
},
500,
);
};
appendContextMenuOption('#txt2img_generate', 'Generate forever', () => {
generateOnRepeat('#txt2img_generate', '#txt2img_interrupt');
});
appendContextMenuOption('#img2img_generate', 'Generate forever', () => {
generateOnRepeat('#img2img_generate', '#img2img_interrupt');
});
const cancelGenerateForever = function () {
clearInterval(window.generateOnRepeatInterval);
};
appendContextMenuOption('#txt2img_interrupt', 'Cancel generate forever', cancelGenerateForever);
appendContextMenuOption('#txt2img_generate', 'Cancel generate forever', cancelGenerateForever);
appendContextMenuOption('#img2img_interrupt', 'Cancel generate forever', cancelGenerateForever);
appendContextMenuOption('#img2img_generate', 'Cancel generate forever', cancelGenerateForever);
appendContextMenuOption(
'#roll',
'Roll three',
() => {
const rollbutton = get_uiCurrentTabContent().querySelector('#roll');
setTimeout(() => { rollbutton.click(); }, 100);
setTimeout(() => { rollbutton.click(); }, 200);
setTimeout(() => { rollbutton.click(); }, 300);
},
);
}());
// End example Context Menu Items
onUiUpdate(() => {
addContextMenuEventListener();
});
contextMenuInit = function () {
let eventListenerApplied = false;
const menuSpecs = new Map();
const uid = function () {
return Date.now().toString(36) + Math.random().toString(36).substr(2);
};
function showContextMenu(event, element, menuEntries) {
const posx = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
const posy = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
const oldMenu = gradioApp().querySelector('#context-menu');
if (oldMenu) {
oldMenu.remove();
}
const tabButton = uiCurrentTab;
const baseStyle = window.getComputedStyle(tabButton);
const contextMenu = document.createElement('nav');
contextMenu.id = 'context-menu';
contextMenu.style.background = baseStyle.background;
contextMenu.style.color = baseStyle.color;
contextMenu.style.fontFamily = baseStyle.fontFamily;
contextMenu.style.top = `${posy}px`;
contextMenu.style.left = `${posx}px`;
const contextMenuList = document.createElement('ul');
contextMenuList.className = 'context-menu-items';
contextMenu.append(contextMenuList);
menuEntries.forEach((entry) => {
const contextMenuEntry = document.createElement('a');
contextMenuEntry.innerHTML = entry.name;
contextMenuEntry.addEventListener('click', (e) => {
entry.func();
});
contextMenuList.append(contextMenuEntry);
});
gradioApp().appendChild(contextMenu);
const menuWidth = contextMenu.offsetWidth + 4;
const menuHeight = contextMenu.offsetHeight + 4;
const windowWidth = window.innerWidth;
const windowHeight = window.innerHeight;
if ((windowWidth - posx) < menuWidth) {
contextMenu.style.left = `${windowWidth - menuWidth}px`;
}
if ((windowHeight - posy) < menuHeight) {
contextMenu.style.top = `${windowHeight - menuHeight}px`;
}
}
function appendContextMenuOption(targetElementSelector, entryName, entryFunction) {
currentItems = menuSpecs.get(targetElementSelector);
if (!currentItems) {
currentItems = [];
menuSpecs.set(targetElementSelector, currentItems);
}
const newItem = {
id: `${targetElementSelector}_${uid()}`,
name: entryName,
func: entryFunction,
isNew: true,
};
currentItems.push(newItem);
return newItem.id;
}
function removeContextMenuOption(uid) {
menuSpecs.forEach((v, k) => {
let index = -1;
v.forEach((e, ei) => { if (e.id === uid) { index = ei; } });
if (index >= 0) {
v.splice(index, 1);
}
});
}
function addContextMenuEventListener() {
if (eventListenerApplied) {
return;
}
gradioApp().addEventListener('click', (e) => {
const source = e.composedPath()[0];
if (source.id && source.id.indexOf('check_progress') > -1) {
return;
}
const oldMenu = gradioApp().querySelector('#context-menu');
if (oldMenu) {
oldMenu.remove();
}
});
gradioApp().addEventListener('contextmenu', (e) => {
const oldMenu = gradioApp().querySelector('#context-menu');
if (oldMenu) {
oldMenu.remove();
}
menuSpecs.forEach((v, k) => {
if (e.composedPath()[0].matches(k)) {
showContextMenu(e, e.composedPath()[0], v);
e.preventDefault();
}
});
});
eventListenerApplied = true;
}
return [appendContextMenuOption, removeContextMenuOption, addContextMenuEventListener];
};
initResponse = contextMenuInit();
appendContextMenuOption = initResponse[0];
removeContextMenuOption = initResponse[1];
addContextMenuEventListener = initResponse[2];
(function () {
// Start example Context Menu Items
const generateOnRepeat = function (genbuttonid, interruptbuttonid) {
const genbutton = gradioApp().querySelector(genbuttonid);
const busy = document.getElementById('progressbar')?.style.display === 'block';
if (!busy) {
genbutton.click();
}
clearInterval(window.generateOnRepeatInterval);
window.generateOnRepeatInterval = setInterval(
() => {
const busy = document.getElementById('progressbar')?.style.display === 'block';
if (!busy) {
genbutton.click();
}
},
500,
);
};
appendContextMenuOption('#txt2img_generate', 'Generate forever', () => {
generateOnRepeat('#txt2img_generate', '#txt2img_interrupt');
});
appendContextMenuOption('#img2img_generate', 'Generate forever', () => {
generateOnRepeat('#img2img_generate', '#img2img_interrupt');
});
const cancelGenerateForever = function () {
clearInterval(window.generateOnRepeatInterval);
};
appendContextMenuOption('#txt2img_interrupt', 'Cancel generate forever', cancelGenerateForever);
appendContextMenuOption('#txt2img_generate', 'Cancel generate forever', cancelGenerateForever);
appendContextMenuOption('#img2img_interrupt', 'Cancel generate forever', cancelGenerateForever);
appendContextMenuOption('#img2img_generate', 'Cancel generate forever', cancelGenerateForever);
appendContextMenuOption(
'#roll',
'Roll three',
() => {
const rollbutton = get_uiCurrentTabContent().querySelector('#roll');
setTimeout(() => { rollbutton.click(); }, 100);
setTimeout(() => { rollbutton.click(); }, 200);
setTimeout(() => { rollbutton.click(); }, 300);
},
);
}());
// End example Context Menu Items
onUiUpdate(() => {
addContextMenuEventListener();
});
+2 -2
View File
@@ -47,7 +47,7 @@ function dropReplaceImage(imgWrap, files) {
window.document.addEventListener('dragover', (e) => {
const target = e.composedPath()[0];
const imgWrap = target.closest('[data-testid="image"]');
if (!imgWrap && target.placeholder && target.placeholder.indexOf('Prompt') == -1) return;
if (!imgWrap && target.placeholder && target.placeholder.indexOf('Prompt') === -1) return;
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
@@ -56,7 +56,7 @@ window.document.addEventListener('dragover', (e) => {
window.document.addEventListener('drop', (e) => {
const target = e.composedPath()[0];
if (!target.placeholder) return;
if (target.placeholder.indexOf('Prompt') == -1) return;
if (target.placeholder.indexOf('Prompt') === -1) return;
const imgWrap = target.closest('[data-testid="image"]');
if (!imgWrap) return;
e.stopPropagation();
+119 -119
View File
@@ -1,119 +1,119 @@
function keyupEditAttention(event) {
const target = event.originalTarget || event.composedPath()[0];
if (!target.matches("[id*='_toprow'] [id*='_prompt'] textarea")) return;
if (!(event.metaKey || event.ctrlKey)) return;
const isPlus = event.key == 'ArrowUp';
const isMinus = event.key == 'ArrowDown';
if (!isPlus && !isMinus) return;
let { selectionStart } = target;
let { selectionEnd } = target;
let text = target.value;
function selectCurrentParenthesisBlock(OPEN, CLOSE) {
if (selectionStart !== selectionEnd) return false;
// Find opening parenthesis around current cursor
const before = text.substring(0, selectionStart);
let beforeParen = before.lastIndexOf(OPEN);
if (beforeParen == -1) return false;
let beforeParenClose = before.lastIndexOf(CLOSE);
while (beforeParenClose !== -1 && beforeParenClose > beforeParen) {
beforeParen = before.lastIndexOf(OPEN, beforeParen - 1);
beforeParenClose = before.lastIndexOf(CLOSE, beforeParenClose - 1);
}
// Find closing parenthesis around current cursor
const after = text.substring(selectionStart);
let afterParen = after.indexOf(CLOSE);
if (afterParen == -1) return false;
let afterParenOpen = after.indexOf(OPEN);
while (afterParenOpen !== -1 && afterParen > afterParenOpen) {
afterParen = after.indexOf(CLOSE, afterParen + 1);
afterParenOpen = after.indexOf(OPEN, afterParenOpen + 1);
}
if (beforeParen === -1 || afterParen === -1) return false;
// Set the selection to the text between the parenthesis
const parenContent = text.substring(beforeParen + 1, selectionStart + afterParen);
const lastColon = parenContent.lastIndexOf(':');
selectionStart = beforeParen + 1;
selectionEnd = selectionStart + lastColon;
target.setSelectionRange(selectionStart, selectionEnd);
return true;
}
function selectCurrentWord() {
if (selectionStart !== selectionEnd) return false;
const delimiters = `${opts.keyedit_delimiters} \r\n\t`;
// seek backward until to find beggining
while (!delimiters.includes(text[selectionStart - 1]) && selectionStart > 0) {
selectionStart--;
}
// seek forward to find end
while (!delimiters.includes(text[selectionEnd]) && selectionEnd < text.length) {
selectionEnd++;
}
target.setSelectionRange(selectionStart, selectionEnd);
return true;
}
// If the user hasn't selected anything, let's select their current parenthesis block or word
if (!selectCurrentParenthesisBlock('<', '>') && !selectCurrentParenthesisBlock('(', ')')) {
selectCurrentWord();
}
event.preventDefault();
closeCharacter = ')';
delta = opts.keyedit_precision_attention;
if (selectionStart > 0 && text[selectionStart - 1] == '<') {
closeCharacter = '>';
delta = opts.keyedit_precision_extra;
} else if (selectionStart == 0 || text[selectionStart - 1] != '(') {
// do not include spaces at the end
while (selectionEnd > selectionStart && text[selectionEnd - 1] == ' ') {
selectionEnd -= 1;
}
if (selectionStart == selectionEnd) {
return;
}
text = `${text.slice(0, selectionStart)}(${text.slice(selectionStart, selectionEnd)}:1.0)${text.slice(selectionEnd)}`;
selectionStart += 1;
selectionEnd += 1;
}
end = text.slice(selectionEnd + 1).indexOf(closeCharacter) + 1;
weight = parseFloat(text.slice(selectionEnd + 1, selectionEnd + 1 + end));
if (isNaN(weight)) return;
weight += isPlus ? delta : -delta;
weight = parseFloat(weight.toPrecision(12));
if (String(weight).length == 1) weight += '.0';
if (closeCharacter == ')' && weight == 1) {
text = text.slice(0, selectionStart - 1) + text.slice(selectionStart, selectionEnd) + text.slice(selectionEnd + 5);
selectionStart--;
selectionEnd--;
} else {
text = text.slice(0, selectionEnd + 1) + weight + text.slice(selectionEnd + 1 + end - 1);
}
target.focus();
target.value = text;
target.selectionStart = selectionStart;
target.selectionEnd = selectionEnd;
updateInput(target);
}
addEventListener('keydown', (event) => {
keyupEditAttention(event);
});
function keyupEditAttention(event) {
const target = event.originalTarget || event.composedPath()[0];
if (!target.matches("[id*='_toprow'] [id*='_prompt'] textarea")) return;
if (!(event.metaKey || event.ctrlKey)) return;
const isPlus = event.key === 'ArrowUp';
const isMinus = event.key === 'ArrowDown';
if (!isPlus && !isMinus) return;
let { selectionStart } = target;
let { selectionEnd } = target;
let text = target.value;
function selectCurrentParenthesisBlock(OPEN, CLOSE) {
if (selectionStart !== selectionEnd) return false;
// Find opening parenthesis around current cursor
const before = text.substring(0, selectionStart);
let beforeParen = before.lastIndexOf(OPEN);
if (beforeParen === -1) return false;
let beforeParenClose = before.lastIndexOf(CLOSE);
while (beforeParenClose !== -1 && beforeParenClose > beforeParen) {
beforeParen = before.lastIndexOf(OPEN, beforeParen - 1);
beforeParenClose = before.lastIndexOf(CLOSE, beforeParenClose - 1);
}
// Find closing parenthesis around current cursor
const after = text.substring(selectionStart);
let afterParen = after.indexOf(CLOSE);
if (afterParen === -1) return false;
let afterParenOpen = after.indexOf(OPEN);
while (afterParenOpen !== -1 && afterParen > afterParenOpen) {
afterParen = after.indexOf(CLOSE, afterParen + 1);
afterParenOpen = after.indexOf(OPEN, afterParenOpen + 1);
}
if (beforeParen === -1 || afterParen === -1) return false;
// Set the selection to the text between the parenthesis
const parenContent = text.substring(beforeParen + 1, selectionStart + afterParen);
const lastColon = parenContent.lastIndexOf(':');
selectionStart = beforeParen + 1;
selectionEnd = selectionStart + lastColon;
target.setSelectionRange(selectionStart, selectionEnd);
return true;
}
function selectCurrentWord() {
if (selectionStart !== selectionEnd) return false;
const delimiters = `${opts.keyedit_delimiters} \r\n\t`;
// seek backward until to find beggining
while (!delimiters.includes(text[selectionStart - 1]) && selectionStart > 0) {
selectionStart--;
}
// seek forward to find end
while (!delimiters.includes(text[selectionEnd]) && selectionEnd < text.length) {
selectionEnd++;
}
target.setSelectionRange(selectionStart, selectionEnd);
return true;
}
// If the user hasn't selected anything, let's select their current parenthesis block or word
if (!selectCurrentParenthesisBlock('<', '>') && !selectCurrentParenthesisBlock('(', ')')) {
selectCurrentWord();
}
event.preventDefault();
closeCharacter = ')';
delta = opts.keyedit_precision_attention;
if (selectionStart > 0 && text[selectionStart - 1] === '<') {
closeCharacter = '>';
delta = opts.keyedit_precision_extra;
} else if (selectionStart === 0 || text[selectionStart - 1] != '(') {
// do not include spaces at the end
while (selectionEnd > selectionStart && text[selectionEnd - 1] === ' ') {
selectionEnd -= 1;
}
if (selectionStart === selectionEnd) {
return;
}
text = `${text.slice(0, selectionStart)}(${text.slice(selectionStart, selectionEnd)}:1.0)${text.slice(selectionEnd)}`;
selectionStart += 1;
selectionEnd += 1;
}
end = text.slice(selectionEnd + 1).indexOf(closeCharacter) + 1;
weight = parseFloat(text.slice(selectionEnd + 1, selectionEnd + 1 + end));
if (isNaN(weight)) return;
weight += isPlus ? delta : -delta;
weight = parseFloat(weight.toPrecision(12));
if (String(weight).length === 1) weight += '.0';
if (closeCharacter === ')' && weight === 1) {
text = text.slice(0, selectionStart - 1) + text.slice(selectionStart, selectionEnd) + text.slice(selectionEnd + 5);
selectionStart--;
selectionEnd--;
} else {
text = text.slice(0, selectionEnd + 1) + weight + text.slice(selectionEnd + 1 + end - 1);
}
target.focus();
target.value = text;
target.selectionStart = selectionStart;
target.selectionEnd = selectionEnd;
updateInput(target);
}
addEventListener('keydown', (event) => {
keyupEditAttention(event);
});
+41 -32
View File
@@ -1,32 +1,41 @@
function extensions_apply(_a, _b, disable_all){
var disable = []
var update = []
gradioApp().querySelectorAll('#extensions input[type="checkbox"]').forEach(function(x){
if(x.name.startsWith("enable_") && ! x.checked) disable.push(x.name.substr(7))
if(x.name.startsWith("update_") && x.checked) update.push(x.name.substr(7))
})
restart_reload()
return [JSON.stringify(disable), JSON.stringify(update), disable_all]
}
function extensions_check(_, _){
var disable = []
gradioApp().querySelectorAll('#extensions input[type="checkbox"]').forEach(function(x){
if(x.name.startsWith("enable_") && ! x.checked) disable.push(x.name.substr(7))
})
gradioApp().querySelectorAll('#extensions .extension_status').forEach(function(x){
x.innerHTML = "Loading..."
})
var id = randomId()
requestProgress(id, gradioApp().getElementById('extensions_installed_top'), null, null, null, false)
return [id, JSON.stringify(disable)]
}
function install_extension_from_index(button, url){
button.disabled = "disabled"
button.value = "Installing..."
textarea = gradioApp().querySelector('#extension_to_install textarea')
textarea.value = url
updateInput(textarea)
gradioApp().querySelector('#install_extension_button').click()
}
function extensions_apply(_a, _b, disable_all) {
const disable = [];
const update = [];
gradioApp().querySelectorAll('#extensions input[type="checkbox"]').forEach((x) => {
if (x.name.startsWith('enable_') && !x.checked) disable.push(x.name.substr(7));
if (x.name.startsWith('update_') && x.checked) update.push(x.name.substr(7));
});
restart_reload();
return [JSON.stringify(disable), JSON.stringify(update), disable_all];
}
function extensions_check(_a, _b) {
const disable = [];
gradioApp().querySelectorAll('#extensions input[type="checkbox"]').forEach((x) => {
if (x.name.startsWith('enable_') && !x.checked) disable.push(x.name.substr(7));
});
gradioApp().querySelectorAll('#extensions .extension_status').forEach((x) => {
x.innerHTML = 'Loading...';
});
const id = randomId();
// requestProgress(id, gradioApp().getElementById('extensions_installed_top'), null, null, null, false);
return [id, JSON.stringify(disable)];
}
function install_extension(button, url) {
button.disabled = 'disabled';
button.value = 'Installing...';
const textarea = gradioApp().querySelector('#extension_to_install textarea');
textarea.value = url;
updateInput(textarea);
gradioApp().querySelector('#install_extension_button').click();
}
function uninstall_extension(button, url) {
button.disabled = 'disabled';
button.value = 'Uninstalling...';
const textarea = gradioApp().querySelector('#extension_to_install textarea');
textarea.value = url;
updateInput(textarea);
gradioApp().querySelector('#uninstall_extension_button').click();
}
+170 -170
View File
@@ -1,170 +1,170 @@
function setupExtraNetworksForTab(tabname) {
gradioApp().querySelector(`#${tabname}_extra_tabs`).classList.add('extra-networks');
const tabs = gradioApp().querySelector(`#${tabname}_extra_tabs > div`);
const search = gradioApp().querySelector(`#${tabname}_extra_search textarea`);
const refresh = gradioApp().getElementById(`${tabname}_extra_refresh`);
const descriptInput = gradioApp().getElementById(`${tabname}_description_input`);
const close = gradioApp().getElementById(`${tabname}_extra_close`);
search.classList.add('search');
tabs.appendChild(search);
tabs.appendChild(refresh);
tabs.appendChild(close);
tabs.appendChild(descriptInput);
search.addEventListener('input', (evt) => {
searchTerm = search.value.toLowerCase();
gradioApp().querySelectorAll(`#${tabname}_extra_tabs div.card`).forEach((elem) => {
text = `${elem.querySelector('.name').textContent.toLowerCase()} ${elem.querySelector('.search_term').textContent.toLowerCase()}`;
elem.style.display = text.indexOf(searchTerm) == -1 ? 'none' : '';
});
});
}
const activePromptTextarea = {};
function setupExtraNetworks() {
setupExtraNetworksForTab('txt2img');
setupExtraNetworksForTab('img2img');
function registerPrompt(tabname, id) {
const textarea = gradioApp().querySelector(`#${id} > label > textarea`);
if (!activePromptTextarea[tabname]) activePromptTextarea[tabname] = textarea;
textarea.addEventListener('focus', () => {
activePromptTextarea[tabname] = textarea;
});
}
registerPrompt('txt2img', 'txt2img_prompt');
registerPrompt('txt2img', 'txt2img_neg_prompt');
registerPrompt('img2img', 'img2img_prompt');
registerPrompt('img2img', 'img2img_neg_prompt');
}
onUiLoaded(setupExtraNetworks);
const re_extranet = /<([^:]+:[^:]+):[\d\.]+>/;
const re_extranet_g = /\s+<([^:]+:[^:]+):[\d\.]+>/g;
function tryToRemoveExtraNetworkFromPrompt(textarea, text) {
let m = text.match(re_extranet);
if (!m) return false;
const partToSearch = m[1];
let replaced = false;
const newTextareaText = textarea.value.replaceAll(re_extranet_g, (found, index) => {
m = found.match(re_extranet);
if (m[1] == partToSearch) {
replaced = true;
return '';
}
return found;
});
if (replaced) {
textarea.value = newTextareaText;
return true;
}
return false;
}
function cardClicked(tabname, textToAdd, allowNegativePrompt) {
const textarea = allowNegativePrompt ? activePromptTextarea[tabname] : gradioApp().querySelector(`#${tabname}_prompt > label > textarea`);
if (!tryToRemoveExtraNetworkFromPrompt(textarea, textToAdd)) textarea.value = textarea.value + opts.extra_networks_add_text_separator + textToAdd;
updateInput(textarea);
}
function saveCardPreview(event, tabname, filename) {
const textarea = gradioApp().querySelector(`#${tabname}_preview_filename > label > textarea`);
const button = gradioApp().getElementById(`${tabname}_save_preview`);
textarea.value = filename;
updateInput(textarea);
button.click();
event.stopPropagation();
event.preventDefault();
}
function saveCardDescription(event, tabname, filename, descript) {
const textarea = gradioApp().querySelector(`#${tabname}_description_filename > label > textarea`);
const button = gradioApp().getElementById(`${tabname}_save_description`);
const description = gradioApp().getElementById(`${tabname}_description_input`);
textarea.value = filename;
description.value = descript;
updateInput(textarea);
button.click();
event.stopPropagation();
event.preventDefault();
}
function readCardDescription(event, tabname, filename, descript, extraPage, cardName) {
const textarea = gradioApp().querySelector(`#${tabname}_description_filename > label > textarea`);
const description_textarea = gradioApp().querySelector(`#${tabname}_description_input > label > textarea`);
const button = gradioApp().getElementById(`${tabname}_read_description`);
textarea.value = filename;
description_textarea.value = descript;
updateInput(textarea);
updateInput(description_textarea);
button.click();
event.stopPropagation();
event.preventDefault();
}
function extraNetworksSearchButton(tabs_id, event) {
searchTextarea = gradioApp().querySelector(`#${tabs_id} > div > textarea`);
button = event.target;
text = button.classList.contains('search-all') ? '' : button.textContent.trim();
searchTextarea.value = text;
updateInput(searchTextarea);
}
let globalPopup = null;
let globalPopupInner = null;
function popup(contents) {
if (!globalPopup) {
globalPopup = document.createElement('div');
globalPopup.onclick = function () { globalPopup.style.display = 'none'; };
globalPopup.classList.add('global-popup');
const close = document.createElement('div');
close.classList.add('global-popup-close');
close.onclick = function () { globalPopup.style.display = 'none'; };
close.title = 'Close';
globalPopup.appendChild(close);
globalPopupInner = document.createElement('div');
globalPopupInner.onclick = function (event) { event.stopPropagation(); return false; };
globalPopupInner.classList.add('global-popup-inner');
globalPopup.appendChild(globalPopupInner);
gradioApp().appendChild(globalPopup);
}
globalPopupInner.innerHTML = '';
globalPopupInner.appendChild(contents);
globalPopup.style.display = 'flex';
}
function readCardMetadata(event, extraPage, cardName) {
requestGet('./sd_extra_networks/metadata', { page: extraPage, item: cardName }, (data) => {
if (data && data.metadata) {
elem = document.createElement('pre');
elem.classList.add('popup-metadata');
elem.textContent = data.metadata;
popup(elem);
}
}, () => {});
event.stopPropagation();
event.preventDefault();
}
function requestGet(url, data, handler, errorHandler) {
const xhr = new XMLHttpRequest();
const args = Object.keys(data).map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(data[k])}`).join('&');
xhr.open('GET', `${url}?${args}`, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
try {
const js = JSON.parse(xhr.responseText);
handler(js);
} catch (error) {
console.error(error);
errorHandler();
}
} else {
errorHandler();
}
}
};
const js = JSON.stringify(data);
xhr.send(js);
}
function setupExtraNetworksForTab(tabname) {
gradioApp().querySelector(`#${tabname}_extra_tabs`).classList.add('extra-networks');
const tabs = gradioApp().querySelector(`#${tabname}_extra_tabs > div`);
const search = gradioApp().querySelector(`#${tabname}_extra_search textarea`);
const refresh = gradioApp().getElementById(`${tabname}_extra_refresh`);
const descriptInput = gradioApp().getElementById(`${tabname}_description_input`);
const close = gradioApp().getElementById(`${tabname}_extra_close`);
search.classList.add('search');
tabs.appendChild(search);
tabs.appendChild(refresh);
tabs.appendChild(close);
tabs.appendChild(descriptInput);
search.addEventListener('input', (evt) => {
searchTerm = search.value.toLowerCase();
gradioApp().querySelectorAll(`#${tabname}_extra_tabs div.card`).forEach((elem) => {
text = `${elem.querySelector('.name').textContent.toLowerCase()} ${elem.querySelector('.search_term').textContent.toLowerCase()}`;
elem.style.display = text.indexOf(searchTerm) == -1 ? 'none' : '';
});
});
}
const activePromptTextarea = {};
function setupExtraNetworks() {
setupExtraNetworksForTab('txt2img');
setupExtraNetworksForTab('img2img');
function registerPrompt(tabname, id) {
const textarea = gradioApp().querySelector(`#${id} > label > textarea`);
if (!activePromptTextarea[tabname]) activePromptTextarea[tabname] = textarea;
textarea.addEventListener('focus', () => {
activePromptTextarea[tabname] = textarea;
});
}
registerPrompt('txt2img', 'txt2img_prompt');
registerPrompt('txt2img', 'txt2img_neg_prompt');
registerPrompt('img2img', 'img2img_prompt');
registerPrompt('img2img', 'img2img_neg_prompt');
}
onUiLoaded(setupExtraNetworks);
const re_extranet = /<([^:]+:[^:]+):[\d\.]+>/;
const re_extranet_g = /\s+<([^:]+:[^:]+):[\d\.]+>/g;
function tryToRemoveExtraNetworkFromPrompt(textarea, text) {
let m = text.match(re_extranet);
if (!m) return false;
const partToSearch = m[1];
let replaced = false;
const newTextareaText = textarea.value.replaceAll(re_extranet_g, (found, index) => {
m = found.match(re_extranet);
if (m[1] == partToSearch) {
replaced = true;
return '';
}
return found;
});
if (replaced) {
textarea.value = newTextareaText;
return true;
}
return false;
}
function cardClicked(tabname, textToAdd, allowNegativePrompt) {
const textarea = allowNegativePrompt ? activePromptTextarea[tabname] : gradioApp().querySelector(`#${tabname}_prompt > label > textarea`);
if (!tryToRemoveExtraNetworkFromPrompt(textarea, textToAdd)) textarea.value = textarea.value + opts.extra_networks_add_text_separator + textToAdd;
updateInput(textarea);
}
function saveCardPreview(event, tabname, filename) {
const textarea = gradioApp().querySelector(`#${tabname}_preview_filename > label > textarea`);
const button = gradioApp().getElementById(`${tabname}_save_preview`);
textarea.value = filename;
updateInput(textarea);
button.click();
event.stopPropagation();
event.preventDefault();
}
function saveCardDescription(event, tabname, filename, descript) {
const textarea = gradioApp().querySelector(`#${tabname}_description_filename > label > textarea`);
const button = gradioApp().getElementById(`${tabname}_save_description`);
const description = gradioApp().getElementById(`${tabname}_description_input`);
textarea.value = filename;
description.value = descript;
updateInput(textarea);
button.click();
event.stopPropagation();
event.preventDefault();
}
function readCardDescription(event, tabname, filename, descript, extraPage, cardName) {
const textarea = gradioApp().querySelector(`#${tabname}_description_filename > label > textarea`);
const description_textarea = gradioApp().querySelector(`#${tabname}_description_input > label > textarea`);
const button = gradioApp().getElementById(`${tabname}_read_description`);
textarea.value = filename;
description_textarea.value = descript;
updateInput(textarea);
updateInput(description_textarea);
button.click();
event.stopPropagation();
event.preventDefault();
}
function extraNetworksSearchButton(tabs_id, event) {
searchTextarea = gradioApp().querySelector(`#${tabs_id} > div > textarea`);
button = event.target;
text = button.classList.contains('search-all') ? '' : button.textContent.trim();
searchTextarea.value = text;
updateInput(searchTextarea);
}
let globalPopup = null;
let globalPopupInner = null;
function popup(contents) {
if (!globalPopup) {
globalPopup = document.createElement('div');
globalPopup.onclick = function () { globalPopup.style.display = 'none'; };
globalPopup.classList.add('global-popup');
const close = document.createElement('div');
close.classList.add('global-popup-close');
close.onclick = function () { globalPopup.style.display = 'none'; };
close.title = 'Close';
globalPopup.appendChild(close);
globalPopupInner = document.createElement('div');
globalPopupInner.onclick = function (event) { event.stopPropagation(); return false; };
globalPopupInner.classList.add('global-popup-inner');
globalPopup.appendChild(globalPopupInner);
gradioApp().appendChild(globalPopup);
}
globalPopupInner.innerHTML = '';
globalPopupInner.appendChild(contents);
globalPopup.style.display = 'flex';
}
function readCardMetadata(event, extraPage, cardName) {
requestGet('./sd_extra_networks/metadata', { page: extraPage, item: cardName }, (data) => {
if (data && data.metadata) {
elem = document.createElement('pre');
elem.classList.add('popup-metadata');
elem.textContent = data.metadata;
popup(elem);
}
}, () => {});
event.stopPropagation();
event.preventDefault();
}
function requestGet(url, data, handler, errorHandler) {
const xhr = new XMLHttpRequest();
const args = Object.keys(data).map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(data[k])}`).join('&');
xhr.open('GET', `${url}?${args}`, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
try {
const js = JSON.parse(xhr.responseText);
handler(js);
} catch (error) {
console.error(error);
errorHandler();
}
} else {
errorHandler();
}
}
};
const js = JSON.stringify(data);
xhr.send(js);
}
+16 -2
View File
@@ -505,11 +505,25 @@ div#extras_scale_to_tab div.form{
font-size: 95%;
}
#available_extensions .info{
#extensions .name{
font-size: 1.1rem
}
#extensions .type{
opacity: 0.5;
font-size: 90%;
text-align: center;
}
#extensions .version{
opacity: 0.7;
}
#extensions .info{
margin: 0;
}
#available_extensions .date_added{
#extensions .date{
opacity: 0.85;
font-size: 90%;
}
+10 -13
View File
@@ -1,13 +1,10 @@
function start_training_textual_inversion(){
gradioApp().querySelector('#ti_error').innerHTML=''
var id = randomId()
const onProgress = (progress) => gradioApp().getElementById('ti_progress').innerHTML = progress.textinfo;
// requestProgress(id_task, progressbarContainer, gallery, atEnd = null, onProgress = null, once = false) {
requestProgress(id, gradioApp().getElementById('ti_output'), gradioApp().getElementById('ti_gallery'), null, onProgress, false)
var res = args_to_array(arguments)
res[0] = id
return res
}
function start_training_textual_inversion() {
gradioApp().querySelector('#ti_error').innerHTML=''
var id = randomId()
const onProgress = (progress) => gradioApp().getElementById('ti_progress').innerHTML = progress.textinfo;
// requestProgress(id_task, progressbarContainer, gallery, atEnd = null, onProgress = null, once = false) {
requestProgress(id, gradioApp().getElementById('ti_output'), gradioApp().getElementById('ti_gallery'), null, onProgress, false)
var res = args_to_array(arguments)
res[0] = id
return res
}