prompts_from_file.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. import copy
  2. import random
  3. import shlex
  4. import modules.scripts as scripts
  5. import gradio as gr
  6. from modules import sd_samplers, errors
  7. from modules.processing import Processed, process_images
  8. from modules.shared import state
  9. def process_string_tag(tag):
  10. return tag
  11. def process_int_tag(tag):
  12. return int(tag)
  13. def process_float_tag(tag):
  14. return float(tag)
  15. def process_boolean_tag(tag):
  16. return True if (tag == "true") else False
  17. prompt_tags = {
  18. "sd_model": None,
  19. "outpath_samples": process_string_tag,
  20. "outpath_grids": process_string_tag,
  21. "prompt_for_display": process_string_tag,
  22. "prompt": process_string_tag,
  23. "negative_prompt": process_string_tag,
  24. "styles": process_string_tag,
  25. "seed": process_int_tag,
  26. "subseed_strength": process_float_tag,
  27. "subseed": process_int_tag,
  28. "seed_resize_from_h": process_int_tag,
  29. "seed_resize_from_w": process_int_tag,
  30. "sampler_index": process_int_tag,
  31. "sampler_name": process_string_tag,
  32. "batch_size": process_int_tag,
  33. "n_iter": process_int_tag,
  34. "steps": process_int_tag,
  35. "cfg_scale": process_float_tag,
  36. "width": process_int_tag,
  37. "height": process_int_tag,
  38. "restore_faces": process_boolean_tag,
  39. "tiling": process_boolean_tag,
  40. "do_not_save_samples": process_boolean_tag,
  41. "do_not_save_grid": process_boolean_tag
  42. }
  43. def cmdargs(line):
  44. args = shlex.split(line)
  45. pos = 0
  46. res = {}
  47. while pos < len(args):
  48. arg = args[pos]
  49. assert arg.startswith("--"), f'must start with "--": {arg}'
  50. assert pos+1 < len(args), f'missing argument for command line option {arg}'
  51. tag = arg[2:]
  52. if tag == "prompt" or tag == "negative_prompt":
  53. pos += 1
  54. prompt = args[pos]
  55. pos += 1
  56. while pos < len(args) and not args[pos].startswith("--"):
  57. prompt += " "
  58. prompt += args[pos]
  59. pos += 1
  60. res[tag] = prompt
  61. continue
  62. func = prompt_tags.get(tag, None)
  63. assert func, f'unknown commandline option: {arg}'
  64. val = args[pos+1]
  65. if tag == "sampler_name":
  66. val = sd_samplers.samplers_map.get(val.lower(), None)
  67. res[tag] = func(val)
  68. pos += 2
  69. return res
  70. def load_prompt_file(file):
  71. if file is None:
  72. return None, gr.update(), gr.update(lines=7)
  73. else:
  74. lines = [x.strip() for x in file.decode('utf8', errors='ignore').split("\n")]
  75. return None, "\n".join(lines), gr.update(lines=7)
  76. class Script(scripts.Script):
  77. def title(self):
  78. return "Prompts from file or textbox"
  79. def ui(self, is_img2img):
  80. checkbox_iterate = gr.Checkbox(label="Iterate seed every line", value=False, elem_id=self.elem_id("checkbox_iterate"))
  81. checkbox_iterate_batch = gr.Checkbox(label="Use same random seed for all lines", value=False, elem_id=self.elem_id("checkbox_iterate_batch"))
  82. prompt_txt = gr.Textbox(label="List of prompt inputs", lines=1, elem_id=self.elem_id("prompt_txt"))
  83. file = gr.File(label="Upload prompt inputs", type='binary', elem_id=self.elem_id("file"))
  84. file.change(fn=load_prompt_file, inputs=[file], outputs=[file, prompt_txt, prompt_txt], show_progress=False)
  85. # We start at one line. When the text changes, we jump to seven lines, or two lines if no \n.
  86. # We don't shrink back to 1, because that causes the control to ignore [enter], and it may
  87. # be unclear to the user that shift-enter is needed.
  88. prompt_txt.change(lambda tb: gr.update(lines=7) if ("\n" in tb) else gr.update(lines=2), inputs=[prompt_txt], outputs=[prompt_txt], show_progress=False)
  89. return [checkbox_iterate, checkbox_iterate_batch, prompt_txt]
  90. def run(self, p, checkbox_iterate, checkbox_iterate_batch, prompt_txt: str):
  91. lines = [x for x in (x.strip() for x in prompt_txt.splitlines()) if x]
  92. p.do_not_save_grid = True
  93. job_count = 0
  94. jobs = []
  95. for line in lines:
  96. if "--" in line:
  97. try:
  98. args = cmdargs(line)
  99. except Exception:
  100. errors.report(f"Error parsing line {line} as commandline", exc_info=True)
  101. args = {"prompt": line}
  102. else:
  103. args = {"prompt": line}
  104. job_count += args.get("n_iter", p.n_iter)
  105. jobs.append(args)
  106. print(f"Will process {len(lines)} lines in {job_count} jobs.")
  107. if (checkbox_iterate or checkbox_iterate_batch) and p.seed == -1:
  108. p.seed = int(random.randrange(4294967294))
  109. state.job_count = job_count
  110. images = []
  111. all_prompts = []
  112. infotexts = []
  113. for args in jobs:
  114. state.job = f"{state.job_no + 1} out of {state.job_count}"
  115. copy_p = copy.copy(p)
  116. for k, v in args.items():
  117. setattr(copy_p, k, v)
  118. proc = process_images(copy_p)
  119. images += proc.images
  120. if checkbox_iterate:
  121. p.seed = p.seed + (p.batch_size * p.n_iter)
  122. all_prompts += proc.all_prompts
  123. infotexts += proc.infotexts
  124. return Processed(p, images, p.seed, "", all_prompts=all_prompts, infotexts=infotexts)