Advertisement
Guest User

Untitled

a guest
Oct 28th, 2022
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.87 KB | None | 0 0
  1. import copy
  2. import math
  3. import os
  4. import sys
  5. import traceback
  6. import shlex
  7. import random
  8.  
  9. import modules.scripts as scripts
  10. import gradio as gr
  11.  
  12. from modules.processing import Processed, process_images
  13. from PIL import Image
  14. from modules.shared import opts, cmd_opts, state
  15.  
  16.  
  17. def process_string_tag(tag):
  18. return tag
  19.  
  20.  
  21. def process_int_tag(tag):
  22. return int(tag)
  23.  
  24.  
  25. def process_float_tag(tag):
  26. return float(tag)
  27.  
  28.  
  29. def process_boolean_tag(tag):
  30. return True if (tag == "true") else False
  31.  
  32.  
  33. prompt_tags = {
  34. "sd_model": None,
  35. "outpath_samples": process_string_tag,
  36. "outpath_grids": process_string_tag,
  37. "prompt_for_display": process_string_tag,
  38. "prompt": process_string_tag,
  39. "negative_prompt": process_string_tag,
  40. "styles": process_string_tag,
  41. "seed": process_int_tag,
  42. "subseed_strength": process_float_tag,
  43. "subseed": process_int_tag,
  44. "seed_resize_from_h": process_int_tag,
  45. "seed_resize_from_w": process_int_tag,
  46. "sampler_index": process_int_tag,
  47. "batch_size": process_int_tag,
  48. "n_iter": process_int_tag,
  49. "steps": process_int_tag,
  50. "cfg_scale": process_float_tag,
  51. "width": process_int_tag,
  52. "height": process_int_tag,
  53. "restore_faces": process_boolean_tag,
  54. "tiling": process_boolean_tag,
  55. "do_not_save_samples": process_boolean_tag,
  56. "do_not_save_grid": process_boolean_tag
  57. }
  58.  
  59.  
  60. def cmdargs(line):
  61. args = shlex.split(line)
  62. pos = 0
  63. res = {}
  64.  
  65. while pos < len(args):
  66. arg = args[pos]
  67.  
  68. assert arg.startswith("--"), f'must start with "--": {arg}'
  69. tag = arg[2:]
  70.  
  71. func = prompt_tags.get(tag, None)
  72. assert func, f'unknown commandline option: {arg}'
  73.  
  74. assert pos+1 < len(args), f'missing argument for command line option {arg}'
  75.  
  76. val = args[pos+1]
  77.  
  78. res[tag] = func(val)
  79.  
  80. pos += 2
  81.  
  82. return res
  83.  
  84.  
  85. class Script(scripts.Script):
  86. def title(self):
  87. return "Prompts from file multi image"
  88.  
  89. def show(self, is_img2img):
  90. return is_img2img
  91.  
  92. def ui(self, is_img2img):
  93. if not is_img2img:
  94. return None
  95. # This checkbox would look nicer as two tabs, but there are two problems:
  96. # 1) There is a bug in Gradio 3.3 that prevents visibility from working on Tabs
  97. # 2) Even with Gradio 3.3.1, returning a control (like Tabs) that can't be used as input
  98. # causes a AttributeError: 'Tabs' object has no attribute 'preprocess' assert,
  99. # due to the way Script assumes all controls returned can be used as inputs.
  100. # Therefore, there's no good way to use grouping components right now,
  101. # so we will use a checkbox! :)
  102. input_dir = gr.Textbox(label="Input Dir", lines=1)
  103. start_line_txt = gr.Textbox(label="Start Line", lines=1, value = "1")
  104. end_line_txt = gr.Textbox(label="End Line", lines=1, value = "-1")
  105. rndimage_txt = gr.Textbox(label="Random Image Count", lines=1, value = "-1")
  106. checkbox_txt = gr.Checkbox(label="Show Textbox", value=False)
  107. file = gr.File(label="File with inputs", type='bytes')
  108. prompt_txt = gr.TextArea(label="Prompts")
  109. checkbox_txt.change(fn=lambda x: [gr.File.update(visible = not x), gr.TextArea.update(visible = x)], inputs=[checkbox_txt], outputs=[file, prompt_txt])
  110. return [checkbox_txt, file, prompt_txt, input_dir, start_line_txt, end_line_txt, rndimage_txt]
  111.  
  112. def on_show(self, checkbox_txt, file, prompt_txt, input_dir, start_line_txt, end_line_txt, rndimage_txt):
  113. return [ gr.Checkbox.update(visible = True), gr.File.update(visible = not checkbox_txt), gr.TextArea.update(visible = checkbox_txt) , gr.Textbox.update(visible = input_dir), gr.Textbox.update(visible = start_line_txt), gr.Textbox.update(visible = end_line_txt), gr.Textbox.update(visible = rndimage_txt)]
  114.  
  115. def run(self, p, checkbox_txt, data: bytes, prompt_txt: str, input_dir: str, start_line_txt: str, end_line_txt: str, rndimage_txt: str):
  116. if checkbox_txt:
  117. lines = [x.strip() for x in prompt_txt.splitlines()]
  118. else:
  119. lines = [x.strip() for x in data.decode('utf8', errors='ignore').split("\n")]
  120.  
  121. if int(end_line_txt) == -1:
  122. end_line_txt = str(len(lines))
  123.  
  124. lines = lines[int(start_line_txt) - 1:int(end_line_txt)]
  125.  
  126. lines = [x for x in lines if len(x) > 0]
  127.  
  128. p.do_not_save_grid = True
  129.  
  130. job_count = 0
  131. jobs = []
  132.  
  133. imagefiles = [file for file in [os.path.join(input_dir, x) for x in os.listdir(input_dir)] if os.path.isfile(file)]
  134.  
  135. for line in lines:
  136. if "--" in line:
  137. try:
  138. args = cmdargs(line)
  139. except Exception:
  140. print(f"Error parsing line [line] as commandline:", file=sys.stderr)
  141. print(traceback.format_exc(), file=sys.stderr)
  142. args = {"prompt": line}
  143. else:
  144. args = {"prompt": line}
  145.  
  146. n_iter = args.get("n_iter", 1)
  147. if n_iter != 1:
  148. job_count += n_iter
  149. else:
  150. job_count += 1
  151.  
  152. jobs.append(args)
  153.  
  154. print(f"Will process {len(lines)} lines in {job_count} jobs.")
  155. state.job_count = job_count
  156.  
  157. images = []
  158. for n, args in enumerate(jobs):
  159. state.job = f"{state.job_no + 1} out of {state.job_count}"
  160.  
  161. for k, v in args.items():
  162.  
  163. if int(rndimage_txt) > -1:
  164.  
  165. for i in range(int(rndimage_txt)):
  166.  
  167. copy_p = copy.copy(p)
  168. setattr(copy_p, k, v)
  169. copy_p.init_images = [Image.open(imagefiles[random.randint(0, len(imagefiles) - 1)])]
  170.  
  171. proc = process_images(copy_p)
  172. images += proc.images
  173.  
  174. if (state.interrupted):
  175. state.job_count = 0
  176. jobs.clear()
  177. return Processed(p, images, p.seed, "")
  178.  
  179. else:
  180.  
  181. for i, cimage in enumerate(imagefiles):
  182.  
  183. copy_p = copy.copy(p)
  184. setattr(copy_p, k, v)
  185. copy_p.init_images = [Image.open(cimage)]
  186.  
  187. proc = process_images(copy_p)
  188. images += proc.images
  189.  
  190. if (state.interrupted):
  191. state.job_count = 0
  192. jobs.clear()
  193. return Processed(p, images, p.seed, "")
  194.  
  195. return Processed(p, images, p.seed, "")
  196.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement