Kizi-Art commited on
Commit
a96ef21
1 Parent(s): 35f4bab

Upload folder using huggingface_hub

Browse files
javascript/aspectRatioOverlay.js ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ let currentWidth = null;
3
+ let currentHeight = null;
4
+ let arFrameTimeout = setTimeout(function() {}, 0);
5
+
6
+ function dimensionChange(e, is_width, is_height) {
7
+
8
+ if (is_width) {
9
+ currentWidth = e.target.value * 1.0;
10
+ }
11
+ if (is_height) {
12
+ currentHeight = e.target.value * 1.0;
13
+ }
14
+
15
+ var inImg2img = gradioApp().querySelector("#tab_img2img").style.display == "block";
16
+
17
+ if (!inImg2img) {
18
+ return;
19
+ }
20
+
21
+ var targetElement = null;
22
+
23
+ var tabIndex = get_tab_index('mode_img2img');
24
+ if (tabIndex == 0) { // img2img
25
+ targetElement = gradioApp().querySelector('#img2img_image div[data-testid=image] img');
26
+ } else if (tabIndex == 1) { //Sketch
27
+ targetElement = gradioApp().querySelector('#img2img_sketch div[data-testid=image] img');
28
+ } else if (tabIndex == 2) { // Inpaint
29
+ targetElement = gradioApp().querySelector('#img2maskimg div[data-testid=image] img');
30
+ } else if (tabIndex == 3) { // Inpaint sketch
31
+ targetElement = gradioApp().querySelector('#inpaint_sketch div[data-testid=image] img');
32
+ }
33
+
34
+
35
+ if (targetElement) {
36
+
37
+ var arPreviewRect = gradioApp().querySelector('#imageARPreview');
38
+ if (!arPreviewRect) {
39
+ arPreviewRect = document.createElement('div');
40
+ arPreviewRect.id = "imageARPreview";
41
+ gradioApp().appendChild(arPreviewRect);
42
+ }
43
+
44
+
45
+
46
+ var viewportOffset = targetElement.getBoundingClientRect();
47
+
48
+ var viewportscale = Math.min(targetElement.clientWidth / targetElement.naturalWidth, targetElement.clientHeight / targetElement.naturalHeight);
49
+
50
+ var scaledx = targetElement.naturalWidth * viewportscale;
51
+ var scaledy = targetElement.naturalHeight * viewportscale;
52
+
53
+ var cleintRectTop = (viewportOffset.top + window.scrollY);
54
+ var cleintRectLeft = (viewportOffset.left + window.scrollX);
55
+ var cleintRectCentreY = cleintRectTop + (targetElement.clientHeight / 2);
56
+ var cleintRectCentreX = cleintRectLeft + (targetElement.clientWidth / 2);
57
+
58
+ var arscale = Math.min(scaledx / currentWidth, scaledy / currentHeight);
59
+ var arscaledx = currentWidth * arscale;
60
+ var arscaledy = currentHeight * arscale;
61
+
62
+ var arRectTop = cleintRectCentreY - (arscaledy / 2);
63
+ var arRectLeft = cleintRectCentreX - (arscaledx / 2);
64
+ var arRectWidth = arscaledx;
65
+ var arRectHeight = arscaledy;
66
+
67
+ arPreviewRect.style.top = arRectTop + 'px';
68
+ arPreviewRect.style.left = arRectLeft + 'px';
69
+ arPreviewRect.style.width = arRectWidth + 'px';
70
+ arPreviewRect.style.height = arRectHeight + 'px';
71
+
72
+ clearTimeout(arFrameTimeout);
73
+ arFrameTimeout = setTimeout(function() {
74
+ arPreviewRect.style.display = 'none';
75
+ }, 2000);
76
+
77
+ arPreviewRect.style.display = 'block';
78
+
79
+ }
80
+
81
+ }
82
+
83
+
84
+ onAfterUiUpdate(function() {
85
+ var arPreviewRect = gradioApp().querySelector('#imageARPreview');
86
+ if (arPreviewRect) {
87
+ arPreviewRect.style.display = 'none';
88
+ }
89
+ var tabImg2img = gradioApp().querySelector("#tab_img2img");
90
+ if (tabImg2img) {
91
+ var inImg2img = tabImg2img.style.display == "block";
92
+ if (inImg2img) {
93
+ let inputs = gradioApp().querySelectorAll('input');
94
+ inputs.forEach(function(e) {
95
+ var is_width = e.parentElement.id == "img2img_width";
96
+ var is_height = e.parentElement.id == "img2img_height";
97
+
98
+ if ((is_width || is_height) && !e.classList.contains('scrollwatch')) {
99
+ e.addEventListener('input', function(e) {
100
+ dimensionChange(e, is_width, is_height);
101
+ });
102
+ e.classList.add('scrollwatch');
103
+ }
104
+ if (is_width) {
105
+ currentWidth = e.value * 1.0;
106
+ }
107
+ if (is_height) {
108
+ currentHeight = e.value * 1.0;
109
+ }
110
+ });
111
+ }
112
+ }
113
+ });
javascript/contextMenus.js ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ var contextMenuInit = function() {
3
+ let eventListenerApplied = false;
4
+ let menuSpecs = new Map();
5
+
6
+ const uid = function() {
7
+ return Date.now().toString(36) + Math.random().toString(36).substring(2);
8
+ };
9
+
10
+ function showContextMenu(event, element, menuEntries) {
11
+ let posx = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
12
+ let posy = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
13
+
14
+ let oldMenu = gradioApp().querySelector('#context-menu');
15
+ if (oldMenu) {
16
+ oldMenu.remove();
17
+ }
18
+
19
+ let baseStyle = window.getComputedStyle(uiCurrentTab);
20
+
21
+ const contextMenu = document.createElement('nav');
22
+ contextMenu.id = "context-menu";
23
+ contextMenu.style.background = baseStyle.background;
24
+ contextMenu.style.color = baseStyle.color;
25
+ contextMenu.style.fontFamily = baseStyle.fontFamily;
26
+ contextMenu.style.top = posy + 'px';
27
+ contextMenu.style.left = posx + 'px';
28
+
29
+
30
+
31
+ const contextMenuList = document.createElement('ul');
32
+ contextMenuList.className = 'context-menu-items';
33
+ contextMenu.append(contextMenuList);
34
+
35
+ menuEntries.forEach(function(entry) {
36
+ let contextMenuEntry = document.createElement('a');
37
+ contextMenuEntry.innerHTML = entry['name'];
38
+ contextMenuEntry.addEventListener("click", function() {
39
+ entry['func']();
40
+ });
41
+ contextMenuList.append(contextMenuEntry);
42
+
43
+ });
44
+
45
+ gradioApp().appendChild(contextMenu);
46
+
47
+ let menuWidth = contextMenu.offsetWidth + 4;
48
+ let menuHeight = contextMenu.offsetHeight + 4;
49
+
50
+ let windowWidth = window.innerWidth;
51
+ let windowHeight = window.innerHeight;
52
+
53
+ if ((windowWidth - posx) < menuWidth) {
54
+ contextMenu.style.left = windowWidth - menuWidth + "px";
55
+ }
56
+
57
+ if ((windowHeight - posy) < menuHeight) {
58
+ contextMenu.style.top = windowHeight - menuHeight + "px";
59
+ }
60
+
61
+ }
62
+
63
+ function appendContextMenuOption(targetElementSelector, entryName, entryFunction) {
64
+
65
+ var currentItems = menuSpecs.get(targetElementSelector);
66
+
67
+ if (!currentItems) {
68
+ currentItems = [];
69
+ menuSpecs.set(targetElementSelector, currentItems);
70
+ }
71
+ let newItem = {
72
+ id: targetElementSelector + '_' + uid(),
73
+ name: entryName,
74
+ func: entryFunction,
75
+ isNew: true
76
+ };
77
+
78
+ currentItems.push(newItem);
79
+ return newItem['id'];
80
+ }
81
+
82
+ function removeContextMenuOption(uid) {
83
+ menuSpecs.forEach(function(v) {
84
+ let index = -1;
85
+ v.forEach(function(e, ei) {
86
+ if (e['id'] == uid) {
87
+ index = ei;
88
+ }
89
+ });
90
+ if (index >= 0) {
91
+ v.splice(index, 1);
92
+ }
93
+ });
94
+ }
95
+
96
+ function addContextMenuEventListener() {
97
+ if (eventListenerApplied) {
98
+ return;
99
+ }
100
+ gradioApp().addEventListener("click", function(e) {
101
+ if (!e.isTrusted) {
102
+ return;
103
+ }
104
+
105
+ let oldMenu = gradioApp().querySelector('#context-menu');
106
+ if (oldMenu) {
107
+ oldMenu.remove();
108
+ }
109
+ });
110
+ gradioApp().addEventListener("contextmenu", function(e) {
111
+ let oldMenu = gradioApp().querySelector('#context-menu');
112
+ if (oldMenu) {
113
+ oldMenu.remove();
114
+ }
115
+ menuSpecs.forEach(function(v, k) {
116
+ if (e.composedPath()[0].matches(k)) {
117
+ showContextMenu(e, e.composedPath()[0], v);
118
+ e.preventDefault();
119
+ }
120
+ });
121
+ });
122
+ eventListenerApplied = true;
123
+
124
+ }
125
+
126
+ return [appendContextMenuOption, removeContextMenuOption, addContextMenuEventListener];
127
+ };
128
+
129
+ var initResponse = contextMenuInit();
130
+ var appendContextMenuOption = initResponse[0];
131
+ var removeContextMenuOption = initResponse[1];
132
+ var addContextMenuEventListener = initResponse[2];
133
+
134
+ (function() {
135
+ //Start example Context Menu Items
136
+ let generateOnRepeat = function(genbuttonid, interruptbuttonid) {
137
+ let genbutton = gradioApp().querySelector(genbuttonid);
138
+ let interruptbutton = gradioApp().querySelector(interruptbuttonid);
139
+ if (!interruptbutton.offsetParent) {
140
+ genbutton.click();
141
+ }
142
+ clearInterval(window.generateOnRepeatInterval);
143
+ window.generateOnRepeatInterval = setInterval(function() {
144
+ if (!interruptbutton.offsetParent) {
145
+ genbutton.click();
146
+ }
147
+ },
148
+ 500);
149
+ };
150
+
151
+ let generateOnRepeat_txt2img = function() {
152
+ generateOnRepeat('#txt2img_generate', '#txt2img_interrupt');
153
+ };
154
+
155
+ let generateOnRepeat_img2img = function() {
156
+ generateOnRepeat('#img2img_generate', '#img2img_interrupt');
157
+ };
158
+
159
+ appendContextMenuOption('#txt2img_generate', 'Generate forever', generateOnRepeat_txt2img);
160
+ appendContextMenuOption('#txt2img_interrupt', 'Generate forever', generateOnRepeat_txt2img);
161
+ appendContextMenuOption('#img2img_generate', 'Generate forever', generateOnRepeat_img2img);
162
+ appendContextMenuOption('#img2img_interrupt', 'Generate forever', generateOnRepeat_img2img);
163
+
164
+ let cancelGenerateForever = function() {
165
+ clearInterval(window.generateOnRepeatInterval);
166
+ };
167
+
168
+ appendContextMenuOption('#txt2img_interrupt', 'Cancel generate forever', cancelGenerateForever);
169
+ appendContextMenuOption('#txt2img_generate', 'Cancel generate forever', cancelGenerateForever);
170
+ appendContextMenuOption('#img2img_interrupt', 'Cancel generate forever', cancelGenerateForever);
171
+ appendContextMenuOption('#img2img_generate', 'Cancel generate forever', cancelGenerateForever);
172
+
173
+ })();
174
+ //End example Context Menu Items
175
+
176
+ onAfterUiUpdate(addContextMenuEventListener);
javascript/dragdrop.js ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // allows drag-dropping files into gradio image elements, and also pasting images from clipboard
2
+
3
+ function isValidImageList(files) {
4
+ return files && files?.length === 1 && ['image/png', 'image/gif', 'image/jpeg'].includes(files[0].type);
5
+ }
6
+
7
+ function dropReplaceImage(imgWrap, files) {
8
+ if (!isValidImageList(files)) {
9
+ return;
10
+ }
11
+
12
+ const tmpFile = files[0];
13
+
14
+ imgWrap.querySelector('.modify-upload button + button, .touch-none + div button + button')?.click();
15
+ const callback = () => {
16
+ const fileInput = imgWrap.querySelector('input[type="file"]');
17
+ if (fileInput) {
18
+ if (files.length === 0) {
19
+ files = new DataTransfer();
20
+ files.items.add(tmpFile);
21
+ fileInput.files = files.files;
22
+ } else {
23
+ fileInput.files = files;
24
+ }
25
+ fileInput.dispatchEvent(new Event('change'));
26
+ }
27
+ };
28
+
29
+ if (imgWrap.closest('#pnginfo_image')) {
30
+ // special treatment for PNG Info tab, wait for fetch request to finish
31
+ const oldFetch = window.fetch;
32
+ window.fetch = async(input, options) => {
33
+ const response = await oldFetch(input, options);
34
+ if ('api/predict/' === input) {
35
+ const content = await response.text();
36
+ window.fetch = oldFetch;
37
+ window.requestAnimationFrame(() => callback());
38
+ return new Response(content, {
39
+ status: response.status,
40
+ statusText: response.statusText,
41
+ headers: response.headers
42
+ });
43
+ }
44
+ return response;
45
+ };
46
+ } else {
47
+ window.requestAnimationFrame(() => callback());
48
+ }
49
+ }
50
+
51
+ function eventHasFiles(e) {
52
+ if (!e.dataTransfer || !e.dataTransfer.files) return false;
53
+ if (e.dataTransfer.files.length > 0) return true;
54
+ if (e.dataTransfer.items.length > 0 && e.dataTransfer.items[0].kind == "file") return true;
55
+
56
+ return false;
57
+ }
58
+
59
+ function dragDropTargetIsPrompt(target) {
60
+ if (target?.placeholder && target?.placeholder.indexOf("Prompt") >= 0) return true;
61
+ if (target?.parentNode?.parentNode?.className?.indexOf("prompt") > 0) return true;
62
+ return false;
63
+ }
64
+
65
+ window.document.addEventListener('dragover', e => {
66
+ const target = e.composedPath()[0];
67
+ if (!eventHasFiles(e)) return;
68
+
69
+ var targetImage = target.closest('[data-testid="image"]');
70
+ if (!dragDropTargetIsPrompt(target) && !targetImage) return;
71
+
72
+ e.stopPropagation();
73
+ e.preventDefault();
74
+ e.dataTransfer.dropEffect = 'copy';
75
+ });
76
+
77
+ window.document.addEventListener('drop', e => {
78
+ const target = e.composedPath()[0];
79
+ if (!eventHasFiles(e)) return;
80
+
81
+ if (dragDropTargetIsPrompt(target)) {
82
+ e.stopPropagation();
83
+ e.preventDefault();
84
+
85
+ let prompt_target = get_tab_index('tabs') == 1 ? "img2img_prompt_image" : "txt2img_prompt_image";
86
+
87
+ const imgParent = gradioApp().getElementById(prompt_target);
88
+ const files = e.dataTransfer.files;
89
+ const fileInput = imgParent.querySelector('input[type="file"]');
90
+ if (fileInput) {
91
+ fileInput.files = files;
92
+ fileInput.dispatchEvent(new Event('change'));
93
+ }
94
+ }
95
+
96
+ var targetImage = target.closest('[data-testid="image"]');
97
+ if (targetImage) {
98
+ e.stopPropagation();
99
+ e.preventDefault();
100
+ const files = e.dataTransfer.files;
101
+ dropReplaceImage(targetImage, files);
102
+ return;
103
+ }
104
+ });
105
+
106
+ window.addEventListener('paste', e => {
107
+ const files = e.clipboardData.files;
108
+ if (!isValidImageList(files)) {
109
+ return;
110
+ }
111
+
112
+ const visibleImageFields = [...gradioApp().querySelectorAll('[data-testid="image"]')]
113
+ .filter(el => uiElementIsVisible(el))
114
+ .sort((a, b) => uiElementInSight(b) - uiElementInSight(a));
115
+
116
+
117
+ if (!visibleImageFields.length) {
118
+ return;
119
+ }
120
+
121
+ const firstFreeImageField = visibleImageFields
122
+ .filter(el => el.querySelector('input[type=file]'))?.[0];
123
+
124
+ dropReplaceImage(
125
+ firstFreeImageField ?
126
+ firstFreeImageField :
127
+ visibleImageFields[visibleImageFields.length - 1]
128
+ , files
129
+ );
130
+ });
javascript/edit-attention.js ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function keyupEditAttention(event) {
2
+ let target = event.originalTarget || event.composedPath()[0];
3
+ if (!target.matches("*:is([id*='_toprow'] [id*='_prompt'], .prompt) textarea")) return;
4
+ if (!(event.metaKey || event.ctrlKey)) return;
5
+
6
+ let isPlus = event.key == "ArrowUp";
7
+ let isMinus = event.key == "ArrowDown";
8
+ if (!isPlus && !isMinus) return;
9
+
10
+ let selectionStart = target.selectionStart;
11
+ let selectionEnd = target.selectionEnd;
12
+ let text = target.value;
13
+
14
+ function selectCurrentParenthesisBlock(OPEN, CLOSE) {
15
+ if (selectionStart !== selectionEnd) return false;
16
+
17
+ // Find opening parenthesis around current cursor
18
+ const before = text.substring(0, selectionStart);
19
+ let beforeParen = before.lastIndexOf(OPEN);
20
+ if (beforeParen == -1) return false;
21
+ let beforeParenClose = before.lastIndexOf(CLOSE);
22
+ while (beforeParenClose !== -1 && beforeParenClose > beforeParen) {
23
+ beforeParen = before.lastIndexOf(OPEN, beforeParen - 1);
24
+ beforeParenClose = before.lastIndexOf(CLOSE, beforeParenClose - 1);
25
+ }
26
+
27
+ // Find closing parenthesis around current cursor
28
+ const after = text.substring(selectionStart);
29
+ let afterParen = after.indexOf(CLOSE);
30
+ if (afterParen == -1) return false;
31
+ let afterParenOpen = after.indexOf(OPEN);
32
+ while (afterParenOpen !== -1 && afterParen > afterParenOpen) {
33
+ afterParen = after.indexOf(CLOSE, afterParen + 1);
34
+ afterParenOpen = after.indexOf(OPEN, afterParenOpen + 1);
35
+ }
36
+ if (beforeParen === -1 || afterParen === -1) return false;
37
+
38
+ // Set the selection to the text between the parenthesis
39
+ const parenContent = text.substring(beforeParen + 1, selectionStart + afterParen);
40
+ const lastColon = parenContent.lastIndexOf(":");
41
+ selectionStart = beforeParen + 1;
42
+ selectionEnd = selectionStart + lastColon;
43
+ target.setSelectionRange(selectionStart, selectionEnd);
44
+ return true;
45
+ }
46
+
47
+ function selectCurrentWord() {
48
+ if (selectionStart !== selectionEnd) return false;
49
+ const delimiters = opts.keyedit_delimiters + " \r\n\t";
50
+
51
+ // seek backward until to find beggining
52
+ while (!delimiters.includes(text[selectionStart - 1]) && selectionStart > 0) {
53
+ selectionStart--;
54
+ }
55
+
56
+ // seek forward to find end
57
+ while (!delimiters.includes(text[selectionEnd]) && selectionEnd < text.length) {
58
+ selectionEnd++;
59
+ }
60
+
61
+ target.setSelectionRange(selectionStart, selectionEnd);
62
+ return true;
63
+ }
64
+
65
+ // If the user hasn't selected anything, let's select their current parenthesis block or word
66
+ if (!selectCurrentParenthesisBlock('<', '>') && !selectCurrentParenthesisBlock('(', ')')) {
67
+ selectCurrentWord();
68
+ }
69
+
70
+ event.preventDefault();
71
+
72
+ var closeCharacter = ')';
73
+ var delta = opts.keyedit_precision_attention;
74
+
75
+ if (selectionStart > 0 && text[selectionStart - 1] == '<') {
76
+ closeCharacter = '>';
77
+ delta = opts.keyedit_precision_extra;
78
+ } else if (selectionStart == 0 || text[selectionStart - 1] != "(") {
79
+
80
+ // do not include spaces at the end
81
+ while (selectionEnd > selectionStart && text[selectionEnd - 1] == ' ') {
82
+ selectionEnd -= 1;
83
+ }
84
+ if (selectionStart == selectionEnd) {
85
+ return;
86
+ }
87
+
88
+ text = text.slice(0, selectionStart) + "(" + text.slice(selectionStart, selectionEnd) + ":1.0)" + text.slice(selectionEnd);
89
+
90
+ selectionStart += 1;
91
+ selectionEnd += 1;
92
+ }
93
+
94
+ var end = text.slice(selectionEnd + 1).indexOf(closeCharacter) + 1;
95
+ var weight = parseFloat(text.slice(selectionEnd + 1, selectionEnd + 1 + end));
96
+ if (isNaN(weight)) return;
97
+
98
+ weight += isPlus ? delta : -delta;
99
+ weight = parseFloat(weight.toPrecision(12));
100
+ if (String(weight).length == 1) weight += ".0";
101
+
102
+ if (closeCharacter == ')' && weight == 1) {
103
+ var endParenPos = text.substring(selectionEnd).indexOf(')');
104
+ text = text.slice(0, selectionStart - 1) + text.slice(selectionStart, selectionEnd) + text.slice(selectionEnd + endParenPos + 1);
105
+ selectionStart--;
106
+ selectionEnd--;
107
+ } else {
108
+ text = text.slice(0, selectionEnd + 1) + weight + text.slice(selectionEnd + end);
109
+ }
110
+
111
+ target.focus();
112
+ target.value = text;
113
+ target.selectionStart = selectionStart;
114
+ target.selectionEnd = selectionEnd;
115
+
116
+ updateInput(target);
117
+ }
118
+
119
+ addEventListener('keydown', (event) => {
120
+ keyupEditAttention(event);
121
+ });
javascript/edit-order.js ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* alt+left/right moves text in prompt */
2
+
3
+ function keyupEditOrder(event) {
4
+ if (!opts.keyedit_move) return;
5
+
6
+ let target = event.originalTarget || event.composedPath()[0];
7
+ if (!target.matches("*:is([id*='_toprow'] [id*='_prompt'], .prompt) textarea")) return;
8
+ if (!event.altKey) return;
9
+
10
+ let isLeft = event.key == "ArrowLeft";
11
+ let isRight = event.key == "ArrowRight";
12
+ if (!isLeft && !isRight) return;
13
+ event.preventDefault();
14
+
15
+ let selectionStart = target.selectionStart;
16
+ let selectionEnd = target.selectionEnd;
17
+ let text = target.value;
18
+ let items = text.split(",");
19
+ let indexStart = (text.slice(0, selectionStart).match(/,/g) || []).length;
20
+ let indexEnd = (text.slice(0, selectionEnd).match(/,/g) || []).length;
21
+ let range = indexEnd - indexStart + 1;
22
+
23
+ if (isLeft && indexStart > 0) {
24
+ items.splice(indexStart - 1, 0, ...items.splice(indexStart, range));
25
+ target.value = items.join();
26
+ target.selectionStart = items.slice(0, indexStart - 1).join().length + (indexStart == 1 ? 0 : 1);
27
+ target.selectionEnd = items.slice(0, indexEnd).join().length;
28
+ } else if (isRight && indexEnd < items.length - 1) {
29
+ items.splice(indexStart + 1, 0, ...items.splice(indexStart, range));
30
+ target.value = items.join();
31
+ target.selectionStart = items.slice(0, indexStart + 1).join().length + 1;
32
+ target.selectionEnd = items.slice(0, indexEnd + 2).join().length;
33
+ }
34
+
35
+ event.preventDefault();
36
+ updateInput(target);
37
+ }
38
+
39
+ addEventListener('keydown', (event) => {
40
+ keyupEditOrder(event);
41
+ });
javascript/extensions.js ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ function extensions_apply(_disabled_list, _update_list, disable_all) {
3
+ var disable = [];
4
+ var update = [];
5
+
6
+ gradioApp().querySelectorAll('#extensions input[type="checkbox"]').forEach(function(x) {
7
+ if (x.name.startsWith("enable_") && !x.checked) {
8
+ disable.push(x.name.substring(7));
9
+ }
10
+
11
+ if (x.name.startsWith("update_") && x.checked) {
12
+ update.push(x.name.substring(7));
13
+ }
14
+ });
15
+
16
+ restart_reload();
17
+
18
+ return [JSON.stringify(disable), JSON.stringify(update), disable_all];
19
+ }
20
+
21
+ function extensions_check() {
22
+ var disable = [];
23
+
24
+ gradioApp().querySelectorAll('#extensions input[type="checkbox"]').forEach(function(x) {
25
+ if (x.name.startsWith("enable_") && !x.checked) {
26
+ disable.push(x.name.substring(7));
27
+ }
28
+ });
29
+
30
+ gradioApp().querySelectorAll('#extensions .extension_status').forEach(function(x) {
31
+ x.innerHTML = "Loading...";
32
+ });
33
+
34
+
35
+ var id = randomId();
36
+ requestProgress(id, gradioApp().getElementById('extensions_installed_html'), null, function() {
37
+
38
+ });
39
+
40
+ return [id, JSON.stringify(disable)];
41
+ }
42
+
43
+ function install_extension_from_index(button, url) {
44
+ button.disabled = "disabled";
45
+ button.value = "Installing...";
46
+
47
+ var textarea = gradioApp().querySelector('#extension_to_install textarea');
48
+ textarea.value = url;
49
+ updateInput(textarea);
50
+
51
+ gradioApp().querySelector('#install_extension_button').click();
52
+ }
53
+
54
+ function config_state_confirm_restore(_, config_state_name, config_restore_type) {
55
+ if (config_state_name == "Current") {
56
+ return [false, config_state_name, config_restore_type];
57
+ }
58
+ let restored = "";
59
+ if (config_restore_type == "extensions") {
60
+ restored = "all saved extension versions";
61
+ } else if (config_restore_type == "webui") {
62
+ restored = "the webui version";
63
+ } else {
64
+ restored = "the webui version and all saved extension versions";
65
+ }
66
+ let confirmed = confirm("Are you sure you want to restore from this state?\nThis will reset " + restored + ".");
67
+ if (confirmed) {
68
+ restart_reload();
69
+ gradioApp().querySelectorAll('#extensions .extension_status').forEach(function(x) {
70
+ x.innerHTML = "Loading...";
71
+ });
72
+ }
73
+ return [confirmed, config_state_name, config_restore_type];
74
+ }
75
+
76
+ function toggle_all_extensions(event) {
77
+ gradioApp().querySelectorAll('#extensions .extension_toggle').forEach(function(checkbox_el) {
78
+ checkbox_el.checked = event.target.checked;
79
+ });
80
+ }
81
+
82
+ function toggle_extension() {
83
+ let all_extensions_toggled = true;
84
+ for (const checkbox_el of gradioApp().querySelectorAll('#extensions .extension_toggle')) {
85
+ if (!checkbox_el.checked) {
86
+ all_extensions_toggled = false;
87
+ break;
88
+ }
89
+ }
90
+
91
+ gradioApp().querySelector('#extensions .all_extensions_toggle').checked = all_extensions_toggled;
92
+ }
javascript/extraNetworks.js ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function toggleCss(key, css, enable) {
2
+ var style = document.getElementById(key);
3
+ if (enable && !style) {
4
+ style = document.createElement('style');
5
+ style.id = key;
6
+ style.type = 'text/css';
7
+ document.head.appendChild(style);
8
+ }
9
+ if (style && !enable) {
10
+ document.head.removeChild(style);
11
+ }
12
+ if (style) {
13
+ style.innerHTML == '';
14
+ style.appendChild(document.createTextNode(css));
15
+ }
16
+ }
17
+
18
+ function setupExtraNetworksForTab(tabname) {
19
+ gradioApp().querySelector('#' + tabname + '_extra_tabs').classList.add('extra-networks');
20
+
21
+ var tabs = gradioApp().querySelector('#' + tabname + '_extra_tabs > div');
22
+ var searchDiv = gradioApp().getElementById(tabname + '_extra_search');
23
+ var search = searchDiv.querySelector('textarea');
24
+ var sort = gradioApp().getElementById(tabname + '_extra_sort');
25
+ var sortOrder = gradioApp().getElementById(tabname + '_extra_sortorder');
26
+ var refresh = gradioApp().getElementById(tabname + '_extra_refresh');
27
+ var showDirsDiv = gradioApp().getElementById(tabname + '_extra_show_dirs');
28
+ var showDirs = gradioApp().querySelector('#' + tabname + '_extra_show_dirs input');
29
+
30
+ sort.dataset.sortkey = 'sortDefault';
31
+ tabs.appendChild(searchDiv);
32
+ tabs.appendChild(sort);
33
+ tabs.appendChild(sortOrder);
34
+ tabs.appendChild(refresh);
35
+ tabs.appendChild(showDirsDiv);
36
+
37
+ var applyFilter = function() {
38
+ var searchTerm = search.value.toLowerCase();
39
+
40
+ gradioApp().querySelectorAll('#' + tabname + '_extra_tabs div.card').forEach(function(elem) {
41
+ var searchOnly = elem.querySelector('.search_only');
42
+ var text = elem.querySelector('.name').textContent.toLowerCase() + " " + elem.querySelector('.search_term').textContent.toLowerCase();
43
+
44
+ var visible = text.indexOf(searchTerm) != -1;
45
+
46
+ if (searchOnly && searchTerm.length < 4) {
47
+ visible = false;
48
+ }
49
+
50
+ elem.style.display = visible ? "" : "none";
51
+ });
52
+ };
53
+
54
+ var applySort = function() {
55
+ var reverse = sortOrder.classList.contains("sortReverse");
56
+ var sortKey = sort.querySelector("input").value.toLowerCase().replace("sort", "").replaceAll(" ", "_").replace(/_+$/, "").trim();
57
+ sortKey = sortKey ? "sort" + sortKey.charAt(0).toUpperCase() + sortKey.slice(1) : "";
58
+ var sortKeyStore = sortKey ? sortKey + (reverse ? "Reverse" : "") : "";
59
+ if (!sortKey || sortKeyStore == sort.dataset.sortkey) {
60
+ return;
61
+ }
62
+
63
+ sort.dataset.sortkey = sortKeyStore;
64
+
65
+ var cards = gradioApp().querySelectorAll('#' + tabname + '_extra_tabs div.card');
66
+ cards.forEach(function(card) {
67
+ card.originalParentElement = card.parentElement;
68
+ });
69
+ var sortedCards = Array.from(cards);
70
+ sortedCards.sort(function(cardA, cardB) {
71
+ var a = cardA.dataset[sortKey];
72
+ var b = cardB.dataset[sortKey];
73
+ if (!isNaN(a) && !isNaN(b)) {
74
+ return parseInt(a) - parseInt(b);
75
+ }
76
+
77
+ return (a < b ? -1 : (a > b ? 1 : 0));
78
+ });
79
+ if (reverse) {
80
+ sortedCards.reverse();
81
+ }
82
+ cards.forEach(function(card) {
83
+ card.remove();
84
+ });
85
+ sortedCards.forEach(function(card) {
86
+ card.originalParentElement.appendChild(card);
87
+ });
88
+ };
89
+
90
+ search.addEventListener("input", applyFilter);
91
+ applyFilter();
92
+ ["change", "blur", "click"].forEach(function(evt) {
93
+ sort.querySelector("input").addEventListener(evt, applySort);
94
+ });
95
+ sortOrder.addEventListener("click", function() {
96
+ sortOrder.classList.toggle("sortReverse");
97
+ applySort();
98
+ });
99
+
100
+ extraNetworksApplyFilter[tabname] = applyFilter;
101
+
102
+ var showDirsUpdate = function() {
103
+ var css = '#' + tabname + '_extra_tabs .extra-network-subdirs { display: none; }';
104
+ toggleCss(tabname + '_extra_show_dirs_style', css, !showDirs.checked);
105
+ localSet('extra-networks-show-dirs', showDirs.checked ? 1 : 0);
106
+ };
107
+ showDirs.checked = localGet('extra-networks-show-dirs', 1) == 1;
108
+ showDirs.addEventListener("change", showDirsUpdate);
109
+ showDirsUpdate();
110
+ }
111
+
112
+ function applyExtraNetworkFilter(tabname) {
113
+ setTimeout(extraNetworksApplyFilter[tabname], 1);
114
+ }
115
+
116
+ var extraNetworksApplyFilter = {};
117
+ var activePromptTextarea = {};
118
+
119
+ function setupExtraNetworks() {
120
+ setupExtraNetworksForTab('txt2img');
121
+ setupExtraNetworksForTab('img2img');
122
+
123
+ function registerPrompt(tabname, id) {
124
+ var textarea = gradioApp().querySelector("#" + id + " > label > textarea");
125
+
126
+ if (!activePromptTextarea[tabname]) {
127
+ activePromptTextarea[tabname] = textarea;
128
+ }
129
+
130
+ textarea.addEventListener("focus", function() {
131
+ activePromptTextarea[tabname] = textarea;
132
+ });
133
+ }
134
+
135
+ registerPrompt('txt2img', 'txt2img_prompt');
136
+ registerPrompt('txt2img', 'txt2img_neg_prompt');
137
+ registerPrompt('img2img', 'img2img_prompt');
138
+ registerPrompt('img2img', 'img2img_neg_prompt');
139
+ }
140
+
141
+ onUiLoaded(setupExtraNetworks);
142
+
143
+ var re_extranet = /<([^:]+:[^:]+):[\d.]+>(.*)/;
144
+ var re_extranet_g = /\s+<([^:]+:[^:]+):[\d.]+>/g;
145
+
146
+ function tryToRemoveExtraNetworkFromPrompt(textarea, text) {
147
+ var m = text.match(re_extranet);
148
+ var replaced = false;
149
+ var newTextareaText;
150
+ if (m) {
151
+ var extraTextAfterNet = m[2];
152
+ var partToSearch = m[1];
153
+ var foundAtPosition = -1;
154
+ newTextareaText = textarea.value.replaceAll(re_extranet_g, function(found, net, pos) {
155
+ m = found.match(re_extranet);
156
+ if (m[1] == partToSearch) {
157
+ replaced = true;
158
+ foundAtPosition = pos;
159
+ return "";
160
+ }
161
+ return found;
162
+ });
163
+
164
+ if (foundAtPosition >= 0 && newTextareaText.substr(foundAtPosition, extraTextAfterNet.length) == extraTextAfterNet) {
165
+ newTextareaText = newTextareaText.substr(0, foundAtPosition) + newTextareaText.substr(foundAtPosition + extraTextAfterNet.length);
166
+ }
167
+ } else {
168
+ newTextareaText = textarea.value.replaceAll(new RegExp(text, "g"), function(found) {
169
+ if (found == text) {
170
+ replaced = true;
171
+ return "";
172
+ }
173
+ return found;
174
+ });
175
+ }
176
+
177
+ if (replaced) {
178
+ textarea.value = newTextareaText;
179
+ return true;
180
+ }
181
+
182
+ return false;
183
+ }
184
+
185
+ function cardClicked(tabname, textToAdd, allowNegativePrompt) {
186
+ var textarea = allowNegativePrompt ? activePromptTextarea[tabname] : gradioApp().querySelector("#" + tabname + "_prompt > label > textarea");
187
+
188
+ if (!tryToRemoveExtraNetworkFromPrompt(textarea, textToAdd)) {
189
+ textarea.value = textarea.value + opts.extra_networks_add_text_separator + textToAdd;
190
+ }
191
+
192
+ updateInput(textarea);
193
+ }
194
+
195
+ function saveCardPreview(event, tabname, filename) {
196
+ var textarea = gradioApp().querySelector("#" + tabname + '_preview_filename > label > textarea');
197
+ var button = gradioApp().getElementById(tabname + '_save_preview');
198
+
199
+ textarea.value = filename;
200
+ updateInput(textarea);
201
+
202
+ button.click();
203
+
204
+ event.stopPropagation();
205
+ event.preventDefault();
206
+ }
207
+
208
+ function extraNetworksSearchButton(tabs_id, event) {
209
+ var searchTextarea = gradioApp().querySelector("#" + tabs_id + ' > label > textarea');
210
+ var button = event.target;
211
+ var text = button.classList.contains("search-all") ? "" : button.textContent.trim();
212
+
213
+ searchTextarea.value = text;
214
+ updateInput(searchTextarea);
215
+ }
216
+
217
+ var globalPopup = null;
218
+ var globalPopupInner = null;
219
+ function closePopup() {
220
+ if (!globalPopup) return;
221
+
222
+ globalPopup.style.display = "none";
223
+ }
224
+ function popup(contents) {
225
+ if (!globalPopup) {
226
+ globalPopup = document.createElement('div');
227
+ globalPopup.onclick = closePopup;
228
+ globalPopup.classList.add('global-popup');
229
+
230
+ var close = document.createElement('div');
231
+ close.classList.add('global-popup-close');
232
+ close.onclick = closePopup;
233
+ close.title = "Close";
234
+ globalPopup.appendChild(close);
235
+
236
+ globalPopupInner = document.createElement('div');
237
+ globalPopupInner.onclick = function(event) {
238
+ event.stopPropagation(); return false;
239
+ };
240
+ globalPopupInner.classList.add('global-popup-inner');
241
+ globalPopup.appendChild(globalPopupInner);
242
+
243
+ gradioApp().querySelector('.main').appendChild(globalPopup);
244
+ }
245
+
246
+ globalPopupInner.innerHTML = '';
247
+ globalPopupInner.appendChild(contents);
248
+
249
+ globalPopup.style.display = "flex";
250
+ }
251
+
252
+ var storedPopupIds = {};
253
+ function popupId(id) {
254
+ if (!storedPopupIds[id]) {
255
+ storedPopupIds[id] = gradioApp().getElementById(id);
256
+ }
257
+
258
+ popup(storedPopupIds[id]);
259
+ }
260
+
261
+ function extraNetworksShowMetadata(text) {
262
+ var elem = document.createElement('pre');
263
+ elem.classList.add('popup-metadata');
264
+ elem.textContent = text;
265
+
266
+ popup(elem);
267
+ }
268
+
269
+ function requestGet(url, data, handler, errorHandler) {
270
+ var xhr = new XMLHttpRequest();
271
+ var args = Object.keys(data).map(function(k) {
272
+ return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]);
273
+ }).join('&');
274
+ xhr.open("GET", url + "?" + args, true);
275
+
276
+ xhr.onreadystatechange = function() {
277
+ if (xhr.readyState === 4) {
278
+ if (xhr.status === 200) {
279
+ try {
280
+ var js = JSON.parse(xhr.responseText);
281
+ handler(js);
282
+ } catch (error) {
283
+ console.error(error);
284
+ errorHandler();
285
+ }
286
+ } else {
287
+ errorHandler();
288
+ }
289
+ }
290
+ };
291
+ var js = JSON.stringify(data);
292
+ xhr.send(js);
293
+ }
294
+
295
+ function extraNetworksRequestMetadata(event, extraPage, cardName) {
296
+ var showError = function() {
297
+ extraNetworksShowMetadata("there was an error getting metadata");
298
+ };
299
+
300
+ requestGet("./sd_extra_networks/metadata", {page: extraPage, item: cardName}, function(data) {
301
+ if (data && data.metadata) {
302
+ extraNetworksShowMetadata(data.metadata);
303
+ } else {
304
+ showError();
305
+ }
306
+ }, showError);
307
+
308
+ event.stopPropagation();
309
+ }
310
+
311
+ var extraPageUserMetadataEditors = {};
312
+
313
+ function extraNetworksEditUserMetadata(event, tabname, extraPage, cardName) {
314
+ var id = tabname + '_' + extraPage + '_edit_user_metadata';
315
+
316
+ var editor = extraPageUserMetadataEditors[id];
317
+ if (!editor) {
318
+ editor = {};
319
+ editor.page = gradioApp().getElementById(id);
320
+ editor.nameTextarea = gradioApp().querySelector("#" + id + "_name" + ' textarea');
321
+ editor.button = gradioApp().querySelector("#" + id + "_button");
322
+ extraPageUserMetadataEditors[id] = editor;
323
+ }
324
+
325
+ editor.nameTextarea.value = cardName;
326
+ updateInput(editor.nameTextarea);
327
+
328
+ editor.button.click();
329
+
330
+ popup(editor.page);
331
+
332
+ event.stopPropagation();
333
+ }
334
+
335
+ function extraNetworksRefreshSingleCard(page, tabname, name) {
336
+ requestGet("./sd_extra_networks/get-single-card", {page: page, tabname: tabname, name: name}, function(data) {
337
+ if (data && data.html) {
338
+ var card = gradioApp().querySelector('.card[data-name=' + JSON.stringify(name) + ']'); // likely using the wrong stringify function
339
+
340
+ var newDiv = document.createElement('DIV');
341
+ newDiv.innerHTML = data.html;
342
+ var newCard = newDiv.firstElementChild;
343
+
344
+ newCard.style.display = '';
345
+ card.parentElement.insertBefore(newCard, card);
346
+ card.parentElement.removeChild(card);
347
+ }
348
+ });
349
+ }
javascript/generationParams.js ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // attaches listeners to the txt2img and img2img galleries to update displayed generation param text when the image changes
2
+
3
+ let txt2img_gallery, img2img_gallery, modal = undefined;
4
+ onAfterUiUpdate(function() {
5
+ if (!txt2img_gallery) {
6
+ txt2img_gallery = attachGalleryListeners("txt2img");
7
+ }
8
+ if (!img2img_gallery) {
9
+ img2img_gallery = attachGalleryListeners("img2img");
10
+ }
11
+ if (!modal) {
12
+ modal = gradioApp().getElementById('lightboxModal');
13
+ modalObserver.observe(modal, {attributes: true, attributeFilter: ['style']});
14
+ }
15
+ });
16
+
17
+ let modalObserver = new MutationObserver(function(mutations) {
18
+ mutations.forEach(function(mutationRecord) {
19
+ let selectedTab = gradioApp().querySelector('#tabs div button.selected')?.innerText;
20
+ if (mutationRecord.target.style.display === 'none' && (selectedTab === 'txt2img' || selectedTab === 'img2img')) {
21
+ gradioApp().getElementById(selectedTab + "_generation_info_button")?.click();
22
+ }
23
+ });
24
+ });
25
+
26
+ function attachGalleryListeners(tab_name) {
27
+ var gallery = gradioApp().querySelector('#' + tab_name + '_gallery');
28
+ gallery?.addEventListener('click', () => gradioApp().getElementById(tab_name + "_generation_info_button").click());
29
+ gallery?.addEventListener('keydown', (e) => {
30
+ if (e.keyCode == 37 || e.keyCode == 39) { // left or right arrow
31
+ gradioApp().getElementById(tab_name + "_generation_info_button").click();
32
+ }
33
+ });
34
+ return gallery;
35
+ }
javascript/hints.js ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // mouseover tooltips for various UI elements
2
+
3
+ var titles = {
4
+ "Sampling steps": "How many times to improve the generated image iteratively; higher values take longer; very low values can produce bad results",
5
+ "Sampling method": "Which algorithm to use to produce the image",
6
+ "GFPGAN": "Restore low quality faces using GFPGAN neural network",
7
+ "Euler a": "Euler Ancestral - very creative, each can get a completely different picture depending on step count, setting steps higher than 30-40 does not help",
8
+ "DDIM": "Denoising Diffusion Implicit Models - best at inpainting",
9
+ "UniPC": "Unified Predictor-Corrector Framework for Fast Sampling of Diffusion Models",
10
+ "DPM adaptive": "Ignores step count - uses a number of steps determined by the CFG and resolution",
11
+
12
+ "\u{1F4D0}": "Auto detect size from img2img",
13
+ "Batch count": "How many batches of images to create (has no impact on generation performance or VRAM usage)",
14
+ "Batch size": "How many image to create in a single batch (increases generation performance at cost of higher VRAM usage)",
15
+ "CFG Scale": "Classifier Free Guidance Scale - how strongly the image should conform to prompt - lower values produce more creative results",
16
+ "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",
17
+ "\u{1f3b2}\ufe0f": "Set seed to -1, which will cause a new random number to be used every time",
18
+ "\u267b\ufe0f": "Reuse seed from last generation, mostly useful if it was randomized",
19
+ "\u2199\ufe0f": "Read generation parameters from prompt or last generation if prompt is empty into user interface.",
20
+ "\u{1f4c2}": "Open images output directory",
21
+ "\u{1f4be}": "Save style",
22
+ "\u{1f5d1}\ufe0f": "Clear prompt",
23
+ "\u{1f4cb}": "Apply selected styles to current prompt",
24
+ "\u{1f4d2}": "Paste available values into the field",
25
+ "\u{1f3b4}": "Show/hide extra networks",
26
+ "\u{1f300}": "Restore progress",
27
+
28
+ "Inpaint a part of image": "Draw a mask over an image, and the script will regenerate the masked area with content according to prompt",
29
+ "SD upscale": "Upscale image normally, split result into tiles, improve each tile using img2img, merge whole image back",
30
+
31
+ "Just resize": "Resize image to target resolution. Unless height and width match, you will get incorrect aspect ratio.",
32
+ "Crop and resize": "Resize the image so that entirety of target resolution is filled with the image. Crop parts that stick out.",
33
+ "Resize and fill": "Resize the image so that entirety of image is inside target resolution. Fill empty space with image's colors.",
34
+
35
+ "Mask blur": "How much to blur the mask before processing, in pixels.",
36
+ "Masked content": "What to put inside the masked area before processing it with Stable Diffusion.",
37
+ "fill": "fill it with colors of the image",
38
+ "original": "keep whatever was there originally",
39
+ "latent noise": "fill it with latent space noise",
40
+ "latent nothing": "fill it with latent space zeroes",
41
+ "Inpaint at full resolution": "Upscale masked region to target resolution, do inpainting, downscale back and paste into original image",
42
+
43
+ "Denoising strength": "Determines how little respect the algorithm should have for image's content. At 0, nothing will change, and at 1 you'll get an unrelated image. With values below 1.0, processing will take less steps than the Sampling Steps slider specifies.",
44
+
45
+ "Skip": "Stop processing current image and continue processing.",
46
+ "Interrupt": "Stop processing images and return any results accumulated so far.",
47
+ "Save": "Write image to a directory (default - log/images) and generation parameters into csv file.",
48
+
49
+ "X values": "Separate values for X axis using commas.",
50
+ "Y values": "Separate values for Y axis using commas.",
51
+
52
+ "None": "Do not do anything special",
53
+ "Prompt matrix": "Separate prompts into parts using vertical pipe character (|) and the script will create a picture for every combination of them (except for the first part, which will be present in all combinations)",
54
+ "X/Y/Z plot": "Create grid(s) where images will have different parameters. Use inputs below to specify which parameters will be shared by columns and rows",
55
+ "Custom code": "Run Python code. Advanced user only. Must run program with --allow-code for this to work",
56
+
57
+ "Prompt S/R": "Separate a list of words with commas, and the first word will be used as a keyword: script will search for this word in the prompt, and replace it with others",
58
+ "Prompt order": "Separate a list of words with commas, and the script will make a variation of prompt with those words for their every possible order",
59
+
60
+ "Tiling": "Produce an image that can be tiled.",
61
+ "Tile overlap": "For SD upscale, how much overlap in pixels should there be between tiles. Tiles overlap so that when they are merged back into one picture, there is no clearly visible seam.",
62
+
63
+ "Variation seed": "Seed of a different picture to be mixed into the generation.",
64
+ "Variation strength": "How strong of a variation to produce. At 0, there will be no effect. At 1, you will get the complete picture with variation seed (except for ancestral samplers, where you will just get something).",
65
+ "Resize seed from height": "Make an attempt to produce a picture similar to what would have been produced with same seed at specified resolution",
66
+ "Resize seed from width": "Make an attempt to produce a picture similar to what would have been produced with same seed at specified resolution",
67
+
68
+ "Interrogate": "Reconstruct prompt from existing image and put it into the prompt field.",
69
+
70
+ "Images filename pattern": "Use tags like [seed] and [date] to define how filenames for images are chosen. Leave empty for default.",
71
+ "Directory name pattern": "Use tags like [seed] and [date] to define how subdirectories for images and grids are chosen. Leave empty for default.",
72
+ "Max prompt words": "Set the maximum number of words to be used in the [prompt_words] option; ATTENTION: If the words are too long, they may exceed the maximum length of the file path that the system can handle",
73
+
74
+ "Loopback": "Performs img2img processing multiple times. Output images are used as input for the next loop.",
75
+ "Loops": "How many times to process an image. Each output is used as the input of the next loop. If set to 1, behavior will be as if this script were not used.",
76
+ "Final denoising strength": "The denoising strength for the final loop of each image in the batch.",
77
+ "Denoising strength curve": "The denoising curve controls the rate of denoising strength change each loop. Aggressive: Most of the change will happen towards the start of the loops. Linear: Change will be constant through all loops. Lazy: Most of the change will happen towards the end of the loops.",
78
+
79
+ "Style 1": "Style to apply; styles have components for both positive and negative prompts and apply to both",
80
+ "Style 2": "Style to apply; styles have components for both positive and negative prompts and apply to both",
81
+ "Apply style": "Insert selected styles into prompt fields",
82
+ "Create style": "Save current prompts as a style. If you add the token {prompt} to the text, the style uses that as a placeholder for your prompt when you use the style in the future.",
83
+
84
+ "Checkpoint name": "Loads weights from checkpoint before making images. You can either use hash or a part of filename (as seen in settings) for checkpoint name. Recommended to use with Y axis for less switching.",
85
+ "Inpainting conditioning mask strength": "Only applies to inpainting models. Determines how strongly to mask off the original image for inpainting and img2img. 1.0 means fully masked, which is the default behaviour. 0.0 means a fully unmasked conditioning. Lower values will help preserve the overall composition of the image, but will struggle with large changes.",
86
+
87
+ "Eta noise seed delta": "If this values is non-zero, it will be added to seed and used to initialize RNG for noises when using samplers with Eta. You can use this to produce even more variation of images, or you can use this to match images of other software if you know what you are doing.",
88
+
89
+ "Filename word regex": "This regular expression will be used extract words from filename, and they will be joined using the option below into label text used for training. Leave empty to keep filename text as it is.",
90
+ "Filename join string": "This string will be used to join split words into a single line if the option above is enabled.",
91
+
92
+ "Quicksettings list": "List of setting names, separated by commas, for settings that should go to the quick access bar at the top, rather than the usual setting tab. See modules/shared.py for setting names. Requires restarting to apply.",
93
+
94
+ "Weighted sum": "Result = A * (1 - M) + B * M",
95
+ "Add difference": "Result = A + (B - C) * M",
96
+ "No interpolation": "Result = A",
97
+
98
+ "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",
99
+ "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.",
100
+
101
+ "Clip skip": "Early stopping parameter for CLIP model; 1 is stop at last layer as usual, 2 is stop at penultimate layer, etc.",
102
+
103
+ "Approx NN": "Cheap neural network approximation. Very fast compared to VAE, but produces pictures with 4 times smaller horizontal/vertical resolution and lower quality.",
104
+ "Approx cheap": "Very cheap approximation. Very fast compared to VAE, but produces pictures with 8 times smaller horizontal/vertical resolution and extremely low quality.",
105
+
106
+ "Hires. fix": "Use a two step process to partially create an image at smaller resolution, upscale, and then improve details in it without changing composition",
107
+ "Hires steps": "Number of sampling steps for upscaled picture. If 0, uses same as for original.",
108
+ "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.",
109
+ "Resize width to": "Resizes image to this width. If 0, width is inferred from either of two nearby sliders.",
110
+ "Resize height to": "Resizes image to this height. If 0, height is inferred from either of two nearby sliders.",
111
+ "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.",
112
+ "Extra networks tab order": "Comma-separated list of tab names; tabs listed here will appear in the extra networks UI first and in order listed.",
113
+ "Negative Guidance minimum sigma": "Skip negative prompt for steps where image is already mostly denoised; the higher this value, the more skips there will be; provides increased performance in exchange for minor quality reduction."
114
+ };
115
+
116
+ function updateTooltip(element) {
117
+ if (element.title) return; // already has a title
118
+
119
+ let text = element.textContent;
120
+ let tooltip = localization[titles[text]] || titles[text];
121
+
122
+ if (!tooltip) {
123
+ let value = element.value;
124
+ if (value) tooltip = localization[titles[value]] || titles[value];
125
+ }
126
+
127
+ if (!tooltip) {
128
+ // Gradio dropdown options have `data-value`.
129
+ let dataValue = element.dataset.value;
130
+ if (dataValue) tooltip = localization[titles[dataValue]] || titles[dataValue];
131
+ }
132
+
133
+ if (!tooltip) {
134
+ for (const c of element.classList) {
135
+ if (c in titles) {
136
+ tooltip = localization[titles[c]] || titles[c];
137
+ break;
138
+ }
139
+ }
140
+ }
141
+
142
+ if (tooltip) {
143
+ element.title = tooltip;
144
+ }
145
+ }
146
+
147
+ // Nodes to check for adding tooltips.
148
+ const tooltipCheckNodes = new Set();
149
+ // Timer for debouncing tooltip check.
150
+ let tooltipCheckTimer = null;
151
+
152
+ function processTooltipCheckNodes() {
153
+ for (const node of tooltipCheckNodes) {
154
+ updateTooltip(node);
155
+ }
156
+ tooltipCheckNodes.clear();
157
+ }
158
+
159
+ onUiUpdate(function(mutationRecords) {
160
+ for (const record of mutationRecords) {
161
+ if (record.type === "childList" && record.target.classList.contains("options")) {
162
+ // This smells like a Gradio dropdown menu having changed,
163
+ // so let's enqueue an update for the input element that shows the current value.
164
+ let wrap = record.target.parentNode;
165
+ let input = wrap?.querySelector("input");
166
+ if (input) {
167
+ input.title = ""; // So we'll even have a chance to update it.
168
+ tooltipCheckNodes.add(input);
169
+ }
170
+ }
171
+ for (const node of record.addedNodes) {
172
+ if (node.nodeType === Node.ELEMENT_NODE && !node.classList.contains("hide")) {
173
+ if (!node.title) {
174
+ if (
175
+ node.tagName === "SPAN" ||
176
+ node.tagName === "BUTTON" ||
177
+ node.tagName === "P" ||
178
+ node.tagName === "INPUT" ||
179
+ (node.tagName === "LI" && node.classList.contains("item")) // Gradio dropdown item
180
+ ) {
181
+ tooltipCheckNodes.add(node);
182
+ }
183
+ }
184
+ node.querySelectorAll('span, button, p').forEach(n => tooltipCheckNodes.add(n));
185
+ }
186
+ }
187
+ }
188
+ if (tooltipCheckNodes.size) {
189
+ clearTimeout(tooltipCheckTimer);
190
+ tooltipCheckTimer = setTimeout(processTooltipCheckNodes, 1000);
191
+ }
192
+ });
193
+
194
+ onUiLoaded(function() {
195
+ for (var comp of window.gradio_config.components) {
196
+ if (comp.props.webui_tooltip && comp.props.elem_id) {
197
+ var elem = gradioApp().getElementById(comp.props.elem_id);
198
+ if (elem) {
199
+ elem.title = comp.props.webui_tooltip;
200
+ }
201
+ }
202
+ }
203
+ });
javascript/hires_fix.js ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ function onCalcResolutionHires(enable, width, height, hr_scale, hr_resize_x, hr_resize_y) {
3
+ function setInactive(elem, inactive) {
4
+ elem.classList.toggle('inactive', !!inactive);
5
+ }
6
+
7
+ var hrUpscaleBy = gradioApp().getElementById('txt2img_hr_scale');
8
+ var hrResizeX = gradioApp().getElementById('txt2img_hr_resize_x');
9
+ var hrResizeY = gradioApp().getElementById('txt2img_hr_resize_y');
10
+
11
+ gradioApp().getElementById('txt2img_hires_fix_row2').style.display = opts.use_old_hires_fix_width_height ? "none" : "";
12
+
13
+ setInactive(hrUpscaleBy, opts.use_old_hires_fix_width_height || hr_resize_x > 0 || hr_resize_y > 0);
14
+ setInactive(hrResizeX, opts.use_old_hires_fix_width_height || hr_resize_x == 0);
15
+ setInactive(hrResizeY, opts.use_old_hires_fix_width_height || hr_resize_y == 0);
16
+
17
+ return [enable, width, height, hr_scale, hr_resize_x, hr_resize_y];
18
+ }
javascript/imageMaskFix.js ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * temporary fix for https://github.com/AUTOMATIC1111/stable-diffusion-webui/issues/668
3
+ * @see https://github.com/gradio-app/gradio/issues/1721
4
+ */
5
+ function imageMaskResize() {
6
+ const canvases = gradioApp().querySelectorAll('#img2maskimg .touch-none canvas');
7
+ if (!canvases.length) {
8
+ window.removeEventListener('resize', imageMaskResize);
9
+ return;
10
+ }
11
+
12
+ const wrapper = canvases[0].closest('.touch-none');
13
+ const previewImage = wrapper.previousElementSibling;
14
+
15
+ if (!previewImage.complete) {
16
+ previewImage.addEventListener('load', imageMaskResize);
17
+ return;
18
+ }
19
+
20
+ const w = previewImage.width;
21
+ const h = previewImage.height;
22
+ const nw = previewImage.naturalWidth;
23
+ const nh = previewImage.naturalHeight;
24
+ const portrait = nh > nw;
25
+
26
+ const wW = Math.min(w, portrait ? h / nh * nw : w / nw * nw);
27
+ const wH = Math.min(h, portrait ? h / nh * nh : w / nw * nh);
28
+
29
+ wrapper.style.width = `${wW}px`;
30
+ wrapper.style.height = `${wH}px`;
31
+ wrapper.style.left = `0px`;
32
+ wrapper.style.top = `0px`;
33
+
34
+ canvases.forEach(c => {
35
+ c.style.width = c.style.height = '';
36
+ c.style.maxWidth = '100%';
37
+ c.style.maxHeight = '100%';
38
+ c.style.objectFit = 'contain';
39
+ });
40
+ }
41
+
42
+ onAfterUiUpdate(imageMaskResize);
43
+ window.addEventListener('resize', imageMaskResize);
javascript/imageviewer.js ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // A full size 'lightbox' preview modal shown when left clicking on gallery previews
2
+ function closeModal() {
3
+ gradioApp().getElementById("lightboxModal").style.display = "none";
4
+ }
5
+
6
+ function showModal(event) {
7
+ const source = event.target || event.srcElement;
8
+ const modalImage = gradioApp().getElementById("modalImage");
9
+ const lb = gradioApp().getElementById("lightboxModal");
10
+ modalImage.src = source.src;
11
+ if (modalImage.style.display === 'none') {
12
+ lb.style.setProperty('background-image', 'url(' + source.src + ')');
13
+ }
14
+ lb.style.display = "flex";
15
+ lb.focus();
16
+
17
+ const tabTxt2Img = gradioApp().getElementById("tab_txt2img");
18
+ const tabImg2Img = gradioApp().getElementById("tab_img2img");
19
+ // show the save button in modal only on txt2img or img2img tabs
20
+ if (tabTxt2Img.style.display != "none" || tabImg2Img.style.display != "none") {
21
+ gradioApp().getElementById("modal_save").style.display = "inline";
22
+ } else {
23
+ gradioApp().getElementById("modal_save").style.display = "none";
24
+ }
25
+ event.stopPropagation();
26
+ }
27
+
28
+ function negmod(n, m) {
29
+ return ((n % m) + m) % m;
30
+ }
31
+
32
+ function updateOnBackgroundChange() {
33
+ const modalImage = gradioApp().getElementById("modalImage");
34
+ if (modalImage && modalImage.offsetParent) {
35
+ let currentButton = selected_gallery_button();
36
+
37
+ if (currentButton?.children?.length > 0 && modalImage.src != currentButton.children[0].src) {
38
+ modalImage.src = currentButton.children[0].src;
39
+ if (modalImage.style.display === 'none') {
40
+ const modal = gradioApp().getElementById("lightboxModal");
41
+ modal.style.setProperty('background-image', `url(${modalImage.src})`);
42
+ }
43
+ }
44
+ }
45
+ }
46
+
47
+ function modalImageSwitch(offset) {
48
+ var galleryButtons = all_gallery_buttons();
49
+
50
+ if (galleryButtons.length > 1) {
51
+ var currentButton = selected_gallery_button();
52
+
53
+ var result = -1;
54
+ galleryButtons.forEach(function(v, i) {
55
+ if (v == currentButton) {
56
+ result = i;
57
+ }
58
+ });
59
+
60
+ if (result != -1) {
61
+ var nextButton = galleryButtons[negmod((result + offset), galleryButtons.length)];
62
+ nextButton.click();
63
+ const modalImage = gradioApp().getElementById("modalImage");
64
+ const modal = gradioApp().getElementById("lightboxModal");
65
+ modalImage.src = nextButton.children[0].src;
66
+ if (modalImage.style.display === 'none') {
67
+ modal.style.setProperty('background-image', `url(${modalImage.src})`);
68
+ }
69
+ setTimeout(function() {
70
+ modal.focus();
71
+ }, 10);
72
+ }
73
+ }
74
+ }
75
+
76
+ function saveImage() {
77
+ const tabTxt2Img = gradioApp().getElementById("tab_txt2img");
78
+ const tabImg2Img = gradioApp().getElementById("tab_img2img");
79
+ const saveTxt2Img = "save_txt2img";
80
+ const saveImg2Img = "save_img2img";
81
+ if (tabTxt2Img.style.display != "none") {
82
+ gradioApp().getElementById(saveTxt2Img).click();
83
+ } else if (tabImg2Img.style.display != "none") {
84
+ gradioApp().getElementById(saveImg2Img).click();
85
+ } else {
86
+ console.error("missing implementation for saving modal of this type");
87
+ }
88
+ }
89
+
90
+ function modalSaveImage(event) {
91
+ saveImage();
92
+ event.stopPropagation();
93
+ }
94
+
95
+ function modalNextImage(event) {
96
+ modalImageSwitch(1);
97
+ event.stopPropagation();
98
+ }
99
+
100
+ function modalPrevImage(event) {
101
+ modalImageSwitch(-1);
102
+ event.stopPropagation();
103
+ }
104
+
105
+ function modalKeyHandler(event) {
106
+ switch (event.key) {
107
+ case "s":
108
+ saveImage();
109
+ break;
110
+ case "ArrowLeft":
111
+ modalPrevImage(event);
112
+ break;
113
+ case "ArrowRight":
114
+ modalNextImage(event);
115
+ break;
116
+ case "Escape":
117
+ closeModal();
118
+ break;
119
+ }
120
+ }
121
+
122
+ function setupImageForLightbox(e) {
123
+ if (e.dataset.modded) {
124
+ return;
125
+ }
126
+
127
+ e.dataset.modded = true;
128
+ e.style.cursor = 'pointer';
129
+ e.style.userSelect = 'none';
130
+
131
+ var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
132
+
133
+ // For Firefox, listening on click first switched to next image then shows the lightbox.
134
+ // If you know how to fix this without switching to mousedown event, please.
135
+ // For other browsers the event is click to make it possiblr to drag picture.
136
+ var event = isFirefox ? 'mousedown' : 'click';
137
+
138
+ e.addEventListener(event, function(evt) {
139
+ if (evt.button == 1) {
140
+ open(evt.target.src);
141
+ evt.preventDefault();
142
+ return;
143
+ }
144
+ if (!opts.js_modal_lightbox || evt.button != 0) return;
145
+
146
+ modalZoomSet(gradioApp().getElementById('modalImage'), opts.js_modal_lightbox_initially_zoomed);
147
+ evt.preventDefault();
148
+ showModal(evt);
149
+ }, true);
150
+
151
+ }
152
+
153
+ function modalZoomSet(modalImage, enable) {
154
+ if (modalImage) modalImage.classList.toggle('modalImageFullscreen', !!enable);
155
+ }
156
+
157
+ function modalZoomToggle(event) {
158
+ var modalImage = gradioApp().getElementById("modalImage");
159
+ modalZoomSet(modalImage, !modalImage.classList.contains('modalImageFullscreen'));
160
+ event.stopPropagation();
161
+ }
162
+
163
+ function modalTileImageToggle(event) {
164
+ const modalImage = gradioApp().getElementById("modalImage");
165
+ const modal = gradioApp().getElementById("lightboxModal");
166
+ const isTiling = modalImage.style.display === 'none';
167
+ if (isTiling) {
168
+ modalImage.style.display = 'block';
169
+ modal.style.setProperty('background-image', 'none');
170
+ } else {
171
+ modalImage.style.display = 'none';
172
+ modal.style.setProperty('background-image', `url(${modalImage.src})`);
173
+ }
174
+
175
+ event.stopPropagation();
176
+ }
177
+
178
+ onAfterUiUpdate(function() {
179
+ var fullImg_preview = gradioApp().querySelectorAll('.gradio-gallery > div > img');
180
+ if (fullImg_preview != null) {
181
+ fullImg_preview.forEach(setupImageForLightbox);
182
+ }
183
+ updateOnBackgroundChange();
184
+ });
185
+
186
+ document.addEventListener("DOMContentLoaded", function() {
187
+ //const modalFragment = document.createDocumentFragment();
188
+ const modal = document.createElement('div');
189
+ modal.onclick = closeModal;
190
+ modal.id = "lightboxModal";
191
+ modal.tabIndex = 0;
192
+ modal.addEventListener('keydown', modalKeyHandler, true);
193
+
194
+ const modalControls = document.createElement('div');
195
+ modalControls.className = 'modalControls gradio-container';
196
+ modal.append(modalControls);
197
+
198
+ const modalZoom = document.createElement('span');
199
+ modalZoom.className = 'modalZoom cursor';
200
+ modalZoom.innerHTML = '&#10529;';
201
+ modalZoom.addEventListener('click', modalZoomToggle, true);
202
+ modalZoom.title = "Toggle zoomed view";
203
+ modalControls.appendChild(modalZoom);
204
+
205
+ const modalTileImage = document.createElement('span');
206
+ modalTileImage.className = 'modalTileImage cursor';
207
+ modalTileImage.innerHTML = '&#8862;';
208
+ modalTileImage.addEventListener('click', modalTileImageToggle, true);
209
+ modalTileImage.title = "Preview tiling";
210
+ modalControls.appendChild(modalTileImage);
211
+
212
+ const modalSave = document.createElement("span");
213
+ modalSave.className = "modalSave cursor";
214
+ modalSave.id = "modal_save";
215
+ modalSave.innerHTML = "&#x1F5AB;";
216
+ modalSave.addEventListener("click", modalSaveImage, true);
217
+ modalSave.title = "Save Image(s)";
218
+ modalControls.appendChild(modalSave);
219
+
220
+ const modalClose = document.createElement('span');
221
+ modalClose.className = 'modalClose cursor';
222
+ modalClose.innerHTML = '&times;';
223
+ modalClose.onclick = closeModal;
224
+ modalClose.title = "Close image viewer";
225
+ modalControls.appendChild(modalClose);
226
+
227
+ const modalImage = document.createElement('img');
228
+ modalImage.id = 'modalImage';
229
+ modalImage.onclick = closeModal;
230
+ modalImage.tabIndex = 0;
231
+ modalImage.addEventListener('keydown', modalKeyHandler, true);
232
+ modal.appendChild(modalImage);
233
+
234
+ const modalPrev = document.createElement('a');
235
+ modalPrev.className = 'modalPrev';
236
+ modalPrev.innerHTML = '&#10094;';
237
+ modalPrev.tabIndex = 0;
238
+ modalPrev.addEventListener('click', modalPrevImage, true);
239
+ modalPrev.addEventListener('keydown', modalKeyHandler, true);
240
+ modal.appendChild(modalPrev);
241
+
242
+ const modalNext = document.createElement('a');
243
+ modalNext.className = 'modalNext';
244
+ modalNext.innerHTML = '&#10095;';
245
+ modalNext.tabIndex = 0;
246
+ modalNext.addEventListener('click', modalNextImage, true);
247
+ modalNext.addEventListener('keydown', modalKeyHandler, true);
248
+
249
+ modal.appendChild(modalNext);
250
+
251
+ try {
252
+ gradioApp().appendChild(modal);
253
+ } catch (e) {
254
+ gradioApp().body.appendChild(modal);
255
+ }
256
+
257
+ document.body.appendChild(modal);
258
+
259
+ });
javascript/imageviewerGamepad.js ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ let gamepads = [];
2
+
3
+ window.addEventListener('gamepadconnected', (e) => {
4
+ const index = e.gamepad.index;
5
+ let isWaiting = false;
6
+ gamepads[index] = setInterval(async() => {
7
+ if (!opts.js_modal_lightbox_gamepad || isWaiting) return;
8
+ const gamepad = navigator.getGamepads()[index];
9
+ const xValue = gamepad.axes[0];
10
+ if (xValue <= -0.3) {
11
+ modalPrevImage(e);
12
+ isWaiting = true;
13
+ } else if (xValue >= 0.3) {
14
+ modalNextImage(e);
15
+ isWaiting = true;
16
+ }
17
+ if (isWaiting) {
18
+ await sleepUntil(() => {
19
+ const xValue = navigator.getGamepads()[index].axes[0];
20
+ if (xValue < 0.3 && xValue > -0.3) {
21
+ return true;
22
+ }
23
+ }, opts.js_modal_lightbox_gamepad_repeat);
24
+ isWaiting = false;
25
+ }
26
+ }, 10);
27
+ });
28
+
29
+ window.addEventListener('gamepaddisconnected', (e) => {
30
+ clearInterval(gamepads[e.gamepad.index]);
31
+ });
32
+
33
+ /*
34
+ Primarily for vr controller type pointer devices.
35
+ I use the wheel event because there's currently no way to do it properly with web xr.
36
+ */
37
+ let isScrolling = false;
38
+ window.addEventListener('wheel', (e) => {
39
+ if (!opts.js_modal_lightbox_gamepad || isScrolling) return;
40
+ isScrolling = true;
41
+
42
+ if (e.deltaX <= -0.6) {
43
+ modalPrevImage(e);
44
+ } else if (e.deltaX >= 0.6) {
45
+ modalNextImage(e);
46
+ }
47
+
48
+ setTimeout(() => {
49
+ isScrolling = false;
50
+ }, opts.js_modal_lightbox_gamepad_repeat);
51
+ });
52
+
53
+ function sleepUntil(f, timeout) {
54
+ return new Promise((resolve) => {
55
+ const timeStart = new Date();
56
+ const wait = setInterval(function() {
57
+ if (f() || new Date() - timeStart > timeout) {
58
+ clearInterval(wait);
59
+ resolve();
60
+ }
61
+ }, 20);
62
+ });
63
+ }
javascript/inputAccordion.js ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ var observerAccordionOpen = new MutationObserver(function(mutations) {
2
+ mutations.forEach(function(mutationRecord) {
3
+ var elem = mutationRecord.target;
4
+ var open = elem.classList.contains('open');
5
+
6
+ var accordion = elem.parentNode;
7
+ accordion.classList.toggle('input-accordion-open', open);
8
+
9
+ var checkbox = gradioApp().querySelector('#' + accordion.id + "-checkbox input");
10
+ checkbox.checked = open;
11
+ updateInput(checkbox);
12
+
13
+ var extra = gradioApp().querySelector('#' + accordion.id + "-extra");
14
+ if (extra) {
15
+ extra.style.display = open ? "" : "none";
16
+ }
17
+ });
18
+ });
19
+
20
+ function inputAccordionChecked(id, checked) {
21
+ var label = gradioApp().querySelector('#' + id + " .label-wrap");
22
+ if (label.classList.contains('open') != checked) {
23
+ label.click();
24
+ }
25
+ }
26
+
27
+ onUiLoaded(function() {
28
+ for (var accordion of gradioApp().querySelectorAll('.input-accordion')) {
29
+ var labelWrap = accordion.querySelector('.label-wrap');
30
+ observerAccordionOpen.observe(labelWrap, {attributes: true, attributeFilter: ['class']});
31
+
32
+ var extra = gradioApp().querySelector('#' + accordion.id + "-extra");
33
+ if (extra) {
34
+ labelWrap.insertBefore(extra, labelWrap.lastElementChild);
35
+ }
36
+ }
37
+ });
javascript/localStorage.js ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ function localSet(k, v) {
3
+ try {
4
+ localStorage.setItem(k, v);
5
+ } catch (e) {
6
+ console.warn(`Failed to save ${k} to localStorage: ${e}`);
7
+ }
8
+ }
9
+
10
+ function localGet(k, def) {
11
+ try {
12
+ return localStorage.getItem(k);
13
+ } catch (e) {
14
+ console.warn(`Failed to load ${k} from localStorage: ${e}`);
15
+ }
16
+
17
+ return def;
18
+ }
19
+
20
+ function localRemove(k) {
21
+ try {
22
+ return localStorage.removeItem(k);
23
+ } catch (e) {
24
+ console.warn(`Failed to remove ${k} from localStorage: ${e}`);
25
+ }
26
+ }
javascript/localization.js ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ // localization = {} -- the dict with translations is created by the backend
3
+
4
+ var ignore_ids_for_localization = {
5
+ setting_sd_hypernetwork: 'OPTION',
6
+ setting_sd_model_checkpoint: 'OPTION',
7
+ modelmerger_primary_model_name: 'OPTION',
8
+ modelmerger_secondary_model_name: 'OPTION',
9
+ modelmerger_tertiary_model_name: 'OPTION',
10
+ train_embedding: 'OPTION',
11
+ train_hypernetwork: 'OPTION',
12
+ txt2img_styles: 'OPTION',
13
+ img2img_styles: 'OPTION',
14
+ setting_random_artist_categories: 'OPTION',
15
+ setting_face_restoration_model: 'OPTION',
16
+ setting_realesrgan_enabled_models: 'OPTION',
17
+ extras_upscaler_1: 'OPTION',
18
+ extras_upscaler_2: 'OPTION',
19
+ };
20
+
21
+ var re_num = /^[.\d]+$/;
22
+ var re_emoji = /[\p{Extended_Pictographic}\u{1F3FB}-\u{1F3FF}\u{1F9B0}-\u{1F9B3}]/u;
23
+
24
+ var original_lines = {};
25
+ var translated_lines = {};
26
+
27
+ function hasLocalization() {
28
+ return window.localization && Object.keys(window.localization).length > 0;
29
+ }
30
+
31
+ function textNodesUnder(el) {
32
+ var n, a = [], walk = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, null, false);
33
+ while ((n = walk.nextNode())) a.push(n);
34
+ return a;
35
+ }
36
+
37
+ function canBeTranslated(node, text) {
38
+ if (!text) return false;
39
+ if (!node.parentElement) return false;
40
+
41
+ var parentType = node.parentElement.nodeName;
42
+ if (parentType == 'SCRIPT' || parentType == 'STYLE' || parentType == 'TEXTAREA') return false;
43
+
44
+ if (parentType == 'OPTION' || parentType == 'SPAN') {
45
+ var pnode = node;
46
+ for (var level = 0; level < 4; level++) {
47
+ pnode = pnode.parentElement;
48
+ if (!pnode) break;
49
+
50
+ if (ignore_ids_for_localization[pnode.id] == parentType) return false;
51
+ }
52
+ }
53
+
54
+ if (re_num.test(text)) return false;
55
+ if (re_emoji.test(text)) return false;
56
+ return true;
57
+ }
58
+
59
+ function getTranslation(text) {
60
+ if (!text) return undefined;
61
+
62
+ if (translated_lines[text] === undefined) {
63
+ original_lines[text] = 1;
64
+ }
65
+
66
+ var tl = localization[text];
67
+ if (tl !== undefined) {
68
+ translated_lines[tl] = 1;
69
+ }
70
+
71
+ return tl;
72
+ }
73
+
74
+ function processTextNode(node) {
75
+ var text = node.textContent.trim();
76
+
77
+ if (!canBeTranslated(node, text)) return;
78
+
79
+ var tl = getTranslation(text);
80
+ if (tl !== undefined) {
81
+ node.textContent = tl;
82
+ }
83
+ }
84
+
85
+ function processNode(node) {
86
+ if (node.nodeType == 3) {
87
+ processTextNode(node);
88
+ return;
89
+ }
90
+
91
+ if (node.title) {
92
+ let tl = getTranslation(node.title);
93
+ if (tl !== undefined) {
94
+ node.title = tl;
95
+ }
96
+ }
97
+
98
+ if (node.placeholder) {
99
+ let tl = getTranslation(node.placeholder);
100
+ if (tl !== undefined) {
101
+ node.placeholder = tl;
102
+ }
103
+ }
104
+
105
+ textNodesUnder(node).forEach(function(node) {
106
+ processTextNode(node);
107
+ });
108
+ }
109
+
110
+ function localizeWholePage() {
111
+ processNode(gradioApp());
112
+
113
+ function elem(comp) {
114
+ var elem_id = comp.props.elem_id ? comp.props.elem_id : "component-" + comp.id;
115
+ return gradioApp().getElementById(elem_id);
116
+ }
117
+
118
+ for (var comp of window.gradio_config.components) {
119
+ if (comp.props.webui_tooltip) {
120
+ let e = elem(comp);
121
+
122
+ let tl = e ? getTranslation(e.title) : undefined;
123
+ if (tl !== undefined) {
124
+ e.title = tl;
125
+ }
126
+ }
127
+ if (comp.props.placeholder) {
128
+ let e = elem(comp);
129
+ let textbox = e ? e.querySelector('[placeholder]') : null;
130
+
131
+ let tl = textbox ? getTranslation(textbox.placeholder) : undefined;
132
+ if (tl !== undefined) {
133
+ textbox.placeholder = tl;
134
+ }
135
+ }
136
+ }
137
+ }
138
+
139
+ function dumpTranslations() {
140
+ if (!hasLocalization()) {
141
+ // If we don't have any localization,
142
+ // we will not have traversed the app to find
143
+ // original_lines, so do that now.
144
+ localizeWholePage();
145
+ }
146
+ var dumped = {};
147
+ if (localization.rtl) {
148
+ dumped.rtl = true;
149
+ }
150
+
151
+ for (const text in original_lines) {
152
+ if (dumped[text] !== undefined) continue;
153
+ dumped[text] = localization[text] || text;
154
+ }
155
+
156
+ return dumped;
157
+ }
158
+
159
+ function download_localization() {
160
+ var text = JSON.stringify(dumpTranslations(), null, 4);
161
+
162
+ var element = document.createElement('a');
163
+ element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
164
+ element.setAttribute('download', "localization.json");
165
+ element.style.display = 'none';
166
+ document.body.appendChild(element);
167
+
168
+ element.click();
169
+
170
+ document.body.removeChild(element);
171
+ }
172
+
173
+ document.addEventListener("DOMContentLoaded", function() {
174
+ if (!hasLocalization()) {
175
+ return;
176
+ }
177
+
178
+ onUiUpdate(function(m) {
179
+ m.forEach(function(mutation) {
180
+ mutation.addedNodes.forEach(function(node) {
181
+ processNode(node);
182
+ });
183
+ });
184
+ });
185
+
186
+ localizeWholePage();
187
+
188
+ if (localization.rtl) { // if the language is from right to left,
189
+ (new MutationObserver((mutations, observer) => { // wait for the style to load
190
+ mutations.forEach(mutation => {
191
+ mutation.addedNodes.forEach(node => {
192
+ if (node.tagName === 'STYLE') {
193
+ observer.disconnect();
194
+
195
+ for (const x of node.sheet.rules) { // find all rtl media rules
196
+ if (Array.from(x.media || []).includes('rtl')) {
197
+ x.media.appendMedium('all'); // enable them
198
+ }
199
+ }
200
+ }
201
+ });
202
+ });
203
+ })).observe(gradioApp(), {childList: true});
204
+ }
205
+ });
javascript/notification.js ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Monitors the gallery and sends a browser notification when the leading image is new.
2
+
3
+ let lastHeadImg = null;
4
+
5
+ let notificationButton = null;
6
+
7
+ onAfterUiUpdate(function() {
8
+ if (notificationButton == null) {
9
+ notificationButton = gradioApp().getElementById('request_notifications');
10
+
11
+ if (notificationButton != null) {
12
+ notificationButton.addEventListener('click', () => {
13
+ void Notification.requestPermission();
14
+ }, true);
15
+ }
16
+ }
17
+
18
+ const galleryPreviews = gradioApp().querySelectorAll('div[id^="tab_"] div[id$="_results"] .thumbnail-item > img');
19
+
20
+ if (galleryPreviews == null) return;
21
+
22
+ const headImg = galleryPreviews[0]?.src;
23
+
24
+ if (headImg == null || headImg == lastHeadImg) return;
25
+
26
+ lastHeadImg = headImg;
27
+
28
+ // play notification sound if available
29
+ gradioApp().querySelector('#audio_notification audio')?.play();
30
+
31
+ if (document.hasFocus()) return;
32
+
33
+ // Multiple copies of the images are in the DOM when one is selected. Dedup with a Set to get the real number generated.
34
+ const imgs = new Set(Array.from(galleryPreviews).map(img => img.src));
35
+
36
+ const notification = new Notification(
37
+ 'Stable Diffusion',
38
+ {
39
+ body: `Generated ${imgs.size > 1 ? imgs.size - opts.return_grid : 1} image${imgs.size > 1 ? 's' : ''}`,
40
+ icon: headImg,
41
+ image: headImg,
42
+ }
43
+ );
44
+
45
+ notification.onclick = function(_) {
46
+ parent.focus();
47
+ this.close();
48
+ };
49
+ });
javascript/profilerVisualization.js ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ function createRow(table, cellName, items) {
3
+ var tr = document.createElement('tr');
4
+ var res = [];
5
+
6
+ items.forEach(function(x, i) {
7
+ if (x === undefined) {
8
+ res.push(null);
9
+ return;
10
+ }
11
+
12
+ var td = document.createElement(cellName);
13
+ td.textContent = x;
14
+ tr.appendChild(td);
15
+ res.push(td);
16
+
17
+ var colspan = 1;
18
+ for (var n = i + 1; n < items.length; n++) {
19
+ if (items[n] !== undefined) {
20
+ break;
21
+ }
22
+
23
+ colspan += 1;
24
+ }
25
+
26
+ if (colspan > 1) {
27
+ td.colSpan = colspan;
28
+ }
29
+ });
30
+
31
+ table.appendChild(tr);
32
+
33
+ return res;
34
+ }
35
+
36
+ function showProfile(path, cutoff = 0.05) {
37
+ requestGet(path, {}, function(data) {
38
+ var table = document.createElement('table');
39
+ table.className = 'popup-table';
40
+
41
+ data.records['total'] = data.total;
42
+ var keys = Object.keys(data.records).sort(function(a, b) {
43
+ return data.records[b] - data.records[a];
44
+ });
45
+ var items = keys.map(function(x) {
46
+ return {key: x, parts: x.split('/'), time: data.records[x]};
47
+ });
48
+ var maxLength = items.reduce(function(a, b) {
49
+ return Math.max(a, b.parts.length);
50
+ }, 0);
51
+
52
+ var cols = createRow(table, 'th', ['record', 'seconds']);
53
+ cols[0].colSpan = maxLength;
54
+
55
+ function arraysEqual(a, b) {
56
+ return !(a < b || b < a);
57
+ }
58
+
59
+ var addLevel = function(level, parent, hide) {
60
+ var matching = items.filter(function(x) {
61
+ return x.parts[level] && !x.parts[level + 1] && arraysEqual(x.parts.slice(0, level), parent);
62
+ });
63
+ var sorted = matching.sort(function(a, b) {
64
+ return b.time - a.time;
65
+ });
66
+ var othersTime = 0;
67
+ var othersList = [];
68
+ var othersRows = [];
69
+ var childrenRows = [];
70
+ sorted.forEach(function(x) {
71
+ var visible = x.time >= cutoff && !hide;
72
+
73
+ var cells = [];
74
+ for (var i = 0; i < maxLength; i++) {
75
+ cells.push(x.parts[i]);
76
+ }
77
+ cells.push(x.time.toFixed(3));
78
+ var cols = createRow(table, 'td', cells);
79
+ for (i = 0; i < level; i++) {
80
+ cols[i].className = 'muted';
81
+ }
82
+
83
+ var tr = cols[0].parentNode;
84
+ if (!visible) {
85
+ tr.classList.add("hidden");
86
+ }
87
+
88
+ if (x.time >= cutoff) {
89
+ childrenRows.push(tr);
90
+ } else {
91
+ othersTime += x.time;
92
+ othersList.push(x.parts[level]);
93
+ othersRows.push(tr);
94
+ }
95
+
96
+ var children = addLevel(level + 1, parent.concat([x.parts[level]]), true);
97
+ if (children.length > 0) {
98
+ var cell = cols[level];
99
+ var onclick = function() {
100
+ cell.classList.remove("link");
101
+ cell.removeEventListener("click", onclick);
102
+ children.forEach(function(x) {
103
+ x.classList.remove("hidden");
104
+ });
105
+ };
106
+ cell.classList.add("link");
107
+ cell.addEventListener("click", onclick);
108
+ }
109
+ });
110
+
111
+ if (othersTime > 0) {
112
+ var cells = [];
113
+ for (var i = 0; i < maxLength; i++) {
114
+ cells.push(parent[i]);
115
+ }
116
+ cells.push(othersTime.toFixed(3));
117
+ cells[level] = 'others';
118
+ var cols = createRow(table, 'td', cells);
119
+ for (i = 0; i < level; i++) {
120
+ cols[i].className = 'muted';
121
+ }
122
+
123
+ var cell = cols[level];
124
+ var tr = cell.parentNode;
125
+ var onclick = function() {
126
+ tr.classList.add("hidden");
127
+ cell.classList.remove("link");
128
+ cell.removeEventListener("click", onclick);
129
+ othersRows.forEach(function(x) {
130
+ x.classList.remove("hidden");
131
+ });
132
+ };
133
+
134
+ cell.title = othersList.join(", ");
135
+ cell.classList.add("link");
136
+ cell.addEventListener("click", onclick);
137
+
138
+ if (hide) {
139
+ tr.classList.add("hidden");
140
+ }
141
+
142
+ childrenRows.push(tr);
143
+ }
144
+
145
+ return childrenRows;
146
+ };
147
+
148
+ addLevel(0, []);
149
+
150
+ popup(table);
151
+ });
152
+ }
153
+
javascript/progressbar.js ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // code related to showing and updating progressbar shown as the image is being made
2
+
3
+ function rememberGallerySelection() {
4
+
5
+ }
6
+
7
+ function getGallerySelectedIndex() {
8
+
9
+ }
10
+
11
+ function request(url, data, handler, errorHandler) {
12
+ var xhr = new XMLHttpRequest();
13
+ xhr.open("POST", url, true);
14
+ xhr.setRequestHeader("Content-Type", "application/json");
15
+ xhr.onreadystatechange = function() {
16
+ if (xhr.readyState === 4) {
17
+ if (xhr.status === 200) {
18
+ try {
19
+ var js = JSON.parse(xhr.responseText);
20
+ handler(js);
21
+ } catch (error) {
22
+ console.error(error);
23
+ errorHandler();
24
+ }
25
+ } else {
26
+ errorHandler();
27
+ }
28
+ }
29
+ };
30
+ var js = JSON.stringify(data);
31
+ xhr.send(js);
32
+ }
33
+
34
+ function pad2(x) {
35
+ return x < 10 ? '0' + x : x;
36
+ }
37
+
38
+ function formatTime(secs) {
39
+ if (secs > 3600) {
40
+ return pad2(Math.floor(secs / 60 / 60)) + ":" + pad2(Math.floor(secs / 60) % 60) + ":" + pad2(Math.floor(secs) % 60);
41
+ } else if (secs > 60) {
42
+ return pad2(Math.floor(secs / 60)) + ":" + pad2(Math.floor(secs) % 60);
43
+ } else {
44
+ return Math.floor(secs) + "s";
45
+ }
46
+ }
47
+
48
+ function setTitle(progress) {
49
+ var title = 'Stable Diffusion';
50
+
51
+ if (opts.show_progress_in_title && progress) {
52
+ title = '[' + progress.trim() + '] ' + title;
53
+ }
54
+
55
+ if (document.title != title) {
56
+ document.title = title;
57
+ }
58
+ }
59
+
60
+
61
+ function randomId() {
62
+ return "task(" + Math.random().toString(36).slice(2, 7) + Math.random().toString(36).slice(2, 7) + Math.random().toString(36).slice(2, 7) + ")";
63
+ }
64
+
65
+ // starts sending progress requests to "/internal/progress" uri, creating progressbar above progressbarContainer element and
66
+ // preview inside gallery element. Cleans up all created stuff when the task is over and calls atEnd.
67
+ // calls onProgress every time there is a progress update
68
+ function requestProgress(id_task, progressbarContainer, gallery, atEnd, onProgress, inactivityTimeout = 40) {
69
+ var dateStart = new Date();
70
+ var wasEverActive = false;
71
+ var parentProgressbar = progressbarContainer.parentNode;
72
+
73
+ var divProgress = document.createElement('div');
74
+ divProgress.className = 'progressDiv';
75
+ divProgress.style.display = opts.show_progressbar ? "block" : "none";
76
+ var divInner = document.createElement('div');
77
+ divInner.className = 'progress';
78
+
79
+ divProgress.appendChild(divInner);
80
+ parentProgressbar.insertBefore(divProgress, progressbarContainer);
81
+
82
+ var livePreview = null;
83
+
84
+ var removeProgressBar = function() {
85
+ if (!divProgress) return;
86
+
87
+ setTitle("");
88
+ parentProgressbar.removeChild(divProgress);
89
+ if (gallery && livePreview) gallery.removeChild(livePreview);
90
+ atEnd();
91
+
92
+ divProgress = null;
93
+ };
94
+
95
+ var funProgress = function(id_task) {
96
+ request("./internal/progress", {id_task: id_task, live_preview: false}, function(res) {
97
+ if (res.completed) {
98
+ removeProgressBar();
99
+ return;
100
+ }
101
+
102
+ let progressText = "";
103
+
104
+ divInner.style.width = ((res.progress || 0) * 100.0) + '%';
105
+ divInner.style.background = res.progress ? "" : "transparent";
106
+
107
+ if (res.progress > 0) {
108
+ progressText = ((res.progress || 0) * 100.0).toFixed(0) + '%';
109
+ }
110
+
111
+ if (res.eta) {
112
+ progressText += " ETA: " + formatTime(res.eta);
113
+ }
114
+
115
+ setTitle(progressText);
116
+
117
+ if (res.textinfo && res.textinfo.indexOf("\n") == -1) {
118
+ progressText = res.textinfo + " " + progressText;
119
+ }
120
+
121
+ divInner.textContent = progressText;
122
+
123
+ var elapsedFromStart = (new Date() - dateStart) / 1000;
124
+
125
+ if (res.active) wasEverActive = true;
126
+
127
+ if (!res.active && wasEverActive) {
128
+ removeProgressBar();
129
+ return;
130
+ }
131
+
132
+ if (elapsedFromStart > inactivityTimeout && !res.queued && !res.active) {
133
+ removeProgressBar();
134
+ return;
135
+ }
136
+
137
+ if (onProgress) {
138
+ onProgress(res);
139
+ }
140
+
141
+ setTimeout(() => {
142
+ funProgress(id_task, res.id_live_preview);
143
+ }, opts.live_preview_refresh_period || 500);
144
+ }, function() {
145
+ removeProgressBar();
146
+ });
147
+ };
148
+
149
+ var funLivePreview = function(id_task, id_live_preview) {
150
+ request("./internal/progress", {id_task: id_task, id_live_preview: id_live_preview}, function(res) {
151
+ if (!divProgress) {
152
+ return;
153
+ }
154
+
155
+ if (res.live_preview && gallery) {
156
+ var img = new Image();
157
+ img.onload = function() {
158
+ if (!livePreview) {
159
+ livePreview = document.createElement('div');
160
+ livePreview.className = 'livePreview';
161
+ gallery.insertBefore(livePreview, gallery.firstElementChild);
162
+ }
163
+
164
+ livePreview.appendChild(img);
165
+ if (livePreview.childElementCount > 2) {
166
+ livePreview.removeChild(livePreview.firstElementChild);
167
+ }
168
+ };
169
+ img.src = res.live_preview;
170
+ }
171
+
172
+ setTimeout(() => {
173
+ funLivePreview(id_task, res.id_live_preview);
174
+ }, opts.live_preview_refresh_period || 500);
175
+ }, function() {
176
+ removeProgressBar();
177
+ });
178
+ };
179
+
180
+ funProgress(id_task, 0);
181
+
182
+ if (gallery) {
183
+ funLivePreview(id_task, 0);
184
+ }
185
+
186
+ }
javascript/resizeHandle.js ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ (function() {
2
+ const GRADIO_MIN_WIDTH = 320;
3
+ const GRID_TEMPLATE_COLUMNS = '1fr 16px 1fr';
4
+ const PAD = 16;
5
+ const DEBOUNCE_TIME = 100;
6
+
7
+ const R = {
8
+ tracking: false,
9
+ parent: null,
10
+ parentWidth: null,
11
+ leftCol: null,
12
+ leftColStartWidth: null,
13
+ screenX: null,
14
+ };
15
+
16
+ let resizeTimer;
17
+ let parents = [];
18
+
19
+ function setLeftColGridTemplate(el, width) {
20
+ el.style.gridTemplateColumns = `${width}px 16px 1fr`;
21
+ }
22
+
23
+ function displayResizeHandle(parent) {
24
+ if (window.innerWidth < GRADIO_MIN_WIDTH * 2 + PAD * 4) {
25
+ parent.style.display = 'flex';
26
+ if (R.handle != null) {
27
+ R.handle.style.opacity = '0';
28
+ }
29
+ return false;
30
+ } else {
31
+ parent.style.display = 'grid';
32
+ if (R.handle != null) {
33
+ R.handle.style.opacity = '100';
34
+ }
35
+ return true;
36
+ }
37
+ }
38
+
39
+ function afterResize(parent) {
40
+ if (displayResizeHandle(parent) && parent.style.gridTemplateColumns != GRID_TEMPLATE_COLUMNS) {
41
+ const oldParentWidth = R.parentWidth;
42
+ const newParentWidth = parent.offsetWidth;
43
+ const widthL = parseInt(parent.style.gridTemplateColumns.split(' ')[0]);
44
+
45
+ const ratio = newParentWidth / oldParentWidth;
46
+
47
+ const newWidthL = Math.max(Math.floor(ratio * widthL), GRADIO_MIN_WIDTH);
48
+ setLeftColGridTemplate(parent, newWidthL);
49
+
50
+ R.parentWidth = newParentWidth;
51
+ }
52
+ }
53
+
54
+ function setup(parent) {
55
+ const leftCol = parent.firstElementChild;
56
+ const rightCol = parent.lastElementChild;
57
+
58
+ parents.push(parent);
59
+
60
+ parent.style.display = 'grid';
61
+ parent.style.gap = '0';
62
+ parent.style.gridTemplateColumns = GRID_TEMPLATE_COLUMNS;
63
+
64
+ const resizeHandle = document.createElement('div');
65
+ resizeHandle.classList.add('resize-handle');
66
+ parent.insertBefore(resizeHandle, rightCol);
67
+
68
+ resizeHandle.addEventListener('mousedown', (evt) => {
69
+ if (evt.button !== 0) return;
70
+
71
+ evt.preventDefault();
72
+ evt.stopPropagation();
73
+
74
+ document.body.classList.add('resizing');
75
+
76
+ R.tracking = true;
77
+ R.parent = parent;
78
+ R.parentWidth = parent.offsetWidth;
79
+ R.handle = resizeHandle;
80
+ R.leftCol = leftCol;
81
+ R.leftColStartWidth = leftCol.offsetWidth;
82
+ R.screenX = evt.screenX;
83
+ });
84
+
85
+ resizeHandle.addEventListener('dblclick', (evt) => {
86
+ evt.preventDefault();
87
+ evt.stopPropagation();
88
+
89
+ parent.style.gridTemplateColumns = GRID_TEMPLATE_COLUMNS;
90
+ });
91
+
92
+ afterResize(parent);
93
+ }
94
+
95
+ window.addEventListener('mousemove', (evt) => {
96
+ if (evt.button !== 0) return;
97
+
98
+ if (R.tracking) {
99
+ evt.preventDefault();
100
+ evt.stopPropagation();
101
+
102
+ const delta = R.screenX - evt.screenX;
103
+ const leftColWidth = Math.max(Math.min(R.leftColStartWidth - delta, R.parent.offsetWidth - GRADIO_MIN_WIDTH - PAD), GRADIO_MIN_WIDTH);
104
+ setLeftColGridTemplate(R.parent, leftColWidth);
105
+ }
106
+ });
107
+
108
+ window.addEventListener('mouseup', (evt) => {
109
+ if (evt.button !== 0) return;
110
+
111
+ if (R.tracking) {
112
+ evt.preventDefault();
113
+ evt.stopPropagation();
114
+
115
+ R.tracking = false;
116
+
117
+ document.body.classList.remove('resizing');
118
+ }
119
+ });
120
+
121
+
122
+ window.addEventListener('resize', () => {
123
+ clearTimeout(resizeTimer);
124
+
125
+ resizeTimer = setTimeout(function() {
126
+ for (const parent of parents) {
127
+ afterResize(parent);
128
+ }
129
+ }, DEBOUNCE_TIME);
130
+ });
131
+
132
+ setupResizeHandle = setup;
133
+ })();
134
+
135
+ onUiLoaded(function() {
136
+ for (var elem of gradioApp().querySelectorAll('.resize-handle-row')) {
137
+ if (!elem.querySelector('.resize-handle')) {
138
+ setupResizeHandle(elem);
139
+ }
140
+ }
141
+ });
javascript/textualInversion.js ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+
4
+ function start_training_textual_inversion() {
5
+ gradioApp().querySelector('#ti_error').innerHTML = '';
6
+
7
+ var id = randomId();
8
+ requestProgress(id, gradioApp().getElementById('ti_output'), gradioApp().getElementById('ti_gallery'), function() {}, function(progress) {
9
+ gradioApp().getElementById('ti_progress').innerHTML = progress.textinfo;
10
+ });
11
+
12
+ var res = Array.from(arguments);
13
+
14
+ res[0] = id;
15
+
16
+ return res;
17
+ }
javascript/token-counters.js ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ let promptTokenCountDebounceTime = 800;
2
+ let promptTokenCountTimeouts = {};
3
+ var promptTokenCountUpdateFunctions = {};
4
+
5
+ function update_txt2img_tokens(...args) {
6
+ // Called from Gradio
7
+ update_token_counter("txt2img_token_button");
8
+ if (args.length == 2) {
9
+ return args[0];
10
+ }
11
+ return args;
12
+ }
13
+
14
+ function update_img2img_tokens(...args) {
15
+ // Called from Gradio
16
+ update_token_counter("img2img_token_button");
17
+ if (args.length == 2) {
18
+ return args[0];
19
+ }
20
+ return args;
21
+ }
22
+
23
+ function update_token_counter(button_id) {
24
+ if (opts.disable_token_counters) {
25
+ return;
26
+ }
27
+ if (promptTokenCountTimeouts[button_id]) {
28
+ clearTimeout(promptTokenCountTimeouts[button_id]);
29
+ }
30
+ promptTokenCountTimeouts[button_id] = setTimeout(
31
+ () => gradioApp().getElementById(button_id)?.click(),
32
+ promptTokenCountDebounceTime,
33
+ );
34
+ }
35
+
36
+
37
+ function recalculatePromptTokens(name) {
38
+ promptTokenCountUpdateFunctions[name]?.();
39
+ }
40
+
41
+ function recalculate_prompts_txt2img() {
42
+ // Called from Gradio
43
+ recalculatePromptTokens('txt2img_prompt');
44
+ recalculatePromptTokens('txt2img_neg_prompt');
45
+ return Array.from(arguments);
46
+ }
47
+
48
+ function recalculate_prompts_img2img() {
49
+ // Called from Gradio
50
+ recalculatePromptTokens('img2img_prompt');
51
+ recalculatePromptTokens('img2img_neg_prompt');
52
+ return Array.from(arguments);
53
+ }
54
+
55
+ function setupTokenCounting(id, id_counter, id_button) {
56
+ var prompt = gradioApp().getElementById(id);
57
+ var counter = gradioApp().getElementById(id_counter);
58
+ var textarea = gradioApp().querySelector(`#${id} > label > textarea`);
59
+
60
+ if (opts.disable_token_counters) {
61
+ counter.style.display = "none";
62
+ return;
63
+ }
64
+
65
+ if (counter.parentElement == prompt.parentElement) {
66
+ return;
67
+ }
68
+
69
+ prompt.parentElement.insertBefore(counter, prompt);
70
+ prompt.parentElement.style.position = "relative";
71
+
72
+ promptTokenCountUpdateFunctions[id] = function() {
73
+ update_token_counter(id_button);
74
+ };
75
+ textarea.addEventListener("input", promptTokenCountUpdateFunctions[id]);
76
+ }
77
+
78
+ function setupTokenCounters() {
79
+ setupTokenCounting('txt2img_prompt', 'txt2img_token_counter', 'txt2img_token_button');
80
+ setupTokenCounting('txt2img_neg_prompt', 'txt2img_negative_token_counter', 'txt2img_negative_token_button');
81
+ setupTokenCounting('img2img_prompt', 'img2img_token_counter', 'img2img_token_button');
82
+ setupTokenCounting('img2img_neg_prompt', 'img2img_negative_token_counter', 'img2img_negative_token_button');
83
+ }
javascript/ui.js ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // various functions for interaction with ui.py not large enough to warrant putting them in separate files
2
+
3
+ function set_theme(theme) {
4
+ var gradioURL = window.location.href;
5
+ if (!gradioURL.includes('?__theme=')) {
6
+ window.location.replace(gradioURL + '?__theme=' + theme);
7
+ }
8
+ }
9
+
10
+ function all_gallery_buttons() {
11
+ var allGalleryButtons = gradioApp().querySelectorAll('[style="display: block;"].tabitem div[id$=_gallery].gradio-gallery .thumbnails > .thumbnail-item.thumbnail-small');
12
+ var visibleGalleryButtons = [];
13
+ allGalleryButtons.forEach(function(elem) {
14
+ if (elem.parentElement.offsetParent) {
15
+ visibleGalleryButtons.push(elem);
16
+ }
17
+ });
18
+ return visibleGalleryButtons;
19
+ }
20
+
21
+ function selected_gallery_button() {
22
+ return all_gallery_buttons().find(elem => elem.classList.contains('selected')) ?? null;
23
+ }
24
+
25
+ function selected_gallery_index() {
26
+ return all_gallery_buttons().findIndex(elem => elem.classList.contains('selected'));
27
+ }
28
+
29
+ function extract_image_from_gallery(gallery) {
30
+ if (gallery.length == 0) {
31
+ return [null];
32
+ }
33
+ if (gallery.length == 1) {
34
+ return [gallery[0]];
35
+ }
36
+
37
+ var index = selected_gallery_index();
38
+
39
+ if (index < 0 || index >= gallery.length) {
40
+ // Use the first image in the gallery as the default
41
+ index = 0;
42
+ }
43
+
44
+ return [gallery[index]];
45
+ }
46
+
47
+ window.args_to_array = Array.from; // Compatibility with e.g. extensions that may expect this to be around
48
+
49
+ function switch_to_txt2img() {
50
+ gradioApp().querySelector('#tabs').querySelectorAll('button')[0].click();
51
+
52
+ return Array.from(arguments);
53
+ }
54
+
55
+ function switch_to_img2img_tab(no) {
56
+ gradioApp().querySelector('#tabs').querySelectorAll('button')[1].click();
57
+ gradioApp().getElementById('mode_img2img').querySelectorAll('button')[no].click();
58
+ }
59
+ function switch_to_img2img() {
60
+ switch_to_img2img_tab(0);
61
+ return Array.from(arguments);
62
+ }
63
+
64
+ function switch_to_sketch() {
65
+ switch_to_img2img_tab(1);
66
+ return Array.from(arguments);
67
+ }
68
+
69
+ function switch_to_inpaint() {
70
+ switch_to_img2img_tab(2);
71
+ return Array.from(arguments);
72
+ }
73
+
74
+ function switch_to_inpaint_sketch() {
75
+ switch_to_img2img_tab(3);
76
+ return Array.from(arguments);
77
+ }
78
+
79
+ function switch_to_extras() {
80
+ gradioApp().querySelector('#tabs').querySelectorAll('button')[2].click();
81
+
82
+ return Array.from(arguments);
83
+ }
84
+
85
+ function get_tab_index(tabId) {
86
+ let buttons = gradioApp().getElementById(tabId).querySelector('div').querySelectorAll('button');
87
+ for (let i = 0; i < buttons.length; i++) {
88
+ if (buttons[i].classList.contains('selected')) {
89
+ return i;
90
+ }
91
+ }
92
+ return 0;
93
+ }
94
+
95
+ function create_tab_index_args(tabId, args) {
96
+ var res = Array.from(args);
97
+ res[0] = get_tab_index(tabId);
98
+ return res;
99
+ }
100
+
101
+ function get_img2img_tab_index() {
102
+ let res = Array.from(arguments);
103
+ res.splice(-2);
104
+ res[0] = get_tab_index('mode_img2img');
105
+ return res;
106
+ }
107
+
108
+ function create_submit_args(args) {
109
+ var res = Array.from(args);
110
+
111
+ // As it is currently, txt2img and img2img send back the previous output args (txt2img_gallery, generation_info, html_info) whenever you generate a new image.
112
+ // This can lead to uploading a huge gallery of previously generated images, which leads to an unnecessary delay between submitting and beginning to generate.
113
+ // I don't know why gradio is sending outputs along with inputs, but we can prevent sending the image gallery here, which seems to be an issue for some.
114
+ // If gradio at some point stops sending outputs, this may break something
115
+ if (Array.isArray(res[res.length - 3])) {
116
+ res[res.length - 3] = null;
117
+ }
118
+
119
+ return res;
120
+ }
121
+
122
+ function showSubmitButtons(tabname, show) {
123
+ gradioApp().getElementById(tabname + '_interrupt').style.display = show ? "none" : "block";
124
+ gradioApp().getElementById(tabname + '_skip').style.display = show ? "none" : "block";
125
+ }
126
+
127
+ function showRestoreProgressButton(tabname, show) {
128
+ var button = gradioApp().getElementById(tabname + "_restore_progress");
129
+ if (!button) return;
130
+
131
+ button.style.display = show ? "flex" : "none";
132
+ }
133
+
134
+ function submit() {
135
+ showSubmitButtons('txt2img', false);
136
+
137
+ var id = randomId();
138
+ localSet("txt2img_task_id", id);
139
+
140
+ requestProgress(id, gradioApp().getElementById('txt2img_gallery_container'), gradioApp().getElementById('txt2img_gallery'), function() {
141
+ showSubmitButtons('txt2img', true);
142
+ localRemove("txt2img_task_id");
143
+ showRestoreProgressButton('txt2img', false);
144
+ });
145
+
146
+ var res = create_submit_args(arguments);
147
+
148
+ res[0] = id;
149
+
150
+ return res;
151
+ }
152
+
153
+ function submit_img2img() {
154
+ showSubmitButtons('img2img', false);
155
+
156
+ var id = randomId();
157
+ localSet("img2img_task_id", id);
158
+
159
+ requestProgress(id, gradioApp().getElementById('img2img_gallery_container'), gradioApp().getElementById('img2img_gallery'), function() {
160
+ showSubmitButtons('img2img', true);
161
+ localRemove("img2img_task_id");
162
+ showRestoreProgressButton('img2img', false);
163
+ });
164
+
165
+ var res = create_submit_args(arguments);
166
+
167
+ res[0] = id;
168
+ res[1] = get_tab_index('mode_img2img');
169
+
170
+ return res;
171
+ }
172
+
173
+ function restoreProgressTxt2img() {
174
+ showRestoreProgressButton("txt2img", false);
175
+ var id = localGet("txt2img_task_id");
176
+
177
+ if (id) {
178
+ requestProgress(id, gradioApp().getElementById('txt2img_gallery_container'), gradioApp().getElementById('txt2img_gallery'), function() {
179
+ showSubmitButtons('txt2img', true);
180
+ }, null, 0);
181
+ }
182
+
183
+ return id;
184
+ }
185
+
186
+ function restoreProgressImg2img() {
187
+ showRestoreProgressButton("img2img", false);
188
+
189
+ var id = localGet("img2img_task_id");
190
+
191
+ if (id) {
192
+ requestProgress(id, gradioApp().getElementById('img2img_gallery_container'), gradioApp().getElementById('img2img_gallery'), function() {
193
+ showSubmitButtons('img2img', true);
194
+ }, null, 0);
195
+ }
196
+
197
+ return id;
198
+ }
199
+
200
+
201
+ onUiLoaded(function() {
202
+ showRestoreProgressButton('txt2img', localGet("txt2img_task_id"));
203
+ showRestoreProgressButton('img2img', localGet("img2img_task_id"));
204
+ });
205
+
206
+
207
+ function modelmerger() {
208
+ var id = randomId();
209
+ requestProgress(id, gradioApp().getElementById('modelmerger_results_panel'), null, function() {});
210
+
211
+ var res = create_submit_args(arguments);
212
+ res[0] = id;
213
+ return res;
214
+ }
215
+
216
+
217
+ function ask_for_style_name(_, prompt_text, negative_prompt_text) {
218
+ var name_ = prompt('Style name:');
219
+ return [name_, prompt_text, negative_prompt_text];
220
+ }
221
+
222
+ function confirm_clear_prompt(prompt, negative_prompt) {
223
+ if (confirm("Delete prompt?")) {
224
+ prompt = "";
225
+ negative_prompt = "";
226
+ }
227
+
228
+ return [prompt, negative_prompt];
229
+ }
230
+
231
+
232
+ var opts = {};
233
+ onAfterUiUpdate(function() {
234
+ if (Object.keys(opts).length != 0) return;
235
+
236
+ var json_elem = gradioApp().getElementById('settings_json');
237
+ if (json_elem == null) return;
238
+
239
+ var textarea = json_elem.querySelector('textarea');
240
+ var jsdata = textarea.value;
241
+ opts = JSON.parse(jsdata);
242
+
243
+ executeCallbacks(optionsChangedCallbacks); /*global optionsChangedCallbacks*/
244
+
245
+ Object.defineProperty(textarea, 'value', {
246
+ set: function(newValue) {
247
+ var valueProp = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value');
248
+ var oldValue = valueProp.get.call(textarea);
249
+ valueProp.set.call(textarea, newValue);
250
+
251
+ if (oldValue != newValue) {
252
+ opts = JSON.parse(textarea.value);
253
+ }
254
+
255
+ executeCallbacks(optionsChangedCallbacks);
256
+ },
257
+ get: function() {
258
+ var valueProp = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value');
259
+ return valueProp.get.call(textarea);
260
+ }
261
+ });
262
+
263
+ json_elem.parentElement.style.display = "none";
264
+
265
+ setupTokenCounters();
266
+
267
+ var show_all_pages = gradioApp().getElementById('settings_show_all_pages');
268
+ var settings_tabs = gradioApp().querySelector('#settings div');
269
+ if (show_all_pages && settings_tabs) {
270
+ settings_tabs.appendChild(show_all_pages);
271
+ show_all_pages.onclick = function() {
272
+ gradioApp().querySelectorAll('#settings > div').forEach(function(elem) {
273
+ if (elem.id == "settings_tab_licenses") {
274
+ return;
275
+ }
276
+
277
+ elem.style.display = "block";
278
+ });
279
+ };
280
+ }
281
+ });
282
+
283
+ onOptionsChanged(function() {
284
+ var elem = gradioApp().getElementById('sd_checkpoint_hash');
285
+ var sd_checkpoint_hash = opts.sd_checkpoint_hash || "";
286
+ var shorthash = sd_checkpoint_hash.substring(0, 10);
287
+
288
+ if (elem && elem.textContent != shorthash) {
289
+ elem.textContent = shorthash;
290
+ elem.title = sd_checkpoint_hash;
291
+ elem.href = "https://google.com/search?q=" + sd_checkpoint_hash;
292
+ }
293
+ });
294
+
295
+ let txt2img_textarea, img2img_textarea = undefined;
296
+
297
+ function restart_reload() {
298
+ document.body.innerHTML = '<h1 style="font-family:monospace;margin-top:20%;color:lightgray;text-align:center;">Reloading...</h1>';
299
+
300
+ var requestPing = function() {
301
+ requestGet("./internal/ping", {}, function(data) {
302
+ location.reload();
303
+ }, function() {
304
+ setTimeout(requestPing, 500);
305
+ });
306
+ };
307
+
308
+ setTimeout(requestPing, 2000);
309
+
310
+ return [];
311
+ }
312
+
313
+ // Simulate an `input` DOM event for Gradio Textbox component. Needed after you edit its contents in javascript, otherwise your edits
314
+ // will only visible on web page and not sent to python.
315
+ function updateInput(target) {
316
+ let e = new Event("input", {bubbles: true});
317
+ Object.defineProperty(e, "target", {value: target});
318
+ target.dispatchEvent(e);
319
+ }
320
+
321
+
322
+ var desiredCheckpointName = null;
323
+ function selectCheckpoint(name) {
324
+ desiredCheckpointName = name;
325
+ gradioApp().getElementById('change_checkpoint').click();
326
+ }
327
+
328
+ function currentImg2imgSourceResolution(w, h, scaleBy) {
329
+ var img = gradioApp().querySelector('#mode_img2img > div[style="display: block;"] img');
330
+ return img ? [img.naturalWidth, img.naturalHeight, scaleBy] : [0, 0, scaleBy];
331
+ }
332
+
333
+ function updateImg2imgResizeToTextAfterChangingImage() {
334
+ // At the time this is called from gradio, the image has no yet been replaced.
335
+ // There may be a better solution, but this is simple and straightforward so I'm going with it.
336
+
337
+ setTimeout(function() {
338
+ gradioApp().getElementById('img2img_update_resize_to').click();
339
+ }, 500);
340
+
341
+ return [];
342
+
343
+ }
344
+
345
+
346
+
347
+ function setRandomSeed(elem_id) {
348
+ var input = gradioApp().querySelector("#" + elem_id + " input");
349
+ if (!input) return [];
350
+
351
+ input.value = "-1";
352
+ updateInput(input);
353
+ return [];
354
+ }
355
+
356
+ function switchWidthHeight(tabname) {
357
+ var width = gradioApp().querySelector("#" + tabname + "_width input[type=number]");
358
+ var height = gradioApp().querySelector("#" + tabname + "_height input[type=number]");
359
+ if (!width || !height) return [];
360
+
361
+ var tmp = width.value;
362
+ width.value = height.value;
363
+ height.value = tmp;
364
+
365
+ updateInput(width);
366
+ updateInput(height);
367
+ return [];
368
+ }
javascript/ui_settings_hints.js ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // various hints and extra info for the settings tab
2
+
3
+ var settingsHintsSetup = false;
4
+
5
+ onOptionsChanged(function() {
6
+ if (settingsHintsSetup) return;
7
+ settingsHintsSetup = true;
8
+
9
+ gradioApp().querySelectorAll('#settings [id^=setting_]').forEach(function(div) {
10
+ var name = div.id.substr(8);
11
+ var commentBefore = opts._comments_before[name];
12
+ var commentAfter = opts._comments_after[name];
13
+
14
+ if (!commentBefore && !commentAfter) return;
15
+
16
+ var span = null;
17
+ if (div.classList.contains('gradio-checkbox')) span = div.querySelector('label span');
18
+ else if (div.classList.contains('gradio-checkboxgroup')) span = div.querySelector('span').firstChild;
19
+ else if (div.classList.contains('gradio-radio')) span = div.querySelector('span').firstChild;
20
+ else span = div.querySelector('label span').firstChild;
21
+
22
+ if (!span) return;
23
+
24
+ if (commentBefore) {
25
+ var comment = document.createElement('DIV');
26
+ comment.className = 'settings-comment';
27
+ comment.innerHTML = commentBefore;
28
+ span.parentElement.insertBefore(document.createTextNode('\xa0'), span);
29
+ span.parentElement.insertBefore(comment, span);
30
+ span.parentElement.insertBefore(document.createTextNode('\xa0'), span);
31
+ }
32
+ if (commentAfter) {
33
+ comment = document.createElement('DIV');
34
+ comment.className = 'settings-comment';
35
+ comment.innerHTML = commentAfter;
36
+ span.parentElement.insertBefore(comment, span.nextSibling);
37
+ span.parentElement.insertBefore(document.createTextNode('\xa0'), span.nextSibling);
38
+ }
39
+ });
40
+ });
41
+
42
+ function settingsHintsShowQuicksettings() {
43
+ requestGet("./internal/quicksettings-hint", {}, function(data) {
44
+ var table = document.createElement('table');
45
+ table.className = 'popup-table';
46
+
47
+ data.forEach(function(obj) {
48
+ var tr = document.createElement('tr');
49
+ var td = document.createElement('td');
50
+ td.textContent = obj.name;
51
+ tr.appendChild(td);
52
+
53
+ td = document.createElement('td');
54
+ td.textContent = obj.label;
55
+ tr.appendChild(td);
56
+
57
+ table.appendChild(tr);
58
+ });
59
+
60
+ popup(table);
61
+ });
62
+ }