diff options
Diffstat (limited to 'javascript')
-rw-r--r-- | javascript/edit-attention.js | 127 | ||||
-rw-r--r-- | javascript/extensions.js | 2 | ||||
-rw-r--r-- | javascript/extraNetworks.js | 69 | ||||
-rw-r--r-- | javascript/hints.js | 9 | ||||
-rw-r--r-- | javascript/hires_fix.js | 3 | ||||
-rw-r--r-- | javascript/imageviewer.js | 10 | ||||
-rw-r--r-- | javascript/localization.js | 6 | ||||
-rw-r--r-- | javascript/progressbar.js | 50 | ||||
-rw-r--r-- | javascript/ui.js | 63 |
9 files changed, 247 insertions, 92 deletions
diff --git a/javascript/edit-attention.js b/javascript/edit-attention.js index b947cbec..619bb1fa 100644 --- a/javascript/edit-attention.js +++ b/javascript/edit-attention.js @@ -1,75 +1,96 @@ -addEventListener('keydown', (event) => {
+function keyupEditAttention(event){
let target = event.originalTarget || event.composedPath()[0];
- if (!target.matches("#toprow textarea.gr-text-input[placeholder]")) return;
+ if (!target.matches("[id*='_toprow'] textarea.gr-text-input[placeholder]")) return;
if (! (event.metaKey || event.ctrlKey)) return;
-
- let plus = "ArrowUp"
- let minus = "ArrowDown"
- if (event.key != plus && event.key != minus) return;
+ let isPlus = event.key == "ArrowUp"
+ let isMinus = event.key == "ArrowDown"
+ if (!isPlus && !isMinus) return;
let selectionStart = target.selectionStart;
let selectionEnd = target.selectionEnd;
- // If the user hasn't selected anything, let's select their current parenthesis block
- if (selectionStart === selectionEnd) {
+ let text = target.value;
+
+ function selectCurrentParenthesisBlock(OPEN, CLOSE){
+ if (selectionStart !== selectionEnd) return false;
+
// Find opening parenthesis around current cursor
- const before = target.value.substring(0, selectionStart);
- let beforeParen = before.lastIndexOf("(");
- if (beforeParen == -1) return;
- let beforeParenClose = before.lastIndexOf(")");
+ 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("(", beforeParen - 1);
- beforeParenClose = before.lastIndexOf(")", beforeParenClose - 1);
+ beforeParen = before.lastIndexOf(OPEN, beforeParen - 1);
+ beforeParenClose = before.lastIndexOf(CLOSE, beforeParenClose - 1);
}
// Find closing parenthesis around current cursor
- const after = target.value.substring(selectionStart);
- let afterParen = after.indexOf(")");
- if (afterParen == -1) return;
- let afterParenOpen = after.indexOf("(");
+ 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(")", afterParen + 1);
- afterParenOpen = after.indexOf("(", afterParenOpen + 1);
+ afterParen = after.indexOf(CLOSE, afterParen + 1);
+ afterParenOpen = after.indexOf(OPEN, afterParenOpen + 1);
}
- if (beforeParen === -1 || afterParen === -1) return;
+ if (beforeParen === -1 || afterParen === -1) return false;
// Set the selection to the text between the parenthesis
- const parenContent = target.value.substring(beforeParen + 1, selectionStart + afterParen);
+ const parenContent = text.substring(beforeParen + 1, selectionStart + afterParen);
const lastColon = parenContent.lastIndexOf(":");
selectionStart = beforeParen + 1;
selectionEnd = selectionStart + lastColon;
target.setSelectionRange(selectionStart, selectionEnd);
- }
+ return true;
+ }
+
+ // If the user hasn't selected anything, let's select their current parenthesis block
+ if(! selectCurrentParenthesisBlock('<', '>')){
+ selectCurrentParenthesisBlock('(', ')')
+ }
event.preventDefault();
- if (selectionStart == 0 || target.value[selectionStart - 1] != "(") {
- target.value = target.value.slice(0, selectionStart) +
- "(" + target.value.slice(selectionStart, selectionEnd) + ":1.0)" +
- target.value.slice(selectionEnd);
-
- target.focus();
- target.selectionStart = selectionStart + 1;
- target.selectionEnd = selectionEnd + 1;
-
- } else {
- end = target.value.slice(selectionEnd + 1).indexOf(")") + 1;
- weight = parseFloat(target.value.slice(selectionEnd + 1, selectionEnd + 1 + end));
- if (isNaN(weight)) return;
- if (event.key == minus) weight -= 0.1;
- if (event.key == plus) weight += 0.1;
-
- weight = parseFloat(weight.toPrecision(12));
-
- target.value = target.value.slice(0, selectionEnd + 1) +
- weight +
- target.value.slice(selectionEnd + 1 + end - 1);
-
- target.focus();
- target.selectionStart = selectionStart;
- target.selectionEnd = selectionEnd;
- }
- // Since we've modified a Gradio Textbox component manually, we need to simulate an `input` DOM event to ensure its
- // internal Svelte data binding remains in sync.
- target.dispatchEvent(new Event("input", { bubbles: true }));
-});
+ 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"
+
+ 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);
+});
\ No newline at end of file diff --git a/javascript/extensions.js b/javascript/extensions.js index 59179ca6..ac6e35b9 100644 --- a/javascript/extensions.js +++ b/javascript/extensions.js @@ -29,7 +29,7 @@ function install_extension_from_index(button, url){ textarea = gradioApp().querySelector('#extension_to_install textarea')
textarea.value = url
- textarea.dispatchEvent(new Event("input", { bubbles: true }))
+ updateInput(textarea)
gradioApp().querySelector('#install_extension_button').click()
}
diff --git a/javascript/extraNetworks.js b/javascript/extraNetworks.js new file mode 100644 index 00000000..c5a9adb3 --- /dev/null +++ b/javascript/extraNetworks.js @@ -0,0 +1,69 @@ +
+function setupExtraNetworksForTab(tabname){
+ gradioApp().querySelector('#'+tabname+'_extra_tabs').classList.add('extra-networks')
+
+ var tabs = gradioApp().querySelector('#'+tabname+'_extra_tabs > div')
+ var search = gradioApp().querySelector('#'+tabname+'_extra_search textarea')
+ var refresh = gradioApp().getElementById(tabname+'_extra_refresh')
+ var close = gradioApp().getElementById(tabname+'_extra_close')
+
+ search.classList.add('search')
+ tabs.appendChild(search)
+ tabs.appendChild(refresh)
+ tabs.appendChild(close)
+
+ search.addEventListener("input", function(evt){
+ searchTerm = search.value.toLowerCase()
+
+ gradioApp().querySelectorAll('#'+tabname+'_extra_tabs div.card').forEach(function(elem){
+ text = elem.querySelector('.name').textContent.toLowerCase()
+ elem.style.display = text.indexOf(searchTerm) == -1 ? "none" : ""
+ })
+ });
+}
+
+var activePromptTextarea = {};
+
+function setupExtraNetworks(){
+ setupExtraNetworksForTab('txt2img')
+ setupExtraNetworksForTab('img2img')
+
+ function registerPrompt(tabname, id){
+ var textarea = gradioApp().querySelector("#" + id + " > label > textarea");
+
+ if (! activePromptTextarea[tabname]){
+ activePromptTextarea[tabname] = textarea
+ }
+
+ textarea.addEventListener("focus", function(){
+ activePromptTextarea[tabname] = textarea;
+ });
+ }
+
+ registerPrompt('txt2img', 'txt2img_prompt')
+ registerPrompt('txt2img', 'txt2img_neg_prompt')
+ registerPrompt('img2img', 'img2img_prompt')
+ registerPrompt('img2img', 'img2img_neg_prompt')
+}
+
+onUiLoaded(setupExtraNetworks)
+
+function cardClicked(tabname, textToAdd, allowNegativePrompt){
+ var textarea = allowNegativePrompt ? activePromptTextarea[tabname] : gradioApp().querySelector("#" + tabname + "_prompt > label > textarea")
+
+ textarea.value = textarea.value + " " + textToAdd
+ updateInput(textarea)
+}
+
+function saveCardPreview(event, tabname, filename){
+ var textarea = gradioApp().querySelector("#" + tabname + '_preview_filename > label > textarea')
+ var button = gradioApp().getElementById(tabname + '_save_preview')
+
+ textarea.value = filename
+ updateInput(textarea)
+
+ button.click()
+
+ event.stopPropagation()
+ event.preventDefault()
+}
diff --git a/javascript/hints.js b/javascript/hints.js index fa5e5ae8..3cf10e20 100644 --- a/javascript/hints.js +++ b/javascript/hints.js @@ -14,13 +14,14 @@ titles = { "Seed": "A value that determines the output of random number generator - if you create an image with same parameters and seed as another image, you'll get the same result", "\u{1f3b2}\ufe0f": "Set seed to -1, which will cause a new random number to be used every time", "\u267b\ufe0f": "Reuse seed from last generation, mostly useful if it was randomed", - "\u{1f3a8}": "Add a random artist to the prompt.", "\u2199\ufe0f": "Read generation parameters from prompt or last generation if prompt is empty into user interface.", "\u{1f4c2}": "Open images output directory", "\u{1f4be}": "Save style", "\U0001F5D1": "Clear prompt", "\u{1f4cb}": "Apply selected styles to current prompt", "\u{1f4d2}": "Paste available values into the field", + "\u{1f3b4}": "Show extra networks", + "Inpaint a part of image": "Draw a mask over an image, and the script will regenerate the masked area with content according to prompt", "SD upscale": "Upscale image normally, split result into tiles, improve each tile using img2img, merge whole image back", @@ -92,6 +93,7 @@ titles = { "Weighted sum": "Result = A * (1 - M) + B * M", "Add difference": "Result = A + (B - C) * M", + "No interpolation": "Result = A", "Initialization text": "If the number of tokens is more than the number of vectors, some may be skipped.\nLeave the textbox empty to start with zeroed out vectors", "Learning rate": "How fast should training go. Low values will take longer to train, high values may fail to converge (not generate accurate results) and/or may break the embedding (This has happened if you see Loss: nan in the training info textbox. If this happens, you need to manually restore your embedding from an older not-broken backup).\n\nYou can set a single numeric value, or multiple learning rates using the syntax:\n\n rate_1:max_steps_1, rate_2:max_steps_2, ...\n\nEG: 0.005:100, 1e-3:1000, 1e-5\n\nWill train with rate of 0.005 for first 100 steps, then 1e-3 until 1000 steps, then 1e-5 for all remaining steps.", @@ -105,7 +107,10 @@ titles = { "Hires steps": "Number of sampling steps for upscaled picture. If 0, uses same as for original.", "Upscale by": "Adjusts the size of the image by multiplying the original width and height by the selected value. Ignored if either Resize width to or Resize height to are non-zero.", "Resize width to": "Resizes image to this width. If 0, width is inferred from either of two nearby sliders.", - "Resize height to": "Resizes image to this height. If 0, height is inferred from either of two nearby sliders." + "Resize height to": "Resizes image to this height. If 0, height is inferred from either of two nearby sliders.", + "Multiplier for extra networks": "When adding extra network such as Hypernetwork or Lora to prompt, use this multiplier for it.", + "Discard weights with matching name": "Regular expression; if weights's name matches it, the weights is not written to the resulting checkpoint. Use ^model_ema to discard EMA weights.", + "Extra networks tab order": "Comma-separated list of tab names; tabs listed here will appear in the extra networks UI first and in order lsited." } diff --git a/javascript/hires_fix.js b/javascript/hires_fix.js index 07fba549..0629475f 100644 --- a/javascript/hires_fix.js +++ b/javascript/hires_fix.js @@ -1,6 +1,5 @@ function setInactive(elem, inactive){
- console.log(elem)
if(inactive){
elem.classList.add('inactive')
} else{
@@ -9,8 +8,6 @@ function setInactive(elem, inactive){ }
function onCalcResolutionHires(enable, width, height, hr_scale, hr_resize_x, hr_resize_y){
- console.log(enable, width, height, hr_scale, hr_resize_x, hr_resize_y)
-
hrUpscaleBy = gradioApp().getElementById('txt2img_hr_scale')
hrResizeX = gradioApp().getElementById('txt2img_hr_resize_x')
hrResizeY = gradioApp().getElementById('txt2img_hr_resize_y')
diff --git a/javascript/imageviewer.js b/javascript/imageviewer.js index 1f29ad7b..aac2ee82 100644 --- a/javascript/imageviewer.js +++ b/javascript/imageviewer.js @@ -148,7 +148,15 @@ function showGalleryImage() { if(e && e.parentElement.tagName == 'DIV'){ e.style.cursor='pointer' e.style.userSelect='none' - e.addEventListener('mousedown', function (evt) { + + var isFirefox = isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1 + + // For Firefox, listening on click first switched to next image then shows the lightbox. + // If you know how to fix this without switching to mousedown event, please. + // For other browsers the event is click to make it possiblr to drag picture. + var event = isFirefox ? 'mousedown' : 'click' + + e.addEventListener(event, function (evt) { if(!opts.js_modal_lightbox || evt.button != 0) return; modalZoomSet(gradioApp().getElementById('modalImage'), opts.js_modal_lightbox_initially_zoomed) evt.preventDefault() diff --git a/javascript/localization.js b/javascript/localization.js index f92d2d24..1a5a1dbb 100644 --- a/javascript/localization.js +++ b/javascript/localization.js @@ -10,10 +10,8 @@ ignore_ids_for_localization={ modelmerger_tertiary_model_name: 'OPTION',
train_embedding: 'OPTION',
train_hypernetwork: 'OPTION',
- txt2img_style_index: 'OPTION',
- txt2img_style2_index: 'OPTION',
- img2img_style_index: 'OPTION',
- img2img_style2_index: 'OPTION',
+ txt2img_styles: 'OPTION',
+ img2img_styles: 'OPTION',
setting_random_artist_categories: 'SPAN',
setting_face_restoration_model: 'SPAN',
setting_realesrgan_enabled_models: 'SPAN',
diff --git a/javascript/progressbar.js b/javascript/progressbar.js index da6709bc..ff6d757b 100644 --- a/javascript/progressbar.js +++ b/javascript/progressbar.js @@ -81,8 +81,13 @@ function request(url, data, handler, errorHandler){ xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { - var js = JSON.parse(xhr.responseText); - handler(js) + try { + var js = JSON.parse(xhr.responseText); + handler(js) + } catch (error) { + console.error(error); + errorHandler() + } } else{ errorHandler() } @@ -106,6 +111,19 @@ function formatTime(secs){ } } +function setTitle(progress){ + var title = 'Stable Diffusion' + + if(opts.show_progress_in_title && progress){ + title = '[' + progress.trim() + '] ' + title; + } + + if(document.title != title){ + document.title = title; + } +} + + function randomId(){ return "task(" + Math.random().toString(36).slice(2, 7) + Math.random().toString(36).slice(2, 7) + Math.random().toString(36).slice(2, 7)+")" } @@ -117,7 +135,7 @@ function requestProgress(id_task, progressbarContainer, gallery, atEnd, onProgre var dateStart = new Date() var wasEverActive = false var parentProgressbar = progressbarContainer.parentNode - var parentGallery = gallery.parentNode + var parentGallery = gallery ? gallery.parentNode : null var divProgress = document.createElement('div') divProgress.className='progressDiv' @@ -128,18 +146,21 @@ function requestProgress(id_task, progressbarContainer, gallery, atEnd, onProgre divProgress.appendChild(divInner) parentProgressbar.insertBefore(divProgress, progressbarContainer) - var livePreview = document.createElement('div') - livePreview.className='livePreview' - parentGallery.insertBefore(livePreview, gallery) + if(parentGallery){ + var livePreview = document.createElement('div') + livePreview.className='livePreview' + parentGallery.insertBefore(livePreview, gallery) + } var removeProgressBar = function(){ + setTitle("") parentProgressbar.removeChild(divProgress) - parentGallery.removeChild(livePreview) + if(parentGallery) parentGallery.removeChild(livePreview) atEnd() } var fun = function(id_task, id_live_preview){ - request("/internal/progress", {"id_task": id_task, "id_live_preview": id_live_preview}, function(res){ + request("./internal/progress", {"id_task": id_task, "id_live_preview": id_live_preview}, function(res){ if(res.completed){ removeProgressBar() return @@ -154,6 +175,7 @@ function requestProgress(id_task, progressbarContainer, gallery, atEnd, onProgre progressText = "" divInner.style.width = ((res.progress || 0) * 100.0) + '%' + divInner.style.background = res.progress ? "" : "transparent" if(res.progress > 0){ progressText = ((res.progress || 0) * 100.0).toFixed(0) + '%' @@ -161,8 +183,13 @@ function requestProgress(id_task, progressbarContainer, gallery, atEnd, onProgre if(res.eta){ progressText += " ETA: " + formatTime(res.eta) - } else if(res.textinfo){ - progressText += " " + res.textinfo + } + + + setTitle(progressText) + + if(res.textinfo && res.textinfo.indexOf("\n") == -1){ + progressText = res.textinfo + " " + progressText } divInner.textContent = progressText @@ -182,8 +209,7 @@ function requestProgress(id_task, progressbarContainer, gallery, atEnd, onProgre } - if(res.live_preview){ - + if(res.live_preview && gallery){ var rect = gallery.getBoundingClientRect() if(rect.width){ livePreview.style.width = rect.width + "px" diff --git a/javascript/ui.js b/javascript/ui.js index ecf97cb3..ba72623c 100644 --- a/javascript/ui.js +++ b/javascript/ui.js @@ -104,9 +104,11 @@ function create_tab_index_args(tabId, args){ return res } -function get_extras_tab_index(){ - const [,,...args] = [...arguments] - return [get_tab_index('mode_extras'), get_tab_index('extras_resize_mode'), ...args] +function get_img2img_tab_index() { + let res = args_to_array(arguments) + res.splice(-2) + res[0] = get_tab_index('mode_img2img') + return res } function create_submit_args(args){ @@ -165,6 +167,15 @@ function submit_img2img(){ return res } +function modelmerger(){ + var id = randomId() + requestProgress(id, gradioApp().getElementById('modelmerger_results_panel'), null, function(){}) + + var res = create_submit_args(arguments) + res[0] = id + return res +} + function ask_for_style_name(_, prompt_text, negative_prompt_text) { name_ = prompt('Style name:') @@ -180,8 +191,6 @@ function confirm_clear_prompt(prompt, negative_prompt) { return [prompt, negative_prompt] } - - opts = {} onUiUpdate(function(){ if(Object.keys(opts).length != 0) return; @@ -189,8 +198,8 @@ onUiUpdate(function(){ json_elem = gradioApp().getElementById('settings_json') if(json_elem == null) return; - textarea = json_elem.querySelector('textarea') - jsdata = textarea.value + var textarea = json_elem.querySelector('textarea') + var jsdata = textarea.value opts = JSON.parse(jsdata) executeCallbacks(optionsChangedCallbacks); @@ -214,14 +223,29 @@ onUiUpdate(function(){ json_elem.parentElement.style.display="none" - if (!txt2img_textarea) { - txt2img_textarea = gradioApp().querySelector("#txt2img_prompt > label > textarea"); - txt2img_textarea?.addEventListener("input", () => update_token_counter("txt2img_token_button")); - } - if (!img2img_textarea) { - img2img_textarea = gradioApp().querySelector("#img2img_prompt > label > textarea"); - img2img_textarea?.addEventListener("input", () => update_token_counter("img2img_token_button")); - } + function registerTextarea(id, id_counter, id_button){ + var prompt = gradioApp().getElementById(id) + var counter = gradioApp().getElementById(id_counter) + var textarea = gradioApp().querySelector("#" + id + " > label > textarea"); + + if(counter.parentElement == prompt.parentElement){ + return + } + + + prompt.parentElement.insertBefore(counter, prompt) + counter.classList.add("token-counter") + prompt.parentElement.style.position = "relative" + + textarea.addEventListener("input", function(){ + update_token_counter(id_button); + }); + } + + registerTextarea('txt2img_prompt', 'txt2img_token_counter', 'txt2img_token_button') + registerTextarea('txt2img_neg_prompt', 'txt2img_negative_token_counter', 'txt2img_negative_token_button') + registerTextarea('img2img_prompt', 'img2img_token_counter', 'img2img_token_button') + registerTextarea('img2img_neg_prompt', 'img2img_negative_token_counter', 'img2img_negative_token_button') show_all_pages = gradioApp().getElementById('settings_show_all_pages') settings_tabs = gradioApp().querySelector('#settings div') @@ -235,7 +259,6 @@ onUiUpdate(function(){ } }) - onOptionsChanged(function(){ elem = gradioApp().getElementById('sd_checkpoint_hash') sd_checkpoint_hash = opts.sd_checkpoint_hash || "" @@ -278,3 +301,11 @@ function restart_reload(){ return [] } + +// Simulate an `input` DOM event for Gradio Textbox component. Needed after you edit its contents in javascript, otherwise your edits +// will only visible on web page and not sent to python. +function updateInput(target){ + let e = new Event("input", { bubbles: true }) + Object.defineProperty(e, "target", {value: target}) + target.dispatchEvent(e); +} |