stable-diffusion-webui

Форк
0
426 строк · 12.4 Кб
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 setSubmitButtonsVisibility(tabname, showInterrupt, showSkip, showInterrupting) {
123
    gradioApp().getElementById(tabname + '_interrupt').style.display = showInterrupt ? "block" : "none";
124
    gradioApp().getElementById(tabname + '_skip').style.display = showSkip ? "block" : "none";
125
    gradioApp().getElementById(tabname + '_interrupting').style.display = showInterrupting ? "block" : "none";
126
}
127

128
function showSubmitButtons(tabname, show) {
129
    setSubmitButtonsVisibility(tabname, !show, !show, false);
130
}
131

132
function showSubmitInterruptingPlaceholder(tabname) {
133
    setSubmitButtonsVisibility(tabname, false, true, true);
134
}
135

136
function showRestoreProgressButton(tabname, show) {
137
    var button = gradioApp().getElementById(tabname + "_restore_progress");
138
    if (!button) return;
139

140
    button.style.display = show ? "flex" : "none";
141
}
142

143
function submit() {
144
    showSubmitButtons('txt2img', false);
145

146
    var id = randomId();
147
    localSet("txt2img_task_id", id);
148

149
    requestProgress(id, gradioApp().getElementById('txt2img_gallery_container'), gradioApp().getElementById('txt2img_gallery'), function() {
150
        showSubmitButtons('txt2img', true);
151
        localRemove("txt2img_task_id");
152
        showRestoreProgressButton('txt2img', false);
153
    });
154

155
    var res = create_submit_args(arguments);
156

157
    res[0] = id;
158

159
    return res;
160
}
161

162
function submit_txt2img_upscale() {
163
    var res = submit(...arguments);
164

165
    res[2] = selected_gallery_index();
166

167
    return res;
168
}
169

170
function submit_img2img() {
171
    showSubmitButtons('img2img', false);
172

173
    var id = randomId();
174
    localSet("img2img_task_id", id);
175

176
    requestProgress(id, gradioApp().getElementById('img2img_gallery_container'), gradioApp().getElementById('img2img_gallery'), function() {
177
        showSubmitButtons('img2img', true);
178
        localRemove("img2img_task_id");
179
        showRestoreProgressButton('img2img', false);
180
    });
181

182
    var res = create_submit_args(arguments);
183

184
    res[0] = id;
185
    res[1] = get_tab_index('mode_img2img');
186

187
    return res;
188
}
189

190
function submit_extras() {
191
    showSubmitButtons('extras', false);
192

193
    var id = randomId();
194

195
    requestProgress(id, gradioApp().getElementById('extras_gallery_container'), gradioApp().getElementById('extras_gallery'), function() {
196
        showSubmitButtons('extras', true);
197
    });
198

199
    var res = create_submit_args(arguments);
200

201
    res[0] = id;
202

203
    console.log(res);
204
    return res;
205
}
206

207
function restoreProgressTxt2img() {
208
    showRestoreProgressButton("txt2img", false);
209
    var id = localGet("txt2img_task_id");
210

211
    if (id) {
212
        requestProgress(id, gradioApp().getElementById('txt2img_gallery_container'), gradioApp().getElementById('txt2img_gallery'), function() {
213
            showSubmitButtons('txt2img', true);
214
        }, null, 0);
215
    }
216

217
    return id;
218
}
219

220
function restoreProgressImg2img() {
221
    showRestoreProgressButton("img2img", false);
222

223
    var id = localGet("img2img_task_id");
224

225
    if (id) {
226
        requestProgress(id, gradioApp().getElementById('img2img_gallery_container'), gradioApp().getElementById('img2img_gallery'), function() {
227
            showSubmitButtons('img2img', true);
228
        }, null, 0);
229
    }
230

231
    return id;
232
}
233

234

235
/**
236
 * Configure the width and height elements on `tabname` to accept
237
 * pasting of resolutions in the form of "width x height".
238
 */
239
function setupResolutionPasting(tabname) {
240
    var width = gradioApp().querySelector(`#${tabname}_width input[type=number]`);
241
    var height = gradioApp().querySelector(`#${tabname}_height input[type=number]`);
242
    for (const el of [width, height]) {
243
        el.addEventListener('paste', function(event) {
244
            var pasteData = event.clipboardData.getData('text/plain');
245
            var parsed = pasteData.match(/^\s*(\d+)\D+(\d+)\s*$/);
246
            if (parsed) {
247
                width.value = parsed[1];
248
                height.value = parsed[2];
249
                updateInput(width);
250
                updateInput(height);
251
                event.preventDefault();
252
            }
253
        });
254
    }
255
}
256

257
onUiLoaded(function() {
258
    showRestoreProgressButton('txt2img', localGet("txt2img_task_id"));
259
    showRestoreProgressButton('img2img', localGet("img2img_task_id"));
260
    setupResolutionPasting('txt2img');
261
    setupResolutionPasting('img2img');
262
});
263

264

265
function modelmerger() {
266
    var id = randomId();
267
    requestProgress(id, gradioApp().getElementById('modelmerger_results_panel'), null, function() {});
268

269
    var res = create_submit_args(arguments);
270
    res[0] = id;
271
    return res;
272
}
273

