ui.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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. var allCurrentButtons = gradioApp().querySelectorAll('[style="display: block;"].tabitem div[id$=_gallery].gradio-gallery .thumbnail-item.thumbnail-small.selected');
  20. var visibleCurrentButton = null;
  21. allCurrentButtons.forEach(function(elem) {
  22. if (elem.parentElement.offsetParent) {
  23. visibleCurrentButton = elem;
  24. }
  25. });
  26. return visibleCurrentButton;
  27. }
  28. function selected_gallery_index() {
  29. var buttons = all_gallery_buttons();
  30. var button = selected_gallery_button();
  31. var result = -1;
  32. buttons.forEach(function(v, i) {
  33. if (v == button) {
  34. result = i;
  35. }
  36. });
  37. return result;
  38. }
  39. function extract_image_from_gallery(gallery) {
  40. if (gallery.length == 0) {
  41. return [null];
  42. }
  43. if (gallery.length == 1) {
  44. return [gallery[0]];
  45. }
  46. var index = selected_gallery_index();
  47. if (index < 0 || index >= gallery.length) {
  48. // Use the first image in the gallery as the default
  49. index = 0;
  50. }
  51. return [gallery[index]];
  52. }
  53. window.args_to_array = Array.from; // Compatibility with e.g. extensions that may expect this to be around
  54. function switch_to_txt2img() {
  55. gradioApp().querySelector('#tabs').querySelectorAll('button')[0].click();
  56. return Array.from(arguments);
  57. }
  58. function switch_to_img2img_tab(no) {
  59. gradioApp().querySelector('#tabs').querySelectorAll('button')[1].click();
  60. gradioApp().getElementById('mode_img2img').querySelectorAll('button')[no].click();
  61. }
  62. function switch_to_img2img() {
  63. switch_to_img2img_tab(0);
  64. return Array.from(arguments);
  65. }
  66. function switch_to_sketch() {
  67. switch_to_img2img_tab(1);
  68. return Array.from(arguments);
  69. }
  70. function switch_to_inpaint() {
  71. switch_to_img2img_tab(2);
  72. return Array.from(arguments);
  73. }
  74. function switch_to_inpaint_sketch() {
  75. switch_to_img2img_tab(3);
  76. return Array.from(arguments);
  77. }
  78. function switch_to_extras() {
  79. gradioApp().querySelector('#tabs').querySelectorAll('button')[2].click();
  80. return Array.from(arguments);
  81. }
  82. function get_tab_index(tabId) {
  83. var res = 0;
  84. gradioApp().getElementById(tabId).querySelector('div').querySelectorAll('button').forEach(function(button, i) {
  85. if (button.className.indexOf('selected') != -1) {
  86. res = i;
  87. }
  88. });
  89. return res;
  90. }
  91. function create_tab_index_args(tabId, args) {
  92. var res = Array.from(args);
  93. res[0] = get_tab_index(tabId);
  94. return res;
  95. }
  96. function get_img2img_tab_index() {
  97. let res = Array.from(arguments);
  98. res.splice(-2);
  99. res[0] = get_tab_index('mode_img2img');
  100. return res;
  101. }
  102. function create_submit_args(args) {
  103. var res = Array.from(args);
  104. // 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.
  105. // This can lead to uploading a huge gallery of previously generated images, which leads to an unnecessary delay between submitting and beginning to generate.
  106. // 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.
  107. // If gradio at some point stops sending outputs, this may break something
  108. if (Array.isArray(res[res.length - 3])) {
  109. res[res.length - 3] = null;
  110. }
  111. return res;
  112. }
  113. function showSubmitButtons(tabname, show) {
  114. gradioApp().getElementById(tabname + '_interrupt').style.display = show ? "none" : "block";
  115. gradioApp().getElementById(tabname + '_skip').style.display = show ? "none" : "block";
  116. }
  117. function showRestoreProgressButton(tabname, show) {
  118. var button = gradioApp().getElementById(tabname + "_restore_progress");
  119. if (!button) return;
  120. button.style.display = show ? "flex" : "none";
  121. }
  122. function submit() {
  123. showSubmitButtons('txt2img', false);
  124. var id = randomId();
  125. localStorage.setItem("txt2img_task_id", id);
  126. requestProgress(id, gradioApp().getElementById('txt2img_gallery_container'), gradioApp().getElementById('txt2img_gallery'), function() {
  127. showSubmitButtons('txt2img', true);
  128. localStorage.removeItem("txt2img_task_id");
  129. showRestoreProgressButton('txt2img', false);
  130. });
  131. var res = create_submit_args(arguments);
  132. res[0] = id;
  133. return res;
  134. }
  135. function submit_img2img() {
  136. showSubmitButtons('img2img', false);
  137. var id = randomId();
  138. localStorage.setItem("img2img_task_id", id);
  139. requestProgress(id, gradioApp().getElementById('img2img_gallery_container'), gradioApp().getElementById('img2img_gallery'), function() {
  140. showSubmitButtons('img2img', true);
  141. localStorage.removeItem("img2img_task_id");
  142. showRestoreProgressButton('img2img', false);
  143. });
  144. var res = create_submit_args(arguments);
  145. res[0] = id;
  146. res[1] = get_tab_index('mode_img2img');
  147. return res;
  148. }
  149. function restoreProgressTxt2img() {
  150. showRestoreProgressButton("txt2img", false);
  151. var id = localStorage.getItem("txt2img_task_id");
  152. id = localStorage.getItem("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 = localStorage.getItem("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. onUiLoaded(function() {
  171. showRestoreProgressButton('txt2img', localStorage.getItem("txt2img_task_id"));
  172. showRestoreProgressButton('img2img', localStorage.getItem("img2img_task_id"));
  173. });
  174. function modelmerger() {
  175. var id = randomId();
  176. requestProgress(id, gradioApp().getElementById('modelmerger_results_panel'), null, function() {});
  177. var res = create_submit_args(arguments);
  178. res[0] = id;
  179. return res;
  180. }
  181. function ask_for_style_name(_, prompt_text, negative_prompt_text) {
  182. var name_ = prompt('Style name:');
  183. return [name_, prompt_text, negative_prompt_text];
  184. }
  185. function confirm_clear_prompt(prompt, negative_prompt) {
  186. if (confirm("Delete prompt?")) {
  187. prompt = "";
  188. negative_prompt = "";
  189. }
  190. return [prompt, negative_prompt];
  191. }
  192. var promptTokecountUpdateFuncs = {};
  193. function recalculatePromptTokens(name) {
  194. if (promptTokecountUpdateFuncs[name]) {
  195. promptTokecountUpdateFuncs[name]();
  196. }
  197. }
  198. function recalculate_prompts_txt2img() {
  199. recalculatePromptTokens('txt2img_prompt');
  200. recalculatePromptTokens('txt2img_neg_prompt');
  201. return Array.from(arguments);
  202. }
  203. function recalculate_prompts_img2img() {
  204. recalculatePromptTokens('img2img_prompt');
  205. recalculatePromptTokens('img2img_neg_prompt');
  206. return Array.from(arguments);
  207. }
  208. var opts = {};
  209. onUiUpdate(function() {
  210. if (Object.keys(opts).length != 0) return;
  211. var json_elem = gradioApp().getElementById('settings_json');
  212. if (json_elem == null) return;
  213. var textarea = json_elem.querySelector('textarea');
  214. var jsdata = textarea.value;
  215. opts = JSON.parse(jsdata);
  216. executeCallbacks(optionsChangedCallbacks); /*global optionsChangedCallbacks*/
  217. Object.defineProperty(textarea, 'value', {
  218. set: function(newValue) {
  219. var valueProp = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value');
  220. var oldValue = valueProp.get.call(textarea);
  221. valueProp.set.call(textarea, newValue);
  222. if (oldValue != newValue) {
  223. opts = JSON.parse(textarea.value);
  224. }
  225. executeCallbacks(optionsChangedCallbacks);
  226. },
  227. get: function() {
  228. var valueProp = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value');
  229. return valueProp.get.call(textarea);
  230. }
  231. });
  232. json_elem.parentElement.style.display = "none";
  233. function registerTextarea(id, id_counter, id_button) {
  234. var prompt = gradioApp().getElementById(id);
  235. var counter = gradioApp().getElementById(id_counter);
  236. var textarea = gradioApp().querySelector("#" + id + " > label > textarea");
  237. if (counter.parentElement == prompt.parentElement) {
  238. return;
  239. }
  240. prompt.parentElement.insertBefore(counter, prompt);
  241. prompt.parentElement.style.position = "relative";
  242. promptTokecountUpdateFuncs[id] = function() {
  243. update_token_counter(id_button);
  244. };
  245. textarea.addEventListener("input", promptTokecountUpdateFuncs[id]);
  246. }
  247. registerTextarea('txt2img_prompt', 'txt2img_token_counter', 'txt2img_token_button');
  248. registerTextarea('txt2img_neg_prompt', 'txt2img_negative_token_counter', 'txt2img_negative_token_button');
  249. registerTextarea('img2img_prompt', 'img2img_token_counter', 'img2img_token_button');
  250. registerTextarea('img2img_neg_prompt', 'img2img_negative_token_counter', 'img2img_negative_token_button');
  251. var show_all_pages = gradioApp().getElementById('settings_show_all_pages');
  252. var settings_tabs = gradioApp().querySelector('#settings div');
  253. if (show_all_pages && settings_tabs) {
  254. settings_tabs.appendChild(show_all_pages);
  255. show_all_pages.onclick = function() {
  256. gradioApp().querySelectorAll('#settings > div').forEach(function(elem) {
  257. if (elem.id == "settings_tab_licenses") {
  258. return;
  259. }
  260. elem.style.display = "block";
  261. });
  262. };
  263. }
  264. });
  265. onOptionsChanged(function() {
  266. var elem = gradioApp().getElementById('sd_checkpoint_hash');
  267. var sd_checkpoint_hash = opts.sd_checkpoint_hash || "";
  268. var shorthash = sd_checkpoint_hash.substring(0, 10);
  269. if (elem && elem.textContent != shorthash) {
  270. elem.textContent = shorthash;
  271. elem.title = sd_checkpoint_hash;
  272. elem.href = "https://google.com/search?q=" + sd_checkpoint_hash;
  273. }
  274. });
  275. let txt2img_textarea, img2img_textarea = undefined;
  276. let wait_time = 800;
  277. let token_timeouts = {};
  278. function update_txt2img_tokens(...args) {
  279. update_token_counter("txt2img_token_button");
  280. if (args.length == 2) {
  281. return args[0];
  282. }
  283. return args;
  284. }
  285. function update_img2img_tokens(...args) {
  286. update_token_counter(
  287. "img2img_token_button"
  288. );
  289. if (args.length == 2) {
  290. return args[0];
  291. }
  292. return args;
  293. }
  294. function update_token_counter(button_id) {
  295. if (token_timeouts[button_id]) {
  296. clearTimeout(token_timeouts[button_id]);
  297. }
  298. token_timeouts[button_id] = setTimeout(() => gradioApp().getElementById(button_id)?.click(), wait_time);
  299. }
  300. function restart_reload() {
  301. document.body.innerHTML = '<h1 style="font-family:monospace;margin-top:20%;color:lightgray;text-align:center;">Reloading...</h1>';
  302. var requestPing = function() {
  303. requestGet("./internal/ping", {}, function(data) {
  304. location.reload();
  305. }, function() {
  306. setTimeout(requestPing, 500);
  307. });
  308. };
  309. setTimeout(requestPing, 2000);
  310. return [];
  311. }
  312. // Simulate an `input` DOM event for Gradio Textbox component. Needed after you edit its contents in javascript, otherwise your edits
  313. // will only visible on web page and not sent to python.
  314. function updateInput(target) {
  315. let e = new Event("input", {bubbles: true});
  316. Object.defineProperty(e, "target", {value: target});
  317. target.dispatchEvent(e);
  318. }
  319. var desiredCheckpointName = null;
  320. function selectCheckpoint(name) {
  321. desiredCheckpointName = name;
  322. gradioApp().getElementById('change_checkpoint').click();
  323. }
  324. function currentImg2imgSourceResolution(w, h, scaleBy) {
  325. var img = gradioApp().querySelector('#mode_img2img > div[style="display: block;"] img');
  326. return img ? [img.naturalWidth, img.naturalHeight, scaleBy] : [0, 0, scaleBy];
  327. }
  328. function updateImg2imgResizeToTextAfterChangingImage() {
  329. // At the time this is called from gradio, the image has no yet been replaced.
  330. // There may be a better solution, but this is simple and straightforward so I'm going with it.
  331. setTimeout(function() {
  332. gradioApp().getElementById('img2img_update_resize_to').click();
  333. }, 500);
  334. return [];
  335. }
  336. function setRandomSeed(elem_id) {
  337. var input = gradioApp().querySelector("#" + elem_id + " input");
  338. if (!input) return [];
  339. input.value = "-1";
  340. updateInput(input);
  341. return [];
  342. }
  343. function switchWidthHeight(tabname) {
  344. var width = gradioApp().querySelector("#" + tabname + "_width input[type=number]");
  345. var height = gradioApp().querySelector("#" + tabname + "_height input[type=number]");
  346. if (!width || !height) return [];
  347. var tmp = width.value;
  348. width.value = height.value;
  349. height.value = tmp;
  350. updateInput(width);
  351. updateInput(height);
  352. return [];
  353. }