prompt-bracket-checker.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // Stable Diffusion WebUI - Bracket checker
  2. // By Hingashi no Florin/Bwin4L & @akx
  3. // Counts open and closed brackets (round, square, curly) in the prompt and negative prompt text boxes in the txt2img and img2img tabs.
  4. // If there's a mismatch, the keyword counter turns red and if you hover on it, a tooltip tells you what's wrong.
  5. function checkBrackets(textArea, counterElt) {
  6. var counts = {};
  7. (textArea.value.match(/[(){}[\]]/g) || []).forEach(bracket => {
  8. counts[bracket] = (counts[bracket] || 0) + 1;
  9. });
  10. var errors = [];
  11. function checkPair(open, close, kind) {
  12. if (counts[open] !== counts[close]) {
  13. errors.push(
  14. `${open}...${close} - Detected ${counts[open] || 0} opening and ${counts[close] || 0} closing ${kind}.`
  15. );
  16. }
  17. }
  18. checkPair('(', ')', 'round brackets');
  19. checkPair('[', ']', 'square brackets');
  20. checkPair('{', '}', 'curly brackets');
  21. counterElt.title = errors.join('\n');
  22. counterElt.classList.toggle('error', errors.length !== 0);
  23. }
  24. function setupBracketChecking(id_prompt, id_counter) {
  25. var textarea = gradioApp().querySelector("#" + id_prompt + " > label > textarea");
  26. var counter = gradioApp().getElementById(id_counter);
  27. if (textarea && counter) {
  28. textarea.addEventListener("input", () => checkBrackets(textarea, counter));
  29. }
  30. }
  31. onUiLoaded(function() {
  32. setupBracketChecking('txt2img_prompt', 'txt2img_token_counter');
  33. setupBracketChecking('txt2img_neg_prompt', 'txt2img_negative_token_counter');
  34. setupBracketChecking('img2img_prompt', 'img2img_token_counter');
  35. setupBracketChecking('img2img_neg_prompt', 'img2img_negative_token_counter');
  36. });