ui.js 12.0 KB
Newer Older
I
Ikko Ashimine 已提交
1
// various functions for interaction with ui.py not large enough to warrant putting them in separate files
2

3 4
function set_theme(theme) {
    var gradioURL = window.location.href;
5
    if (!gradioURL.includes('?__theme=')) {
6
        window.location.replace(gradioURL + '?__theme=' + theme);
M
Michoko 已提交
7 8 9
    }
}

S
space-nuko 已提交
10 11 12 13 14 15 16
function all_gallery_buttons() {
    var allGalleryButtons = gradioApp().querySelectorAll('[style="display: block;"].tabitem div[id$=_gallery].gradio-gallery .thumbnails > .thumbnail-item.thumbnail-small');
    var visibleGalleryButtons = [];
    allGalleryButtons.forEach(function(elem) {
        if (elem.parentElement.offsetParent) {
            visibleGalleryButtons.push(elem);
        }
17
    });
S
space-nuko 已提交
18 19 20 21
    return visibleGalleryButtons;
}

function selected_gallery_button() {
B
bluelovers 已提交
22
    return all_gallery_buttons().find(elem => elem.classList.contains('selected')) ?? null;
S
space-nuko 已提交
23 24
}

25
function selected_gallery_index() {
B
bluelovers 已提交
26
    return all_gallery_buttons().findIndex(elem => elem.classList.contains('selected'));
27 28
}

29 30
function extract_image_from_gallery(gallery) {
    if (gallery.length == 0) {
S
space-nuko 已提交
31 32
        return [null];
    }
33
    if (gallery.length == 1) {
S
space-nuko 已提交
34
        return [gallery[0]];
35 36
    }

37
    var index = selected_gallery_index();
38

39
    if (index < 0 || index >= gallery.length) {
S
space-nuko 已提交
40 41
        // Use the first image in the gallery as the default
        index = 0;
42 43
    }

44
    return [gallery[index]];
S
Seki 已提交
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 58
    gradioApp().getElementById('mode_img2img').querySelectorAll('button')[no].click();
}
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 87 88 89
    let buttons = gradioApp().getElementById(tabId).querySelector('div').querySelectorAll('button');
    for (let i = 0; i < buttons.length; i++) {
        if (buttons[i].classList.contains('selected')) {
            return i;
90
        }
91 92
    }
    return 0;
93 94
}

95
function create_tab_index_args(tabId, args) {
96
    var res = Array.from(args);
97 98
    res[0] = get_tab_index(tabId);
    return res;
99 100
}

101
function get_img2img_tab_index() {
102
    let res = Array.from(arguments);
103 104 105
    res.splice(-2);
    res[0] = get_tab_index('mode_img2img');
    return res;
106 107
}

108
function create_submit_args(args) {
109
    var res = Array.from(args);
110 111 112

    // 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.
    // This can lead to uploading a huge gallery of previously generated images, which leads to an unnecessary delay between submitting and beginning to generate.
J
Jim Hays 已提交
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 116
    if (Array.isArray(res[res.length - 3])) {
        res[res.length - 3] = null;
117 118
    }

119
    return res;
120
}
121

122 123 124
function showSubmitButtons(tabname, show) {
    gradioApp().getElementById(tabname + '_interrupt').style.display = show ? "none" : "block";
    gradioApp().getElementById(tabname + '_skip').style.display = show ? "none" : "block";
125 126
}

127 128 129
function showRestoreProgressButton(tabname, show) {
    var button = gradioApp().getElementById(tabname + "_restore_progress");
    if (!button) return;
130

131
    button.style.display = show ? "flex" : "none";
132 133
}

134 135
function submit() {
    showSubmitButtons('txt2img', false);
136

137
    var id = randomId();
138
    localSet("txt2img_task_id", id);
139

140 141
    requestProgress(id, gradioApp().getElementById('txt2img_gallery_container'), gradioApp().getElementById('txt2img_gallery'), function() {
        showSubmitButtons('txt2img', true);
142
        localRemove("txt2img_task_id");
143 144
        showRestoreProgressButton('txt2img', false);
    });
145

146
    var res = create_submit_args(arguments);
147

148
    res[0] = id;
149

150
    return res;
151 152
}

