Upload magic_prompt.py
Browse files- magic_prompt.py +169 -0
magic_prompt.py
ADDED
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
User script for AUTOMATIC111's SD WebUI that integrates MagicPrompt
|
3 |
+
Copyright (C) 2022 Spaceginner
|
4 |
+
|
5 |
+
This user script is free software: you can redistribute it and/or modify
|
6 |
+
it under the terms of the GNU General Public License as published by
|
7 |
+
the Free Software Foundation, either version 3 of the License, or
|
8 |
+
(at your option) any later version.
|
9 |
+
|
10 |
+
This user script is distributed in the hope that it will be useful,
|
11 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
12 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
13 |
+
GNU General Public License for more details.
|
14 |
+
|
15 |
+
You should have received a copy of the GNU General Public License
|
16 |
+
along with this user script. If not, see <https://www.gnu.org/licenses/>.
|
17 |
+
|
18 |
+
Contact me via Discord (Spaceginner#7688), email (ivan.demian2009@gmail.com)
|
19 |
+
or via "Issues" tab on Github page of this script
|
20 |
+
(https://github.com/Spaceginner/MagicPrompt-awebui)
|
21 |
+
|
22 |
+
Credits:
|
23 |
+
Special thanks to Gustavosta for creating MagicPrompt AI model.
|
24 |
+
Also credits go to u/Letharguss (for creating basic script)
|
25 |
+
and SoCalGuitarist#2586 (for figuring out how to change prompt batch to batch)
|
26 |
+
|
27 |
+
Version: 1.0.0
|
28 |
+
"""
|
29 |
+
|
30 |
+
import os
|
31 |
+
import sys
|
32 |
+
import subprocess
|
33 |
+
|
34 |
+
# Try to import aitextgen, if it is not found, download
|
35 |
+
try:
|
36 |
+
from aitextgen import aitextgen
|
37 |
+
except:
|
38 |
+
print("[MagicPrompt script] aitextgen module is not found, downloading...")
|
39 |
+
if os.path.exists("./venv"):
|
40 |
+
subprocess.call(["./venv/Scripts/python", "-m", "pip", "-q", "--disable-pip-version-check", "--no-input", "install", "aitextgen"])
|
41 |
+
else:
|
42 |
+
subprocess.call(["python", "-m", "pip", "-q", "--disable-pip-version-check", "--no-input", "install", "aitextgen"])
|
43 |
+
print("[MagicPrompt script] aitextgen module is downloaded")
|
44 |
+
|
45 |
+
import gradio as gr
|
46 |
+
import torch
|
47 |
+
|
48 |
+
import modules.scripts as scripts
|
49 |
+
from modules.processing import Processed, process_images
|
50 |
+
from modules.shared import state
|
51 |
+
|
52 |
+
# Searching for folder with MagicPrompt model, if not found, download model
|
53 |
+
if (not os.path.isdir("./models/MagicPrompt/")):
|
54 |
+
print("[MagicPrompt script] MagicPrompt model is not found, downloading MagicPrompt model...")
|
55 |
+
os.mkdir("./models/MagicPrompt/")
|
56 |
+
subprocess.call(["git", "clone", "--quiet", "https://huggingface.co/Gustavosta/MagicPrompt-Stable-Diffusion", "./models/MagicPrompt/."])
|
57 |
+
print("[MagicPrompt script] MagicPrompt model is downloaded")
|
58 |
+
|
59 |
+
def getOrdinalNum(n):
|
60 |
+
if str(n)[-1] == "1":
|
61 |
+
return f"{n}st"
|
62 |
+
elif str(n)[-1] == "2":
|
63 |
+
return f"{n}nd"
|
64 |
+
elif str(n)[-1] == "3":
|
65 |
+
return f"{n}rd"
|
66 |
+
else:
|
67 |
+
return f"{n}th"
|
68 |
+
|
69 |
+
class Script(scripts.Script):
|
70 |
+
# "Black magic to keep model between runs"
|
71 |
+
gpt = None
|
72 |
+
|
73 |
+
def title(self):
|
74 |
+
return "MagicPrompt"
|
75 |
+
|
76 |
+
def show(self, isImg2img):
|
77 |
+
# Will show up only in txt2img tab
|
78 |
+
return not isImg2img
|
79 |
+
|
80 |
+
def ui(self, isImg2img):
|
81 |
+
# Some settings
|
82 |
+
promptLength = gr.Slider(label="Prompt max. length", value=75, minimum=1, maximum=300, step=1)
|
83 |
+
temp = gr.Slider(label="Temperature", value=0.7, minimum=0.1, maximum=2, step=0.1)
|
84 |
+
useSameSeed = gr.Checkbox(label="Use same seed for each batch", value=False)
|
85 |
+
useUniquePrompt = gr.Checkbox(label="Use unique prompt for each batch", value=True)
|
86 |
+
isPrioritized = gr.Checkbox(label="Iniatial prompt will have more prority over generated one", value=False)
|
87 |
+
doPregenerating = gr.Checkbox(label="Enable prompt pregenerating (Theoretical perfomance boost). If you dont know how many images do you want to generate, disable it", value=True)
|
88 |
+
doUnloadModel = gr.Checkbox(label="Unload MagicPrompt model from VRAM/RAM after this run. (Decreased perfomance between runs, as it need to load again)", value=False)
|
89 |
+
|
90 |
+
return [promptLength, temp, useSameSeed, useUniquePrompt, isPrioritized, doPregenerating, doUnloadModel]
|
91 |
+
|
92 |
+
def run(self, p, promptLength, temp, useSameSeed, useUniquePrompt, isPrioritized, doPregenerating, doUnloadModel):
|
93 |
+
print()
|
94 |
+
|
95 |
+
# Load MagicPrompt model
|
96 |
+
if type(self.gpt) != aitextgen:
|
97 |
+
self.gpt = aitextgen(model_folder="./models/MagicPrompt/", tokenizer_file="./models/MagicPrompt/tokenizer.json", to_gpu=torch.cuda.is_available())
|
98 |
+
|
99 |
+
p.do_not_save_grid = True
|
100 |
+
|
101 |
+
# If prompt is a list, take first time out of it.
|
102 |
+
p.prompt = p.prompt[0] if type(p.prompt) == list else p.prompt
|
103 |
+
|
104 |
+
# As we will change prompt every batch
|
105 |
+
# we need to process only 1 batch at a time
|
106 |
+
state.job_count = p.n_iter
|
107 |
+
p.n_iter = 1
|
108 |
+
|
109 |
+
# Init prompt prioritazing
|
110 |
+
originalPrompt = p.prompt
|
111 |
+
if (originalPrompt != "" and isPrioritized):
|
112 |
+
originalPrompt = "(" + originalPrompt + ")"
|
113 |
+
|
114 |
+
# Pregenerating prompts
|
115 |
+
prompts = []
|
116 |
+
if (doPregenerating):
|
117 |
+
print(f"[MagicPrompt script] Pregenerating prompt{'s' if state.job_count > 1 else ''}...")
|
118 |
+
for i in range(state.job_count):
|
119 |
+
if (i == 0 or useUniquePrompt):
|
120 |
+
if state.interrupted:
|
121 |
+
print(f"[MagicPrompt script] Pregeneration interrupted")
|
122 |
+
break
|
123 |
+
|
124 |
+
prompts.append(self.gpt.generate_one(prompt=originalPrompt, max_length=promptLength, temperature=temp))
|
125 |
+
if state.job_count > 1:
|
126 |
+
print(f"[MagicPrompt script] Pregenerated {getOrdinalNum(i+1)} prompt...")
|
127 |
+
else:
|
128 |
+
break
|
129 |
+
print("[MagicPrompt script] Pregenerating finished")
|
130 |
+
|
131 |
+
images = []
|
132 |
+
for i in range(state.job_count):
|
133 |
+
if state.skipped:
|
134 |
+
print("Rendering of current batch skipped")
|
135 |
+
continue
|
136 |
+
|
137 |
+
if state.interrupted:
|
138 |
+
print(f"Rendering interrupted")
|
139 |
+
break
|
140 |
+
|
141 |
+
state.job = f"{i+1} out of {state.job_count}"
|
142 |
+
|
143 |
+
# Remove total bar
|
144 |
+
sys.stdout.write('\033[2K\033[1G')
|
145 |
+
print("\n")
|
146 |
+
|
147 |
+
# Prompt applying
|
148 |
+
if (i == 0 or useUniquePrompt):
|
149 |
+
if doPregenerating:
|
150 |
+
p.prompt = prompts[i]
|
151 |
+
else:
|
152 |
+
# ...or generate one if pregenerating is disabled
|
153 |
+
print(f"[MagicPrompt script] Generating prompt for {getOrdinalNum(i+1)} batch...")
|
154 |
+
p.prompt = self.gpt.generate_one(prompt=originalPrompt, max_length=promptLength, temperature=temp)
|
155 |
+
|
156 |
+
print(f"[MagicPrompt script] Generated prompt for {getOrdinalNum(i+1)} batch: {p.prompt}")
|
157 |
+
|
158 |
+
# for whatever reason .append() doesn't work
|
159 |
+
images += process_images(p).images
|
160 |
+
|
161 |
+
if not useSameSeed:
|
162 |
+
if not p.seed == -1:
|
163 |
+
p.seed += 1
|
164 |
+
|
165 |
+
# Unload model
|
166 |
+
if doUnloadModel:
|
167 |
+
del self.gpt
|
168 |
+
|
169 |
+
return Processed(p, images, p.seed, "")
|