274

275
function ask_for_style_name(_, prompt_text, negative_prompt_text) {
276
    var name_ = prompt('Style name:');
277
    return [name_, prompt_text, negative_prompt_text];
278
}
279

280
function confirm_clear_prompt(prompt, negative_prompt) {
281
    if (confirm("Delete prompt?")) {
282
        prompt = "";
283
        negative_prompt = "";
284
    }
285

286
    return [prompt, negative_prompt];
287
}
288

289

290
var opts = {};
291
onAfterUiUpdate(function() {
292
    if (Object.keys(opts).length != 0) return;
293

294
    var json_elem = gradioApp().getElementById('settings_json');
295
    if (json_elem == null) return;
296

297
    var textarea = json_elem.querySelector('textarea');
298
    var jsdata = textarea.value;
299
    opts = JSON.parse(jsdata);
300

301
    executeCallbacks(optionsChangedCallbacks); /*global optionsChangedCallbacks*/
302

303
    Object.defineProperty(textarea, 'value', {
304
        set: function(newValue) {
305
            var valueProp = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value');
306
            var oldValue = valueProp.get.call(textarea);
307
            valueProp.set.call(textarea, newValue);
308

309
            if (oldValue != newValue) {
310
                opts = JSON.parse(textarea.value);
311
            }
312

313
            executeCallbacks(optionsChangedCallbacks);
314
        },
315
        get: function() {
316
            var valueProp = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value');
317
            return valueProp.get.call(textarea);
318
        }
319
    });
320

321
    json_elem.parentElement.style.display = "none";
322
});
323

324
onOptionsChanged(function() {
325
    var elem = gradioApp().getElementById('sd_checkpoint_hash');
326
    var sd_checkpoint_hash = opts.sd_checkpoint_hash || "";
327
    var shorthash = sd_checkpoint_hash.substring(0, 10);
328

329
    if (elem && elem.textContent != shorthash) {
330
        elem.textContent = shorthash;
331
        elem.title = sd_checkpoint_hash;
332
        elem.href = "https://google.com/search?q=" + sd_checkpoint_hash;
333
    }
334
});
335

336
let txt2img_textarea, img2img_textarea = undefined;
337

338
function restart_reload() {
339
    document.body.innerHTML = '<h1 style="font-family:monospace;margin-top:20%;color:lightgray;text-align:center;">Reloading...</h1>';
340

341
    var requestPing = function() {
342
        requestGet("./internal/ping", {}, function(data) {
343
            location.reload();
344
        }, function() {
345
            setTimeout(requestPing, 500);
346
        });
347
    };
348

349
    setTimeout(requestPing, 2000);
350

351
    return [];
352
}
353

354
// Simulate an `input` DOM event for Gradio Textbox component. Needed after you edit its contents in javascript, otherwise your edits
355
// will only visible on web page and not sent to python.
356
function updateInput(target) {
357
    let e = new Event("input", {bubbles: true});
358
    Object.defineProperty(e, "target", {value: target});
359
    target.dispatchEvent(e);
360
}
361

362

363
var desiredCheckpointName = null;
364
function selectCheckpoint(name) {
365
    desiredCheckpointName = name;
366
    gradioApp().getElementById('change_checkpoint').click();
367
}
368

369
function currentImg2imgSourceResolution(w, h, scaleBy) {
370
    var img = gradioApp().querySelector('#mode_img2img > div[style="display: block;"] img');
371
    return img ? [img.naturalWidth, img.naturalHeight, scaleBy] : [0, 0, scaleBy];
372
}
373

374
function updateImg2imgResizeToTextAfterChangingImage() {
375
    // At the time this is called from gradio, the image has no yet been replaced.
376
    // There may be a better solution, but this is simple and straightforward so I'm going with it.
377

378
    setTimeout(function() {
379
        gradioApp().getElementById('img2img_update_resize_to').click();
380
    }, 500);
381

382
    return [];
383

384
}
385

386

387

388
function setRandomSeed(elem_id) {
389
    var input = gradioApp().querySelector("#" + elem_id + " input");
390
    if (!input) return [];
391

392
    input.value = "-1";
393
    updateInput(input);
394
    return [];
395
}
396

397
function switchWidthHeight(tabname) {
398
    var width = gradioApp().querySelector("#" + tabname + "_width input[type=number]");
399
    var height = gradioApp().querySelector("#" + tabname + "_height input[type=number]");
400
    if (!width || !height) return [];
401

402
    var tmp = width.value;
403
    width.value = height.value;
404
    height.value = tmp;
405

406
    updateInput(width);
407
    updateInput(height);
408
    return [];
409
}
410

411

412
var onEditTimers = {};
413

414
// calls func after afterMs milliseconds has passed since the input elem has beed enited by user
415
function onEdit(editId, elem, afterMs, func) {
416
    var edited = function() {
417
        var existingTimer = onEditTimers[editId];
418
        if (existingTimer) clearTimeout(existingTimer);
419

420
        onEditTimers[editId] = setTimeout(func, afterMs);
421
    };
422

423
    elem.addEventListener("input", edited);
424

425
    return edited;
426
}
427

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.