Path: blob/master/javascript/token-counters.js
3055 views
let promptTokenCountUpdateFunctions = {};12function update_txt2img_tokens(...args) {3// Called from Gradio4update_token_counter("txt2img_token_button");5update_token_counter("txt2img_negative_token_button");6if (args.length == 2) {7return args[0];8}9return args;10}1112function update_img2img_tokens(...args) {13// Called from Gradio14update_token_counter("img2img_token_button");15update_token_counter("img2img_negative_token_button");16if (args.length == 2) {17return args[0];18}19return args;20}2122function update_token_counter(button_id) {23promptTokenCountUpdateFunctions[button_id]?.();24}252627function recalculatePromptTokens(name) {28promptTokenCountUpdateFunctions[name]?.();29}3031function recalculate_prompts_txt2img() {32// Called from Gradio33recalculatePromptTokens('txt2img_prompt');34recalculatePromptTokens('txt2img_neg_prompt');35return Array.from(arguments);36}3738function recalculate_prompts_img2img() {39// Called from Gradio40recalculatePromptTokens('img2img_prompt');41recalculatePromptTokens('img2img_neg_prompt');42return Array.from(arguments);43}4445function setupTokenCounting(id, id_counter, id_button) {46var prompt = gradioApp().getElementById(id);47var counter = gradioApp().getElementById(id_counter);48var textarea = gradioApp().querySelector(`#${id} > label > textarea`);4950if (counter.parentElement == prompt.parentElement) {51return;52}5354prompt.parentElement.insertBefore(counter, prompt);55prompt.parentElement.style.position = "relative";5657var func = onEdit(id, textarea, 800, function() {58if (counter.classList.contains("token-counter-visible")) {59gradioApp().getElementById(id_button)?.click();60}61});62promptTokenCountUpdateFunctions[id] = func;63promptTokenCountUpdateFunctions[id_button] = func;64}6566function toggleTokenCountingVisibility(id, id_counter, id_button) {67var counter = gradioApp().getElementById(id_counter);6869counter.style.display = opts.disable_token_counters ? "none" : "block";70counter.classList.toggle("token-counter-visible", !opts.disable_token_counters);71}7273function runCodeForTokenCounters(fun) {74fun('txt2img_prompt', 'txt2img_token_counter', 'txt2img_token_button');75fun('txt2img_neg_prompt', 'txt2img_negative_token_counter', 'txt2img_negative_token_button');76fun('img2img_prompt', 'img2img_token_counter', 'img2img_token_button');77fun('img2img_neg_prompt', 'img2img_negative_token_counter', 'img2img_negative_token_button');78}7980onUiLoaded(function() {81runCodeForTokenCounters(setupTokenCounting);82});8384onOptionsChanged(function() {85runCodeForTokenCounters(toggleTokenCountingVisibility);86});878889