|
| 1 | +from collections import namedtuple |
| 2 | +import re |
| 3 | +import gradio as gr |
| 4 | + |
| 5 | +re_param = re.compile(r"\s*([\w ]+):\s*([^,]+)(?:,|$)") |
| 6 | +re_imagesize = re.compile(r"^(\d+)x(\d+)$") |
| 7 | + |
| 8 | + |
| 9 | +def parse_generation_parameters(x: str): |
| 10 | + """parses generation parameters string, the one you see in text field under the picture in UI: |
| 11 | +``` |
| 12 | +girl with an artist's beret, determined, blue eyes, desert scene, computer monitors, heavy makeup, by Alphonse Mucha and Charlie Bowater, ((eyeshadow)), (coquettish), detailed, intricate |
| 13 | +Negative prompt: ugly, fat, obese, chubby, (((deformed))), [blurry], bad anatomy, disfigured, poorly drawn face, mutation, mutated, (extra_limb), (ugly), (poorly drawn hands), messy drawing |
| 14 | +Steps: 20, Sampler: Euler a, CFG scale: 7, Seed: 965400086, Size: 512x512, Model hash: 45dee52b |
| 15 | +``` |
| 16 | +
|
| 17 | + returns a dict with field values |
| 18 | + """ |
| 19 | + |
| 20 | + res = {} |
| 21 | + |
| 22 | + prompt = "" |
| 23 | + negative_prompt = "" |
| 24 | + |
| 25 | + done_with_prompt = False |
| 26 | + |
| 27 | + *lines, lastline = x.strip().split("\n") |
| 28 | + for i, line in enumerate(lines): |
| 29 | + line = line.strip() |
| 30 | + if line.startswith("Negative prompt:"): |
| 31 | + done_with_prompt = True |
| 32 | + line = line[16:].strip() |
| 33 | + |
| 34 | + if done_with_prompt: |
| 35 | + negative_prompt += line |
| 36 | + else: |
| 37 | + prompt += line |
| 38 | + |
| 39 | + if len(prompt) > 0: |
| 40 | + res["Prompt"] = prompt |
| 41 | + |
| 42 | + if len(negative_prompt) > 0: |
| 43 | + res["Negative prompt"] = negative_prompt |
| 44 | + |
| 45 | + for k, v in re_param.findall(lastline): |
| 46 | + m = re_imagesize.match(v) |
| 47 | + if m is not None: |
| 48 | + res[k+"-1"] = m.group(1) |
| 49 | + res[k+"-2"] = m.group(2) |
| 50 | + else: |
| 51 | + res[k] = v |
| 52 | + |
| 53 | + return res |
| 54 | + |
| 55 | + |
| 56 | +def connect_paste(button, d, input_comp, js=None): |
| 57 | + items = [] |
| 58 | + outputs = [] |
| 59 | + |
| 60 | + def paste_func(prompt): |
| 61 | + params = parse_generation_parameters(prompt) |
| 62 | + res = [] |
| 63 | + |
| 64 | + for key, output in zip(items, outputs): |
| 65 | + v = params.get(key, None) |
| 66 | + |
| 67 | + if v is None: |
| 68 | + res.append(gr.update()) |
| 69 | + else: |
| 70 | + try: |
| 71 | + valtype = type(output.value) |
| 72 | + val = valtype(v) |
| 73 | + res.append(gr.update(value=val)) |
| 74 | + except Exception: |
| 75 | + res.append(gr.update()) |
| 76 | + |
| 77 | + return res |
| 78 | + |
| 79 | + for k, v in d.items(): |
| 80 | + items.append(k) |
| 81 | + outputs.append(v) |
| 82 | + |
| 83 | + button.click( |
| 84 | + fn=paste_func, |
| 85 | + _js=js, |
| 86 | + inputs=[input_comp], |
| 87 | + outputs=outputs, |
| 88 | + ) |
0 commit comments