ui.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. // various functions for interaction with ui.py not large enough to warrant putting them in separate files
  2. function set_theme(theme) {
  3. var gradioURL = window.location.href;
  4. if (!gradioURL.includes('?__theme=')) {
  5. window.location.replace(gradioURL + '?__theme=' + theme);
  6. }
  7. }
  8. function all_gallery_buttons() {
  9. var allGalleryButtons = gradioApp().querySelectorAll('[style="display: block;"].tabitem div[id$=_gallery].gradio-gallery .thumbnails > .thumbnail-item.thumbnail-small');
  10. var visibleGalleryButtons = [];
  11. allGalleryButtons.forEach(function(elem) {
  12. if (elem.parentElement.offsetParent) {
  13. visibleGalleryButtons.push(elem);
  14. }
  15. });
  16. return visibleGalleryButtons;
  17. }
  18. function selected_gallery_button() {
  19. return all_gallery_buttons().find(elem => elem.classList.contains('selected')) ?? null;
  20. }
  21. function selected_gallery_index() {
  22. return all_gallery_buttons().findIndex(elem => elem.classList.contains('selected'));
  23. }
  24. function extract_image_from_gallery(gallery) {
  25. if (gallery.length == 0) {
  26. return [null];
  27. }
  28. if (gallery.length == 1) {
  29. return [gallery[0]];
  30. }
  31. var index = selected_gallery_index();
  32. if (index < 0 || index >= gallery.length) {
  33. // Use the first image in the gallery as the default
  34. index = 0;
  35. }
  36. return [gallery[index]];
  37. }
  38. window.args_to_array = Array.from; // Compatibility with e.g. extensions that may expect this to be around
  39. function switch_to_txt2img() {
  40. gradioApp().querySelector('#tabs').querySelectorAll('button')[0].click();
  41. return Array.from(arguments);
  42. }
  43. function switch_to_img2img_tab(no) {
  44. gradioApp().querySelector('#tabs').querySelectorAll('button')[1].click();
  45. gradioApp().getElementById('mode_img2img').querySelectorAll('button')[no].click();
  46. }
  47. function switch_to_img2img() {
  48. switch_to_img2img_tab(0);
  49. return Array.from(arguments);
  50. }
  51. function switch_to_sketch() {
  52. switch_to_img2img_tab(1);
  53. return Array.from(arguments);
  54. }
  55. function switch_to_inpaint() {
  56. switch_to_img2img_tab(2);
  57. return Array.from(arguments);
  58. }
  59. function switch_to_inpaint_sketch() {
  60. switch_to_img2img_tab(3);
  61. return Array.from(arguments);
  62. }
  63. function switch_to_extras() {
  64. gradioApp().querySelector('#tabs').querySelectorAll('button')[2].click();
  65. return Array.from(arguments);
  66. }
  67. function get_tab_index(tabId) {
  68. let buttons = gradioApp().getElementById(tabId).querySelector('div').querySelectorAll('button');
  69. for (let i = 0; i < buttons.length; i++) {
  70. if (buttons[i].classList.contains('selected')) {
  71. return i;
  72. }
  73. }
  74. return 0;
  75. }
  76. function create_tab_index_args(tabId, args) {
  77. var res = Array.from(args);
  78. res[0] = get_tab_index(tabId);
  79. return res;
  80. }
  81. function get_img2img_tab_index() {
  82. let res = Array.from(arguments);
  83. res.splice(-2);
  84. res[0] = get_tab_index('mode_img2img');
  85. return res;
  86. }
  87. function create_submit_args(args) {
  88. var res = Array.from(args);
  89. // 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.
  90. // This can lead to uploading a huge gallery of previously generated images, which leads to an unnecessary delay between submitting and beginning to generate.
  91. // 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.
  92. // If gradio at some point stops sending outputs, this may break something
  93. if (Array.isArray(res[res.length - 3])) {
  94. res[res.length - 3] = null;
  95. }
  96. return res;
  97. }
  98. function setSubmitButtonsVisibility(tabname, showInterrupt, showSkip, showInterrupting) {
  99. gradioApp().getElementById(tabname + '_interrupt').style.display = showInterrupt ? "block" : "none";
  100. gradioApp().getElementById(tabname + '_skip').style.display = showSkip ? "block" : "none";
  101. gradioApp().getElementById(tabname + '_interrupting').style.display = showInterrupting ? "block" : "none";
  102. }
  103. function showSubmitButtons(tabname, show) {
  104. setSubmitButtonsVisibility(tabname, ! show, !show, false);
  105. }
  106. function showSubmitInterruptingPlaceholder(tabname) {
  107. setSubmitButtonsVisibility(tabname, false, true, true);
  108. }
  109. function showRestoreProgressButton(tabname, show) {
  110. var button = gradioApp().getElementById(tabname + "_restore_progress");
  111. if (!button) return;
  112. button.style.display = show ? "flex" : "none";
  113. }
  114. function submit() {
  115. showSubmitButtons('txt2img', false);
  116. var id = randomId();
  117. localSet("txt2img_task_id", id);
  118. requestProgress(id, gradioApp().getElementById('txt2img_gallery_container'), gradioApp().getElementById('txt2img_gallery'), function() {
  119. showSubmitButtons('txt2img', true);
  120. localRemove("txt2img_task_id");
  121. showRestoreProgressButton('txt2img', false);
  122. });
  123. var res = create_submit_args(arguments);
  124. res[0] = id;
  125. return res;
  126. }
  127. function submit_txt2img_upscale() {
  128. var res = submit(...arguments);
  129. res[2] = selected_gallery_index();
  130. return res;
  131. }
  132. function submit_img2img() {
  133. showSubmitButtons('img2img', false);
  134. var id = randomId();
  135. localSet("img2img_task_id", id);
  136. requestProgress(id, gradioApp().getElementById('img2img_gallery_container'), gradioApp().getElementById('img2img_gallery'), function() {
  137. showSubmitButtons('img2img', true);
  138. localRemove("img2img_task_id");
  139. showRestoreProgressButton('img2img', false);
  140. });
  141. var res = create_submit_args(arguments);
  142. res[0] = id;
  143. res[1] = get_tab_index('mode_img2img');
  144. return res;
  145. }
  146. function submit_extras() {
  147. showSubmitButtons('extras', false);
  148. var id = randomId();
  149. requestProgress(id, gradioApp().getElementById('extras_gallery_container'), gradioApp().getElementById('extras_gallery'), function() {
  150. showSubmitButtons('extras', true);
  151. });
  152. var res = create_submit_args(arguments);
  153. res[0] = id;
  154. console.log(res);
  155. return res;
  156. }
  157. function restoreProgressTxt2img() {
  158. showRestoreProgressButton("txt2img", false);
  159. var id = localGet("txt2img_task_id");
  160. if (id) {
  161. requestProgress(id, gradioApp().getElementById('txt2img_gallery_container'), gradioApp().getElementById('txt2img_gallery'), function() {
  162. showSubmitButtons('txt2img', true);
  163. }, null, 0);
  164. }
  165. return id;
  166. }
  167. function restoreProgressImg2img() {
  168. showRestoreProgressButton("img2img", false);
  169. var id = localGet("img2img_task_id");
  170. if (id) {
  171. requestProgress(id, gradioApp().getElementById('img2img_gallery_container'), gradioApp().getElementById('img2img_gallery'), function() {
  172. showSubmitButtons('img2img', true);
  173. }, null, 0);
  174. }
  175. return id;
  176. }
  177. /**
  178. * Configure the width and height elements on `tabname` to accept
  179. * pasting of resolutions in the form of "width x height".
  180. */
  181. function setupResolutionPasting(tabname) {
  182. var width = gradioApp().querySelector(`#${tabname}_width input[type=number]`);
  183. var height = gradioApp().querySelector(`#${tabname}_height input[type=number]`);
  184. for (const el of [width, height]) {
  185. el.addEventListener('paste', function(event) {
  186. var pasteData = event.clipboardData.getData('text/plain');
  187. var parsed = pasteData.match(/^\s*(\d+)\D+(\d+)\s*$/);
  188. if (parsed) {
  189. width.value = parsed[1];
  190. height.value = parsed[2];
  191. updateInput(width);
  192. updateInput(height);
  193. event.preventDefault();
  194. }
  195. });
  196. }
  197. }
  198. onUiLoaded(function() {
  199. showRestoreProgressButton('txt2img', localGet("txt2img_task_id"));
  200. showRestoreProgressButton('img2img', localGet("img2img_task_id"));
  201. setupResolutionPasting('txt2img');
  202. setupResolutionPasting('img2img');
  203. });
  204. function modelmerger() {
  205. var id = randomId();
  206. requestProgress(id, gradioApp().getElementById('modelmerger_results_panel'), null, function() {});
  207. var res = create_submit_args(arguments);
  208. res[0] = id;
  209. return res;
  210. }
  211. function ask_for_style_name(_, prompt_text, negative_prompt_text) {
  212. var name_ = prompt('Style name:');
  213. return [name_, prompt_text, negative_prompt_text];
  214. }
  215. function confirm_clear_prompt(prompt, negative_prompt) {
  216. if (confirm("Delete prompt?")) {
  217. prompt = "";
  218. negative_prompt = "";
  219. }
  220. return [prompt, negative_prompt];
  221. }
  222. var opts = {};
  223. onAfterUiUpdate(function() {
  224. if (Object.keys(opts).length != 0) return;
  225. var json_elem = gradioApp().getElementById('settings_json');
  226. if (json_elem == null) return;
  227. var textarea = json_elem.querySelector('textarea');
  228. var jsdata = textarea.value;
  229. opts = JSON.parse(jsdata);
  230. executeCallbacks(optionsChangedCallbacks); /*global optionsChangedCallbacks*/
  231. Object.defineProperty(textarea, 'value', {
  232. set: function(newValue) {
  233. var valueProp = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value');
  234. var oldValue = valueProp.get.call(textarea);
  235. valueProp.set.call(textarea, newValue);
  236. if (oldValue != newValue) {
  237. opts = JSON.parse(textarea.value);
  238. }
  239. executeCallbacks(optionsChangedCallbacks);
  240. },
  241. get: function() {
  242. var valueProp = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value');
  243. return valueProp.get.call(textarea);
  244. }
  245. });
  246. json_elem.parentElement.style.display = "none";
  247. setupTokenCounters();
  248. });
  249. onOptionsChanged(function() {
  250. var elem = gradioApp().getElementById('sd_checkpoint_hash');
  251. var sd_checkpoint_hash = opts.sd_checkpoint_hash || "";
  252. var shorthash = sd_checkpoint_hash.substring(0, 10);
  253. if (elem && elem.textContent != shorthash) {
  254. elem.textContent = shorthash;
  255. elem.title = sd_checkpoint_hash;
  256. elem.href = "https://google.com/search?q=" + sd_checkpoint_hash;
  257. }
  258. });
  259. let txt2img_textarea, img2img_textarea = undefined;
  260. function restart_reload() {
  261. document.body.innerHTML = '<h1 style="font-family:monospace;margin-top:20%;color:lightgray;text-align:center;">Reloading...</h1>';
  262. var requestPing = function() {
  263. requestGet("./internal/ping", {}, function(data) {
  264. location.reload();
  265. }, function() {
  266. setTimeout(requestPing, 500);
  267. });
  268. };
  269. setTimeout(requestPing, 2000);
  270. return [];
  271. }
  272. // Simulate an `input` DOM event for Gradio Textbox component. Needed after you edit its contents in javascript, otherwise your edits
  273. // will only visible on web page and not sent to python.
  274. function updateInput(target) {
  275. let e = new Event("input", {bubbles: true});
  276. Object.defineProperty(e, "target", {value: target});
  277. target.dispatchEvent(e);
  278. }
  279. var desiredCheckpointName = null;
  280. function selectCheckpoint(name) {
  281. desiredCheckpointName = name;
  282. gradioApp().getElementById('change_checkpoint').click();
  283. }
  284. function currentImg2imgSourceResolution(w, h, scaleBy) {
  285. var img = gradioApp().querySelector('#mode_img2img > div[style="display: block;"] img');
  286. return img ? [img.naturalWidth, img.naturalHeight, scaleBy] : [0, 0, scaleBy];
  287. }
  288. function updateImg2imgResizeToTextAfterChangingImage() {
  289. // At the time this is called from gradio, the image has no yet been replaced.
  290. // There may be a better solution, but this is simple and straightforward so I'm going with it.
  291. setTimeout(function() {
  292. gradioApp().getElementById('img2img_update_resize_to').click();
  293. }, 500);
  294. return [];
  295. }
  296. function setRandomSeed(elem_id) {
  297. var input = gradioApp().querySelector("#" + elem_id + " input");
  298. if (!input) return [];
  299. input.value = "-1";
  300. updateInput(input);
  301. return [];
  302. }
  303. function switchWidthHeight(tabname) {
  304. var width = gradioApp().querySelector("#" + tabname + "_width input[type=number]");
  305. var height = gradioApp().querySelector("#" + tabname + "_height input[type=number]");
  306. if (!width || !height) return [];
  307. var tmp = width.value;
  308. width.value = height.value;
  309. height.value = tmp;
  310. updateInput(width);
  311. updateInput(height);
  312. return [];
  313. }
  314. var onEditTimers = {};
  315. // calls func after afterMs milliseconds has passed since the input elem has beed enited by user
  316. function onEdit(editId, elem, afterMs, func) {
  317. var edited = function() {
  318. var existingTimer = onEditTimers[editId];
  319. if (existingTimer) clearTimeout(existingTimer);
  320. onEditTimers[editId] = setTimeout(func, afterMs);
  321. };
  322. elem.addEventListener("input", edited);
  323. return edited;
  324. }