153 154
function submit_img2img() {
    showSubmitButtons('img2img', false);
155

156
    var id = randomId();
157
    localSet("img2img_task_id", id);
158

159 160
    requestProgress(id, gradioApp().getElementById('img2img_gallery_container'), gradioApp().getElementById('img2img_gallery'), function() {
        showSubmitButtons('img2img', true);
161
        localRemove("img2img_task_id");
162 163
        showRestoreProgressButton('img2img', false);
    });
164

165
    var res = create_submit_args(arguments);
166

167 168
    res[0] = id;
    res[1] = get_tab_index('mode_img2img');
169

170
    return res;
171 172
}

173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
function submit_extras() {
    showSubmitButtons('extras', false);

    var id = randomId();

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

    var res = create_submit_args(arguments);

    res[0] = id;

    console.log(res);
    return res;
}

190 191
function restoreProgressTxt2img() {
    showRestoreProgressButton("txt2img", false);
192
    var id = localGet("txt2img_task_id");
193

194 195 196 197
    if (id) {
        requestProgress(id, gradioApp().getElementById('txt2img_gallery_container'), gradioApp().getElementById('txt2img_gallery'), function() {
            showSubmitButtons('txt2img', true);
        }, null, 0);
198 199
    }

200
    return id;
201
}
202

203 204
function restoreProgressImg2img() {
    showRestoreProgressButton("img2img", false);
205

206
    var id = localGet("img2img_task_id");
207

208 209 210 211
    if (id) {
        requestProgress(id, gradioApp().getElementById('img2img_gallery_container'), gradioApp().getElementById('img2img_gallery'), function() {
            showSubmitButtons('img2img', true);
        }, null, 0);
212 213
    }

214
    return id;
215 216 217
}


218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
/**
 * Configure the width and height elements on `tabname` to accept
 * pasting of resolutions in the form of "width x height".
 */
function setupResolutionPasting(tabname) {
    var width = gradioApp().querySelector(`#${tabname}_width input[type=number]`);
    var height = gradioApp().querySelector(`#${tabname}_height input[type=number]`);
    for (const el of [width, height]) {
        el.addEventListener('paste', function(event) {
            var pasteData = event.clipboardData.getData('text/plain');
            var parsed = pasteData.match(/^\s*(\d+)\D+(\d+)\s*$/);
            if (parsed) {
                width.value = parsed[1];
                height.value = parsed[2];
                updateInput(width);
                updateInput(height);
                event.preventDefault();
            }
        });
    }
}

240
onUiLoaded(function() {
241 242
    showRestoreProgressButton('txt2img', localGet("txt2img_task_id"));
    showRestoreProgressButton('img2img', localGet("img2img_task_id"));
243 244
    setupResolutionPasting('txt2img');
    setupResolutionPasting('img2img');
245 246 247
});


248 249 250
function modelmerger() {
    var id = randomId();
    requestProgress(id, gradioApp().getElementById('modelmerger_results_panel'), null, function() {});
A
AUTOMATIC 已提交
251

252 253 254
    var res = create_submit_args(arguments);
    res[0] = id;
    return res;
A
AUTOMATIC 已提交
255 256
}

257

258
function ask_for_style_name(_, prompt_text, negative_prompt_text) {
259 260
    var name_ = prompt('Style name:');
    return [name_, prompt_text, negative_prompt_text];
A
AUTOMATIC 已提交
261
}
262

263
function confirm_clear_prompt(prompt, negative_prompt) {
264 265 266
    if (confirm("Delete prompt?")) {
        prompt = "";
        negative_prompt = "";
267
    }
P
papuSpartan 已提交
268

269
    return [prompt, negative_prompt];
270 271
}

