Upload 100 files
Browse files- modules/ui_extensions.py +672 -0
- modules/ui_extra_networks.py +482 -0
- modules/ui_loadsave.py +235 -0
- modules/ui_postprocessing.py +63 -0
- modules/ui_prompt_styles.py +120 -0
- modules/ui_settings.py +337 -0
- modules/ui_tempdir.py +88 -0
- modules/ui_toprow.py +143 -0
- modules/upscaler.py +144 -0
- modules/util.py +58 -0
- modules/xlmr.py +137 -0
- modules/xlmr_m18.py +164 -0
- modules/xpu_specific.py +59 -0
modules/ui_extensions.py
ADDED
@@ -0,0 +1,672 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import os
|
3 |
+
import threading
|
4 |
+
import time
|
5 |
+
from datetime import datetime, timezone
|
6 |
+
|
7 |
+
import git
|
8 |
+
|
9 |
+
import gradio as gr
|
10 |
+
import html
|
11 |
+
import shutil
|
12 |
+
import errno
|
13 |
+
|
14 |
+
from modules import extensions, shared, paths, config_states, errors, restart
|
15 |
+
from modules.paths_internal import config_states_dir
|
16 |
+
from modules.call_queue import wrap_gradio_gpu_call
|
17 |
+
|
18 |
+
available_extensions = {"extensions": []}
|
19 |
+
STYLE_PRIMARY = ' style="color: var(--primary-400)"'
|
20 |
+
|
21 |
+
|
22 |
+
def check_access():
|
23 |
+
assert not shared.cmd_opts.disable_extension_access, "extension access disabled because of command line flags"
|
24 |
+
|
25 |
+
|
26 |
+
def apply_and_restart(disable_list, update_list, disable_all):
|
27 |
+
check_access()
|
28 |
+
|
29 |
+
disabled = json.loads(disable_list)
|
30 |
+
assert type(disabled) == list, f"wrong disable_list data for apply_and_restart: {disable_list}"
|
31 |
+
|
32 |
+
update = json.loads(update_list)
|
33 |
+
assert type(update) == list, f"wrong update_list data for apply_and_restart: {update_list}"
|
34 |
+
|
35 |
+
if update:
|
36 |
+
save_config_state("Backup (pre-update)")
|
37 |
+
|
38 |
+
update = set(update)
|
39 |
+
|
40 |
+
for ext in extensions.extensions:
|
41 |
+
if ext.name not in update:
|
42 |
+
continue
|
43 |
+
|
44 |
+
try:
|
45 |
+
ext.fetch_and_reset_hard()
|
46 |
+
except Exception:
|
47 |
+
errors.report(f"Error getting updates for {ext.name}", exc_info=True)
|
48 |
+
|
49 |
+
shared.opts.disabled_extensions = disabled
|
50 |
+
shared.opts.disable_all_extensions = disable_all
|
51 |
+
shared.opts.save(shared.config_filename)
|
52 |
+
|
53 |
+
if restart.is_restartable():
|
54 |
+
restart.restart_program()
|
55 |
+
else:
|
56 |
+
restart.stop_program()
|
57 |
+
|
58 |
+
|
59 |
+
def save_config_state(name):
|
60 |
+
current_config_state = config_states.get_config()
|
61 |
+
if not name:
|
62 |
+
name = "Config"
|
63 |
+
current_config_state["name"] = name
|
64 |
+
timestamp = datetime.now().strftime('%Y_%m_%d-%H_%M_%S')
|
65 |
+
filename = os.path.join(config_states_dir, f"{timestamp}_{name}.json")
|
66 |
+
print(f"Saving backup of webui/extension state to {filename}.")
|
67 |
+
with open(filename, "w", encoding="utf-8") as f:
|
68 |
+
json.dump(current_config_state, f, indent=4, ensure_ascii=False)
|
69 |
+
config_states.list_config_states()
|
70 |
+
new_value = next(iter(config_states.all_config_states.keys()), "Current")
|
71 |
+
new_choices = ["Current"] + list(config_states.all_config_states.keys())
|
72 |
+
return gr.Dropdown.update(value=new_value, choices=new_choices), f"<span>Saved current webui/extension state to \"{filename}\"</span>"
|
73 |
+
|
74 |
+
|
75 |
+
def restore_config_state(confirmed, config_state_name, restore_type):
|
76 |
+
if config_state_name == "Current":
|
77 |
+
return "<span>Select a config to restore from.</span>"
|
78 |
+
if not confirmed:
|
79 |
+
return "<span>Cancelled.</span>"
|
80 |
+
|
81 |
+
check_access()
|
82 |
+
|
83 |
+
config_state = config_states.all_config_states[config_state_name]
|
84 |
+
|
85 |
+
print(f"*** Restoring webui state from backup: {restore_type} ***")
|
86 |
+
|
87 |
+
if restore_type == "extensions" or restore_type == "both":
|
88 |
+
shared.opts.restore_config_state_file = config_state["filepath"]
|
89 |
+
shared.opts.save(shared.config_filename)
|
90 |
+
|
91 |
+
if restore_type == "webui" or restore_type == "both":
|
92 |
+
config_states.restore_webui_config(config_state)
|
93 |
+
|
94 |
+
shared.state.request_restart()
|
95 |
+
|
96 |
+
return ""
|
97 |
+
|
98 |
+
|
99 |
+
def check_updates(id_task, disable_list):
|
100 |
+
check_access()
|
101 |
+
|
102 |
+
disabled = json.loads(disable_list)
|
103 |
+
assert type(disabled) == list, f"wrong disable_list data for apply_and_restart: {disable_list}"
|
104 |
+
|
105 |
+
exts = [ext for ext in extensions.extensions if ext.remote is not None and ext.name not in disabled]
|
106 |
+
shared.state.job_count = len(exts)
|
107 |
+
|
108 |
+
for ext in exts:
|
109 |
+
shared.state.textinfo = ext.name
|
110 |
+
|
111 |
+
try:
|
112 |
+
ext.check_updates()
|
113 |
+
except FileNotFoundError as e:
|
114 |
+
if 'FETCH_HEAD' not in str(e):
|
115 |
+
raise
|
116 |
+
except Exception:
|
117 |
+
errors.report(f"Error checking updates for {ext.name}", exc_info=True)
|
118 |
+
|
119 |
+
shared.state.nextjob()
|
120 |
+
|
121 |
+
return extension_table(), ""
|
122 |
+
|
123 |
+
|
124 |
+
def make_commit_link(commit_hash, remote, text=None):
|
125 |
+
if text is None:
|
126 |
+
text = commit_hash[:8]
|
127 |
+
if remote.startswith("https://github.com/"):
|
128 |
+
if remote.endswith(".git"):
|
129 |
+
remote = remote[:-4]
|
130 |
+
href = remote + "/commit/" + commit_hash
|
131 |
+
return f'<a href="{href}" target="_blank">{text}</a>'
|
132 |
+
else:
|
133 |
+
return text
|
134 |
+
|
135 |
+
|
136 |
+
def extension_table():
|
137 |
+
code = f"""<!-- {time.time()} -->
|
138 |
+
<table id="extensions">
|
139 |
+
<thead>
|
140 |
+
<tr>
|
141 |
+
<th>
|
142 |
+
<input class="gr-check-radio gr-checkbox all_extensions_toggle" type="checkbox" {'checked="checked"' if all(ext.enabled for ext in extensions.extensions) else ''} onchange="toggle_all_extensions(event)" />
|
143 |
+
<abbr title="Use checkbox to enable the extension; it will be enabled or disabled when you click apply button">Extension</abbr>
|
144 |
+
</th>
|
145 |
+
<th>URL</th>
|
146 |
+
<th>Branch</th>
|
147 |
+
<th>Version</th>
|
148 |
+
<th>Date</th>
|
149 |
+
<th><abbr title="Use checkbox to mark the extension for update; it will be updated when you click apply button">Update</abbr></th>
|
150 |
+
</tr>
|
151 |
+
</thead>
|
152 |
+
<tbody>
|
153 |
+
"""
|
154 |
+
|
155 |
+
for ext in extensions.extensions:
|
156 |
+
ext: extensions.Extension
|
157 |
+
ext.read_info_from_repo()
|
158 |
+
|
159 |
+
remote = f"""<a href="{html.escape(ext.remote or '')}" target="_blank">{html.escape("built-in" if ext.is_builtin else ext.remote or '')}</a>"""
|
160 |
+
|
161 |
+
if ext.can_update:
|
162 |
+
ext_status = f"""<label><input class="gr-check-radio gr-checkbox" name="update_{html.escape(ext.name)}" checked="checked" type="checkbox">{html.escape(ext.status)}</label>"""
|
163 |
+
else:
|
164 |
+
ext_status = ext.status
|
165 |
+
|
166 |
+
style = ""
|
167 |
+
if shared.cmd_opts.disable_extra_extensions and not ext.is_builtin or shared.opts.disable_all_extensions == "extra" and not ext.is_builtin or shared.cmd_opts.disable_all_extensions or shared.opts.disable_all_extensions == "all":
|
168 |
+
style = STYLE_PRIMARY
|
169 |
+
|
170 |
+
version_link = ext.version
|
171 |
+
if ext.commit_hash and ext.remote:
|
172 |
+
version_link = make_commit_link(ext.commit_hash, ext.remote, ext.version)
|
173 |
+
|
174 |
+
code += f"""
|
175 |
+
<tr>
|
176 |
+
<td><label{style}><input class="gr-check-radio gr-checkbox extension_toggle" name="enable_{html.escape(ext.name)}" type="checkbox" {'checked="checked"' if ext.enabled else ''} onchange="toggle_extension(event)" />{html.escape(ext.name)}</label></td>
|
177 |
+
<td>{remote}</td>
|
178 |
+
<td>{ext.branch}</td>
|
179 |
+
<td>{version_link}</td>
|
180 |
+
<td>{datetime.fromtimestamp(ext.commit_date) if ext.commit_date else ""}</td>
|
181 |
+
<td{' class="extension_status"' if ext.remote is not None else ''}>{ext_status}</td>
|
182 |
+
</tr>
|
183 |
+
"""
|
184 |
+
|
185 |
+
code += """
|
186 |
+
</tbody>
|
187 |
+
</table>
|
188 |
+
"""
|
189 |
+
|
190 |
+
return code
|
191 |
+
|
192 |
+
|
193 |
+
def update_config_states_table(state_name):
|
194 |
+
if state_name == "Current":
|
195 |
+
config_state = config_states.get_config()
|
196 |
+
else:
|
197 |
+
config_state = config_states.all_config_states[state_name]
|
198 |
+
|
199 |
+
config_name = config_state.get("name", "Config")
|
200 |
+
created_date = datetime.fromtimestamp(config_state["created_at"]).strftime('%Y-%m-%d %H:%M:%S')
|
201 |
+
filepath = config_state.get("filepath", "<unknown>")
|
202 |
+
|
203 |
+
try:
|
204 |
+
webui_remote = config_state["webui"]["remote"] or ""
|
205 |
+
webui_branch = config_state["webui"]["branch"]
|
206 |
+
webui_commit_hash = config_state["webui"]["commit_hash"] or "<unknown>"
|
207 |
+
webui_commit_date = config_state["webui"]["commit_date"]
|
208 |
+
if webui_commit_date:
|
209 |
+
webui_commit_date = time.asctime(time.gmtime(webui_commit_date))
|
210 |
+
else:
|
211 |
+
webui_commit_date = "<unknown>"
|
212 |
+
|
213 |
+
remote = f"""<a href="{html.escape(webui_remote)}" target="_blank">{html.escape(webui_remote or '')}</a>"""
|
214 |
+
commit_link = make_commit_link(webui_commit_hash, webui_remote)
|
215 |
+
date_link = make_commit_link(webui_commit_hash, webui_remote, webui_commit_date)
|
216 |
+
|
217 |
+
current_webui = config_states.get_webui_config()
|
218 |
+
|
219 |
+
style_remote = ""
|
220 |
+
style_branch = ""
|
221 |
+
style_commit = ""
|
222 |
+
if current_webui["remote"] != webui_remote:
|
223 |
+
style_remote = STYLE_PRIMARY
|
224 |
+
if current_webui["branch"] != webui_branch:
|
225 |
+
style_branch = STYLE_PRIMARY
|
226 |
+
if current_webui["commit_hash"] != webui_commit_hash:
|
227 |
+
style_commit = STYLE_PRIMARY
|
228 |
+
|
229 |
+
code = f"""<!-- {time.time()} -->
|
230 |
+
<h2>Config Backup: {config_name}</h2>
|
231 |
+
<div><b>Filepath:</b> {filepath}</div>
|
232 |
+
<div><b>Created at:</b> {created_date}</div>
|
233 |
+
<h2>WebUI State</h2>
|
234 |
+
<table id="config_state_webui">
|
235 |
+
<thead>
|
236 |
+
<tr>
|
237 |
+
<th>URL</th>
|
238 |
+
<th>Branch</th>
|
239 |
+
<th>Commit</th>
|
240 |
+
<th>Date</th>
|
241 |
+
</tr>
|
242 |
+
</thead>
|
243 |
+
<tbody>
|
244 |
+
<tr>
|
245 |
+
<td>
|
246 |
+
<label{style_remote}>{remote}</label>
|
247 |
+
</td>
|
248 |
+
<td>
|
249 |
+
<label{style_branch}>{webui_branch}</label>
|
250 |
+
</td>
|
251 |
+
<td>
|
252 |
+
<label{style_commit}>{commit_link}</label>
|
253 |
+
</td>
|
254 |
+
<td>
|
255 |
+
<label{style_commit}>{date_link}</label>
|
256 |
+
</td>
|
257 |
+
</tr>
|
258 |
+
</tbody>
|
259 |
+
</table>
|
260 |
+
<h2>Extension State</h2>
|
261 |
+
<table id="config_state_extensions">
|
262 |
+
<thead>
|
263 |
+
<tr>
|
264 |
+
<th>Extension</th>
|
265 |
+
<th>URL</th>
|
266 |
+
<th>Branch</th>
|
267 |
+
<th>Commit</th>
|
268 |
+
<th>Date</th>
|
269 |
+
</tr>
|
270 |
+
</thead>
|
271 |
+
<tbody>
|
272 |
+
"""
|
273 |
+
|
274 |
+
ext_map = {ext.name: ext for ext in extensions.extensions}
|
275 |
+
|
276 |
+
for ext_name, ext_conf in config_state["extensions"].items():
|
277 |
+
ext_remote = ext_conf["remote"] or ""
|
278 |
+
ext_branch = ext_conf["branch"] or "<unknown>"
|
279 |
+
ext_enabled = ext_conf["enabled"]
|
280 |
+
ext_commit_hash = ext_conf["commit_hash"] or "<unknown>"
|
281 |
+
ext_commit_date = ext_conf["commit_date"]
|
282 |
+
if ext_commit_date:
|
283 |
+
ext_commit_date = time.asctime(time.gmtime(ext_commit_date))
|
284 |
+
else:
|
285 |
+
ext_commit_date = "<unknown>"
|
286 |
+
|
287 |
+
remote = f"""<a href="{html.escape(ext_remote)}" target="_blank">{html.escape(ext_remote or '')}</a>"""
|
288 |
+
commit_link = make_commit_link(ext_commit_hash, ext_remote)
|
289 |
+
date_link = make_commit_link(ext_commit_hash, ext_remote, ext_commit_date)
|
290 |
+
|
291 |
+
style_enabled = ""
|
292 |
+
style_remote = ""
|
293 |
+
style_branch = ""
|
294 |
+
style_commit = ""
|
295 |
+
if ext_name in ext_map:
|
296 |
+
current_ext = ext_map[ext_name]
|
297 |
+
current_ext.read_info_from_repo()
|
298 |
+
if current_ext.enabled != ext_enabled:
|
299 |
+
style_enabled = STYLE_PRIMARY
|
300 |
+
if current_ext.remote != ext_remote:
|
301 |
+
style_remote = STYLE_PRIMARY
|
302 |
+
if current_ext.branch != ext_branch:
|
303 |
+
style_branch = STYLE_PRIMARY
|
304 |
+
if current_ext.commit_hash != ext_commit_hash:
|
305 |
+
style_commit = STYLE_PRIMARY
|
306 |
+
|
307 |
+
code += f""" <tr>
|
308 |
+
<td><label{style_enabled}><input class="gr-check-radio gr-checkbox" type="checkbox" disabled="true" {'checked="checked"' if ext_enabled else ''}>{html.escape(ext_name)}</label></td>
|
309 |
+
<td><label{style_remote}>{remote}</label></td>
|
310 |
+
<td><label{style_branch}>{ext_branch}</label></td>
|
311 |
+
<td><label{style_commit}>{commit_link}</label></td>
|
312 |
+
<td><label{style_commit}>{date_link}</label></td>
|
313 |
+
</tr>
|
314 |
+
"""
|
315 |
+
|
316 |
+
code += """ </tbody>
|
317 |
+
</table>"""
|
318 |
+
|
319 |
+
except Exception as e:
|
320 |
+
print(f"[ERROR]: Config states {filepath}, {e}")
|
321 |
+
code = f"""<!-- {time.time()} -->
|
322 |
+
<h2>Config Backup: {config_name}</h2>
|
323 |
+
<div><b>Filepath:</b> {filepath}</div>
|
324 |
+
<div><b>Created at:</b> {created_date}</div>
|
325 |
+
<h2>This file is corrupted</h2>"""
|
326 |
+
|
327 |
+
return code
|
328 |
+
|
329 |
+
|
330 |
+
def normalize_git_url(url):
|
331 |
+
if url is None:
|
332 |
+
return ""
|
333 |
+
|
334 |
+
url = url.replace(".git", "")
|
335 |
+
return url
|
336 |
+
|
337 |
+
|
338 |
+
def get_extension_dirname_from_url(url):
|
339 |
+
*parts, last_part = url.split('/')
|
340 |
+
return normalize_git_url(last_part)
|
341 |
+
|
342 |
+
|
343 |
+
def install_extension_from_url(dirname, url, branch_name=None):
|
344 |
+
check_access()
|
345 |
+
|
346 |
+
if isinstance(dirname, str):
|
347 |
+
dirname = dirname.strip()
|
348 |
+
if isinstance(url, str):
|
349 |
+
url = url.strip()
|
350 |
+
|
351 |
+
assert url, 'No URL specified'
|
352 |
+
|
353 |
+
if dirname is None or dirname == "":
|
354 |
+
dirname = get_extension_dirname_from_url(url)
|
355 |
+
|
356 |
+
target_dir = os.path.join(extensions.extensions_dir, dirname)
|
357 |
+
assert not os.path.exists(target_dir), f'Extension directory already exists: {target_dir}'
|
358 |
+
|
359 |
+
normalized_url = normalize_git_url(url)
|
360 |
+
if any(x for x in extensions.extensions if normalize_git_url(x.remote) == normalized_url):
|
361 |
+
raise Exception(f'Extension with this URL is already installed: {url}')
|
362 |
+
|
363 |
+
tmpdir = os.path.join(paths.data_path, "tmp", dirname)
|
364 |
+
|
365 |
+
try:
|
366 |
+
shutil.rmtree(tmpdir, True)
|
367 |
+
if not branch_name:
|
368 |
+
# if no branch is specified, use the default branch
|
369 |
+
with git.Repo.clone_from(url, tmpdir, filter=['blob:none']) as repo:
|
370 |
+
repo.remote().fetch()
|
371 |
+
for submodule in repo.submodules:
|
372 |
+
submodule.update()
|
373 |
+
else:
|
374 |
+
with git.Repo.clone_from(url, tmpdir, filter=['blob:none'], branch=branch_name) as repo:
|
375 |
+
repo.remote().fetch()
|
376 |
+
for submodule in repo.submodules:
|
377 |
+
submodule.update()
|
378 |
+
try:
|
379 |
+
os.rename(tmpdir, target_dir)
|
380 |
+
except OSError as err:
|
381 |
+
if err.errno == errno.EXDEV:
|
382 |
+
# Cross device link, typical in docker or when tmp/ and extensions/ are on different file systems
|
383 |
+
# Since we can't use a rename, do the slower but more versitile shutil.move()
|
384 |
+
shutil.move(tmpdir, target_dir)
|
385 |
+
else:
|
386 |
+
# Something else, not enough free space, permissions, etc. rethrow it so that it gets handled.
|
387 |
+
raise err
|
388 |
+
|
389 |
+
import launch
|
390 |
+
launch.run_extension_installer(target_dir)
|
391 |
+
|
392 |
+
extensions.list_extensions()
|
393 |
+
return [extension_table(), html.escape(f"Installed into {target_dir}. Use Installed tab to restart.")]
|
394 |
+
finally:
|
395 |
+
shutil.rmtree(tmpdir, True)
|
396 |
+
|
397 |
+
|
398 |
+
def install_extension_from_index(url, hide_tags, sort_column, filter_text):
|
399 |
+
ext_table, message = install_extension_from_url(None, url)
|
400 |
+
|
401 |
+
code, _ = refresh_available_extensions_from_data(hide_tags, sort_column, filter_text)
|
402 |
+
|
403 |
+
return code, ext_table, message, ''
|
404 |
+
|
405 |
+
|
406 |
+
def refresh_available_extensions(url, hide_tags, sort_column):
|
407 |
+
global available_extensions
|
408 |
+
|
409 |
+
import urllib.request
|
410 |
+
with urllib.request.urlopen(url) as response:
|
411 |
+
text = response.read()
|
412 |
+
|
413 |
+
available_extensions = json.loads(text)
|
414 |
+
|
415 |
+
code, tags = refresh_available_extensions_from_data(hide_tags, sort_column)
|
416 |
+
|
417 |
+
return url, code, gr.CheckboxGroup.update(choices=tags), '', ''
|
418 |
+
|
419 |
+
|
420 |
+
def refresh_available_extensions_for_tags(hide_tags, sort_column, filter_text):
|
421 |
+
code, _ = refresh_available_extensions_from_data(hide_tags, sort_column, filter_text)
|
422 |
+
|
423 |
+
return code, ''
|
424 |
+
|
425 |
+
|
426 |
+
def search_extensions(filter_text, hide_tags, sort_column):
|
427 |
+
code, _ = refresh_available_extensions_from_data(hide_tags, sort_column, filter_text)
|
428 |
+
|
429 |
+
return code, ''
|
430 |
+
|
431 |
+
|
432 |
+
sort_ordering = [
|
433 |
+
# (reverse, order_by_function)
|
434 |
+
(True, lambda x: x.get('added', 'z')),
|
435 |
+
(False, lambda x: x.get('added', 'z')),
|
436 |
+
(False, lambda x: x.get('name', 'z')),
|
437 |
+
(True, lambda x: x.get('name', 'z')),
|
438 |
+
(False, lambda x: 'z'),
|
439 |
+
(True, lambda x: x.get('commit_time', '')),
|
440 |
+
(True, lambda x: x.get('created_at', '')),
|
441 |
+
(True, lambda x: x.get('stars', 0)),
|
442 |
+
]
|
443 |
+
|
444 |
+
|
445 |
+
def get_date(info: dict, key):
|
446 |
+
try:
|
447 |
+
return datetime.strptime(info.get(key), "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc).astimezone().strftime("%Y-%m-%d")
|
448 |
+
except (ValueError, TypeError):
|
449 |
+
return ''
|
450 |
+
|
451 |
+
|
452 |
+
def refresh_available_extensions_from_data(hide_tags, sort_column, filter_text=""):
|
453 |
+
extlist = available_extensions["extensions"]
|
454 |
+
installed_extensions = {extension.name for extension in extensions.extensions}
|
455 |
+
installed_extension_urls = {normalize_git_url(extension.remote) for extension in extensions.extensions if extension.remote is not None}
|
456 |
+
|
457 |
+
tags = available_extensions.get("tags", {})
|
458 |
+
tags_to_hide = set(hide_tags)
|
459 |
+
hidden = 0
|
460 |
+
|
461 |
+
code = f"""<!-- {time.time()} -->
|
462 |
+
<table id="available_extensions">
|
463 |
+
<thead>
|
464 |
+
<tr>
|
465 |
+
<th>Extension</th>
|
466 |
+
<th>Description</th>
|
467 |
+
<th>Action</th>
|
468 |
+
</tr>
|
469 |
+
</thead>
|
470 |
+
<tbody>
|
471 |
+
"""
|
472 |
+
|
473 |
+
sort_reverse, sort_function = sort_ordering[sort_column if 0 <= sort_column < len(sort_ordering) else 0]
|
474 |
+
|
475 |
+
for ext in sorted(extlist, key=sort_function, reverse=sort_reverse):
|
476 |
+
name = ext.get("name", "noname")
|
477 |
+
stars = int(ext.get("stars", 0))
|
478 |
+
added = ext.get('added', 'unknown')
|
479 |
+
update_time = get_date(ext, 'commit_time')
|
480 |
+
create_time = get_date(ext, 'created_at')
|
481 |
+
url = ext.get("url", None)
|
482 |
+
description = ext.get("description", "")
|
483 |
+
extension_tags = ext.get("tags", [])
|
484 |
+
|
485 |
+
if url is None:
|
486 |
+
continue
|
487 |
+
|
488 |
+
existing = get_extension_dirname_from_url(url) in installed_extensions or normalize_git_url(url) in installed_extension_urls
|
489 |
+
extension_tags = extension_tags + ["installed"] if existing else extension_tags
|
490 |
+
|
491 |
+
if any(x for x in extension_tags if x in tags_to_hide):
|
492 |
+
hidden += 1
|
493 |
+
continue
|
494 |
+
|
495 |
+
if filter_text and filter_text.strip():
|
496 |
+
if filter_text.lower() not in html.escape(name).lower() and filter_text.lower() not in html.escape(description).lower():
|
497 |
+
hidden += 1
|
498 |
+
continue
|
499 |
+
|
500 |
+
install_code = f"""<button onclick="install_extension_from_index(this, '{html.escape(url)}')" {"disabled=disabled" if existing else ""} class="lg secondary gradio-button custom-button">{"Install" if not existing else "Installed"}</button>"""
|
501 |
+
|
502 |
+
tags_text = ", ".join([f"<span class='extension-tag' title='{tags.get(x, '')}'>{x}</span>" for x in extension_tags])
|
503 |
+
|
504 |
+
code += f"""
|
505 |
+
<tr>
|
506 |
+
<td><a href="{html.escape(url)}" target="_blank">{html.escape(name)}</a><br />{tags_text}</td>
|
507 |
+
<td>{html.escape(description)}<p class="info">
|
508 |
+
<span class="date_added">Update: {html.escape(update_time)} Added: {html.escape(added)} Created: {html.escape(create_time)}</span><span class="star_count">stars: <b>{stars}</b></a></p></td>
|
509 |
+
<td>{install_code}</td>
|
510 |
+
</tr>
|
511 |
+
|
512 |
+
"""
|
513 |
+
|
514 |
+
for tag in [x for x in extension_tags if x not in tags]:
|
515 |
+
tags[tag] = tag
|
516 |
+
|
517 |
+
code += """
|
518 |
+
</tbody>
|
519 |
+
</table>
|
520 |
+
"""
|
521 |
+
|
522 |
+
if hidden > 0:
|
523 |
+
code += f"<p>Extension hidden: {hidden}</p>"
|
524 |
+
|
525 |
+
return code, list(tags)
|
526 |
+
|
527 |
+
|
528 |
+
def preload_extensions_git_metadata():
|
529 |
+
for extension in extensions.extensions:
|
530 |
+
extension.read_info_from_repo()
|
531 |
+
|
532 |
+
|
533 |
+
def create_ui():
|
534 |
+
import modules.ui
|
535 |
+
|
536 |
+
config_states.list_config_states()
|
537 |
+
|
538 |
+
threading.Thread(target=preload_extensions_git_metadata).start()
|
539 |
+
|
540 |
+
with gr.Blocks(analytics_enabled=False) as ui:
|
541 |
+
with gr.Tabs(elem_id="tabs_extensions"):
|
542 |
+
with gr.TabItem("Installed", id="installed"):
|
543 |
+
|
544 |
+
with gr.Row(elem_id="extensions_installed_top"):
|
545 |
+
apply_label = ("Apply and restart UI" if restart.is_restartable() else "Apply and quit")
|
546 |
+
apply = gr.Button(value=apply_label, variant="primary")
|
547 |
+
check = gr.Button(value="Check for updates")
|
548 |
+
extensions_disable_all = gr.Radio(label="Disable all extensions", choices=["none", "extra", "all"], value=shared.opts.disable_all_extensions, elem_id="extensions_disable_all")
|
549 |
+
extensions_disabled_list = gr.Text(elem_id="extensions_disabled_list", visible=False, container=False)
|
550 |
+
extensions_update_list = gr.Text(elem_id="extensions_update_list", visible=False, container=False)
|
551 |
+
|
552 |
+
html = ""
|
553 |
+
|
554 |
+
if shared.cmd_opts.disable_all_extensions or shared.cmd_opts.disable_extra_extensions or shared.opts.disable_all_extensions != "none":
|
555 |
+
if shared.cmd_opts.disable_all_extensions:
|
556 |
+
msg = '"--disable-all-extensions" was used, remove it to load all extensions again'
|
557 |
+
elif shared.opts.disable_all_extensions != "none":
|
558 |
+
msg = '"Disable all extensions" was set, change it to "none" to load all extensions again'
|
559 |
+
elif shared.cmd_opts.disable_extra_extensions:
|
560 |
+
msg = '"--disable-extra-extensions" was used, remove it to load all extensions again'
|
561 |
+
html = f'<span style="color: var(--primary-400);">{msg}</span>'
|
562 |
+
|
563 |
+
with gr.Row():
|
564 |
+
info = gr.HTML(html)
|
565 |
+
|
566 |
+
with gr.Row(elem_classes="progress-container"):
|
567 |
+
extensions_table = gr.HTML('Loading...', elem_id="extensions_installed_html")
|
568 |
+
|
569 |
+
ui.load(fn=extension_table, inputs=[], outputs=[extensions_table])
|
570 |
+
|
571 |
+
apply.click(
|
572 |
+
fn=apply_and_restart,
|
573 |
+
_js="extensions_apply",
|
574 |
+
inputs=[extensions_disabled_list, extensions_update_list, extensions_disable_all],
|
575 |
+
outputs=[],
|
576 |
+
)
|
577 |
+
|
578 |
+
check.click(
|
579 |
+
fn=wrap_gradio_gpu_call(check_updates, extra_outputs=[gr.update()]),
|
580 |
+
_js="extensions_check",
|
581 |
+
inputs=[info, extensions_disabled_list],
|
582 |
+
outputs=[extensions_table, info],
|
583 |
+
)
|
584 |
+
|
585 |
+
with gr.TabItem("Available", id="available"):
|
586 |
+
with gr.Row():
|
587 |
+
refresh_available_extensions_button = gr.Button(value="Load from:", variant="primary")
|
588 |
+
extensions_index_url = os.environ.get('WEBUI_EXTENSIONS_INDEX', "https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui-extensions/master/index.json")
|
589 |
+
available_extensions_index = gr.Text(value=extensions_index_url, label="Extension index URL", container=False)
|
590 |
+
extension_to_install = gr.Text(elem_id="extension_to_install", visible=False)
|
591 |
+
install_extension_button = gr.Button(elem_id="install_extension_button", visible=False)
|
592 |
+
|
593 |
+
with gr.Row():
|
594 |
+
hide_tags = gr.CheckboxGroup(value=["ads", "localization", "installed"], label="Hide extensions with tags", choices=["script", "ads", "localization", "installed"])
|
595 |
+
sort_column = gr.Radio(value="newest first", label="Order", choices=["newest first", "oldest first", "a-z", "z-a", "internal order",'update time', 'create time', "stars"], type="index")
|
596 |
+
|
597 |
+
with gr.Row():
|
598 |
+
search_extensions_text = gr.Text(label="Search", container=False)
|
599 |
+
|
600 |
+
install_result = gr.HTML()
|
601 |
+
available_extensions_table = gr.HTML()
|
602 |
+
|
603 |
+
refresh_available_extensions_button.click(
|
604 |
+
fn=modules.ui.wrap_gradio_call(refresh_available_extensions, extra_outputs=[gr.update(), gr.update(), gr.update(), gr.update()]),
|
605 |
+
inputs=[available_extensions_index, hide_tags, sort_column],
|
606 |
+
outputs=[available_extensions_index, available_extensions_table, hide_tags, search_extensions_text, install_result],
|
607 |
+
)
|
608 |
+
|
609 |
+
install_extension_button.click(
|
610 |
+
fn=modules.ui.wrap_gradio_call(install_extension_from_index, extra_outputs=[gr.update(), gr.update()]),
|
611 |
+
inputs=[extension_to_install, hide_tags, sort_column, search_extensions_text],
|
612 |
+
outputs=[available_extensions_table, extensions_table, install_result],
|
613 |
+
)
|
614 |
+
|
615 |
+
search_extensions_text.change(
|
616 |
+
fn=modules.ui.wrap_gradio_call(search_extensions, extra_outputs=[gr.update()]),
|
617 |
+
inputs=[search_extensions_text, hide_tags, sort_column],
|
618 |
+
outputs=[available_extensions_table, install_result],
|
619 |
+
)
|
620 |
+
|
621 |
+
hide_tags.change(
|
622 |
+
fn=modules.ui.wrap_gradio_call(refresh_available_extensions_for_tags, extra_outputs=[gr.update()]),
|
623 |
+
inputs=[hide_tags, sort_column, search_extensions_text],
|
624 |
+
outputs=[available_extensions_table, install_result]
|
625 |
+
)
|
626 |
+
|
627 |
+
sort_column.change(
|
628 |
+
fn=modules.ui.wrap_gradio_call(refresh_available_extensions_for_tags, extra_outputs=[gr.update()]),
|
629 |
+
inputs=[hide_tags, sort_column, search_extensions_text],
|
630 |
+
outputs=[available_extensions_table, install_result]
|
631 |
+
)
|
632 |
+
|
633 |
+
with gr.TabItem("Install from URL", id="install_from_url"):
|
634 |
+
install_url = gr.Text(label="URL for extension's git repository")
|
635 |
+
install_branch = gr.Text(label="Specific branch name", placeholder="Leave empty for default main branch")
|
636 |
+
install_dirname = gr.Text(label="Local directory name", placeholder="Leave empty for auto")
|
637 |
+
install_button = gr.Button(value="Install", variant="primary")
|
638 |
+
install_result = gr.HTML(elem_id="extension_install_result")
|
639 |
+
|
640 |
+
install_button.click(
|
641 |
+
fn=modules.ui.wrap_gradio_call(lambda *args: [gr.update(), *install_extension_from_url(*args)], extra_outputs=[gr.update(), gr.update()]),
|
642 |
+
inputs=[install_dirname, install_url, install_branch],
|
643 |
+
outputs=[install_url, extensions_table, install_result],
|
644 |
+
)
|
645 |
+
|
646 |
+
with gr.TabItem("Backup/Restore"):
|
647 |
+
with gr.Row(elem_id="extensions_backup_top_row"):
|
648 |
+
config_states_list = gr.Dropdown(label="Saved Configs", elem_id="extension_backup_saved_configs", value="Current", choices=["Current"] + list(config_states.all_config_states.keys()))
|
649 |
+
modules.ui.create_refresh_button(config_states_list, config_states.list_config_states, lambda: {"choices": ["Current"] + list(config_states.all_config_states.keys())}, "refresh_config_states")
|
650 |
+
config_restore_type = gr.Radio(label="State to restore", choices=["extensions", "webui", "both"], value="extensions", elem_id="extension_backup_restore_type")
|
651 |
+
config_restore_button = gr.Button(value="Restore Selected Config", variant="primary", elem_id="extension_backup_restore")
|
652 |
+
with gr.Row(elem_id="extensions_backup_top_row2"):
|
653 |
+
config_save_name = gr.Textbox("", placeholder="Config Name", show_label=False)
|
654 |
+
config_save_button = gr.Button(value="Save Current Config")
|
655 |
+
|
656 |
+
config_states_info = gr.HTML("")
|
657 |
+
config_states_table = gr.HTML("Loading...")
|
658 |
+
ui.load(fn=update_config_states_table, inputs=[config_states_list], outputs=[config_states_table])
|
659 |
+
|
660 |
+
config_save_button.click(fn=save_config_state, inputs=[config_save_name], outputs=[config_states_list, config_states_info])
|
661 |
+
|
662 |
+
dummy_component = gr.Label(visible=False)
|
663 |
+
config_restore_button.click(fn=restore_config_state, _js="config_state_confirm_restore", inputs=[dummy_component, config_states_list, config_restore_type], outputs=[config_states_info])
|
664 |
+
|
665 |
+
config_states_list.change(
|
666 |
+
fn=update_config_states_table,
|
667 |
+
inputs=[config_states_list],
|
668 |
+
outputs=[config_states_table],
|
669 |
+
)
|
670 |
+
|
671 |
+
|
672 |
+
return ui
|
modules/ui_extra_networks.py
ADDED
@@ -0,0 +1,482 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import functools
|
2 |
+
import os.path
|
3 |
+
import urllib.parse
|
4 |
+
from pathlib import Path
|
5 |
+
|
6 |
+
from modules import shared, ui_extra_networks_user_metadata, errors, extra_networks
|
7 |
+
from modules.images import read_info_from_image, save_image_with_geninfo
|
8 |
+
import gradio as gr
|
9 |
+
import json
|
10 |
+
import html
|
11 |
+
from fastapi.exceptions import HTTPException
|
12 |
+
|
13 |
+
from modules.generation_parameters_copypaste import image_from_url_text
|
14 |
+
from modules.ui_components import ToolButton
|
15 |
+
|
16 |
+
extra_pages = []
|
17 |
+
allowed_dirs = set()
|
18 |
+
|
19 |
+
default_allowed_preview_extensions = ["png", "jpg", "jpeg", "webp", "gif"]
|
20 |
+
|
21 |
+
|
22 |
+
@functools.cache
|
23 |
+
def allowed_preview_extensions_with_extra(extra_extensions=None):
|
24 |
+
return set(default_allowed_preview_extensions) | set(extra_extensions or [])
|
25 |
+
|
26 |
+
|
27 |
+
def allowed_preview_extensions():
|
28 |
+
return allowed_preview_extensions_with_extra((shared.opts.samples_format, ))
|
29 |
+
|
30 |
+
|
31 |
+
def register_page(page):
|
32 |
+
"""registers extra networks page for the UI; recommend doing it in on_before_ui() callback for extensions"""
|
33 |
+
|
34 |
+
extra_pages.append(page)
|
35 |
+
allowed_dirs.clear()
|
36 |
+
allowed_dirs.update(set(sum([x.allowed_directories_for_previews() for x in extra_pages], [])))
|
37 |
+
|
38 |
+
|
39 |
+
def fetch_file(filename: str = ""):
|
40 |
+
from starlette.responses import FileResponse
|
41 |
+
|
42 |
+
if not os.path.isfile(filename):
|
43 |
+
raise HTTPException(status_code=404, detail="File not found")
|
44 |
+
|
45 |
+
if not any(Path(x).absolute() in Path(filename).absolute().parents for x in allowed_dirs):
|
46 |
+
raise ValueError(f"File cannot be fetched: {filename}. Must be in one of directories registered by extra pages.")
|
47 |
+
|
48 |
+
ext = os.path.splitext(filename)[1].lower()[1:]
|
49 |
+
if ext not in allowed_preview_extensions():
|
50 |
+
raise ValueError(f"File cannot be fetched: {filename}. Extensions allowed: {allowed_preview_extensions()}.")
|
51 |
+
|
52 |
+
# would profit from returning 304
|
53 |
+
return FileResponse(filename, headers={"Accept-Ranges": "bytes"})
|
54 |
+
|
55 |
+
|
56 |
+
def get_metadata(page: str = "", item: str = ""):
|
57 |
+
from starlette.responses import JSONResponse
|
58 |
+
|
59 |
+
page = next(iter([x for x in extra_pages if x.name == page]), None)
|
60 |
+
if page is None:
|
61 |
+
return JSONResponse({})
|
62 |
+
|
63 |
+
metadata = page.metadata.get(item)
|
64 |
+
if metadata is None:
|
65 |
+
return JSONResponse({})
|
66 |
+
|
67 |
+
return JSONResponse({"metadata": json.dumps(metadata, indent=4, ensure_ascii=False)})
|
68 |
+
|
69 |
+
|
70 |
+
def get_single_card(page: str = "", tabname: str = "", name: str = ""):
|
71 |
+
from starlette.responses import JSONResponse
|
72 |
+
|
73 |
+
page = next(iter([x for x in extra_pages if x.name == page]), None)
|
74 |
+
|
75 |
+
try:
|
76 |
+
item = page.create_item(name, enable_filter=False)
|
77 |
+
page.items[name] = item
|
78 |
+
except Exception as e:
|
79 |
+
errors.display(e, "creating item for extra network")
|
80 |
+
item = page.items.get(name)
|
81 |
+
|
82 |
+
page.read_user_metadata(item)
|
83 |
+
item_html = page.create_html_for_item(item, tabname)
|
84 |
+
|
85 |
+
return JSONResponse({"html": item_html})
|
86 |
+
|
87 |
+
|
88 |
+
def add_pages_to_demo(app):
|
89 |
+
app.add_api_route("/sd_extra_networks/thumb", fetch_file, methods=["GET"])
|
90 |
+
app.add_api_route("/sd_extra_networks/metadata", get_metadata, methods=["GET"])
|
91 |
+
app.add_api_route("/sd_extra_networks/get-single-card", get_single_card, methods=["GET"])
|
92 |
+
|
93 |
+
|
94 |
+
def quote_js(s):
|
95 |
+
s = s.replace('\\', '\\\\')
|
96 |
+
s = s.replace('"', '\\"')
|
97 |
+
return f'"{s}"'
|
98 |
+
|
99 |
+
|
100 |
+
class ExtraNetworksPage:
|
101 |
+
def __init__(self, title):
|
102 |
+
self.title = title
|
103 |
+
self.name = title.lower()
|
104 |
+
self.id_page = self.name.replace(" ", "_")
|
105 |
+
self.card_page = shared.html("extra-networks-card.html")
|
106 |
+
self.allow_prompt = True
|
107 |
+
self.allow_negative_prompt = False
|
108 |
+
self.metadata = {}
|
109 |
+
self.items = {}
|
110 |
+
|
111 |
+
def refresh(self):
|
112 |
+
pass
|
113 |
+
|
114 |
+
def read_user_metadata(self, item):
|
115 |
+
filename = item.get("filename", None)
|
116 |
+
metadata = extra_networks.get_user_metadata(filename)
|
117 |
+
|
118 |
+
desc = metadata.get("description", None)
|
119 |
+
if desc is not None:
|
120 |
+
item["description"] = desc
|
121 |
+
|
122 |
+
item["user_metadata"] = metadata
|
123 |
+
|
124 |
+
def link_preview(self, filename):
|
125 |
+
quoted_filename = urllib.parse.quote(filename.replace('\\', '/'))
|
126 |
+
mtime = os.path.getmtime(filename)
|
127 |
+
return f"./sd_extra_networks/thumb?filename={quoted_filename}&mtime={mtime}"
|
128 |
+
|
129 |
+
def search_terms_from_path(self, filename, possible_directories=None):
|
130 |
+
abspath = os.path.abspath(filename)
|
131 |
+
|
132 |
+
for parentdir in (possible_directories if possible_directories is not None else self.allowed_directories_for_previews()):
|
133 |
+
parentdir = os.path.abspath(parentdir)
|
134 |
+
if abspath.startswith(parentdir):
|
135 |
+
return abspath[len(parentdir):].replace('\\', '/')
|
136 |
+
|
137 |
+
return ""
|
138 |
+
|
139 |
+
def create_html(self, tabname):
|
140 |
+
items_html = ''
|
141 |
+
|
142 |
+
self.metadata = {}
|
143 |
+
|
144 |
+
subdirs = {}
|
145 |
+
for parentdir in [os.path.abspath(x) for x in self.allowed_directories_for_previews()]:
|
146 |
+
for root, dirs, _ in sorted(os.walk(parentdir, followlinks=True), key=lambda x: shared.natural_sort_key(x[0])):
|
147 |
+
for dirname in sorted(dirs, key=shared.natural_sort_key):
|
148 |
+
x = os.path.join(root, dirname)
|
149 |
+
|
150 |
+
if not os.path.isdir(x):
|
151 |
+
continue
|
152 |
+
|
153 |
+
subdir = os.path.abspath(x)[len(parentdir):].replace("\\", "/")
|
154 |
+
|
155 |
+
if shared.opts.extra_networks_dir_button_function:
|
156 |
+
if not subdir.startswith("/"):
|
157 |
+
subdir = "/" + subdir
|
158 |
+
else:
|
159 |
+
while subdir.startswith("/"):
|
160 |
+
subdir = subdir[1:]
|
161 |
+
|
162 |
+
is_empty = len(os.listdir(x)) == 0
|
163 |
+
if not is_empty and not subdir.endswith("/"):
|
164 |
+
subdir = subdir + "/"
|
165 |
+
|
166 |
+
if ("/." in subdir or subdir.startswith(".")) and not shared.opts.extra_networks_show_hidden_directories:
|
167 |
+
continue
|
168 |
+
|
169 |
+
subdirs[subdir] = 1
|
170 |
+
|
171 |
+
if subdirs:
|
172 |
+
subdirs = {"": 1, **subdirs}
|
173 |
+
|
174 |
+
subdirs_html = "".join([f"""
|
175 |
+
<button class='lg secondary gradio-button custom-button{" search-all" if subdir=="" else ""}' onclick='extraNetworksSearchButton("{tabname}_extra_search", event)'>
|
176 |
+
{html.escape(subdir if subdir!="" else "all")}
|
177 |
+
</button>
|
178 |
+
""" for subdir in subdirs])
|
179 |
+
|
180 |
+
self.items = {x["name"]: x for x in self.list_items()}
|
181 |
+
for item in self.items.values():
|
182 |
+
metadata = item.get("metadata")
|
183 |
+
if metadata:
|
184 |
+
self.metadata[item["name"]] = metadata
|
185 |
+
|
186 |
+
if "user_metadata" not in item:
|
187 |
+
self.read_user_metadata(item)
|
188 |
+
|
189 |
+
items_html += self.create_html_for_item(item, tabname)
|
190 |
+
|
191 |
+
if items_html == '':
|
192 |
+
dirs = "".join([f"<li>{x}</li>" for x in self.allowed_directories_for_previews()])
|
193 |
+
items_html = shared.html("extra-networks-no-cards.html").format(dirs=dirs)
|
194 |
+
|
195 |
+
self_name_id = self.name.replace(" ", "_")
|
196 |
+
|
197 |
+
res = f"""
|
198 |
+
<div id='{tabname}_{self_name_id}_subdirs' class='extra-network-subdirs extra-network-subdirs-cards'>
|
199 |
+
{subdirs_html}
|
200 |
+
</div>
|
201 |
+
<div id='{tabname}_{self_name_id}_cards' class='extra-network-cards'>
|
202 |
+
{items_html}
|
203 |
+
</div>
|
204 |
+
"""
|
205 |
+
|
206 |
+
return res
|
207 |
+
|
208 |
+
def create_item(self, name, index=None):
|
209 |
+
raise NotImplementedError()
|
210 |
+
|
211 |
+
def list_items(self):
|
212 |
+
raise NotImplementedError()
|
213 |
+
|
214 |
+
def allowed_directories_for_previews(self):
|
215 |
+
return []
|
216 |
+
|
217 |
+
def create_html_for_item(self, item, tabname):
|
218 |
+
"""
|
219 |
+
Create HTML for card item in tab tabname; can return empty string if the item is not meant to be shown.
|
220 |
+
"""
|
221 |
+
|
222 |
+
preview = item.get("preview", None)
|
223 |
+
|
224 |
+
onclick = item.get("onclick", None)
|
225 |
+
if onclick is None:
|
226 |
+
onclick = '"' + html.escape(f"""return cardClicked({quote_js(tabname)}, {item["prompt"]}, {"true" if self.allow_negative_prompt else "false"})""") + '"'
|
227 |
+
|
228 |
+
height = f"height: {shared.opts.extra_networks_card_height}px;" if shared.opts.extra_networks_card_height else ''
|
229 |
+
width = f"width: {shared.opts.extra_networks_card_width}px;" if shared.opts.extra_networks_card_width else ''
|
230 |
+
background_image = f'<img src="{html.escape(preview)}" class="preview" loading="lazy">' if preview else ''
|
231 |
+
metadata_button = ""
|
232 |
+
metadata = item.get("metadata")
|
233 |
+
if metadata:
|
234 |
+
metadata_button = f"<div class='metadata-button card-button' title='Show internal metadata' onclick='extraNetworksRequestMetadata(event, {quote_js(self.name)}, {quote_js(html.escape(item['name']))})'></div>"
|
235 |
+
|
236 |
+
edit_button = f"<div class='edit-button card-button' title='Edit metadata' onclick='extraNetworksEditUserMetadata(event, {quote_js(tabname)}, {quote_js(self.id_page)}, {quote_js(html.escape(item['name']))})'></div>"
|
237 |
+
|
238 |
+
local_path = ""
|
239 |
+
filename = item.get("filename", "")
|
240 |
+
for reldir in self.allowed_directories_for_previews():
|
241 |
+
absdir = os.path.abspath(reldir)
|
242 |
+
|
243 |
+
if filename.startswith(absdir):
|
244 |
+
local_path = filename[len(absdir):]
|
245 |
+
|
246 |
+
# if this is true, the item must not be shown in the default view, and must instead only be
|
247 |
+
# shown when searching for it
|
248 |
+
if shared.opts.extra_networks_hidden_models == "Always":
|
249 |
+
search_only = False
|
250 |
+
else:
|
251 |
+
search_only = "/." in local_path or "\\." in local_path
|
252 |
+
|
253 |
+
if search_only and shared.opts.extra_networks_hidden_models == "Never":
|
254 |
+
return ""
|
255 |
+
|
256 |
+
sort_keys = " ".join([f'data-sort-{k}="{html.escape(str(v))}"' for k, v in item.get("sort_keys", {}).items()]).strip()
|
257 |
+
|
258 |
+
args = {
|
259 |
+
"background_image": background_image,
|
260 |
+
"style": f"'display: none; {height}{width}; font-size: {shared.opts.extra_networks_card_text_scale*100}%'",
|
261 |
+
"prompt": item.get("prompt", None),
|
262 |
+
"tabname": quote_js(tabname),
|
263 |
+
"local_preview": quote_js(item["local_preview"]),
|
264 |
+
"name": html.escape(item["name"]),
|
265 |
+
"description": (item.get("description") or "" if shared.opts.extra_networks_card_show_desc else ""),
|
266 |
+
"card_clicked": onclick,
|
267 |
+
"save_card_preview": '"' + html.escape(f"""return saveCardPreview(event, {quote_js(tabname)}, {quote_js(item["local_preview"])})""") + '"',
|
268 |
+
"search_term": item.get("search_term", ""),
|
269 |
+
"metadata_button": metadata_button,
|
270 |
+
"edit_button": edit_button,
|
271 |
+
"search_only": " search_only" if search_only else "",
|
272 |
+
"sort_keys": sort_keys,
|
273 |
+
}
|
274 |
+
|
275 |
+
return self.card_page.format(**args)
|
276 |
+
|
277 |
+
def get_sort_keys(self, path):
|
278 |
+
"""
|
279 |
+
List of default keys used for sorting in the UI.
|
280 |
+
"""
|
281 |
+
pth = Path(path)
|
282 |
+
stat = pth.stat()
|
283 |
+
return {
|
284 |
+
"date_created": int(stat.st_ctime or 0),
|
285 |
+
"date_modified": int(stat.st_mtime or 0),
|
286 |
+
"name": pth.name.lower(),
|
287 |
+
"path": str(pth.parent).lower(),
|
288 |
+
}
|
289 |
+
|
290 |
+
def find_preview(self, path):
|
291 |
+
"""
|
292 |
+
Find a preview PNG for a given path (without extension) and call link_preview on it.
|
293 |
+
"""
|
294 |
+
|
295 |
+
potential_files = sum([[path + "." + ext, path + ".preview." + ext] for ext in allowed_preview_extensions()], [])
|
296 |
+
|
297 |
+
for file in potential_files:
|
298 |
+
if os.path.isfile(file):
|
299 |
+
return self.link_preview(file)
|
300 |
+
|
301 |
+
return None
|
302 |
+
|
303 |
+
def find_description(self, path):
|
304 |
+
"""
|
305 |
+
Find and read a description file for a given path (without extension).
|
306 |
+
"""
|
307 |
+
for file in [f"{path}.txt", f"{path}.description.txt"]:
|
308 |
+
try:
|
309 |
+
with open(file, "r", encoding="utf-8", errors="replace") as f:
|
310 |
+
return f.read()
|
311 |
+
except OSError:
|
312 |
+
pass
|
313 |
+
return None
|
314 |
+
|
315 |
+
def create_user_metadata_editor(self, ui, tabname):
|
316 |
+
return ui_extra_networks_user_metadata.UserMetadataEditor(ui, tabname, self)
|
317 |
+
|
318 |
+
|
319 |
+
def initialize():
|
320 |
+
extra_pages.clear()
|
321 |
+
|
322 |
+
|
323 |
+
def register_default_pages():
|
324 |
+
from modules.ui_extra_networks_textual_inversion import ExtraNetworksPageTextualInversion
|
325 |
+
from modules.ui_extra_networks_hypernets import ExtraNetworksPageHypernetworks
|
326 |
+
from modules.ui_extra_networks_checkpoints import ExtraNetworksPageCheckpoints
|
327 |
+
register_page(ExtraNetworksPageTextualInversion())
|
328 |
+
register_page(ExtraNetworksPageHypernetworks())
|
329 |
+
register_page(ExtraNetworksPageCheckpoints())
|
330 |
+
|
331 |
+
|
332 |
+
class ExtraNetworksUi:
|
333 |
+
def __init__(self):
|
334 |
+
self.pages = None
|
335 |
+
"""gradio HTML components related to extra networks' pages"""
|
336 |
+
|
337 |
+
self.page_contents = None
|
338 |
+
"""HTML content of the above; empty initially, filled when extra pages have to be shown"""
|
339 |
+
|
340 |
+
self.stored_extra_pages = None
|
341 |
+
|
342 |
+
self.button_save_preview = None
|
343 |
+
self.preview_target_filename = None
|
344 |
+
|
345 |
+
self.tabname = None
|
346 |
+
|
347 |
+
|
348 |
+
def pages_in_preferred_order(pages):
|
349 |
+
tab_order = [x.lower().strip() for x in shared.opts.ui_extra_networks_tab_reorder.split(",")]
|
350 |
+
|
351 |
+
def tab_name_score(name):
|
352 |
+
name = name.lower()
|
353 |
+
for i, possible_match in enumerate(tab_order):
|
354 |
+
if possible_match in name:
|
355 |
+
return i
|
356 |
+
|
357 |
+
return len(pages)
|
358 |
+
|
359 |
+
tab_scores = {page.name: (tab_name_score(page.name), original_index) for original_index, page in enumerate(pages)}
|
360 |
+
|
361 |
+
return sorted(pages, key=lambda x: tab_scores[x.name])
|
362 |
+
|
363 |
+
|
364 |
+
def create_ui(interface: gr.Blocks, unrelated_tabs, tabname):
|
365 |
+
from modules.ui import switch_values_symbol
|
366 |
+
|
367 |
+
ui = ExtraNetworksUi()
|
368 |
+
ui.pages = []
|
369 |
+
ui.pages_contents = []
|
370 |
+
ui.user_metadata_editors = []
|
371 |
+
ui.stored_extra_pages = pages_in_preferred_order(extra_pages.copy())
|
372 |
+
ui.tabname = tabname
|
373 |
+
|
374 |
+
related_tabs = []
|
375 |
+
|
376 |
+
for page in ui.stored_extra_pages:
|
377 |
+
with gr.Tab(page.title, elem_id=f"{tabname}_{page.id_page}", elem_classes=["extra-page"]) as tab:
|
378 |
+
with gr.Column(elem_id=f"{tabname}_{page.id_page}_prompts", elem_classes=["extra-page-prompts"]):
|
379 |
+
pass
|
380 |
+
|
381 |
+
elem_id = f"{tabname}_{page.id_page}_cards_html"
|
382 |
+
page_elem = gr.HTML('Loading...', elem_id=elem_id)
|
383 |
+
ui.pages.append(page_elem)
|
384 |
+
|
385 |
+
page_elem.change(fn=lambda: None, _js='function(){applyExtraNetworkFilter(' + quote_js(tabname) + '); return []}', inputs=[], outputs=[])
|
386 |
+
|
387 |
+
editor = page.create_user_metadata_editor(ui, tabname)
|
388 |
+
editor.create_ui()
|
389 |
+
ui.user_metadata_editors.append(editor)
|
390 |
+
|
391 |
+
related_tabs.append(tab)
|
392 |
+
|
393 |
+
edit_search = gr.Textbox('', show_label=False, elem_id=tabname+"_extra_search", elem_classes="search", placeholder="Search...", visible=False, interactive=True)
|
394 |
+
dropdown_sort = gr.Dropdown(choices=['Path', 'Name', 'Date Created', 'Date Modified', ], value=shared.opts.extra_networks_card_order_field, elem_id=tabname+"_extra_sort", elem_classes="sort", multiselect=False, visible=False, show_label=False, interactive=True, label=tabname+"_extra_sort_order")
|
395 |
+
button_sortorder = ToolButton(switch_values_symbol, elem_id=tabname+"_extra_sortorder", elem_classes=["sortorder"] + ([] if shared.opts.extra_networks_card_order == "Ascending" else ["sortReverse"]), visible=False, tooltip="Invert sort order")
|
396 |
+
button_refresh = gr.Button('Refresh', elem_id=tabname+"_extra_refresh", visible=False)
|
397 |
+
checkbox_show_dirs = gr.Checkbox(True, label='Show dirs', elem_id=tabname+"_extra_show_dirs", elem_classes="show-dirs", visible=False)
|
398 |
+
|
399 |
+
ui.button_save_preview = gr.Button('Save preview', elem_id=tabname+"_save_preview", visible=False)
|
400 |
+
ui.preview_target_filename = gr.Textbox('Preview save filename', elem_id=tabname+"_preview_filename", visible=False)
|
401 |
+
|
402 |
+
tab_controls = [edit_search, dropdown_sort, button_sortorder, button_refresh, checkbox_show_dirs]
|
403 |
+
|
404 |
+
for tab in unrelated_tabs:
|
405 |
+
tab.select(fn=lambda: [gr.update(visible=False) for _ in tab_controls], _js='function(){ extraNetworksUrelatedTabSelected("' + tabname + '"); }', inputs=[], outputs=tab_controls, show_progress=False)
|
406 |
+
|
407 |
+
for page, tab in zip(ui.stored_extra_pages, related_tabs):
|
408 |
+
allow_prompt = "true" if page.allow_prompt else "false"
|
409 |
+
allow_negative_prompt = "true" if page.allow_negative_prompt else "false"
|
410 |
+
|
411 |
+
jscode = 'extraNetworksTabSelected("' + tabname + '", "' + f"{tabname}_{page.id_page}_prompts" + '", ' + allow_prompt + ', ' + allow_negative_prompt + ');'
|
412 |
+
|
413 |
+
tab.select(fn=lambda: [gr.update(visible=True) for _ in tab_controls], _js='function(){ ' + jscode + ' }', inputs=[], outputs=tab_controls, show_progress=False)
|
414 |
+
|
415 |
+
dropdown_sort.change(fn=lambda: None, _js="function(){ applyExtraNetworkSort('" + tabname + "'); }")
|
416 |
+
|
417 |
+
def pages_html():
|
418 |
+
if not ui.pages_contents:
|
419 |
+
return refresh()
|
420 |
+
|
421 |
+
return ui.pages_contents
|
422 |
+
|
423 |
+
def refresh():
|
424 |
+
for pg in ui.stored_extra_pages:
|
425 |
+
pg.refresh()
|
426 |
+
|
427 |
+
ui.pages_contents = [pg.create_html(ui.tabname) for pg in ui.stored_extra_pages]
|
428 |
+
|
429 |
+
return ui.pages_contents
|
430 |
+
|
431 |
+
interface.load(fn=pages_html, inputs=[], outputs=[*ui.pages])
|
432 |
+
button_refresh.click(fn=refresh, inputs=[], outputs=ui.pages)
|
433 |
+
|
434 |
+
return ui
|
435 |
+
|
436 |
+
|
437 |
+
def path_is_parent(parent_path, child_path):
|
438 |
+
parent_path = os.path.abspath(parent_path)
|
439 |
+
child_path = os.path.abspath(child_path)
|
440 |
+
|
441 |
+
return child_path.startswith(parent_path)
|
442 |
+
|
443 |
+
|
444 |
+
def setup_ui(ui, gallery):
|
445 |
+
def save_preview(index, images, filename):
|
446 |
+
# this function is here for backwards compatibility and likely will be removed soon
|
447 |
+
|
448 |
+
if len(images) == 0:
|
449 |
+
print("There is no image in gallery to save as a preview.")
|
450 |
+
return [page.create_html(ui.tabname) for page in ui.stored_extra_pages]
|
451 |
+
|
452 |
+
index = int(index)
|
453 |
+
index = 0 if index < 0 else index
|
454 |
+
index = len(images) - 1 if index >= len(images) else index
|
455 |
+
|
456 |
+
img_info = images[index if index >= 0 else 0]
|
457 |
+
image = image_from_url_text(img_info)
|
458 |
+
geninfo, items = read_info_from_image(image)
|
459 |
+
|
460 |
+
is_allowed = False
|
461 |
+
for extra_page in ui.stored_extra_pages:
|
462 |
+
if any(path_is_parent(x, filename) for x in extra_page.allowed_directories_for_previews()):
|
463 |
+
is_allowed = True
|
464 |
+
break
|
465 |
+
|
466 |
+
assert is_allowed, f'writing to {filename} is not allowed'
|
467 |
+
|
468 |
+
save_image_with_geninfo(image, geninfo, filename)
|
469 |
+
|
470 |
+
return [page.create_html(ui.tabname) for page in ui.stored_extra_pages]
|
471 |
+
|
472 |
+
ui.button_save_preview.click(
|
473 |
+
fn=save_preview,
|
474 |
+
_js="function(x, y, z){return [selected_gallery_index(), y, z]}",
|
475 |
+
inputs=[ui.preview_target_filename, gallery, ui.preview_target_filename],
|
476 |
+
outputs=[*ui.pages]
|
477 |
+
)
|
478 |
+
|
479 |
+
for editor in ui.user_metadata_editors:
|
480 |
+
editor.setup_ui(gallery)
|
481 |
+
|
482 |
+
|
modules/ui_loadsave.py
ADDED
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import os
|
3 |
+
|
4 |
+
import gradio as gr
|
5 |
+
|
6 |
+
from modules import errors
|
7 |
+
from modules.ui_components import ToolButton, InputAccordion
|
8 |
+
|
9 |
+
|
10 |
+
def radio_choices(comp): # gradio 3.41 changes choices from list of values to list of pairs
|
11 |
+
return [x[0] if isinstance(x, tuple) else x for x in getattr(comp, 'choices', [])]
|
12 |
+
|
13 |
+
|
14 |
+
class UiLoadsave:
|
15 |
+
"""allows saving and restoring default values for gradio components"""
|
16 |
+
|
17 |
+
def __init__(self, filename):
|
18 |
+
self.filename = filename
|
19 |
+
self.ui_settings = {}
|
20 |
+
self.component_mapping = {}
|
21 |
+
self.error_loading = False
|
22 |
+
self.finalized_ui = False
|
23 |
+
|
24 |
+
self.ui_defaults_view = None
|
25 |
+
self.ui_defaults_apply = None
|
26 |
+
self.ui_defaults_review = None
|
27 |
+
|
28 |
+
try:
|
29 |
+
if os.path.exists(self.filename):
|
30 |
+
self.ui_settings = self.read_from_file()
|
31 |
+
except Exception as e:
|
32 |
+
self.error_loading = True
|
33 |
+
errors.display(e, "loading settings")
|
34 |
+
|
35 |
+
def add_component(self, path, x):
|
36 |
+
"""adds component to the registry of tracked components"""
|
37 |
+
|
38 |
+
assert not self.finalized_ui
|
39 |
+
|
40 |
+
def apply_field(obj, field, condition=None, init_field=None):
|
41 |
+
key = f"{path}/{field}"
|
42 |
+
|
43 |
+
if getattr(obj, 'custom_script_source', None) is not None:
|
44 |
+
key = f"customscript/{obj.custom_script_source}/{key}"
|
45 |
+
|
46 |
+
if getattr(obj, 'do_not_save_to_config', False):
|
47 |
+
return
|
48 |
+
|
49 |
+
saved_value = self.ui_settings.get(key, None)
|
50 |
+
|
51 |
+
if isinstance(obj, gr.Accordion) and isinstance(x, InputAccordion) and field == 'value':
|
52 |
+
field = 'open'
|
53 |
+
|
54 |
+
if saved_value is None:
|
55 |
+
self.ui_settings[key] = getattr(obj, field)
|
56 |
+
elif condition and not condition(saved_value):
|
57 |
+
pass
|
58 |
+
else:
|
59 |
+
if isinstance(obj, gr.Textbox) and field == 'value': # due to an undesirable behavior of gr.Textbox, if you give it an int value instead of str, everything dies
|
60 |
+
saved_value = str(saved_value)
|
61 |
+
elif isinstance(obj, gr.Number) and field == 'value':
|
62 |
+
try:
|
63 |
+
saved_value = float(saved_value)
|
64 |
+
except ValueError:
|
65 |
+
return
|
66 |
+
|
67 |
+
setattr(obj, field, saved_value)
|
68 |
+
if init_field is not None:
|
69 |
+
init_field(saved_value)
|
70 |
+
|
71 |
+
if field == 'value' and key not in self.component_mapping:
|
72 |
+
self.component_mapping[key] = obj
|
73 |
+
|
74 |
+
if type(x) in [gr.Slider, gr.Radio, gr.Checkbox, gr.Textbox, gr.Number, gr.Dropdown, ToolButton, gr.Button] and x.visible:
|
75 |
+
apply_field(x, 'visible')
|
76 |
+
|
77 |
+
if type(x) == gr.Slider:
|
78 |
+
apply_field(x, 'value')
|
79 |
+
apply_field(x, 'minimum')
|
80 |
+
apply_field(x, 'maximum')
|
81 |
+
apply_field(x, 'step')
|
82 |
+
|
83 |
+
if type(x) == gr.Radio:
|
84 |
+
apply_field(x, 'value', lambda val: val in radio_choices(x))
|
85 |
+
|
86 |
+
if type(x) == gr.Checkbox:
|
87 |
+
apply_field(x, 'value')
|
88 |
+
|
89 |
+
if type(x) == gr.Textbox:
|
90 |
+
apply_field(x, 'value')
|
91 |
+
|
92 |
+
if type(x) == gr.Number:
|
93 |
+
apply_field(x, 'value')
|
94 |
+
|
95 |
+
if type(x) == gr.Dropdown:
|
96 |
+
def check_dropdown(val):
|
97 |
+
choices = radio_choices(x)
|
98 |
+
if getattr(x, 'multiselect', False):
|
99 |
+
return all(value in choices for value in val)
|
100 |
+
else:
|
101 |
+
return val in choices
|
102 |
+
|
103 |
+
apply_field(x, 'value', check_dropdown, getattr(x, 'init_field', None))
|
104 |
+
|
105 |
+
if type(x) == InputAccordion:
|
106 |
+
if x.accordion.visible:
|
107 |
+
apply_field(x.accordion, 'visible')
|
108 |
+
apply_field(x, 'value')
|
109 |
+
apply_field(x.accordion, 'value')
|
110 |
+
|
111 |
+
def check_tab_id(tab_id):
|
112 |
+
tab_items = list(filter(lambda e: isinstance(e, gr.TabItem), x.children))
|
113 |
+
if type(tab_id) == str:
|
114 |
+
tab_ids = [t.id for t in tab_items]
|
115 |
+
return tab_id in tab_ids
|
116 |
+
elif type(tab_id) == int:
|
117 |
+
return 0 <= tab_id < len(tab_items)
|
118 |
+
else:
|
119 |
+
return False
|
120 |
+
|
121 |
+
if type(x) == gr.Tabs:
|
122 |
+
apply_field(x, 'selected', check_tab_id)
|
123 |
+
|
124 |
+
def add_block(self, x, path=""):
|
125 |
+
"""adds all components inside a gradio block x to the registry of tracked components"""
|
126 |
+
|
127 |
+
if hasattr(x, 'children'):
|
128 |
+
if isinstance(x, gr.Tabs) and x.elem_id is not None:
|
129 |
+
# Tabs element can't have a label, have to use elem_id instead
|
130 |
+
self.add_component(f"{path}/Tabs@{x.elem_id}", x)
|
131 |
+
for c in x.children:
|
132 |
+
self.add_block(c, path)
|
133 |
+
elif x.label is not None:
|
134 |
+
self.add_component(f"{path}/{x.label}", x)
|
135 |
+
elif isinstance(x, gr.Button) and x.value is not None:
|
136 |
+
self.add_component(f"{path}/{x.value}", x)
|
137 |
+
|
138 |
+
def read_from_file(self):
|
139 |
+
with open(self.filename, "r", encoding="utf8") as file:
|
140 |
+
return json.load(file)
|
141 |
+
|
142 |
+
def write_to_file(self, current_ui_settings):
|
143 |
+
with open(self.filename, "w", encoding="utf8") as file:
|
144 |
+
json.dump(current_ui_settings, file, indent=4, ensure_ascii=False)
|
145 |
+
|
146 |
+
def dump_defaults(self):
|
147 |
+
"""saves default values to a file unless tjhe file is present and there was an error loading default values at start"""
|
148 |
+
|
149 |
+
if self.error_loading and os.path.exists(self.filename):
|
150 |
+
return
|
151 |
+
|
152 |
+
self.write_to_file(self.ui_settings)
|
153 |
+
|
154 |
+
def iter_changes(self, current_ui_settings, values):
|
155 |
+
"""
|
156 |
+
given a dictionary with defaults from a file and current values from gradio elements, returns
|
157 |
+
an iterator over tuples of values that are not the same between the file and the current;
|
158 |
+
tuple contents are: path, old value, new value
|
159 |
+
"""
|
160 |
+
|
161 |
+
for (path, component), new_value in zip(self.component_mapping.items(), values):
|
162 |
+
old_value = current_ui_settings.get(path)
|
163 |
+
|
164 |
+
choices = radio_choices(component)
|
165 |
+
if isinstance(new_value, int) and choices:
|
166 |
+
if new_value >= len(choices):
|
167 |
+
continue
|
168 |
+
|
169 |
+
new_value = choices[new_value]
|
170 |
+
if isinstance(new_value, tuple):
|
171 |
+
new_value = new_value[0]
|
172 |
+
|
173 |
+
if new_value == old_value:
|
174 |
+
continue
|
175 |
+
|
176 |
+
if old_value is None and new_value == '' or new_value == []:
|
177 |
+
continue
|
178 |
+
|
179 |
+
yield path, old_value, new_value
|
180 |
+
|
181 |
+
def ui_view(self, *values):
|
182 |
+
text = ["<table><thead><tr><th>Path</th><th>Old value</th><th>New value</th></thead><tbody>"]
|
183 |
+
|
184 |
+
for path, old_value, new_value in self.iter_changes(self.read_from_file(), values):
|
185 |
+
if old_value is None:
|
186 |
+
old_value = "<span class='ui-defaults-none'>None</span>"
|
187 |
+
|
188 |
+
text.append(f"<tr><td>{path}</td><td>{old_value}</td><td>{new_value}</td></tr>")
|
189 |
+
|
190 |
+
if len(text) == 1:
|
191 |
+
text.append("<tr><td colspan=3>No changes</td></tr>")
|
192 |
+
|
193 |
+
text.append("</tbody>")
|
194 |
+
return "".join(text)
|
195 |
+
|
196 |
+
def ui_apply(self, *values):
|
197 |
+
num_changed = 0
|
198 |
+
|
199 |
+
current_ui_settings = self.read_from_file()
|
200 |
+
|
201 |
+
for path, _, new_value in self.iter_changes(current_ui_settings.copy(), values):
|
202 |
+
num_changed += 1
|
203 |
+
current_ui_settings[path] = new_value
|
204 |
+
|
205 |
+
if num_changed == 0:
|
206 |
+
return "No changes."
|
207 |
+
|
208 |
+
self.write_to_file(current_ui_settings)
|
209 |
+
|
210 |
+
return f"Wrote {num_changed} changes."
|
211 |
+
|
212 |
+
def create_ui(self):
|
213 |
+
"""creates ui elements for editing defaults UI, without adding any logic to them"""
|
214 |
+
|
215 |
+
gr.HTML(
|
216 |
+
f"This page allows you to change default values in UI elements on other tabs.<br />"
|
217 |
+
f"Make your changes, press 'View changes' to review the changed default values,<br />"
|
218 |
+
f"then press 'Apply' to write them to {self.filename}.<br />"
|
219 |
+
f"New defaults will apply after you restart the UI.<br />"
|
220 |
+
)
|
221 |
+
|
222 |
+
with gr.Row():
|
223 |
+
self.ui_defaults_view = gr.Button(value='View changes', elem_id="ui_defaults_view", variant="secondary")
|
224 |
+
self.ui_defaults_apply = gr.Button(value='Apply', elem_id="ui_defaults_apply", variant="primary")
|
225 |
+
|
226 |
+
self.ui_defaults_review = gr.HTML("")
|
227 |
+
|
228 |
+
def setup_ui(self):
|
229 |
+
"""adds logic to elements created with create_ui; all add_block class must be made before this"""
|
230 |
+
|
231 |
+
assert not self.finalized_ui
|
232 |
+
self.finalized_ui = True
|
233 |
+
|
234 |
+
self.ui_defaults_view.click(fn=self.ui_view, inputs=list(self.component_mapping.values()), outputs=[self.ui_defaults_review])
|
235 |
+
self.ui_defaults_apply.click(fn=self.ui_apply, inputs=list(self.component_mapping.values()), outputs=[self.ui_defaults_review])
|
modules/ui_postprocessing.py
ADDED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from modules import scripts, shared, ui_common, postprocessing, call_queue, ui_toprow
|
3 |
+
import modules.generation_parameters_copypaste as parameters_copypaste
|
4 |
+
|
5 |
+
|
6 |
+
def create_ui():
|
7 |
+
dummy_component = gr.Label(visible=False)
|
8 |
+
tab_index = gr.State(value=0)
|
9 |
+
|
10 |
+
with gr.Row(equal_height=False, variant='compact'):
|
11 |
+
with gr.Column(variant='compact'):
|
12 |
+
with gr.Tabs(elem_id="mode_extras"):
|
13 |
+
with gr.TabItem('Single Image', id="single_image", elem_id="extras_single_tab") as tab_single:
|
14 |
+
extras_image = gr.Image(label="Source", source="upload", interactive=True, type="pil", elem_id="extras_image")
|
15 |
+
|
16 |
+
with gr.TabItem('Batch Process', id="batch_process", elem_id="extras_batch_process_tab") as tab_batch:
|
17 |
+
image_batch = gr.Files(label="Batch Process", interactive=True, elem_id="extras_image_batch")
|
18 |
+
|
19 |
+
with gr.TabItem('Batch from Directory', id="batch_from_directory", elem_id="extras_batch_directory_tab") as tab_batch_dir:
|
20 |
+
extras_batch_input_dir = gr.Textbox(label="Input directory", **shared.hide_dirs, placeholder="A directory on the same machine where the server is running.", elem_id="extras_batch_input_dir")
|
21 |
+
extras_batch_output_dir = gr.Textbox(label="Output directory", **shared.hide_dirs, placeholder="Leave blank to save images to the default path.", elem_id="extras_batch_output_dir")
|
22 |
+
show_extras_results = gr.Checkbox(label='Show result images', value=True, elem_id="extras_show_extras_results")
|
23 |
+
|
24 |
+
script_inputs = scripts.scripts_postproc.setup_ui()
|
25 |
+
|
26 |
+
with gr.Column():
|
27 |
+
toprow = ui_toprow.Toprow(is_compact=True, is_img2img=False, id_part="extras")
|
28 |
+
toprow.create_inline_toprow_image()
|
29 |
+
submit = toprow.submit
|
30 |
+
|
31 |
+
result_images, html_info_x, html_info, html_log = ui_common.create_output_panel("extras", shared.opts.outdir_extras_samples)
|
32 |
+
|
33 |
+
tab_single.select(fn=lambda: 0, inputs=[], outputs=[tab_index])
|
34 |
+
tab_batch.select(fn=lambda: 1, inputs=[], outputs=[tab_index])
|
35 |
+
tab_batch_dir.select(fn=lambda: 2, inputs=[], outputs=[tab_index])
|
36 |
+
|
37 |
+
submit.click(
|
38 |
+
fn=call_queue.wrap_gradio_gpu_call(postprocessing.run_postprocessing_webui, extra_outputs=[None, '']),
|
39 |
+
_js="submit_extras",
|
40 |
+
inputs=[
|
41 |
+
dummy_component,
|
42 |
+
tab_index,
|
43 |
+
extras_image,
|
44 |
+
image_batch,
|
45 |
+
extras_batch_input_dir,
|
46 |
+
extras_batch_output_dir,
|
47 |
+
show_extras_results,
|
48 |
+
*script_inputs
|
49 |
+
],
|
50 |
+
outputs=[
|
51 |
+
result_images,
|
52 |
+
html_info_x,
|
53 |
+
html_log,
|
54 |
+
],
|
55 |
+
show_progress=False,
|
56 |
+
)
|
57 |
+
|
58 |
+
parameters_copypaste.add_paste_fields("extras", extras_image, None)
|
59 |
+
|
60 |
+
extras_image.change(
|
61 |
+
fn=scripts.scripts_postproc.image_changed,
|
62 |
+
inputs=[], outputs=[]
|
63 |
+
)
|
modules/ui_prompt_styles.py
ADDED
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
|
3 |
+
from modules import shared, ui_common, ui_components, styles
|
4 |
+
|
5 |
+
styles_edit_symbol = '\U0001f58c\uFE0F' # 🖌️
|
6 |
+
styles_materialize_symbol = '\U0001f4cb' # 📋
|
7 |
+
styles_copy_symbol = '\U0001f4dd' # 📝
|
8 |
+
|
9 |
+
|
10 |
+
def select_style(name):
|
11 |
+
style = shared.prompt_styles.styles.get(name)
|
12 |
+
existing = style is not None
|
13 |
+
empty = not name
|
14 |
+
|
15 |
+
prompt = style.prompt if style else gr.update()
|
16 |
+
negative_prompt = style.negative_prompt if style else gr.update()
|
17 |
+
|
18 |
+
return prompt, negative_prompt, gr.update(visible=existing), gr.update(visible=not empty)
|
19 |
+
|
20 |
+
|
21 |
+
def save_style(name, prompt, negative_prompt):
|
22 |
+
if not name:
|
23 |
+
return gr.update(visible=False)
|
24 |
+
|
25 |
+
style = styles.PromptStyle(name, prompt, negative_prompt)
|
26 |
+
shared.prompt_styles.styles[style.name] = style
|
27 |
+
shared.prompt_styles.save_styles(shared.styles_filename)
|
28 |
+
|
29 |
+
return gr.update(visible=True)
|
30 |
+
|
31 |
+
|
32 |
+
def delete_style(name):
|
33 |
+
if name == "":
|
34 |
+
return
|
35 |
+
|
36 |
+
shared.prompt_styles.styles.pop(name, None)
|
37 |
+
shared.prompt_styles.save_styles(shared.styles_filename)
|
38 |
+
|
39 |
+
return '', '', ''
|
40 |
+
|
41 |
+
|
42 |
+
def materialize_styles(prompt, negative_prompt, styles):
|
43 |
+
prompt = shared.prompt_styles.apply_styles_to_prompt(prompt, styles)
|
44 |
+
negative_prompt = shared.prompt_styles.apply_negative_styles_to_prompt(negative_prompt, styles)
|
45 |
+
|
46 |
+
return [gr.Textbox.update(value=prompt), gr.Textbox.update(value=negative_prompt), gr.Dropdown.update(value=[])]
|
47 |
+
|
48 |
+
|
49 |
+
def refresh_styles():
|
50 |
+
return gr.update(choices=list(shared.prompt_styles.styles)), gr.update(choices=list(shared.prompt_styles.styles))
|
51 |
+
|
52 |
+
|
53 |
+
class UiPromptStyles:
|
54 |
+
def __init__(self, tabname, main_ui_prompt, main_ui_negative_prompt):
|
55 |
+
self.tabname = tabname
|
56 |
+
self.main_ui_prompt = main_ui_prompt
|
57 |
+
self.main_ui_negative_prompt = main_ui_negative_prompt
|
58 |
+
|
59 |
+
with gr.Row(elem_id=f"{tabname}_styles_row"):
|
60 |
+
self.dropdown = gr.Dropdown(label="Styles", show_label=False, elem_id=f"{tabname}_styles", choices=list(shared.prompt_styles.styles), value=[], multiselect=True, tooltip="Styles")
|
61 |
+
edit_button = ui_components.ToolButton(value=styles_edit_symbol, elem_id=f"{tabname}_styles_edit_button", tooltip="Edit styles")
|
62 |
+
|
63 |
+
with gr.Box(elem_id=f"{tabname}_styles_dialog", elem_classes="popup-dialog") as styles_dialog:
|
64 |
+
with gr.Row():
|
65 |
+
self.selection = gr.Dropdown(label="Styles", elem_id=f"{tabname}_styles_edit_select", choices=list(shared.prompt_styles.styles), value=[], allow_custom_value=True, info="Styles allow you to add custom text to prompt. Use the {prompt} token in style text, and it will be replaced with user's prompt when applying style. Otherwise, style's text will be added to the end of the prompt.")
|
66 |
+
ui_common.create_refresh_button([self.dropdown, self.selection], shared.prompt_styles.reload, lambda: {"choices": list(shared.prompt_styles.styles)}, f"refresh_{tabname}_styles")
|
67 |
+
self.materialize = ui_components.ToolButton(value=styles_materialize_symbol, elem_id=f"{tabname}_style_apply_dialog", tooltip="Apply all selected styles from the style selction dropdown in main UI to the prompt.")
|
68 |
+
self.copy = ui_components.ToolButton(value=styles_copy_symbol, elem_id=f"{tabname}_style_copy", tooltip="Copy main UI prompt to style.")
|
69 |
+
|
70 |
+
with gr.Row():
|
71 |
+
self.prompt = gr.Textbox(label="Prompt", show_label=True, elem_id=f"{tabname}_edit_style_prompt", lines=3, elem_classes=["prompt"])
|
72 |
+
|
73 |
+
with gr.Row():
|
74 |
+
self.neg_prompt = gr.Textbox(label="Negative prompt", show_label=True, elem_id=f"{tabname}_edit_style_neg_prompt", lines=3, elem_classes=["prompt"])
|
75 |
+
|
76 |
+
with gr.Row():
|
77 |
+
self.save = gr.Button('Save', variant='primary', elem_id=f'{tabname}_edit_style_save', visible=False)
|
78 |
+
self.delete = gr.Button('Delete', variant='primary', elem_id=f'{tabname}_edit_style_delete', visible=False)
|
79 |
+
self.close = gr.Button('Close', variant='secondary', elem_id=f'{tabname}_edit_style_close')
|
80 |
+
|
81 |
+
self.selection.change(
|
82 |
+
fn=select_style,
|
83 |
+
inputs=[self.selection],
|
84 |
+
outputs=[self.prompt, self.neg_prompt, self.delete, self.save],
|
85 |
+
show_progress=False,
|
86 |
+
)
|
87 |
+
|
88 |
+
self.save.click(
|
89 |
+
fn=save_style,
|
90 |
+
inputs=[self.selection, self.prompt, self.neg_prompt],
|
91 |
+
outputs=[self.delete],
|
92 |
+
show_progress=False,
|
93 |
+
).then(refresh_styles, outputs=[self.dropdown, self.selection], show_progress=False)
|
94 |
+
|
95 |
+
self.delete.click(
|
96 |
+
fn=delete_style,
|
97 |
+
_js='function(name){ if(name == "") return ""; return confirm("Delete style " + name + "?") ? name : ""; }',
|
98 |
+
inputs=[self.selection],
|
99 |
+
outputs=[self.selection, self.prompt, self.neg_prompt],
|
100 |
+
show_progress=False,
|
101 |
+
).then(refresh_styles, outputs=[self.dropdown, self.selection], show_progress=False)
|
102 |
+
|
103 |
+
self.setup_apply_button(self.materialize)
|
104 |
+
|
105 |
+
self.copy.click(
|
106 |
+
fn=lambda p, n: (p, n),
|
107 |
+
inputs=[main_ui_prompt, main_ui_negative_prompt],
|
108 |
+
outputs=[self.prompt, self.neg_prompt],
|
109 |
+
show_progress=False,
|
110 |
+
)
|
111 |
+
|
112 |
+
ui_common.setup_dialog(button_show=edit_button, dialog=styles_dialog, button_close=self.close)
|
113 |
+
|
114 |
+
def setup_apply_button(self, button):
|
115 |
+
button.click(
|
116 |
+
fn=materialize_styles,
|
117 |
+
inputs=[self.main_ui_prompt, self.main_ui_negative_prompt, self.dropdown],
|
118 |
+
outputs=[self.main_ui_prompt, self.main_ui_negative_prompt, self.dropdown],
|
119 |
+
show_progress=False,
|
120 |
+
).then(fn=None, _js="function(){update_"+self.tabname+"_tokens(); closePopup();}", show_progress=False)
|
modules/ui_settings.py
ADDED
@@ -0,0 +1,337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
|
3 |
+
from modules import ui_common, shared, script_callbacks, scripts, sd_models, sysinfo, timer
|
4 |
+
from modules.call_queue import wrap_gradio_call
|
5 |
+
from modules.shared import opts
|
6 |
+
from modules.ui_components import FormRow
|
7 |
+
from modules.ui_gradio_extensions import reload_javascript
|
8 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
9 |
+
|
10 |
+
|
11 |
+
def get_value_for_setting(key):
|
12 |
+
value = getattr(opts, key)
|
13 |
+
|
14 |
+
info = opts.data_labels[key]
|
15 |
+
args = info.component_args() if callable(info.component_args) else info.component_args or {}
|
16 |
+
args = {k: v for k, v in args.items() if k not in {'precision'}}
|
17 |
+
|
18 |
+
return gr.update(value=value, **args)
|
19 |
+
|
20 |
+
|
21 |
+
def create_setting_component(key, is_quicksettings=False):
|
22 |
+
def fun():
|
23 |
+
return opts.data[key] if key in opts.data else opts.data_labels[key].default
|
24 |
+
|
25 |
+
info = opts.data_labels[key]
|
26 |
+
t = type(info.default)
|
27 |
+
|
28 |
+
args = info.component_args() if callable(info.component_args) else info.component_args
|
29 |
+
|
30 |
+
if info.component is not None:
|
31 |
+
comp = info.component
|
32 |
+
elif t == str:
|
33 |
+
comp = gr.Textbox
|
34 |
+
elif t == int:
|
35 |
+
comp = gr.Number
|
36 |
+
elif t == bool:
|
37 |
+
comp = gr.Checkbox
|
38 |
+
else:
|
39 |
+
raise Exception(f'bad options item type: {t} for key {key}')
|
40 |
+
|
41 |
+
elem_id = f"setting_{key}"
|
42 |
+
|
43 |
+
if info.refresh is not None:
|
44 |
+
if is_quicksettings:
|
45 |
+
res = comp(label=info.label, value=fun(), elem_id=elem_id, **(args or {}))
|
46 |
+
ui_common.create_refresh_button(res, info.refresh, info.component_args, f"refresh_{key}")
|
47 |
+
else:
|
48 |
+
with FormRow():
|
49 |
+
res = comp(label=info.label, value=fun(), elem_id=elem_id, **(args or {}))
|
50 |
+
ui_common.create_refresh_button(res, info.refresh, info.component_args, f"refresh_{key}")
|
51 |
+
else:
|
52 |
+
res = comp(label=info.label, value=fun(), elem_id=elem_id, **(args or {}))
|
53 |
+
|
54 |
+
return res
|
55 |
+
|
56 |
+
|
57 |
+
class UiSettings:
|
58 |
+
submit = None
|
59 |
+
result = None
|
60 |
+
interface = None
|
61 |
+
components = None
|
62 |
+
component_dict = None
|
63 |
+
dummy_component = None
|
64 |
+
quicksettings_list = None
|
65 |
+
quicksettings_names = None
|
66 |
+
text_settings = None
|
67 |
+
show_all_pages = None
|
68 |
+
show_one_page = None
|
69 |
+
search_input = None
|
70 |
+
|
71 |
+
def run_settings(self, *args):
|
72 |
+
changed = []
|
73 |
+
|
74 |
+
for key, value, comp in zip(opts.data_labels.keys(), args, self.components):
|
75 |
+
assert comp == self.dummy_component or opts.same_type(value, opts.data_labels[key].default), f"Bad value for setting {key}: {value}; expecting {type(opts.data_labels[key].default).__name__}"
|
76 |
+
|
77 |
+
for key, value, comp in zip(opts.data_labels.keys(), args, self.components):
|
78 |
+
if comp == self.dummy_component:
|
79 |
+
continue
|
80 |
+
|
81 |
+
if opts.set(key, value):
|
82 |
+
changed.append(key)
|
83 |
+
|
84 |
+
try:
|
85 |
+
opts.save(shared.config_filename)
|
86 |
+
except RuntimeError:
|
87 |
+
return opts.dumpjson(), f'{len(changed)} settings changed without save: {", ".join(changed)}.'
|
88 |
+
return opts.dumpjson(), f'{len(changed)} settings changed{": " if changed else ""}{", ".join(changed)}.'
|
89 |
+
|
90 |
+
def run_settings_single(self, value, key):
|
91 |
+
if not opts.same_type(value, opts.data_labels[key].default):
|
92 |
+
return gr.update(visible=True), opts.dumpjson()
|
93 |
+
|
94 |
+
if value is None or not opts.set(key, value):
|
95 |
+
return gr.update(value=getattr(opts, key)), opts.dumpjson()
|
96 |
+
|
97 |
+
opts.save(shared.config_filename)
|
98 |
+
|
99 |
+
return get_value_for_setting(key), opts.dumpjson()
|
100 |
+
|
101 |
+
def create_ui(self, loadsave, dummy_component):
|
102 |
+
self.components = []
|
103 |
+
self.component_dict = {}
|
104 |
+
self.dummy_component = dummy_component
|
105 |
+
|
106 |
+
shared.settings_components = self.component_dict
|
107 |
+
|
108 |
+
script_callbacks.ui_settings_callback()
|
109 |
+
opts.reorder()
|
110 |
+
|
111 |
+
with gr.Blocks(analytics_enabled=False) as settings_interface:
|
112 |
+
with gr.Row():
|
113 |
+
with gr.Column(scale=6):
|
114 |
+
self.submit = gr.Button(value="Apply settings", variant='primary', elem_id="settings_submit")
|
115 |
+
with gr.Column():
|
116 |
+
restart_gradio = gr.Button(value='Reload UI', variant='primary', elem_id="settings_restart_gradio")
|
117 |
+
|
118 |
+
self.result = gr.HTML(elem_id="settings_result")
|
119 |
+
|
120 |
+
self.quicksettings_names = opts.quicksettings_list
|
121 |
+
self.quicksettings_names = {x: i for i, x in enumerate(self.quicksettings_names) if x != 'quicksettings'}
|
122 |
+
|
123 |
+
self.quicksettings_list = []
|
124 |
+
|
125 |
+
previous_section = None
|
126 |
+
current_tab = None
|
127 |
+
current_row = None
|
128 |
+
with gr.Tabs(elem_id="settings"):
|
129 |
+
for i, (k, item) in enumerate(opts.data_labels.items()):
|
130 |
+
section_must_be_skipped = item.section[0] is None
|
131 |
+
|
132 |
+
if previous_section != item.section and not section_must_be_skipped:
|
133 |
+
elem_id, text = item.section
|
134 |
+
|
135 |
+
if current_tab is not None:
|
136 |
+
current_row.__exit__()
|
137 |
+
current_tab.__exit__()
|
138 |
+
|
139 |
+
gr.Group()
|
140 |
+
current_tab = gr.TabItem(elem_id=f"settings_{elem_id}", label=text)
|
141 |
+
current_tab.__enter__()
|
142 |
+
current_row = gr.Column(elem_id=f"column_settings_{elem_id}", variant='compact')
|
143 |
+
current_row.__enter__()
|
144 |
+
|
145 |
+
previous_section = item.section
|
146 |
+
|
147 |
+
if k in self.quicksettings_names and not shared.cmd_opts.freeze_settings:
|
148 |
+
self.quicksettings_list.append((i, k, item))
|
149 |
+
self.components.append(dummy_component)
|
150 |
+
elif section_must_be_skipped:
|
151 |
+
self.components.append(dummy_component)
|
152 |
+
else:
|
153 |
+
component = create_setting_component(k)
|
154 |
+
self.component_dict[k] = component
|
155 |
+
self.components.append(component)
|
156 |
+
|
157 |
+
if current_tab is not None:
|
158 |
+
current_row.__exit__()
|
159 |
+
current_tab.__exit__()
|
160 |
+
|
161 |
+
with gr.TabItem("Defaults", id="defaults", elem_id="settings_tab_defaults"):
|
162 |
+
loadsave.create_ui()
|
163 |
+
|
164 |
+
with gr.TabItem("Sysinfo", id="sysinfo", elem_id="settings_tab_sysinfo"):
|
165 |
+
gr.HTML('<a href="./internal/sysinfo-download" class="sysinfo_big_link" download>Download system info</a><br /><a href="./internal/sysinfo" target="_blank">(or open as text in a new page)</a>', elem_id="sysinfo_download")
|
166 |
+
|
167 |
+
with gr.Row():
|
168 |
+
with gr.Column(scale=1):
|
169 |
+
sysinfo_check_file = gr.File(label="Check system info for validity", type='binary')
|
170 |
+
with gr.Column(scale=1):
|
171 |
+
sysinfo_check_output = gr.HTML("", elem_id="sysinfo_validity")
|
172 |
+
with gr.Column(scale=100):
|
173 |
+
pass
|
174 |
+
|
175 |
+
with gr.TabItem("Actions", id="actions", elem_id="settings_tab_actions"):
|
176 |
+
request_notifications = gr.Button(value='Request browser notifications', elem_id="request_notifications")
|
177 |
+
download_localization = gr.Button(value='Download localization template', elem_id="download_localization")
|
178 |
+
reload_script_bodies = gr.Button(value='Reload custom script bodies (No ui updates, No restart)', variant='secondary', elem_id="settings_reload_script_bodies")
|
179 |
+
with gr.Row():
|
180 |
+
unload_sd_model = gr.Button(value='Unload SD checkpoint to RAM', elem_id="sett_unload_sd_model")
|
181 |
+
reload_sd_model = gr.Button(value='Load SD checkpoint to VRAM from RAM', elem_id="sett_reload_sd_model")
|
182 |
+
with gr.Row():
|
183 |
+
calculate_all_checkpoint_hash = gr.Button(value='Calculate hash for all checkpoint', elem_id="calculate_all_checkpoint_hash")
|
184 |
+
calculate_all_checkpoint_hash_threads = gr.Number(value=1, label="Number of parallel calculations", elem_id="calculate_all_checkpoint_hash_threads", precision=0, minimum=1)
|
185 |
+
|
186 |
+
with gr.TabItem("Licenses", id="licenses", elem_id="settings_tab_licenses"):
|
187 |
+
gr.HTML(shared.html("licenses.html"), elem_id="licenses")
|
188 |
+
|
189 |
+
self.show_all_pages = gr.Button(value="Show all pages", elem_id="settings_show_all_pages")
|
190 |
+
self.show_one_page = gr.Button(value="Show only one page", elem_id="settings_show_one_page", visible=False)
|
191 |
+
self.show_one_page.click(lambda: None)
|
192 |
+
|
193 |
+
self.search_input = gr.Textbox(value="", elem_id="settings_search", max_lines=1, placeholder="Search...", show_label=False)
|
194 |
+
|
195 |
+
self.text_settings = gr.Textbox(elem_id="settings_json", value=lambda: opts.dumpjson(), visible=False)
|
196 |
+
|
197 |
+
def call_func_and_return_text(func, text):
|
198 |
+
def handler():
|
199 |
+
t = timer.Timer()
|
200 |
+
func()
|
201 |
+
t.record(text)
|
202 |
+
|
203 |
+
return f'{text} in {t.total:.1f}s'
|
204 |
+
|
205 |
+
return handler
|
206 |
+
|
207 |
+
unload_sd_model.click(
|
208 |
+
fn=call_func_and_return_text(sd_models.unload_model_weights, 'Unloaded the checkpoint'),
|
209 |
+
inputs=[],
|
210 |
+
outputs=[self.result]
|
211 |
+
)
|
212 |
+
|
213 |
+
reload_sd_model.click(
|
214 |
+
fn=call_func_and_return_text(lambda: sd_models.send_model_to_device(shared.sd_model), 'Loaded the checkpoint'),
|
215 |
+
inputs=[],
|
216 |
+
outputs=[self.result]
|
217 |
+
)
|
218 |
+
|
219 |
+
request_notifications.click(
|
220 |
+
fn=lambda: None,
|
221 |
+
inputs=[],
|
222 |
+
outputs=[],
|
223 |
+
_js='function(){}'
|
224 |
+
)
|
225 |
+
|
226 |
+
download_localization.click(
|
227 |
+
fn=lambda: None,
|
228 |
+
inputs=[],
|
229 |
+
outputs=[],
|
230 |
+
_js='download_localization'
|
231 |
+
)
|
232 |
+
|
233 |
+
def reload_scripts():
|
234 |
+
scripts.reload_script_body_only()
|
235 |
+
reload_javascript() # need to refresh the html page
|
236 |
+
|
237 |
+
reload_script_bodies.click(
|
238 |
+
fn=reload_scripts,
|
239 |
+
inputs=[],
|
240 |
+
outputs=[]
|
241 |
+
)
|
242 |
+
|
243 |
+
restart_gradio.click(
|
244 |
+
fn=shared.state.request_restart,
|
245 |
+
_js='restart_reload',
|
246 |
+
inputs=[],
|
247 |
+
outputs=[],
|
248 |
+
)
|
249 |
+
|
250 |
+
def check_file(x):
|
251 |
+
if x is None:
|
252 |
+
return ''
|
253 |
+
|
254 |
+
if sysinfo.check(x.decode('utf8', errors='ignore')):
|
255 |
+
return 'Valid'
|
256 |
+
|
257 |
+
return 'Invalid'
|
258 |
+
|
259 |
+
sysinfo_check_file.change(
|
260 |
+
fn=check_file,
|
261 |
+
inputs=[sysinfo_check_file],
|
262 |
+
outputs=[sysinfo_check_output],
|
263 |
+
)
|
264 |
+
|
265 |
+
def calculate_all_checkpoint_hash_fn(max_thread):
|
266 |
+
checkpoints_list = sd_models.checkpoints_list.values()
|
267 |
+
with ThreadPoolExecutor(max_workers=max_thread) as executor:
|
268 |
+
futures = [executor.submit(checkpoint.calculate_shorthash) for checkpoint in checkpoints_list]
|
269 |
+
completed = 0
|
270 |
+
for _ in as_completed(futures):
|
271 |
+
completed += 1
|
272 |
+
print(f"{completed} / {len(checkpoints_list)} ")
|
273 |
+
print("Finish calculating hash for all checkpoints")
|
274 |
+
|
275 |
+
calculate_all_checkpoint_hash.click(
|
276 |
+
fn=calculate_all_checkpoint_hash_fn,
|
277 |
+
inputs=[calculate_all_checkpoint_hash_threads],
|
278 |
+
)
|
279 |
+
|
280 |
+
self.interface = settings_interface
|
281 |
+
|
282 |
+
def add_quicksettings(self):
|
283 |
+
with gr.Row(elem_id="quicksettings", variant="compact"):
|
284 |
+
for _i, k, _item in sorted(self.quicksettings_list, key=lambda x: self.quicksettings_names.get(x[1], x[0])):
|
285 |
+
component = create_setting_component(k, is_quicksettings=True)
|
286 |
+
self.component_dict[k] = component
|
287 |
+
|
288 |
+
def add_functionality(self, demo):
|
289 |
+
self.submit.click(
|
290 |
+
fn=wrap_gradio_call(lambda *args: self.run_settings(*args), extra_outputs=[gr.update()]),
|
291 |
+
inputs=self.components,
|
292 |
+
outputs=[self.text_settings, self.result],
|
293 |
+
)
|
294 |
+
|
295 |
+
for _i, k, _item in self.quicksettings_list:
|
296 |
+
component = self.component_dict[k]
|
297 |
+
info = opts.data_labels[k]
|
298 |
+
|
299 |
+
if isinstance(component, gr.Textbox):
|
300 |
+
methods = [component.submit, component.blur]
|
301 |
+
elif hasattr(component, 'release'):
|
302 |
+
methods = [component.release]
|
303 |
+
else:
|
304 |
+
methods = [component.change]
|
305 |
+
|
306 |
+
for method in methods:
|
307 |
+
method(
|
308 |
+
fn=lambda value, k=k: self.run_settings_single(value, key=k),
|
309 |
+
inputs=[component],
|
310 |
+
outputs=[component, self.text_settings],
|
311 |
+
show_progress=info.refresh is not None,
|
312 |
+
)
|
313 |
+
|
314 |
+
button_set_checkpoint = gr.Button('Change checkpoint', elem_id='change_checkpoint', visible=False)
|
315 |
+
button_set_checkpoint.click(
|
316 |
+
fn=lambda value, _: self.run_settings_single(value, key='sd_model_checkpoint'),
|
317 |
+
_js="function(v){ var res = desiredCheckpointName; desiredCheckpointName = ''; return [res || v, null]; }",
|
318 |
+
inputs=[self.component_dict['sd_model_checkpoint'], self.dummy_component],
|
319 |
+
outputs=[self.component_dict['sd_model_checkpoint'], self.text_settings],
|
320 |
+
)
|
321 |
+
|
322 |
+
component_keys = [k for k in opts.data_labels.keys() if k in self.component_dict]
|
323 |
+
|
324 |
+
def get_settings_values():
|
325 |
+
return [get_value_for_setting(key) for key in component_keys]
|
326 |
+
|
327 |
+
demo.load(
|
328 |
+
fn=get_settings_values,
|
329 |
+
inputs=[],
|
330 |
+
outputs=[self.component_dict[k] for k in component_keys],
|
331 |
+
queue=False,
|
332 |
+
)
|
333 |
+
|
334 |
+
def search(self, text):
|
335 |
+
print(text)
|
336 |
+
|
337 |
+
return [gr.update(visible=text in (comp.label or "")) for comp in self.components]
|
modules/ui_tempdir.py
ADDED
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import tempfile
|
3 |
+
from collections import namedtuple
|
4 |
+
from pathlib import Path
|
5 |
+
|
6 |
+
import gradio.components
|
7 |
+
|
8 |
+
from PIL import PngImagePlugin
|
9 |
+
|
10 |
+
from modules import shared
|
11 |
+
|
12 |
+
|
13 |
+
Savedfile = namedtuple("Savedfile", ["name"])
|
14 |
+
|
15 |
+
|
16 |
+
def register_tmp_file(gradio, filename):
|
17 |
+
if hasattr(gradio, 'temp_file_sets'): # gradio 3.15
|
18 |
+
gradio.temp_file_sets[0] = gradio.temp_file_sets[0] | {os.path.abspath(filename)}
|
19 |
+
|
20 |
+
if hasattr(gradio, 'temp_dirs'): # gradio 3.9
|
21 |
+
gradio.temp_dirs = gradio.temp_dirs | {os.path.abspath(os.path.dirname(filename))}
|
22 |
+
|
23 |
+
|
24 |
+
def check_tmp_file(gradio, filename):
|
25 |
+
if hasattr(gradio, 'temp_file_sets'):
|
26 |
+
return any(filename in fileset for fileset in gradio.temp_file_sets)
|
27 |
+
|
28 |
+
if hasattr(gradio, 'temp_dirs'):
|
29 |
+
return any(Path(temp_dir).resolve() in Path(filename).resolve().parents for temp_dir in gradio.temp_dirs)
|
30 |
+
|
31 |
+
return False
|
32 |
+
|
33 |
+
|
34 |
+
def save_pil_to_file(self, pil_image, dir=None, format="png"):
|
35 |
+
already_saved_as = getattr(pil_image, 'already_saved_as', None)
|
36 |
+
if already_saved_as and os.path.isfile(already_saved_as):
|
37 |
+
register_tmp_file(shared.demo, already_saved_as)
|
38 |
+
filename = already_saved_as
|
39 |
+
|
40 |
+
if not shared.opts.save_images_add_number:
|
41 |
+
filename += f'?{os.path.getmtime(already_saved_as)}'
|
42 |
+
|
43 |
+
return filename
|
44 |
+
|
45 |
+
if shared.opts.temp_dir != "":
|
46 |
+
dir = shared.opts.temp_dir
|
47 |
+
else:
|
48 |
+
os.makedirs(dir, exist_ok=True)
|
49 |
+
|
50 |
+
use_metadata = False
|
51 |
+
metadata = PngImagePlugin.PngInfo()
|
52 |
+
for key, value in pil_image.info.items():
|
53 |
+
if isinstance(key, str) and isinstance(value, str):
|
54 |
+
metadata.add_text(key, value)
|
55 |
+
use_metadata = True
|
56 |
+
|
57 |
+
file_obj = tempfile.NamedTemporaryFile(delete=False, suffix=".png", dir=dir)
|
58 |
+
pil_image.save(file_obj, pnginfo=(metadata if use_metadata else None))
|
59 |
+
return file_obj.name
|
60 |
+
|
61 |
+
|
62 |
+
def install_ui_tempdir_override():
|
63 |
+
"""override save to file function so that it also writes PNG info"""
|
64 |
+
gradio.components.IOComponent.pil_to_temp_file = save_pil_to_file
|
65 |
+
|
66 |
+
|
67 |
+
def on_tmpdir_changed():
|
68 |
+
if shared.opts.temp_dir == "" or shared.demo is None:
|
69 |
+
return
|
70 |
+
|
71 |
+
os.makedirs(shared.opts.temp_dir, exist_ok=True)
|
72 |
+
|
73 |
+
register_tmp_file(shared.demo, os.path.join(shared.opts.temp_dir, "x"))
|
74 |
+
|
75 |
+
|
76 |
+
def cleanup_tmpdr():
|
77 |
+
temp_dir = shared.opts.temp_dir
|
78 |
+
if temp_dir == "" or not os.path.isdir(temp_dir):
|
79 |
+
return
|
80 |
+
|
81 |
+
for root, _, files in os.walk(temp_dir, topdown=False):
|
82 |
+
for name in files:
|
83 |
+
_, extension = os.path.splitext(name)
|
84 |
+
if extension != ".png":
|
85 |
+
continue
|
86 |
+
|
87 |
+
filename = os.path.join(root, name)
|
88 |
+
os.remove(filename)
|
modules/ui_toprow.py
ADDED
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
|
3 |
+
from modules import shared, ui_prompt_styles
|
4 |
+
import modules.images
|
5 |
+
|
6 |
+
from modules.ui_components import ToolButton
|
7 |
+
|
8 |
+
|
9 |
+
class Toprow:
|
10 |
+
"""Creates a top row UI with prompts, generate button, styles, extra little buttons for things, and enables some functionality related to their operation"""
|
11 |
+
|
12 |
+
prompt = None
|
13 |
+
prompt_img = None
|
14 |
+
negative_prompt = None
|
15 |
+
|
16 |
+
button_interrogate = None
|
17 |
+
button_deepbooru = None
|
18 |
+
|
19 |
+
interrupt = None
|
20 |
+
skip = None
|
21 |
+
submit = None
|
22 |
+
|
23 |
+
paste = None
|
24 |
+
clear_prompt_button = None
|
25 |
+
apply_styles = None
|
26 |
+
restore_progress_button = None
|
27 |
+
|
28 |
+
token_counter = None
|
29 |
+
token_button = None
|
30 |
+
negative_token_counter = None
|
31 |
+
negative_token_button = None
|
32 |
+
|
33 |
+
ui_styles = None
|
34 |
+
|
35 |
+
submit_box = None
|
36 |
+
|
37 |
+
def __init__(self, is_img2img, is_compact=False, id_part=None):
|
38 |
+
if id_part is None:
|
39 |
+
id_part = "img2img" if is_img2img else "txt2img"
|
40 |
+
|
41 |
+
self.id_part = id_part
|
42 |
+
self.is_img2img = is_img2img
|
43 |
+
self.is_compact = is_compact
|
44 |
+
|
45 |
+
if not is_compact:
|
46 |
+
with gr.Row(elem_id=f"{id_part}_toprow", variant="compact"):
|
47 |
+
self.create_classic_toprow()
|
48 |
+
else:
|
49 |
+
self.create_submit_box()
|
50 |
+
|
51 |
+
def create_classic_toprow(self):
|
52 |
+
self.create_prompts()
|
53 |
+
|
54 |
+
with gr.Column(scale=1, elem_id=f"{self.id_part}_actions_column"):
|
55 |
+
self.create_submit_box()
|
56 |
+
|
57 |
+
self.create_tools_row()
|
58 |
+
|
59 |
+
self.create_styles_ui()
|
60 |
+
|
61 |
+
def create_inline_toprow_prompts(self):
|
62 |
+
if not self.is_compact:
|
63 |
+
return
|
64 |
+
|
65 |
+
self.create_prompts()
|
66 |
+
|
67 |
+
with gr.Row(elem_classes=["toprow-compact-stylerow"]):
|
68 |
+
with gr.Column(elem_classes=["toprow-compact-tools"]):
|
69 |
+
self.create_tools_row()
|
70 |
+
with gr.Column():
|
71 |
+
self.create_styles_ui()
|
72 |
+
|
73 |
+
def create_inline_toprow_image(self):
|
74 |
+
if not self.is_compact:
|
75 |
+
return
|
76 |
+
|
77 |
+
self.submit_box.render()
|
78 |
+
|
79 |
+
def create_prompts(self):
|
80 |
+
with gr.Column(elem_id=f"{self.id_part}_prompt_container", elem_classes=["prompt-container-compact"] if self.is_compact else [], scale=6):
|
81 |
+
with gr.Row(elem_id=f"{self.id_part}_prompt_row", elem_classes=["prompt-row"]):
|
82 |
+
self.prompt = gr.Textbox(label="Prompt", elem_id=f"{self.id_part}_prompt", show_label=False, lines=3, placeholder="Prompt (press Ctrl+Enter or Alt+Enter to generate)", elem_classes=["prompt"])
|
83 |
+
self.prompt_img = gr.File(label="", elem_id=f"{self.id_part}_prompt_image", file_count="single", type="binary", visible=False)
|
84 |
+
|
85 |
+
with gr.Row(elem_id=f"{self.id_part}_neg_prompt_row", elem_classes=["prompt-row"]):
|
86 |
+
self.negative_prompt = gr.Textbox(label="Negative prompt", elem_id=f"{self.id_part}_neg_prompt", show_label=False, lines=3, placeholder="Negative prompt (press Ctrl+Enter or Alt+Enter to generate)", elem_classes=["prompt"])
|
87 |
+
|
88 |
+
self.prompt_img.change(
|
89 |
+
fn=modules.images.image_data,
|
90 |
+
inputs=[self.prompt_img],
|
91 |
+
outputs=[self.prompt, self.prompt_img],
|
92 |
+
show_progress=False,
|
93 |
+
)
|
94 |
+
|
95 |
+
def create_submit_box(self):
|
96 |
+
with gr.Row(elem_id=f"{self.id_part}_generate_box", elem_classes=["generate-box"] + (["generate-box-compact"] if self.is_compact else []), render=not self.is_compact) as submit_box:
|
97 |
+
self.submit_box = submit_box
|
98 |
+
|
99 |
+
self.interrupt = gr.Button('Interrupt', elem_id=f"{self.id_part}_interrupt", elem_classes="generate-box-interrupt")
|
100 |
+
self.skip = gr.Button('Skip', elem_id=f"{self.id_part}_skip", elem_classes="generate-box-skip")
|
101 |
+
self.submit = gr.Button('Generate', elem_id=f"{self.id_part}_generate", variant='primary')
|
102 |
+
|
103 |
+
self.skip.click(
|
104 |
+
fn=lambda: shared.state.skip(),
|
105 |
+
inputs=[],
|
106 |
+
outputs=[],
|
107 |
+
)
|
108 |
+
|
109 |
+
self.interrupt.click(
|
110 |
+
fn=lambda: shared.state.interrupt(),
|
111 |
+
inputs=[],
|
112 |
+
outputs=[],
|
113 |
+
)
|
114 |
+
|
115 |
+
def create_tools_row(self):
|
116 |
+
with gr.Row(elem_id=f"{self.id_part}_tools"):
|
117 |
+
from modules.ui import paste_symbol, clear_prompt_symbol, restore_progress_symbol
|
118 |
+
|
119 |
+
self.paste = ToolButton(value=paste_symbol, elem_id="paste", tooltip="Read generation parameters from prompt or last generation if prompt is empty into user interface.")
|
120 |
+
self.clear_prompt_button = ToolButton(value=clear_prompt_symbol, elem_id=f"{self.id_part}_clear_prompt", tooltip="Clear prompt")
|
121 |
+
self.apply_styles = ToolButton(value=ui_prompt_styles.styles_materialize_symbol, elem_id=f"{self.id_part}_style_apply", tooltip="Apply all selected styles to prompts.")
|
122 |
+
|
123 |
+
if self.is_img2img:
|
124 |
+
self.button_interrogate = ToolButton('📎', tooltip='Interrogate CLIP - use CLIP neural network to create a text describing the image, and put it into the prompt field', elem_id="interrogate")
|
125 |
+
self.button_deepbooru = ToolButton('📦', tooltip='Interrogate DeepBooru - use DeepBooru neural network to create a text describing the image, and put it into the prompt field', elem_id="deepbooru")
|
126 |
+
|
127 |
+
self.restore_progress_button = ToolButton(value=restore_progress_symbol, elem_id=f"{self.id_part}_restore_progress", visible=False, tooltip="Restore progress")
|
128 |
+
|
129 |
+
self.token_counter = gr.HTML(value="<span>0/75</span>", elem_id=f"{self.id_part}_token_counter", elem_classes=["token-counter"])
|
130 |
+
self.token_button = gr.Button(visible=False, elem_id=f"{self.id_part}_token_button")
|
131 |
+
self.negative_token_counter = gr.HTML(value="<span>0/75</span>", elem_id=f"{self.id_part}_negative_token_counter", elem_classes=["token-counter"])
|
132 |
+
self.negative_token_button = gr.Button(visible=False, elem_id=f"{self.id_part}_negative_token_button")
|
133 |
+
|
134 |
+
self.clear_prompt_button.click(
|
135 |
+
fn=lambda *x: x,
|
136 |
+
_js="confirm_clear_prompt",
|
137 |
+
inputs=[self.prompt, self.negative_prompt],
|
138 |
+
outputs=[self.prompt, self.negative_prompt],
|
139 |
+
)
|
140 |
+
|
141 |
+
def create_styles_ui(self):
|
142 |
+
self.ui_styles = ui_prompt_styles.UiPromptStyles(self.id_part, self.prompt, self.negative_prompt)
|
143 |
+
self.ui_styles.setup_apply_button(self.apply_styles)
|
modules/upscaler.py
ADDED
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from abc import abstractmethod
|
3 |
+
|
4 |
+
import PIL
|
5 |
+
from PIL import Image
|
6 |
+
|
7 |
+
import modules.shared
|
8 |
+
from modules import modelloader, shared
|
9 |
+
|
10 |
+
LANCZOS = (Image.Resampling.LANCZOS if hasattr(Image, 'Resampling') else Image.LANCZOS)
|
11 |
+
NEAREST = (Image.Resampling.NEAREST if hasattr(Image, 'Resampling') else Image.NEAREST)
|
12 |
+
|
13 |
+
|
14 |
+
class Upscaler:
|
15 |
+
name = None
|
16 |
+
model_path = None
|
17 |
+
model_name = None
|
18 |
+
model_url = None
|
19 |
+
enable = True
|
20 |
+
filter = None
|
21 |
+
model = None
|
22 |
+
user_path = None
|
23 |
+
scalers: []
|
24 |
+
tile = True
|
25 |
+
|
26 |
+
def __init__(self, create_dirs=False):
|
27 |
+
self.mod_pad_h = None
|
28 |
+
self.tile_size = modules.shared.opts.ESRGAN_tile
|
29 |
+
self.tile_pad = modules.shared.opts.ESRGAN_tile_overlap
|
30 |
+
self.device = modules.shared.device
|
31 |
+
self.img = None
|
32 |
+
self.output = None
|
33 |
+
self.scale = 1
|
34 |
+
self.half = not modules.shared.cmd_opts.no_half
|
35 |
+
self.pre_pad = 0
|
36 |
+
self.mod_scale = None
|
37 |
+
self.model_download_path = None
|
38 |
+
|
39 |
+
if self.model_path is None and self.name:
|
40 |
+
self.model_path = os.path.join(shared.models_path, self.name)
|
41 |
+
if self.model_path and create_dirs:
|
42 |
+
os.makedirs(self.model_path, exist_ok=True)
|
43 |
+
|
44 |
+
try:
|
45 |
+
import cv2 # noqa: F401
|
46 |
+
self.can_tile = True
|
47 |
+
except Exception:
|
48 |
+
pass
|
49 |
+
|
50 |
+
@abstractmethod
|
51 |
+
def do_upscale(self, img: PIL.Image, selected_model: str):
|
52 |
+
return img
|
53 |
+
|
54 |
+
def upscale(self, img: PIL.Image, scale, selected_model: str = None):
|
55 |
+
self.scale = scale
|
56 |
+
dest_w = int((img.width * scale) // 8 * 8)
|
57 |
+
dest_h = int((img.height * scale) // 8 * 8)
|
58 |
+
|
59 |
+
for _ in range(3):
|
60 |
+
if img.width >= dest_w and img.height >= dest_h:
|
61 |
+
break
|
62 |
+
|
63 |
+
shape = (img.width, img.height)
|
64 |
+
|
65 |
+
img = self.do_upscale(img, selected_model)
|
66 |
+
|
67 |
+
if shape == (img.width, img.height):
|
68 |
+
break
|
69 |
+
|
70 |
+
if img.width != dest_w or img.height != dest_h:
|
71 |
+
img = img.resize((int(dest_w), int(dest_h)), resample=LANCZOS)
|
72 |
+
|
73 |
+
return img
|
74 |
+
|
75 |
+
@abstractmethod
|
76 |
+
def load_model(self, path: str):
|
77 |
+
pass
|
78 |
+
|
79 |
+
def find_models(self, ext_filter=None) -> list:
|
80 |
+
return modelloader.load_models(model_path=self.model_path, model_url=self.model_url, command_path=self.user_path, ext_filter=ext_filter)
|
81 |
+
|
82 |
+
def update_status(self, prompt):
|
83 |
+
print(f"\nextras: {prompt}", file=shared.progress_print_out)
|
84 |
+
|
85 |
+
|
86 |
+
class UpscalerData:
|
87 |
+
name = None
|
88 |
+
data_path = None
|
89 |
+
scale: int = 4
|
90 |
+
scaler: Upscaler = None
|
91 |
+
model: None
|
92 |
+
|
93 |
+
def __init__(self, name: str, path: str, upscaler: Upscaler = None, scale: int = 4, model=None):
|
94 |
+
self.name = name
|
95 |
+
self.data_path = path
|
96 |
+
self.local_data_path = path
|
97 |
+
self.scaler = upscaler
|
98 |
+
self.scale = scale
|
99 |
+
self.model = model
|
100 |
+
|
101 |
+
|
102 |
+
class UpscalerNone(Upscaler):
|
103 |
+
name = "None"
|
104 |
+
scalers = []
|
105 |
+
|
106 |
+
def load_model(self, path):
|
107 |
+
pass
|
108 |
+
|
109 |
+
def do_upscale(self, img, selected_model=None):
|
110 |
+
return img
|
111 |
+
|
112 |
+
def __init__(self, dirname=None):
|
113 |
+
super().__init__(False)
|
114 |
+
self.scalers = [UpscalerData("None", None, self)]
|
115 |
+
|
116 |
+
|
117 |
+
class UpscalerLanczos(Upscaler):
|
118 |
+
scalers = []
|
119 |
+
|
120 |
+
def do_upscale(self, img, selected_model=None):
|
121 |
+
return img.resize((int(img.width * self.scale), int(img.height * self.scale)), resample=LANCZOS)
|
122 |
+
|
123 |
+
def load_model(self, _):
|
124 |
+
pass
|
125 |
+
|
126 |
+
def __init__(self, dirname=None):
|
127 |
+
super().__init__(False)
|
128 |
+
self.name = "Lanczos"
|
129 |
+
self.scalers = [UpscalerData("Lanczos", None, self)]
|
130 |
+
|
131 |
+
|
132 |
+
class UpscalerNearest(Upscaler):
|
133 |
+
scalers = []
|
134 |
+
|
135 |
+
def do_upscale(self, img, selected_model=None):
|
136 |
+
return img.resize((int(img.width * self.scale), int(img.height * self.scale)), resample=NEAREST)
|
137 |
+
|
138 |
+
def load_model(self, _):
|
139 |
+
pass
|
140 |
+
|
141 |
+
def __init__(self, dirname=None):
|
142 |
+
super().__init__(False)
|
143 |
+
self.name = "Nearest"
|
144 |
+
self.scalers = [UpscalerData("Nearest", None, self)]
|
modules/util.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import re
|
3 |
+
|
4 |
+
from modules import shared
|
5 |
+
from modules.paths_internal import script_path
|
6 |
+
|
7 |
+
|
8 |
+
def natural_sort_key(s, regex=re.compile('([0-9]+)')):
|
9 |
+
return [int(text) if text.isdigit() else text.lower() for text in regex.split(s)]
|
10 |
+
|
11 |
+
|
12 |
+
def listfiles(dirname):
|
13 |
+
filenames = [os.path.join(dirname, x) for x in sorted(os.listdir(dirname), key=natural_sort_key) if not x.startswith(".")]
|
14 |
+
return [file for file in filenames if os.path.isfile(file)]
|
15 |
+
|
16 |
+
|
17 |
+
def html_path(filename):
|
18 |
+
return os.path.join(script_path, "html", filename)
|
19 |
+
|
20 |
+
|
21 |
+
def html(filename):
|
22 |
+
path = html_path(filename)
|
23 |
+
|
24 |
+
if os.path.exists(path):
|
25 |
+
with open(path, encoding="utf8") as file:
|
26 |
+
return file.read()
|
27 |
+
|
28 |
+
return ""
|
29 |
+
|
30 |
+
|
31 |
+
def walk_files(path, allowed_extensions=None):
|
32 |
+
if not os.path.exists(path):
|
33 |
+
return
|
34 |
+
|
35 |
+
if allowed_extensions is not None:
|
36 |
+
allowed_extensions = set(allowed_extensions)
|
37 |
+
|
38 |
+
items = list(os.walk(path, followlinks=True))
|
39 |
+
items = sorted(items, key=lambda x: natural_sort_key(x[0]))
|
40 |
+
|
41 |
+
for root, _, files in items:
|
42 |
+
for filename in sorted(files, key=natural_sort_key):
|
43 |
+
if allowed_extensions is not None:
|
44 |
+
_, ext = os.path.splitext(filename)
|
45 |
+
if ext not in allowed_extensions:
|
46 |
+
continue
|
47 |
+
|
48 |
+
if not shared.opts.list_hidden_files and ("/." in root or "\\." in root):
|
49 |
+
continue
|
50 |
+
|
51 |
+
yield os.path.join(root, filename)
|
52 |
+
|
53 |
+
|
54 |
+
def ldm_print(*args, **kwargs):
|
55 |
+
if shared.opts.hide_ldm_prints:
|
56 |
+
return
|
57 |
+
|
58 |
+
print(*args, **kwargs)
|
modules/xlmr.py
ADDED
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import BertPreTrainedModel, BertConfig
|
2 |
+
import torch.nn as nn
|
3 |
+
import torch
|
4 |
+
from transformers.models.xlm_roberta.configuration_xlm_roberta import XLMRobertaConfig
|
5 |
+
from transformers import XLMRobertaModel,XLMRobertaTokenizer
|
6 |
+
from typing import Optional
|
7 |
+
|
8 |
+
class BertSeriesConfig(BertConfig):
|
9 |
+
def __init__(self, vocab_size=30522, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=2, initializer_range=0.02, layer_norm_eps=1e-12, pad_token_id=0, position_embedding_type="absolute", use_cache=True, classifier_dropout=None,project_dim=512, pooler_fn="average",learn_encoder=False,model_type='bert',**kwargs):
|
10 |
+
|
11 |
+
super().__init__(vocab_size, hidden_size, num_hidden_layers, num_attention_heads, intermediate_size, hidden_act, hidden_dropout_prob, attention_probs_dropout_prob, max_position_embeddings, type_vocab_size, initializer_range, layer_norm_eps, pad_token_id, position_embedding_type, use_cache, classifier_dropout, **kwargs)
|
12 |
+
self.project_dim = project_dim
|
13 |
+
self.pooler_fn = pooler_fn
|
14 |
+
self.learn_encoder = learn_encoder
|
15 |
+
|
16 |
+
class RobertaSeriesConfig(XLMRobertaConfig):
|
17 |
+
def __init__(self, pad_token_id=1, bos_token_id=0, eos_token_id=2,project_dim=512,pooler_fn='cls',learn_encoder=False, **kwargs):
|
18 |
+
super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
19 |
+
self.project_dim = project_dim
|
20 |
+
self.pooler_fn = pooler_fn
|
21 |
+
self.learn_encoder = learn_encoder
|
22 |
+
|
23 |
+
|
24 |
+
class BertSeriesModelWithTransformation(BertPreTrainedModel):
|
25 |
+
|
26 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler"]
|
27 |
+
_keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
|
28 |
+
config_class = BertSeriesConfig
|
29 |
+
|
30 |
+
def __init__(self, config=None, **kargs):
|
31 |
+
# modify initialization for autoloading
|
32 |
+
if config is None:
|
33 |
+
config = XLMRobertaConfig()
|
34 |
+
config.attention_probs_dropout_prob= 0.1
|
35 |
+
config.bos_token_id=0
|
36 |
+
config.eos_token_id=2
|
37 |
+
config.hidden_act='gelu'
|
38 |
+
config.hidden_dropout_prob=0.1
|
39 |
+
config.hidden_size=1024
|
40 |
+
config.initializer_range=0.02
|
41 |
+
config.intermediate_size=4096
|
42 |
+
config.layer_norm_eps=1e-05
|
43 |
+
config.max_position_embeddings=514
|
44 |
+
|
45 |
+
config.num_attention_heads=16
|
46 |
+
config.num_hidden_layers=24
|
47 |
+
config.output_past=True
|
48 |
+
config.pad_token_id=1
|
49 |
+
config.position_embedding_type= "absolute"
|
50 |
+
|
51 |
+
config.type_vocab_size= 1
|
52 |
+
config.use_cache=True
|
53 |
+
config.vocab_size= 250002
|
54 |
+
config.project_dim = 768
|
55 |
+
config.learn_encoder = False
|
56 |
+
super().__init__(config)
|
57 |
+
self.roberta = XLMRobertaModel(config)
|
58 |
+
self.transformation = nn.Linear(config.hidden_size,config.project_dim)
|
59 |
+
self.pre_LN=nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
60 |
+
self.tokenizer = XLMRobertaTokenizer.from_pretrained('xlm-roberta-large')
|
61 |
+
self.pooler = lambda x: x[:,0]
|
62 |
+
self.post_init()
|
63 |
+
|
64 |
+
def encode(self,c):
|
65 |
+
device = next(self.parameters()).device
|
66 |
+
text = self.tokenizer(c,
|
67 |
+
truncation=True,
|
68 |
+
max_length=77,
|
69 |
+
return_length=False,
|
70 |
+
return_overflowing_tokens=False,
|
71 |
+
padding="max_length",
|
72 |
+
return_tensors="pt")
|
73 |
+
text["input_ids"] = torch.tensor(text["input_ids"]).to(device)
|
74 |
+
text["attention_mask"] = torch.tensor(
|
75 |
+
text['attention_mask']).to(device)
|
76 |
+
features = self(**text)
|
77 |
+
return features['projection_state']
|
78 |
+
|
79 |
+
def forward(
|
80 |
+
self,
|
81 |
+
input_ids: Optional[torch.Tensor] = None,
|
82 |
+
attention_mask: Optional[torch.Tensor] = None,
|
83 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
84 |
+
position_ids: Optional[torch.Tensor] = None,
|
85 |
+
head_mask: Optional[torch.Tensor] = None,
|
86 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
87 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
88 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
89 |
+
output_attentions: Optional[bool] = None,
|
90 |
+
return_dict: Optional[bool] = None,
|
91 |
+
output_hidden_states: Optional[bool] = None,
|
92 |
+
) :
|
93 |
+
r"""
|
94 |
+
"""
|
95 |
+
|
96 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
97 |
+
|
98 |
+
|
99 |
+
outputs = self.roberta(
|
100 |
+
input_ids=input_ids,
|
101 |
+
attention_mask=attention_mask,
|
102 |
+
token_type_ids=token_type_ids,
|
103 |
+
position_ids=position_ids,
|
104 |
+
head_mask=head_mask,
|
105 |
+
inputs_embeds=inputs_embeds,
|
106 |
+
encoder_hidden_states=encoder_hidden_states,
|
107 |
+
encoder_attention_mask=encoder_attention_mask,
|
108 |
+
output_attentions=output_attentions,
|
109 |
+
output_hidden_states=True,
|
110 |
+
return_dict=return_dict,
|
111 |
+
)
|
112 |
+
|
113 |
+
# last module outputs
|
114 |
+
sequence_output = outputs[0]
|
115 |
+
|
116 |
+
|
117 |
+
# project every module
|
118 |
+
sequence_output_ln = self.pre_LN(sequence_output)
|
119 |
+
|
120 |
+
# pooler
|
121 |
+
pooler_output = self.pooler(sequence_output_ln)
|
122 |
+
pooler_output = self.transformation(pooler_output)
|
123 |
+
projection_state = self.transformation(outputs.last_hidden_state)
|
124 |
+
|
125 |
+
return {
|
126 |
+
'pooler_output':pooler_output,
|
127 |
+
'last_hidden_state':outputs.last_hidden_state,
|
128 |
+
'hidden_states':outputs.hidden_states,
|
129 |
+
'attentions':outputs.attentions,
|
130 |
+
'projection_state':projection_state,
|
131 |
+
'sequence_out': sequence_output
|
132 |
+
}
|
133 |
+
|
134 |
+
|
135 |
+
class RobertaSeriesModelWithTransformation(BertSeriesModelWithTransformation):
|
136 |
+
base_model_prefix = 'roberta'
|
137 |
+
config_class= RobertaSeriesConfig
|
modules/xlmr_m18.py
ADDED
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import BertPreTrainedModel,BertConfig
|
2 |
+
import torch.nn as nn
|
3 |
+
import torch
|
4 |
+
from transformers.models.xlm_roberta.configuration_xlm_roberta import XLMRobertaConfig
|
5 |
+
from transformers import XLMRobertaModel,XLMRobertaTokenizer
|
6 |
+
from typing import Optional
|
7 |
+
|
8 |
+
class BertSeriesConfig(BertConfig):
|
9 |
+
def __init__(self, vocab_size=30522, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=2, initializer_range=0.02, layer_norm_eps=1e-12, pad_token_id=0, position_embedding_type="absolute", use_cache=True, classifier_dropout=None,project_dim=512, pooler_fn="average",learn_encoder=False,model_type='bert',**kwargs):
|
10 |
+
|
11 |
+
super().__init__(vocab_size, hidden_size, num_hidden_layers, num_attention_heads, intermediate_size, hidden_act, hidden_dropout_prob, attention_probs_dropout_prob, max_position_embeddings, type_vocab_size, initializer_range, layer_norm_eps, pad_token_id, position_embedding_type, use_cache, classifier_dropout, **kwargs)
|
12 |
+
self.project_dim = project_dim
|
13 |
+
self.pooler_fn = pooler_fn
|
14 |
+
self.learn_encoder = learn_encoder
|
15 |
+
|
16 |
+
class RobertaSeriesConfig(XLMRobertaConfig):
|
17 |
+
def __init__(self, pad_token_id=1, bos_token_id=0, eos_token_id=2,project_dim=512,pooler_fn='cls',learn_encoder=False, **kwargs):
|
18 |
+
super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
19 |
+
self.project_dim = project_dim
|
20 |
+
self.pooler_fn = pooler_fn
|
21 |
+
self.learn_encoder = learn_encoder
|
22 |
+
|
23 |
+
|
24 |
+
class BertSeriesModelWithTransformation(BertPreTrainedModel):
|
25 |
+
|
26 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler"]
|
27 |
+
_keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
|
28 |
+
config_class = BertSeriesConfig
|
29 |
+
|
30 |
+
def __init__(self, config=None, **kargs):
|
31 |
+
# modify initialization for autoloading
|
32 |
+
if config is None:
|
33 |
+
config = XLMRobertaConfig()
|
34 |
+
config.attention_probs_dropout_prob= 0.1
|
35 |
+
config.bos_token_id=0
|
36 |
+
config.eos_token_id=2
|
37 |
+
config.hidden_act='gelu'
|
38 |
+
config.hidden_dropout_prob=0.1
|
39 |
+
config.hidden_size=1024
|
40 |
+
config.initializer_range=0.02
|
41 |
+
config.intermediate_size=4096
|
42 |
+
config.layer_norm_eps=1e-05
|
43 |
+
config.max_position_embeddings=514
|
44 |
+
|
45 |
+
config.num_attention_heads=16
|
46 |
+
config.num_hidden_layers=24
|
47 |
+
config.output_past=True
|
48 |
+
config.pad_token_id=1
|
49 |
+
config.position_embedding_type= "absolute"
|
50 |
+
|
51 |
+
config.type_vocab_size= 1
|
52 |
+
config.use_cache=True
|
53 |
+
config.vocab_size= 250002
|
54 |
+
config.project_dim = 1024
|
55 |
+
config.learn_encoder = False
|
56 |
+
super().__init__(config)
|
57 |
+
self.roberta = XLMRobertaModel(config)
|
58 |
+
self.transformation = nn.Linear(config.hidden_size,config.project_dim)
|
59 |
+
# self.pre_LN=nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
60 |
+
self.tokenizer = XLMRobertaTokenizer.from_pretrained('xlm-roberta-large')
|
61 |
+
# self.pooler = lambda x: x[:,0]
|
62 |
+
# self.post_init()
|
63 |
+
|
64 |
+
self.has_pre_transformation = True
|
65 |
+
if self.has_pre_transformation:
|
66 |
+
self.transformation_pre = nn.Linear(config.hidden_size, config.project_dim)
|
67 |
+
self.pre_LN = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
68 |
+
self.post_init()
|
69 |
+
|
70 |
+
def encode(self,c):
|
71 |
+
device = next(self.parameters()).device
|
72 |
+
text = self.tokenizer(c,
|
73 |
+
truncation=True,
|
74 |
+
max_length=77,
|
75 |
+
return_length=False,
|
76 |
+
return_overflowing_tokens=False,
|
77 |
+
padding="max_length",
|
78 |
+
return_tensors="pt")
|
79 |
+
text["input_ids"] = torch.tensor(text["input_ids"]).to(device)
|
80 |
+
text["attention_mask"] = torch.tensor(
|
81 |
+
text['attention_mask']).to(device)
|
82 |
+
features = self(**text)
|
83 |
+
return features['projection_state']
|
84 |
+
|
85 |
+
def forward(
|
86 |
+
self,
|
87 |
+
input_ids: Optional[torch.Tensor] = None,
|
88 |
+
attention_mask: Optional[torch.Tensor] = None,
|
89 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
90 |
+
position_ids: Optional[torch.Tensor] = None,
|
91 |
+
head_mask: Optional[torch.Tensor] = None,
|
92 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
93 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
94 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
95 |
+
output_attentions: Optional[bool] = None,
|
96 |
+
return_dict: Optional[bool] = None,
|
97 |
+
output_hidden_states: Optional[bool] = None,
|
98 |
+
) :
|
99 |
+
r"""
|
100 |
+
"""
|
101 |
+
|
102 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
103 |
+
|
104 |
+
|
105 |
+
outputs = self.roberta(
|
106 |
+
input_ids=input_ids,
|
107 |
+
attention_mask=attention_mask,
|
108 |
+
token_type_ids=token_type_ids,
|
109 |
+
position_ids=position_ids,
|
110 |
+
head_mask=head_mask,
|
111 |
+
inputs_embeds=inputs_embeds,
|
112 |
+
encoder_hidden_states=encoder_hidden_states,
|
113 |
+
encoder_attention_mask=encoder_attention_mask,
|
114 |
+
output_attentions=output_attentions,
|
115 |
+
output_hidden_states=True,
|
116 |
+
return_dict=return_dict,
|
117 |
+
)
|
118 |
+
|
119 |
+
# # last module outputs
|
120 |
+
# sequence_output = outputs[0]
|
121 |
+
|
122 |
+
|
123 |
+
# # project every module
|
124 |
+
# sequence_output_ln = self.pre_LN(sequence_output)
|
125 |
+
|
126 |
+
# # pooler
|
127 |
+
# pooler_output = self.pooler(sequence_output_ln)
|
128 |
+
# pooler_output = self.transformation(pooler_output)
|
129 |
+
# projection_state = self.transformation(outputs.last_hidden_state)
|
130 |
+
|
131 |
+
if self.has_pre_transformation:
|
132 |
+
sequence_output2 = outputs["hidden_states"][-2]
|
133 |
+
sequence_output2 = self.pre_LN(sequence_output2)
|
134 |
+
projection_state2 = self.transformation_pre(sequence_output2)
|
135 |
+
|
136 |
+
return {
|
137 |
+
"projection_state": projection_state2,
|
138 |
+
"last_hidden_state": outputs.last_hidden_state,
|
139 |
+
"hidden_states": outputs.hidden_states,
|
140 |
+
"attentions": outputs.attentions,
|
141 |
+
}
|
142 |
+
else:
|
143 |
+
projection_state = self.transformation(outputs.last_hidden_state)
|
144 |
+
return {
|
145 |
+
"projection_state": projection_state,
|
146 |
+
"last_hidden_state": outputs.last_hidden_state,
|
147 |
+
"hidden_states": outputs.hidden_states,
|
148 |
+
"attentions": outputs.attentions,
|
149 |
+
}
|
150 |
+
|
151 |
+
|
152 |
+
# return {
|
153 |
+
# 'pooler_output':pooler_output,
|
154 |
+
# 'last_hidden_state':outputs.last_hidden_state,
|
155 |
+
# 'hidden_states':outputs.hidden_states,
|
156 |
+
# 'attentions':outputs.attentions,
|
157 |
+
# 'projection_state':projection_state,
|
158 |
+
# 'sequence_out': sequence_output
|
159 |
+
# }
|
160 |
+
|
161 |
+
|
162 |
+
class RobertaSeriesModelWithTransformation(BertSeriesModelWithTransformation):
|
163 |
+
base_model_prefix = 'roberta'
|
164 |
+
config_class= RobertaSeriesConfig
|
modules/xpu_specific.py
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from modules import shared
|
2 |
+
from modules.sd_hijack_utils import CondFunc
|
3 |
+
|
4 |
+
has_ipex = False
|
5 |
+
try:
|
6 |
+
import torch
|
7 |
+
import intel_extension_for_pytorch as ipex # noqa: F401
|
8 |
+
has_ipex = True
|
9 |
+
except Exception:
|
10 |
+
pass
|
11 |
+
|
12 |
+
|
13 |
+
def check_for_xpu():
|
14 |
+
return has_ipex and hasattr(torch, 'xpu') and torch.xpu.is_available()
|
15 |
+
|
16 |
+
|
17 |
+
def get_xpu_device_string():
|
18 |
+
if shared.cmd_opts.device_id is not None:
|
19 |
+
return f"xpu:{shared.cmd_opts.device_id}"
|
20 |
+
return "xpu"
|
21 |
+
|
22 |
+
|
23 |
+
def torch_xpu_gc():
|
24 |
+
with torch.xpu.device(get_xpu_device_string()):
|
25 |
+
torch.xpu.empty_cache()
|
26 |
+
|
27 |
+
|
28 |
+
has_xpu = check_for_xpu()
|
29 |
+
|
30 |
+
if has_xpu:
|
31 |
+
# W/A for https://github.com/intel/intel-extension-for-pytorch/issues/452: torch.Generator API doesn't support XPU device
|
32 |
+
CondFunc('torch.Generator',
|
33 |
+
lambda orig_func, device=None: torch.xpu.Generator(device),
|
34 |
+
lambda orig_func, device=None: device is not None and device.type == "xpu")
|
35 |
+
|
36 |
+
# W/A for some OPs that could not handle different input dtypes
|
37 |
+
CondFunc('torch.nn.functional.layer_norm',
|
38 |
+
lambda orig_func, input, normalized_shape=None, weight=None, *args, **kwargs:
|
39 |
+
orig_func(input.to(weight.data.dtype), normalized_shape, weight, *args, **kwargs),
|
40 |
+
lambda orig_func, input, normalized_shape=None, weight=None, *args, **kwargs:
|
41 |
+
weight is not None and input.dtype != weight.data.dtype)
|
42 |
+
CondFunc('torch.nn.modules.GroupNorm.forward',
|
43 |
+
lambda orig_func, self, input: orig_func(self, input.to(self.weight.data.dtype)),
|
44 |
+
lambda orig_func, self, input: input.dtype != self.weight.data.dtype)
|
45 |
+
CondFunc('torch.nn.modules.linear.Linear.forward',
|
46 |
+
lambda orig_func, self, input: orig_func(self, input.to(self.weight.data.dtype)),
|
47 |
+
lambda orig_func, self, input: input.dtype != self.weight.data.dtype)
|
48 |
+
CondFunc('torch.nn.modules.conv.Conv2d.forward',
|
49 |
+
lambda orig_func, self, input: orig_func(self, input.to(self.weight.data.dtype)),
|
50 |
+
lambda orig_func, self, input: input.dtype != self.weight.data.dtype)
|
51 |
+
CondFunc('torch.bmm',
|
52 |
+
lambda orig_func, input, mat2, out=None: orig_func(input.to(mat2.dtype), mat2, out=out),
|
53 |
+
lambda orig_func, input, mat2, out=None: input.dtype != mat2.dtype)
|
54 |
+
CondFunc('torch.cat',
|
55 |
+
lambda orig_func, tensors, dim=0, out=None: orig_func([t.to(tensors[0].dtype) for t in tensors], dim=dim, out=out),
|
56 |
+
lambda orig_func, tensors, dim=0, out=None: not all(t.dtype == tensors[0].dtype for t in tensors))
|
57 |
+
CondFunc('torch.nn.functional.scaled_dot_product_attention',
|
58 |
+
lambda orig_func, query, key, value, attn_mask=None, dropout_p=0.0, is_causal=False: orig_func(query, key.to(query.dtype), value.to(query.dtype), attn_mask, dropout_p, is_causal),
|
59 |
+
lambda orig_func, query, key, value, attn_mask=None, dropout_p=0.0, is_causal=False: query.dtype != key.dtype or query.dtype != value.dtype)
|