ui.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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 showSubmitButtons(tabname, show) {
  99. gradioApp().getElementById(tabname + '_interrupt').style.display = show ? "none" : "block";
  100. gradioApp().getElementById(tabname + '_skip').style.display = show ? "none" : "block";
  101. }
  102. function showRestoreProgressButton(tabname, show) {
  103. var button = gradioApp().getElementById(tabname + "_restore_progress");
  104. if (!button) return;
  105. button.style.display = show ? "flex" : "none";
  106. }
  107. function submit() {
  108. showSubmitButtons('txt2img', false);
  109. var id = randomId();
  110. localSet("txt2img_task_id", id);
  111. requestProgress(id, gradioApp().getElementById('txt2img_gallery_container'), gradioApp().getElementById('txt2img_gallery'), function() {
  112. showSubmitButtons('txt2img', true);
  113. localRemove("txt2img_task_id");
  114. showRestoreProgressButton('txt2img', false);
  115. });
  116. var res = create_submit_args(arguments);
  117. res[0] = id;
  118. return res;
  119. }
  120. function submit_txt2img_upscale() {
  121. var res = submit(...arguments);
  122. res[2] = selected_gallery_index();
  123. return res;
  124. }
  125. function submit_img2img() {
  126. showSubmitButtons('img2img', false);
  127. var id = randomId();
  128. localSet("img2img_task_id", id);
  129. requestProgress(id, gradioApp().getElementById('img2img_gallery_container'), gradioApp().getElementById('img2img_gallery'), function() {
  130. showSubmitButtons('img2img', true);
  131. localRemove("img2img_task_id");
  132. showRestoreProgressButton('img2img', false);
  133. });
  134. var res = create_submit_args(arguments);
  135. res[0] = id;
  136. res[1] = get_tab_index('mode_img2img');
  137. return res;
  138. }
  139. function submit_extras() {
  140. showSubmitButtons('extras', false);
  141. var id = randomId();
  142. requestProgress(id, gradioApp().getElementById('extras_gallery_container'), gradioApp().getElementById('extras_gallery'), function() {
  143. showSubmitButtons('extras', true);
  144. });
  145. var res = create_submit_args(arguments);
  146. res[0] = id;
  147. console.log(res);
  148. return res;
  149. }
  150. function restoreProgressTxt2img() {
  151. showRestoreProgressButton("txt2img", false);
  152. var id = localGet("txt2img_task_id");
  153. if (id) {
  154. requestProgress(id, gradioApp().getElementById('txt2img_gallery_container'), gradioApp().getElementById('txt2img_gallery'), function() {
  155. showSubmitButtons('txt2img', true);
  156. }, null, 0);
  157. }
  158. return id;
  159. }
  160. function restoreProgressImg2img() {
  161. showRestoreProgressButton("img2img", false);
  162. var id = localGet("img2img_task_id");
  163. if (id) {
  164. requestProgress(id, gradioApp().getElementById('img2img_gallery_container'), gradioApp().getElementById('img2img_gallery'), function() {
  165. showSubmitButtons('img2img', true);
  166. }, null, 0);
  167. }
  168. return id;
  169. }
  170. /**
  171. * Configure the width and height elements on `tabname` to accept
  172. * pasting of resolutions in the form of "width x height".
  173. */
  174. function setupResolutionPasting(tabname) {
  175. var width = gradioApp().querySelector(`#${tabname}_width input[type=number]`);
  176. var height = gradioApp().querySelector(`#${tabname}_height input[type=number]`);
  177. for (const el of [width, height]) {
  178. el.addEventListener('paste', function(event) {
  179. var pasteData = event.clipboardData.getData('text/plain');
  180. var parsed = pasteData.match(/^\s*(\d+)\D+(\d+)\s*$/);
  181. if (parsed) {
  182. width.value = parsed[1];
  183. height.value = parsed[2];
  184. updateInput(width);
  185. updateInput(height);
  186. event.preventDefault();
  187. }
  188. });
  189. }
  190. }
  191. onUiLoaded(function() {
  192. showRestoreProgressButton('txt2img', localGet("txt2img_task_id"));
  193. showRestoreProgressButton('img2img', localGet("img2img_task_id"));
  194. setupResolutionPasting('txt2img');
  195. setupResolutionPasting('img2img');
  196. });
  197. function modelmerger() {
  198. var id = randomId();
  199. requestProgress(id, gradioApp().getElementById('modelmerger_results_panel'), null, function() {});
  200. var res = create_submit_args(arguments);
  201. res[0] = id;
  202. return res;
  203. }
  204. function ask_for_style_name(_, prompt_text, negative_prompt_text) {
  205. var name_ = prompt('Style name:');
  206. return [name_, prompt_text, negative_prompt_text];
  207. }
  208. function confirm_clear_prompt(prompt, negative_prompt) {
  209. if (confirm("Delete prompt?")) {
  210. prompt = "";
  211. negative_prompt = "";
  212. }
  213. return [prompt, negative_prompt];
  214. }
  215. var opts = {};
  216. onAfterUiUpdate(function() {
  217. if (Object.keys(opts).length != 0) return;
  218. var json_elem = gradioApp().getElementById('settings_json');
  219. if (json_elem == null) return;
  220. var textarea = json_elem.querySelector('textarea');
  221. var jsdata = textarea.value;
  222. opts = JSON.parse(jsdata);
  223. executeCallbacks(optionsChangedCallbacks); /*global optionsChangedCallbacks*/
  224. Object.defineProperty(textarea, 'value', {
  225. set: function(newValue) {
  226. var valueProp = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value');
  227. var oldValue = valueProp.get.call(textarea);
  228. valueProp.set.call(textarea, newValue);
  229. if (oldValue != newValue) {
  230. opts = JSON.parse(textarea.value);
  231. }
  232. executeCallbacks(optionsChangedCallbacks);
  233. },
  234. get: function() {
  235. var valueProp = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value');
  236. return valueProp.get.call(textarea);
  237. }
  238. });
  239. json_elem.parentElement.style.display = "none";
  240. setupTokenCounters();
  241. });
  242. onOptionsChanged(function() {
  243. var elem = gradioApp().getElementById('sd_checkpoint_hash');
  244. var sd_checkpoint_hash = opts.sd_checkpoint_hash || "";
  245. var shorthash = sd_checkpoint_hash.substring(0, 10);
  246. if (elem && elem.textContent != shorthash) {
  247. elem.textContent = shorthash;
  248. elem.title = sd_checkpoint_hash;
  249. elem.href = "https://google.com/search?q=" + sd_checkpoint_hash;
  250. }
  251. });
  252. let txt2img_textarea, img2img_textarea = undefined;
  253. function restart_reload() {
  254. document.body.innerHTML = '<h1 style="font-family:monospace;margin-top:20%;color:lightgray;text-align:center;">Reloading...</h1>';
  255. var requestPing = function() {
  256. requestGet("./internal/ping", {}, function(data) {
  257. location.reload();
  258. }, function() {
  259. setTimeout(requestPing, 500);
  260. });
  261. };
  262. setTimeout(requestPing, 2000);
  263. return [];
  264. }
  265. // Simulate an `input` DOM event for Gradio Textbox component. Needed after you edit its contents in javascript, otherwise your edits
  266. // will only visible on web page and not sent to python.
  267. function updateInput(target) {
  268. let e = new Event("input", {bubbles: true});
  269. Object.defineProperty(e, "target", {value: target});
  270. target.dispatchEvent(e);
  271. }
  272. var desiredCheckpointName = null;
  273. function selectCheckpoint(name) {
  274. desiredCheckpointName = name;
  275. gradioApp().getElementById('change_checkpoint').click();
  276. }
  277. function currentImg2imgSourceResolution(w, h, scaleBy) {
  278. var img = gradioApp().querySelector('#mode_img2img > div[style="display: block;"] img');
  279. return img ? [img.naturalWidth, img.naturalHeight, scaleBy] : [0, 0, scaleBy];
  280. }
  281. function updateImg2imgResizeToTextAfterChangingImage() {
  282. // At the time this is called from gradio, the image has no yet been replaced.
  283. // There may be a better solution, but this is simple and straightforward so I'm going with it.
  284. setTimeout(function() {
  285. gradioApp().getElementById('img2img_update_resize_to').click();
  286. }, 500);
  287. return [];
  288. }
  289. function setRandomSeed(elem_id) {
  290. var input = gradioApp().querySelector("#" + elem_id + " input");
  291. if (!input) return [];
  292. input.value = "-1";
  293. updateInput(input);
  294. return [];
  295. }
  296. function switchWidthHeight(tabname) {
  297. var width = gradioApp().querySelector("#" + tabname + "_width input[type=number]");
  298. var height = gradioApp().querySelector("#" + tabname + "_height input[type=number]");
  299. if (!width || !height) return [];
  300. var tmp = width.value;
  301. width.value = height.value;
  302. height.value = tmp;
  303. updateInput(width);
  304. updateInput(height);
  305. return [];
  306. }
  307. var onEditTimers = {};
  308. // calls func after afterMs milliseconds has passed since the input elem has beed enited by user
  309. function onEdit(editId, elem, afterMs, func) {
  310. var edited = function() {
  311. var existingTimer = onEditTimers[editId];
  312. if (existingTimer) clearTimeout(existingTimer);
  313. onEditTimers[editId] = setTimeout(func, afterMs);
  314. };
  315. elem.addEventListener("input", edited);
  316. return edited;
  317. }