272

273
var opts = {};
274
onAfterUiUpdate(function() {
275
    if (Object.keys(opts).length != 0) return;
276

277 278
    var json_elem = gradioApp().getElementById('settings_json');
    if (json_elem == null) return;
279

280 281 282
    var textarea = json_elem.querySelector('textarea');
    var jsdata = textarea.value;
    opts = JSON.parse(jsdata);
283

A
AUTOMATIC 已提交
284
    executeCallbacks(optionsChangedCallbacks); /*global optionsChangedCallbacks*/
285 286 287 288 289 290 291 292

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

            if (oldValue != newValue) {
293
                opts = JSON.parse(textarea.value);
294
            }
295 296

            executeCallbacks(optionsChangedCallbacks);
297 298 299 300 301 302 303
        },
        get: function() {
            var valueProp = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value');
            return valueProp.get.call(textarea);
        }
    });

304
    json_elem.parentElement.style.display = "none";
305

306
    setupTokenCounters();
307
});
308

309 310 311 312
onOptionsChanged(function() {
    var elem = gradioApp().getElementById('sd_checkpoint_hash');
    var sd_checkpoint_hash = opts.sd_checkpoint_hash || "";
    var shorthash = sd_checkpoint_hash.substring(0, 10);
313

314 315 316 317 318 319
    if (elem && elem.textContent != shorthash) {
        elem.textContent = shorthash;
        elem.title = sd_checkpoint_hash;
        elem.href = "https://google.com/search?q=" + sd_checkpoint_hash;
    }
});
320

321
let txt2img_textarea, img2img_textarea = undefined;
D
DepFA 已提交
322

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

326 327
    var requestPing = function() {
        requestGet("./internal/ping", {}, function(data) {
328
            location.reload();
329
        }, function() {
330
            setTimeout(requestPing, 500);
331 332
        });
    };
333 334

    setTimeout(requestPing, 2000);
335

336
    return [];
D
DepFA 已提交
337
}
338 339 340

// Simulate an `input` DOM event for Gradio Textbox component. Needed after you edit its contents in javascript, otherwise your edits
// will only visible on web page and not sent to python.
341
function updateInput(target) {
A
AUTOMATIC 已提交
342
    let e = new Event("input", {bubbles: true});
343 344
    Object.defineProperty(e, "target", {value: target});
    target.dispatchEvent(e);
345
}
346 347 348


var desiredCheckpointName = null;
349
function selectCheckpoint(name) {
350
    desiredCheckpointName = name;
351
    gradioApp().getElementById('change_checkpoint').click();
352
}
353

A
AUTOMATIC 已提交
354
function currentImg2imgSourceResolution(w, h, scaleBy) {
355 356
    var img = gradioApp().querySelector('#mode_img2img > div[style="display: block;"] img');
    return img ? [img.naturalWidth, img.naturalHeight, scaleBy] : [0, 0, scaleBy];
357
}
358

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

    setTimeout(function() {
364
        gradioApp().getElementById('img2img_update_resize_to').click();
365 366
    }, 500);

A
AUTOMATIC 已提交
367
    return [];
368 369 370

}

371 372


373 374 375 376 377 378
function setRandomSeed(elem_id) {
    var input = gradioApp().querySelector("#" + elem_id + " input");
    if (!input) return [];

    input.value = "-1";
    updateInput(input);
379 380 381
    return [];
}

382 383 384 385 386 387
function switchWidthHeight(tabname) {
    var width = gradioApp().querySelector("#" + tabname + "_width input[type=number]");
    var height = gradioApp().querySelector("#" + tabname + "_height input[type=number]");
    if (!width || !height) return [];

    var tmp = width.value;
388 389
    width.value = height.value;
    height.value = tmp;
390 391 392

    updateInput(width);
    updateInput(height);
393 394
    return [];
}
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411


var onEditTimers = {};

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

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

    elem.addEventListener("input", edited);

    return edited;
}