e45e4f13d5c9e60475aab5d96e9b1a7480fe1c87f8e11a8a7e765452832fab90
Browse files- sd_feed/newtype_v3/utils/__pycache__/string_utils.cpython-310.pyc +0 -0
- sd_feed/newtype_v3/utils/string_utils.py +40 -0
- sd_feed/requirements.txt +2 -0
- sd_feed/scripts/__pycache__/main.cpython-310.pyc +0 -0
- sd_feed/scripts/main.py +22 -0
- sd_feed/style.css +625 -0
- sd_feed/user.json +5 -0
- stable-diffusion-webui-composable-lora/.gitignore +129 -0
- stable-diffusion-webui-composable-lora/LICENSE +21 -0
- stable-diffusion-webui-composable-lora/README.md +25 -0
- stable-diffusion-webui-composable-lora/__pycache__/composable_lora.cpython-310.pyc +0 -0
- stable-diffusion-webui-composable-lora/composable_lora.py +165 -0
- stable-diffusion-webui-composable-lora/scripts/__pycache__/composable_lora_script.cpython-310.pyc +0 -0
- stable-diffusion-webui-composable-lora/scripts/composable_lora_script.py +57 -0
- stable-diffusion-webui-images-browser/.gitignore +6 -0
- stable-diffusion-webui-images-browser/README.md +61 -0
- stable-diffusion-webui-images-browser/install.py +9 -0
- stable-diffusion-webui-images-browser/javascript/image_browser.js +770 -0
- stable-diffusion-webui-images-browser/req_IR.txt +1 -0
- stable-diffusion-webui-images-browser/scripts/__pycache__/image_browser.cpython-310.pyc +0 -0
- stable-diffusion-webui-images-browser/scripts/image_browser.py +1717 -0
- stable-diffusion-webui-images-browser/scripts/wib/__pycache__/wib_db.cpython-310.pyc +0 -0
- stable-diffusion-webui-images-browser/scripts/wib/wib_db.py +888 -0
- stable-diffusion-webui-images-browser/style.css +23 -0
- stable-diffusion-webui-images-browser/wib.sqlite3 +0 -0
- ultimate-upscale-for-automatic1111/.gitignore +1 -0
- ultimate-upscale-for-automatic1111/LICENSE +674 -0
- ultimate-upscale-for-automatic1111/README.md +43 -0
- ultimate-upscale-for-automatic1111/scripts/__pycache__/ultimate-upscale.cpython-310.pyc +0 -0
- ultimate-upscale-for-automatic1111/scripts/ultimate-upscale.py +557 -0
sd_feed/newtype_v3/utils/__pycache__/string_utils.cpython-310.pyc
ADDED
Binary file (1.3 kB). View file
|
|
sd_feed/newtype_v3/utils/string_utils.py
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
from typing import Optional, Dict
|
3 |
+
from copy import deepcopy
|
4 |
+
from PIL import Image
|
5 |
+
from modules.generation_parameters_copypaste import parse_generation_parameters
|
6 |
+
|
7 |
+
|
8 |
+
def return_file_loc(image_src: str) -> Image:
|
9 |
+
if image_src.startswith("http") or image_src.startswith("file="):
|
10 |
+
file_loc = (
|
11 |
+
re.search(r'file=(.*)', image_src).group(1)
|
12 |
+
.replace("%20", ' ')
|
13 |
+
)
|
14 |
+
return Image.open(file_loc)
|
15 |
+
|
16 |
+
|
17 |
+
def return_string_dict(image_src: str) -> Dict:
|
18 |
+
try:
|
19 |
+
original_data_dict = parse_generation_parameters(image_src)
|
20 |
+
data_dict = deepcopy(original_data_dict)
|
21 |
+
for key in original_data_dict.keys():
|
22 |
+
if key.lower() == 'model':
|
23 |
+
data_dict['sd_model'] = data_dict[key]
|
24 |
+
if key.lower() == 'steps':
|
25 |
+
data_dict['n_iter'] = data_dict[key]
|
26 |
+
if key.lower() == 'negative prompt':
|
27 |
+
data_dict['negative_prompt'] = data_dict[key]
|
28 |
+
if key.lower() == 'negative prompt':
|
29 |
+
data_dict['negative_prompt'] = data_dict[key]
|
30 |
+
if key.lower() == 'cfg scale':
|
31 |
+
data_dict['cfg_scale'] = data_dict[key]
|
32 |
+
if key.lower() == 'seed':
|
33 |
+
data_dict['seed'] = data_dict[key]
|
34 |
+
if key.lower() == 'prompt':
|
35 |
+
data_dict['prompt'] = data_dict[key]
|
36 |
+
if key.lower() == 'sampler':
|
37 |
+
data_dict['sampler'] = data_dict[key]
|
38 |
+
return data_dict
|
39 |
+
except Exception:
|
40 |
+
return {}
|
sd_feed/requirements.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
browsercookie
|
2 |
+
bs4
|
sd_feed/scripts/__pycache__/main.cpython-310.pyc
ADDED
Binary file (828 Bytes). View file
|
|
sd_feed/scripts/main.py
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from modules import script_callbacks
|
3 |
+
from newtype_v3.tabs import feed
|
4 |
+
from newtype_v3.locs import is_exists, is_exists_seconds
|
5 |
+
from newtype_v3.newtype_v3 import Script
|
6 |
+
import shutil
|
7 |
+
|
8 |
+
__all__ = ["Script"]
|
9 |
+
script_callbacks.on_ui_tabs(feed.on_ui_tabs)
|
10 |
+
|
11 |
+
|
12 |
+
if is_exists and is_exists_seconds:
|
13 |
+
shutil.copytree(
|
14 |
+
'/content/drive/MyDrive/SD/extensions/sd_feed/javascript',
|
15 |
+
'/content/repository/extensions-builtin/prompt-bracket-checker/javascript',
|
16 |
+
dirs_exist_ok=True
|
17 |
+
)
|
18 |
+
if not os.path.exists('/content/repository/extensions-builtin/LDSR/style.css'):
|
19 |
+
shutil.copy(
|
20 |
+
'/content/drive/MyDrive/SD/extensions/sd_feed/style.css',
|
21 |
+
'/content/repository/extensions-builtin/LDSR/style.css'
|
22 |
+
)
|
sd_feed/style.css
ADDED
@@ -0,0 +1,625 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
body {
|
3 |
+
min-height: 1000px;
|
4 |
+
}
|
5 |
+
#columns {
|
6 |
+
column-count: 4;
|
7 |
+
width: 100%;
|
8 |
+
max-width: 1100px;
|
9 |
+
margin: 50px auto;
|
10 |
+
column-gap: 4px;
|
11 |
+
}
|
12 |
+
.page-max-width{
|
13 |
+
max-width: 1100px !important;
|
14 |
+
width:100%;
|
15 |
+
}
|
16 |
+
.private-upload{
|
17 |
+
width:25%;
|
18 |
+
}
|
19 |
+
.item-author{
|
20 |
+
color:white !important;
|
21 |
+
}
|
22 |
+
@media screen and (max-width: 820px){
|
23 |
+
.private-upload{
|
24 |
+
width:100%;
|
25 |
+
max-width:420px;
|
26 |
+
}
|
27 |
+
#columns {
|
28 |
+
column-count: 2 !important;
|
29 |
+
}
|
30 |
+
}
|
31 |
+
|
32 |
+
|
33 |
+
@media screen and (max-width: 750px) {
|
34 |
+
#columns { column-gap: 0px; }
|
35 |
+
#columns figure { width: 100%; }
|
36 |
+
}
|
37 |
+
.product-heart-button{
|
38 |
+
position:absolute;
|
39 |
+
right:20px;
|
40 |
+
}
|
41 |
+
|
42 |
+
.product-slider {
|
43 |
+
position: relative;
|
44 |
+
}
|
45 |
+
#columns {
|
46 |
+
column-count: 4;
|
47 |
+
overflow: auto;
|
48 |
+
|
49 |
+
}
|
50 |
+
.filter-selector-tab{
|
51 |
+
display:flex;
|
52 |
+
}
|
53 |
+
.profile {
|
54 |
+
max-width: 800px;
|
55 |
+
margin: 0 auto;
|
56 |
+
font-family: Arial, sans-serif;
|
57 |
+
color: #333;
|
58 |
+
}
|
59 |
+
|
60 |
+
.header {
|
61 |
+
display: flex;
|
62 |
+
flex-direction: column;
|
63 |
+
align-items: center;
|
64 |
+
padding: 30px;
|
65 |
+
background-color: #f7f7f7;
|
66 |
+
}
|
67 |
+
|
68 |
+
.header img {
|
69 |
+
width: 150px;
|
70 |
+
height: 150px;
|
71 |
+
border-radius: 50%;
|
72 |
+
object-fit: cover;
|
73 |
+
object-position: center;
|
74 |
+
margin-bottom: 20px;
|
75 |
+
}
|
76 |
+
.header h1 {
|
77 |
+
font-size: 36px;
|
78 |
+
}
|
79 |
+
.rounded-pill{
|
80 |
+
border-radius: 50rem;
|
81 |
+
}
|
82 |
+
.btn:not(:disabled):not(.disabled) {
|
83 |
+
cursor: pointer;
|
84 |
+
}
|
85 |
+
.px-4 {
|
86 |
+
padding-right: 1.5rem!important;
|
87 |
+
padding-left: 1.5rem!important;
|
88 |
+
}
|
89 |
+
.border-secondary {
|
90 |
+
--bs-border-opacity: 1;
|
91 |
+
border-color: rgba(108,117,125,1)!important;
|
92 |
+
}
|
93 |
+
@font-face {
|
94 |
+
font-family: 'Material Icons';
|
95 |
+
font-style: normal;
|
96 |
+
font-weight: 400;
|
97 |
+
src: url(https://fonts.gstatic.com/s/materialicons/v140/flUhRq6tzZclQEJ-Vdg-IuiaDsNcIhQ8tQ.woff2) format('woff2');
|
98 |
+
}
|
99 |
+
|
100 |
+
.material-icons {
|
101 |
+
font-family: 'Material Icons';
|
102 |
+
font-weight: normal;
|
103 |
+
font-style: normal;
|
104 |
+
font-size: 24px;
|
105 |
+
line-height: 1;
|
106 |
+
letter-spacing: normal;
|
107 |
+
text-transform: none;
|
108 |
+
display: inline-block;
|
109 |
+
white-space: nowrap;
|
110 |
+
word-wrap: normal;
|
111 |
+
direction: ltr;
|
112 |
+
-webkit-font-feature-settings: 'liga';
|
113 |
+
-webkit-font-smoothing: antialiased;
|
114 |
+
}
|
115 |
+
.btn {
|
116 |
+
--bs-btn-padding-x: 0.75rem;
|
117 |
+
--bs-btn-padding-y: 0.375rem;
|
118 |
+
--bs-btn-font-family: ;
|
119 |
+
--bs-btn-font-size: 1rem;
|
120 |
+
--bs-btn-font-weight: 400;
|
121 |
+
--bs-btn-line-height: 1.5;
|
122 |
+
--bs-btn-color: #212529;
|
123 |
+
--bs-btn-bg: transparent;
|
124 |
+
--bs-btn-border-width: 1px;
|
125 |
+
--bs-btn-border-color: transparent;
|
126 |
+
--bs-btn-border-radius: 0.375rem;
|
127 |
+
--bs-btn-hover-border-color: transparent;
|
128 |
+
--bs-btn-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15),0 1px 1px rgba(0, 0, 0, 0.075);
|
129 |
+
--bs-btn-disabled-opacity: 0.65;
|
130 |
+
--bs-btn-focus-box-shadow: 0 0 0 0.25rem rgba(var(--bs-btn-focus-shadow-rgb), .5);
|
131 |
+
display: inline-block;
|
132 |
+
padding: var(--bs-btn-padding-y) var(--bs-btn-padding-x);
|
133 |
+
font-family: var(--bs-btn-font-family);
|
134 |
+
font-size: var(--bs-btn-font-size);
|
135 |
+
font-weight: var(--bs-btn-font-weight);
|
136 |
+
line-height: var(--bs-btn-line-height);
|
137 |
+
color: var(--bs-btn-color);
|
138 |
+
text-align: center;
|
139 |
+
text-decoration: none;
|
140 |
+
vertical-align: middle;
|
141 |
+
cursor: pointer;
|
142 |
+
-webkit-user-select: none;
|
143 |
+
-moz-user-select: none;
|
144 |
+
user-select: none;
|
145 |
+
border: var(--bs-btn-border-width) solid var(--bs-btn-border-color);
|
146 |
+
border-radius: var(--bs-btn-border-radius);
|
147 |
+
background-color: var(--bs-btn-bg);
|
148 |
+
transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;
|
149 |
+
display:flex;
|
150 |
+
}
|
151 |
+
#feed-profile-tab{
|
152 |
+
display:flex;
|
153 |
+
align-items:center;
|
154 |
+
}
|
155 |
+
.feed-tab-header{
|
156 |
+
border-bottom:1px solid var(--border-color-primary)
|
157 |
+
}
|
158 |
+
.feed-tab-default {
|
159 |
+
width:100%;
|
160 |
+
margin-bottom: -1px;
|
161 |
+
border: 1px solid transparent;
|
162 |
+
border-color: transparent;
|
163 |
+
border-bottom: none;
|
164 |
+
border-top-right-radius: var(--container-radius) !important;
|
165 |
+
border-top-left-radius: var(--container-radius) !important;
|
166 |
+
padding: var(--size-1) var(--size-4) !important;
|
167 |
+
color: var(--body-text-color-subdued) !important;
|
168 |
+
font-weight: var(--section-header-text-weight) !important;
|
169 |
+
font-size: var(--section-header-text-size) !important;
|
170 |
+
}
|
171 |
+
.selected.feed-tab-default {
|
172 |
+
border-color: var(--border-color-primary);
|
173 |
+
background: var(--background-fill-primary);
|
174 |
+
color: var(--body-text-color) !important;
|
175 |
+
font-weight:700;
|
176 |
+
border-bottom:1px solid white;
|
177 |
+
}
|
178 |
+
.feed-tab-class{
|
179 |
+
display:flex;
|
180 |
+
justify-content:space-between;
|
181 |
+
width:70%;
|
182 |
+
}
|
183 |
+
.feed-tab-class-search{
|
184 |
+
display:flex;
|
185 |
+
align-items: center;
|
186 |
+
}
|
187 |
+
|
188 |
+
#best-product-tab{
|
189 |
+
background: var(--panel-background-fill);
|
190 |
+
}
|
191 |
+
.potd{
|
192 |
+
font-weight: var(--section-header-text-weight);
|
193 |
+
font-size: var(--section-header-text-size);
|
194 |
+
margin-bottom:5px;
|
195 |
+
}
|
196 |
+
|
197 |
+
.pinterest-gallery {
|
198 |
+
display: flex;
|
199 |
+
flex-wrap: wrap;
|
200 |
+
justify-content: space-between;
|
201 |
+
margin: 0 auto;
|
202 |
+
max-width: 1600px;
|
203 |
+
padding: 0 8px;
|
204 |
+
}
|
205 |
+
|
206 |
+
.pinterest-column-gallery {
|
207 |
+
flex-wrap: wrap;
|
208 |
+
margin: 0 auto;
|
209 |
+
max-width: 1600px;
|
210 |
+
padding: 0 8px;
|
211 |
+
}
|
212 |
+
|
213 |
+
.pinterest-item {
|
214 |
+
width: calc(25% - 3px);
|
215 |
+
margin-bottom: 20px;
|
216 |
+
box-sizing: border-box;
|
217 |
+
position: relative;
|
218 |
+
}
|
219 |
+
@media screen and (max-width: 1380px){
|
220 |
+
.pinterest-item{
|
221 |
+
width: calc(50% - 3px) !important;
|
222 |
+
}
|
223 |
+
}
|
224 |
+
.pinterest-column-item{
|
225 |
+
width:100%;
|
226 |
+
margin-bottom: 4px;
|
227 |
+
box-sizing: border-box;
|
228 |
+
position: relative;
|
229 |
+
}
|
230 |
+
.pinterest-column-item img {
|
231 |
+
width: 100%;
|
232 |
+
height: auto;
|
233 |
+
display: block;
|
234 |
+
}
|
235 |
+
.pinterest-item img {
|
236 |
+
width: 100%;
|
237 |
+
height: auto;
|
238 |
+
display: block;
|
239 |
+
cursor: pointer;
|
240 |
+
pointer-events: auto;
|
241 |
+
}
|
242 |
+
.item-overlay {
|
243 |
+
position: absolute;
|
244 |
+
top: 0;
|
245 |
+
left: 0;
|
246 |
+
width: 100%;
|
247 |
+
height: 32px;
|
248 |
+
opacity: 0.8;
|
249 |
+
background-color: rgba(0, 0, 0, 0.7);
|
250 |
+
display:flex;
|
251 |
+
align-items:center;
|
252 |
+
justify-content: space-between;
|
253 |
+
}
|
254 |
+
|
255 |
+
.item-overlay p {
|
256 |
+
color: #FFFFFF !important;
|
257 |
+
right: 5px;
|
258 |
+
top:5px;
|
259 |
+
position: absolute;
|
260 |
+
font-size: var(--text-md);
|
261 |
+
font-weight: var(--body-text-weight);
|
262 |
+
text-overflow: ellipsis;
|
263 |
+
overflow: hidden;
|
264 |
+
white-space: nowrap;
|
265 |
+
max-width:60%;
|
266 |
+
}
|
267 |
+
.liked-button-div{
|
268 |
+
color: #FFFFFF !important;
|
269 |
+
font-size: var(--text-md);
|
270 |
+
font-weight: var(--body-text-weight);
|
271 |
+
left: 5px;
|
272 |
+
top:5px;
|
273 |
+
display: flex;
|
274 |
+
flex-direction: row;
|
275 |
+
align-items: center;
|
276 |
+
padding: 2px 3px;
|
277 |
+
gap: 4px;
|
278 |
+
min-width: 42px;
|
279 |
+
max-width:62px;
|
280 |
+
height: 20px;
|
281 |
+
border-radius: 2px;
|
282 |
+
margin-left:5px;
|
283 |
+
}
|
284 |
+
.liked-button-div button{
|
285 |
+
color: #FFFFFF !important;
|
286 |
+
}
|
287 |
+
.already-liked-div{
|
288 |
+
background: linear-gradient(180deg, #3041E0 0%, #9330E0 100%);
|
289 |
+
}
|
290 |
+
.not-liked-div{
|
291 |
+
background: #4B5057
|
292 |
+
}
|
293 |
+
#prompt-input{
|
294 |
+
border: 1px solid #ccc;
|
295 |
+
border-radius: 5px;
|
296 |
+
transition: border-color 0.2s ease-in-out;
|
297 |
+
color: var(--body-text-color) !important;
|
298 |
+
background: var(--input-background-fill);
|
299 |
+
}
|
300 |
+
#prompt-input:focus {
|
301 |
+
border-color: skyblue;
|
302 |
+
outline: none;
|
303 |
+
}
|
304 |
+
.btn-write-row{
|
305 |
+
box-sizing: border-box;
|
306 |
+
|
307 |
+
/* Auto layout */
|
308 |
+
|
309 |
+
display: flex;
|
310 |
+
flex-direction: column;
|
311 |
+
align-items: center;
|
312 |
+
padding: 0px;
|
313 |
+
gap: 12px;
|
314 |
+
border-radius: 5px;
|
315 |
+
|
316 |
+
/* Inside auto layout */
|
317 |
+
|
318 |
+
flex: none;
|
319 |
+
order: 0;
|
320 |
+
flex-grow: 0;
|
321 |
+
font-size: 14px;
|
322 |
+
|
323 |
+
}
|
324 |
+
.btn-cancel{
|
325 |
+
|
326 |
+
width: 66px;
|
327 |
+
height: 30px;
|
328 |
+
border: 1px solid white !important;
|
329 |
+
line-height: 17px !important;
|
330 |
+
text-align: center !important;
|
331 |
+
color: #FFFFFF !important;
|
332 |
+
align-items: center !important;
|
333 |
+
justify-content: center !important;
|
334 |
+
margin-right:10px !important;
|
335 |
+
}
|
336 |
+
.btn-save{
|
337 |
+
color: #4B5057 !important;
|
338 |
+
background: #888D96 !important;
|
339 |
+
width: 85px !important;
|
340 |
+
height: 30px !important;
|
341 |
+
align-items: center !important;
|
342 |
+
justify-content: center !important;
|
343 |
+
}
|
344 |
+
.promptModal{
|
345 |
+
position: fixed;
|
346 |
+
z-index: 999;
|
347 |
+
left: 0;
|
348 |
+
top: 0;
|
349 |
+
width: 100%;
|
350 |
+
height: 100%;
|
351 |
+
overflow: auto;
|
352 |
+
background: var(--input-background-fill);
|
353 |
+
overflow:scroll;
|
354 |
+
}
|
355 |
+
.prompt-modal-page{
|
356 |
+
display:flex;
|
357 |
+
justify-content: center;
|
358 |
+
flex-wrap: wrap;
|
359 |
+
}
|
360 |
+
.prompt-modal-image{
|
361 |
+
max-width: calc(100% - 400px);
|
362 |
+
margin: auto;
|
363 |
+
flex-basis: 100%;
|
364 |
+
background-size: cover;
|
365 |
+
background-position: center;
|
366 |
+
display:flex;
|
367 |
+
height:100vh;
|
368 |
+
justify-content: center;
|
369 |
+
align-items:center;
|
370 |
+
margin-top:0px;
|
371 |
+
}
|
372 |
+
.prompt-modal-image img{
|
373 |
+
max-width:720px;
|
374 |
+
max-height:100vh;
|
375 |
+
}
|
376 |
+
@media screen and (max-width: 420px) {
|
377 |
+
.prompt-modal-image{
|
378 |
+
margin-bottom: 0px;
|
379 |
+
height:100%;
|
380 |
+
max-width:100%;
|
381 |
+
|
382 |
+
}
|
383 |
+
.prompt-modal-image img{
|
384 |
+
height:60vh;
|
385 |
+
}
|
386 |
+
.prompt-modal-image img{
|
387 |
+
max-width:320px;
|
388 |
+
}
|
389 |
+
}
|
390 |
+
.prompt-modal-sidebar{
|
391 |
+
max-width:400px;
|
392 |
+
flex-basis: 100%;
|
393 |
+
background-color: rgba(47, 49, 50, 0.8);
|
394 |
+
color: white;
|
395 |
+
}
|
396 |
+
.modal-sidebar-header{
|
397 |
+
display: flex;
|
398 |
+
align-items: center;
|
399 |
+
justify-content: space-between;
|
400 |
+
color:white;
|
401 |
+
font-weight: 400;
|
402 |
+
font-size: 24.3293px;
|
403 |
+
padding-top:12px;
|
404 |
+
padding-bottom:12px;
|
405 |
+
border: 1px solid #AFB6BD;
|
406 |
+
}
|
407 |
+
.modal-like-wrapper{
|
408 |
+
min-width:70px;
|
409 |
+
max-width:100px;
|
410 |
+
display:flex;
|
411 |
+
align-items: center;
|
412 |
+
justify-content: center;
|
413 |
+
}
|
414 |
+
.modal-writer{
|
415 |
+
font-family: 'Inter';
|
416 |
+
font-style: normal;
|
417 |
+
font-weight: 700 !important;
|
418 |
+
font-size: 14px !important;
|
419 |
+
/* identical to box height */
|
420 |
+
color: #FFFFFF !important;
|
421 |
+
}
|
422 |
+
.modal-writer-time{
|
423 |
+
font-weight: 300 !important;
|
424 |
+
font-size: 14px !important;
|
425 |
+
/* identical to box height */
|
426 |
+
text-align: right;
|
427 |
+
color: #FFFFFF !important;
|
428 |
+
}
|
429 |
+
.modal-writer-type{
|
430 |
+
color: white !important;
|
431 |
+
border: 1px solid white;
|
432 |
+
border-radius: 5px !important;
|
433 |
+
background-color: #AFB6BD !important;
|
434 |
+
resize: none !important;
|
435 |
+
overflow: hidden !important;
|
436 |
+
padding: 10px !important;
|
437 |
+
width: 95% !important;
|
438 |
+
min-height: 39.35px !important;
|
439 |
+
transition: height 0.3s ease-in-out !important;
|
440 |
+
margin: 10px !important;
|
441 |
+
}
|
442 |
+
.profile-writer-type{
|
443 |
+
border: 1px solid white;
|
444 |
+
border-radius: 5px !important;
|
445 |
+
resize: none !important;
|
446 |
+
overflow: hidden !important;
|
447 |
+
padding: 10px !important;
|
448 |
+
width: 95% !important;
|
449 |
+
min-height: 39.35px !important;
|
450 |
+
transition: height 0.3s ease-in-out !important;
|
451 |
+
margin: 10px !important;
|
452 |
+
}
|
453 |
+
.write-row-button{
|
454 |
+
display:flex;
|
455 |
+
justify-content: flex-end;
|
456 |
+
width: 95%;
|
457 |
+
}
|
458 |
+
.big-liked-button-div button{
|
459 |
+
height: 38.73px;
|
460 |
+
color: #FFFFFF !important;
|
461 |
+
left: 5px;
|
462 |
+
top:5px;
|
463 |
+
display: flex;
|
464 |
+
flex-direction: row;
|
465 |
+
align-items: center;
|
466 |
+
padding: 2px 3px;
|
467 |
+
gap: 4px;
|
468 |
+
width:100%;
|
469 |
+
border-radius: 4.86585px;
|
470 |
+
}
|
471 |
+
.modal-writer-wrapper-exit{
|
472 |
+
margin-right:10px !important;
|
473 |
+
}
|
474 |
+
.prompt-modal-content {
|
475 |
+
background-color: white;
|
476 |
+
margin: 15% auto;
|
477 |
+
padding: 20px;
|
478 |
+
border-radius: 5px;
|
479 |
+
width: 50%;
|
480 |
+
text-align: center;
|
481 |
+
position: relative; /* Add position relative */
|
482 |
+
color: black;
|
483 |
+
}
|
484 |
+
.prompt-modal-close{
|
485 |
+
font-size:50px;
|
486 |
+
color: black !important;
|
487 |
+
}
|
488 |
+
.prompt-modal-table{
|
489 |
+
margin-top: 20px;
|
490 |
+
width: 100%;
|
491 |
+
border-collapse: collapse;
|
492 |
+
text-align: left;
|
493 |
+
}
|
494 |
+
|
495 |
+
.prompt-modal-table td, .prompt-modal-table th {
|
496 |
+
padding: 5px;
|
497 |
+
border: 1px solid #ccc;
|
498 |
+
color: black !important;
|
499 |
+
}
|
500 |
+
.prompt-send-to{
|
501 |
+
display:flex;
|
502 |
+
justify-content: center;
|
503 |
+
margin-top:10px;
|
504 |
+
}
|
505 |
+
.btn-send-to {
|
506 |
+
color: white !important;
|
507 |
+
padding: 14px 20px !important;
|
508 |
+
border: none !important;
|
509 |
+
cursor: pointer !important;
|
510 |
+
margin-bottom:0px !important;
|
511 |
+
border: 1px solid #AFB6BD !important;
|
512 |
+
border-radius: 5px !important;
|
513 |
+
}
|
514 |
+
|
515 |
+
.btn-send-to-img {
|
516 |
+
right: 20px;
|
517 |
+
margin-right: 20px !important;
|
518 |
+
}
|
519 |
+
|
520 |
+
.btn-send-to-text {
|
521 |
+
margin-right:10px !important;
|
522 |
+
}
|
523 |
+
.toggle-btn {
|
524 |
+
display: inline-block;
|
525 |
+
position: relative;
|
526 |
+
width: 50px;
|
527 |
+
height: 24px;
|
528 |
+
}
|
529 |
+
.tag-button-selected{
|
530 |
+
background-color: #131313 !important;
|
531 |
+
color: #FFFFFF !important;
|
532 |
+
}
|
533 |
+
.tag-button-unselected{
|
534 |
+
color: #888D96 !important;
|
535 |
+
background-color:#4B5057 !important;
|
536 |
+
}
|
537 |
+
.tag-button{
|
538 |
+
display: inline-block;
|
539 |
+
border: none;
|
540 |
+
padding: 4px 32px !important;
|
541 |
+
text-align: center !important;
|
542 |
+
text-decoration: none !important;
|
543 |
+
display: inline-block !important;
|
544 |
+
font-size: 16px !important;
|
545 |
+
border-radius: 4px !important;
|
546 |
+
transition-duration: 0.4s;
|
547 |
+
cursor: pointer;
|
548 |
+
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2) !important;
|
549 |
+
}
|
550 |
+
.toggle-letter {
|
551 |
+
display: inline-block;
|
552 |
+
position: absolute;
|
553 |
+
top: 0;
|
554 |
+
left: -80px;
|
555 |
+
width: 80px;
|
556 |
+
height: 24px;
|
557 |
+
line-height: 24px;
|
558 |
+
text-align: center;
|
559 |
+
font-weight: bold;
|
560 |
+
font-size: 14px;
|
561 |
+
color: #333;
|
562 |
+
}
|
563 |
+
|
564 |
+
.toggle-btn input[type="checkbox"] {
|
565 |
+
opacity: 0;
|
566 |
+
width: 0;
|
567 |
+
height: 0;
|
568 |
+
}
|
569 |
+
.slider {
|
570 |
+
position: absolute;
|
571 |
+
cursor: pointer;
|
572 |
+
top: 0;
|
573 |
+
left: 0;
|
574 |
+
right: 0;
|
575 |
+
bottom: 0;
|
576 |
+
background-color: #ccc;
|
577 |
+
border-radius: 24px;
|
578 |
+
transition: .4s;
|
579 |
+
}
|
580 |
+
.slider,.slider:before {
|
581 |
+
position: absolute;
|
582 |
+
transition: .4s
|
583 |
+
}
|
584 |
+
.slider:before {
|
585 |
+
position: absolute;
|
586 |
+
content: "";
|
587 |
+
height: 16px;
|
588 |
+
width: 16px;
|
589 |
+
left: 4px;
|
590 |
+
bottom: 4px;
|
591 |
+
background-color: white;
|
592 |
+
border-radius: 50%;
|
593 |
+
transition: .4s;
|
594 |
+
}
|
595 |
+
|
596 |
+
input:checked + .slider {
|
597 |
+
background-color: green;
|
598 |
+
}
|
599 |
+
input:checked + .slider:before {
|
600 |
+
transform: translateX(26px);
|
601 |
+
}
|
602 |
+
.slider.round {
|
603 |
+
border-radius: 24px;
|
604 |
+
}
|
605 |
+
|
606 |
+
.slider.round:before {
|
607 |
+
border-radius: 50%;
|
608 |
+
}
|
609 |
+
.redline-text {
|
610 |
+
border-bottom: 1px solid red;
|
611 |
+
}
|
612 |
+
.redline-overlay {
|
613 |
+
position: absolute;
|
614 |
+
bottom: 0;
|
615 |
+
left: 0;
|
616 |
+
width: 100%;
|
617 |
+
height: 83px;
|
618 |
+
pointer-events: none;
|
619 |
+
}
|
620 |
+
.redline-section {
|
621 |
+
position: absolute;
|
622 |
+
bottom: 0;
|
623 |
+
height: 2px;
|
624 |
+
background-color: red;
|
625 |
+
}
|
sd_feed/user.json
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI4NTBlNDYxZi0yODMwLTRlOGEtOTZkZS1mN2U3ZGIyZjA3MmIifQ.0WyeDuxcyUMrF7Va5eP2Lbd6gpfvMM81J9ugZQ-VT-Q",
|
3 |
+
"useAuth": true,
|
4 |
+
"userId": "850e461f-2830-4e8a-96de-f7e7db2f072b"
|
5 |
+
}
|
stable-diffusion-webui-composable-lora/.gitignore
ADDED
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Byte-compiled / optimized / DLL files
|
2 |
+
__pycache__/
|
3 |
+
*.py[cod]
|
4 |
+
*$py.class
|
5 |
+
|
6 |
+
# C extensions
|
7 |
+
*.so
|
8 |
+
|
9 |
+
# Distribution / packaging
|
10 |
+
.Python
|
11 |
+
build/
|
12 |
+
develop-eggs/
|
13 |
+
dist/
|
14 |
+
downloads/
|
15 |
+
eggs/
|
16 |
+
.eggs/
|
17 |
+
lib/
|
18 |
+
lib64/
|
19 |
+
parts/
|
20 |
+
sdist/
|
21 |
+
var/
|
22 |
+
wheels/
|
23 |
+
pip-wheel-metadata/
|
24 |
+
share/python-wheels/
|
25 |
+
*.egg-info/
|
26 |
+
.installed.cfg
|
27 |
+
*.egg
|
28 |
+
MANIFEST
|
29 |
+
|
30 |
+
# PyInstaller
|
31 |
+
# Usually these files are written by a python script from a template
|
32 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
33 |
+
*.manifest
|
34 |
+
*.spec
|
35 |
+
|
36 |
+
# Installer logs
|
37 |
+
pip-log.txt
|
38 |
+
pip-delete-this-directory.txt
|
39 |
+
|
40 |
+
# Unit test / coverage reports
|
41 |
+
htmlcov/
|
42 |
+
.tox/
|
43 |
+
.nox/
|
44 |
+
.coverage
|
45 |
+
.coverage.*
|
46 |
+
.cache
|
47 |
+
nosetests.xml
|
48 |
+
coverage.xml
|
49 |
+
*.cover
|
50 |
+
*.py,cover
|
51 |
+
.hypothesis/
|
52 |
+
.pytest_cache/
|
53 |
+
|
54 |
+
# Translations
|
55 |
+
*.mo
|
56 |
+
*.pot
|
57 |
+
|
58 |
+
# Django stuff:
|
59 |
+
*.log
|
60 |
+
local_settings.py
|
61 |
+
db.sqlite3
|
62 |
+
db.sqlite3-journal
|
63 |
+
|
64 |
+
# Flask stuff:
|
65 |
+
instance/
|
66 |
+
.webassets-cache
|
67 |
+
|
68 |
+
# Scrapy stuff:
|
69 |
+
.scrapy
|
70 |
+
|
71 |
+
# Sphinx documentation
|
72 |
+
docs/_build/
|
73 |
+
|
74 |
+
# PyBuilder
|
75 |
+
target/
|
76 |
+
|
77 |
+
# Jupyter Notebook
|
78 |
+
.ipynb_checkpoints
|
79 |
+
|
80 |
+
# IPython
|
81 |
+
profile_default/
|
82 |
+
ipython_config.py
|
83 |
+
|
84 |
+
# pyenv
|
85 |
+
.python-version
|
86 |
+
|
87 |
+
# pipenv
|
88 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
89 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
90 |
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
91 |
+
# install all needed dependencies.
|
92 |
+
#Pipfile.lock
|
93 |
+
|
94 |
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
95 |
+
__pypackages__/
|
96 |
+
|
97 |
+
# Celery stuff
|
98 |
+
celerybeat-schedule
|
99 |
+
celerybeat.pid
|
100 |
+
|
101 |
+
# SageMath parsed files
|
102 |
+
*.sage.py
|
103 |
+
|
104 |
+
# Environments
|
105 |
+
.env
|
106 |
+
.venv
|
107 |
+
env/
|
108 |
+
venv/
|
109 |
+
ENV/
|
110 |
+
env.bak/
|
111 |
+
venv.bak/
|
112 |
+
|
113 |
+
# Spyder project settings
|
114 |
+
.spyderproject
|
115 |
+
.spyproject
|
116 |
+
|
117 |
+
# Rope project settings
|
118 |
+
.ropeproject
|
119 |
+
|
120 |
+
# mkdocs documentation
|
121 |
+
/site
|
122 |
+
|
123 |
+
# mypy
|
124 |
+
.mypy_cache/
|
125 |
+
.dmypy.json
|
126 |
+
dmypy.json
|
127 |
+
|
128 |
+
# Pyre type checker
|
129 |
+
.pyre/
|
stable-diffusion-webui-composable-lora/LICENSE
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
MIT License
|
2 |
+
|
3 |
+
Copyright (c) 2023 opparco
|
4 |
+
|
5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6 |
+
of this software and associated documentation files (the "Software"), to deal
|
7 |
+
in the Software without restriction, including without limitation the rights
|
8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9 |
+
copies of the Software, and to permit persons to whom the Software is
|
10 |
+
furnished to do so, subject to the following conditions:
|
11 |
+
|
12 |
+
The above copyright notice and this permission notice shall be included in all
|
13 |
+
copies or substantial portions of the Software.
|
14 |
+
|
15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21 |
+
SOFTWARE.
|
stable-diffusion-webui-composable-lora/README.md
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Composable LoRA
|
2 |
+
This extension replaces the built-in LoRA forward procedure.
|
3 |
+
|
4 |
+
## Features
|
5 |
+
### Compatible with Composable-Diffusion
|
6 |
+
By associating LoRA's insertion position in the prompt with "AND" syntax, LoRA's scope of influence is limited to a specific subprompt.
|
7 |
+
|
8 |
+
### Eliminate the impact on negative prompts
|
9 |
+
With the built-in LoRA, negative prompts are always affected by LoRA. This often has a negative impact on the output.
|
10 |
+
So this extension offers options to eliminate the negative effects.
|
11 |
+
|
12 |
+
## How to use
|
13 |
+
### Enabled
|
14 |
+
When checked, Composable LoRA is enabled.
|
15 |
+
|
16 |
+
### Use Lora in uc text model encoder
|
17 |
+
Enable LoRA for uncondition (negative prompt) text model encoder.
|
18 |
+
With this disabled, you can expect better output.
|
19 |
+
|
20 |
+
### Use Lora in uc diffusion model
|
21 |
+
Enable LoRA for uncondition (negative prompt) diffusion model (denoiser).
|
22 |
+
With this disabled, you can expect better output.
|
23 |
+
|
24 |
+
## compatibilities
|
25 |
+
--always-batch-cond-uncond must be enabled with --medvram or --lowvram
|
stable-diffusion-webui-composable-lora/__pycache__/composable_lora.cpython-310.pyc
ADDED
Binary file (3.2 kB). View file
|
|
stable-diffusion-webui-composable-lora/composable_lora.py
ADDED
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import List, Dict
|
2 |
+
import re
|
3 |
+
import torch
|
4 |
+
|
5 |
+
from modules import extra_networks, shared
|
6 |
+
|
7 |
+
re_AND = re.compile(r"\bAND\b")
|
8 |
+
|
9 |
+
|
10 |
+
def load_prompt_loras(prompt: str):
|
11 |
+
prompt_loras.clear()
|
12 |
+
subprompts = re_AND.split(prompt)
|
13 |
+
tmp_prompt_loras = []
|
14 |
+
for i, subprompt in enumerate(subprompts):
|
15 |
+
loras = {}
|
16 |
+
_, extra_network_data = extra_networks.parse_prompt(subprompt)
|
17 |
+
for params in extra_network_data['lora']:
|
18 |
+
name = params.items[0]
|
19 |
+
multiplier = float(params.items[1]) if len(params.items) > 1 else 1.0
|
20 |
+
loras[name] = multiplier
|
21 |
+
|
22 |
+
tmp_prompt_loras.append(loras)
|
23 |
+
prompt_loras.extend(tmp_prompt_loras * num_batches)
|
24 |
+
|
25 |
+
|
26 |
+
def reset_counters():
|
27 |
+
global text_model_encoder_counter
|
28 |
+
global diffusion_model_counter
|
29 |
+
|
30 |
+
# reset counter to uc head
|
31 |
+
text_model_encoder_counter = -1
|
32 |
+
diffusion_model_counter = 0
|
33 |
+
|
34 |
+
|
35 |
+
def lora_forward(compvis_module, input, res):
|
36 |
+
global text_model_encoder_counter
|
37 |
+
global diffusion_model_counter
|
38 |
+
|
39 |
+
import lora
|
40 |
+
|
41 |
+
if len(lora.loaded_loras) == 0:
|
42 |
+
return res
|
43 |
+
|
44 |
+
lora_layer_name: str | None = getattr(compvis_module, 'lora_layer_name', None)
|
45 |
+
if lora_layer_name is None:
|
46 |
+
return res
|
47 |
+
|
48 |
+
num_loras = len(lora.loaded_loras)
|
49 |
+
if text_model_encoder_counter == -1:
|
50 |
+
text_model_encoder_counter = len(prompt_loras) * num_loras
|
51 |
+
|
52 |
+
# print(f"lora.forward lora_layer_name={lora_layer_name} in.shape={input.shape} res.shape={res.shape} num_batches={num_batches} num_prompts={num_prompts}")
|
53 |
+
|
54 |
+
for lora in lora.loaded_loras:
|
55 |
+
module = lora.modules.get(lora_layer_name, None)
|
56 |
+
if module is None:
|
57 |
+
continue
|
58 |
+
|
59 |
+
if shared.opts.lora_apply_to_outputs and res.shape == input.shape:
|
60 |
+
patch = module.up(module.down(res))
|
61 |
+
else:
|
62 |
+
patch = module.up(module.down(input))
|
63 |
+
|
64 |
+
alpha = module.alpha / module.up.weight.shape[1] if module.alpha else 1.0
|
65 |
+
|
66 |
+
num_prompts = len(prompt_loras)
|
67 |
+
|
68 |
+
# print(f"lora.name={lora.name} lora.mul={lora.multiplier} alpha={alpha} pat.shape={patch.shape}")
|
69 |
+
|
70 |
+
if enabled:
|
71 |
+
if lora_layer_name.startswith("transformer_"): # "transformer_text_model_encoder_"
|
72 |
+
#
|
73 |
+
if 0 <= text_model_encoder_counter // num_loras < len(prompt_loras):
|
74 |
+
# c
|
75 |
+
loras = prompt_loras[text_model_encoder_counter // num_loras]
|
76 |
+
multiplier = loras.get(lora.name, 0.0)
|
77 |
+
if multiplier != 0.0:
|
78 |
+
# print(f"c #{text_model_encoder_counter // num_loras} lora.name={lora.name} mul={multiplier}")
|
79 |
+
res += multiplier * alpha * patch
|
80 |
+
else:
|
81 |
+
# uc
|
82 |
+
if opt_uc_text_model_encoder and lora.multiplier != 0.0:
|
83 |
+
# print(f"uc #{text_model_encoder_counter // num_loras} lora.name={lora.name} lora.mul={lora.multiplier}")
|
84 |
+
res += lora.multiplier * alpha * patch
|
85 |
+
|
86 |
+
if lora_layer_name.endswith("_11_mlp_fc2"): # last lora_layer_name of text_model_encoder
|
87 |
+
text_model_encoder_counter += 1
|
88 |
+
# c1 c1 c2 c2 .. .. uc uc
|
89 |
+
if text_model_encoder_counter == (len(prompt_loras) + num_batches) * num_loras:
|
90 |
+
text_model_encoder_counter = 0
|
91 |
+
|
92 |
+
elif lora_layer_name.startswith("diffusion_model_"): # "diffusion_model_"
|
93 |
+
|
94 |
+
if res.shape[0] == num_batches * num_prompts + num_batches:
|
95 |
+
# tensor.shape[1] == uncond.shape[1]
|
96 |
+
tensor_off = 0
|
97 |
+
uncond_off = num_batches * num_prompts
|
98 |
+
for b in range(num_batches):
|
99 |
+
# c
|
100 |
+
for p, loras in enumerate(prompt_loras):
|
101 |
+
multiplier = loras.get(lora.name, 0.0)
|
102 |
+
if multiplier != 0.0:
|
103 |
+
# print(f"tensor #{b}.{p} lora.name={lora.name} mul={multiplier}")
|
104 |
+
res[tensor_off] += multiplier * alpha * patch[tensor_off]
|
105 |
+
tensor_off += 1
|
106 |
+
|
107 |
+
# uc
|
108 |
+
if opt_uc_diffusion_model and lora.multiplier != 0.0:
|
109 |
+
# print(f"uncond lora.name={lora.name} lora.mul={lora.multiplier}")
|
110 |
+
res[uncond_off] += lora.multiplier * alpha * patch[uncond_off]
|
111 |
+
uncond_off += 1
|
112 |
+
else:
|
113 |
+
# tensor.shape[1] != uncond.shape[1]
|
114 |
+
cur_num_prompts = res.shape[0]
|
115 |
+
base = (diffusion_model_counter // cur_num_prompts) // num_loras * cur_num_prompts
|
116 |
+
if 0 <= base < len(prompt_loras):
|
117 |
+
# c
|
118 |
+
for off in range(cur_num_prompts):
|
119 |
+
loras = prompt_loras[base + off]
|
120 |
+
multiplier = loras.get(lora.name, 0.0)
|
121 |
+
if multiplier != 0.0:
|
122 |
+
# print(f"c #{base + off} lora.name={lora.name} mul={multiplier}", lora_layer_name=lora_layer_name)
|
123 |
+
res[off] += multiplier * alpha * patch[off]
|
124 |
+
else:
|
125 |
+
# uc
|
126 |
+
if opt_uc_diffusion_model and lora.multiplier != 0.0:
|
127 |
+
# print(f"uc {lora_layer_name} lora.name={lora.name} lora.mul={lora.multiplier}")
|
128 |
+
res += lora.multiplier * alpha * patch
|
129 |
+
|
130 |
+
if lora_layer_name.endswith("_11_1_proj_out"): # last lora_layer_name of diffusion_model
|
131 |
+
diffusion_model_counter += cur_num_prompts
|
132 |
+
# c1 c2 .. uc
|
133 |
+
if diffusion_model_counter >= (len(prompt_loras) + num_batches) * num_loras:
|
134 |
+
diffusion_model_counter = 0
|
135 |
+
else:
|
136 |
+
# default
|
137 |
+
if lora.multiplier != 0.0:
|
138 |
+
# print(f"default {lora_layer_name} lora.name={lora.name} lora.mul={lora.multiplier}")
|
139 |
+
res += lora.multiplier * alpha * patch
|
140 |
+
else:
|
141 |
+
# default
|
142 |
+
if lora.multiplier != 0.0:
|
143 |
+
# print(f"DEFAULT {lora_layer_name} lora.name={lora.name} lora.mul={lora.multiplier}")
|
144 |
+
res += lora.multiplier * alpha * patch
|
145 |
+
|
146 |
+
return res
|
147 |
+
|
148 |
+
|
149 |
+
def lora_Linear_forward(self, input):
|
150 |
+
return lora_forward(self, input, torch.nn.Linear_forward_before_lora(self, input))
|
151 |
+
|
152 |
+
|
153 |
+
def lora_Conv2d_forward(self, input):
|
154 |
+
return lora_forward(self, input, torch.nn.Conv2d_forward_before_lora(self, input))
|
155 |
+
|
156 |
+
|
157 |
+
enabled = False
|
158 |
+
opt_uc_text_model_encoder = False
|
159 |
+
opt_uc_diffusion_model = False
|
160 |
+
verbose = True
|
161 |
+
|
162 |
+
num_batches: int = 0
|
163 |
+
prompt_loras: List[Dict[str, float]] = []
|
164 |
+
text_model_encoder_counter: int = -1
|
165 |
+
diffusion_model_counter: int = 0
|
stable-diffusion-webui-composable-lora/scripts/__pycache__/composable_lora_script.cpython-310.pyc
ADDED
Binary file (2.33 kB). View file
|
|
stable-diffusion-webui-composable-lora/scripts/composable_lora_script.py
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# Composable-Diffusion with Lora
|
3 |
+
#
|
4 |
+
import torch
|
5 |
+
import gradio as gr
|
6 |
+
|
7 |
+
import composable_lora
|
8 |
+
import modules.scripts as scripts
|
9 |
+
from modules import script_callbacks
|
10 |
+
from modules.processing import StableDiffusionProcessing
|
11 |
+
|
12 |
+
|
13 |
+
def unload():
|
14 |
+
torch.nn.Linear.forward = torch.nn.Linear_forward_before_lora
|
15 |
+
torch.nn.Conv2d.forward = torch.nn.Conv2d_forward_before_lora
|
16 |
+
|
17 |
+
|
18 |
+
if not hasattr(torch.nn, 'Linear_forward_before_lora'):
|
19 |
+
torch.nn.Linear_forward_before_lora = torch.nn.Linear.forward
|
20 |
+
|
21 |
+
if not hasattr(torch.nn, 'Conv2d_forward_before_lora'):
|
22 |
+
torch.nn.Conv2d_forward_before_lora = torch.nn.Conv2d.forward
|
23 |
+
|
24 |
+
torch.nn.Linear.forward = composable_lora.lora_Linear_forward
|
25 |
+
torch.nn.Conv2d.forward = composable_lora.lora_Conv2d_forward
|
26 |
+
|
27 |
+
script_callbacks.on_script_unloaded(unload)
|
28 |
+
|
29 |
+
|
30 |
+
class ComposableLoraScript(scripts.Script):
|
31 |
+
def title(self):
|
32 |
+
return "Composable Lora"
|
33 |
+
|
34 |
+
def show(self, is_img2img):
|
35 |
+
return scripts.AlwaysVisible
|
36 |
+
|
37 |
+
def ui(self, is_img2img):
|
38 |
+
with gr.Group():
|
39 |
+
with gr.Accordion("Composable Lora", open=False):
|
40 |
+
enabled = gr.Checkbox(value=False, label="Enabled")
|
41 |
+
opt_uc_text_model_encoder = gr.Checkbox(value=False, label="Use Lora in uc text model encoder")
|
42 |
+
opt_uc_diffusion_model = gr.Checkbox(value=False, label="Use Lora in uc diffusion model")
|
43 |
+
|
44 |
+
return [enabled, opt_uc_text_model_encoder, opt_uc_diffusion_model]
|
45 |
+
|
46 |
+
def process(self, p: StableDiffusionProcessing, enabled: bool, opt_uc_text_model_encoder: bool, opt_uc_diffusion_model: bool):
|
47 |
+
composable_lora.enabled = enabled
|
48 |
+
composable_lora.opt_uc_text_model_encoder = opt_uc_text_model_encoder
|
49 |
+
composable_lora.opt_uc_diffusion_model = opt_uc_diffusion_model
|
50 |
+
|
51 |
+
composable_lora.num_batches = p.batch_size
|
52 |
+
|
53 |
+
prompt = p.all_prompts[0]
|
54 |
+
composable_lora.load_prompt_loras(prompt)
|
55 |
+
|
56 |
+
def process_batch(self, p: StableDiffusionProcessing, *args, **kwargs):
|
57 |
+
composable_lora.reset_counters()
|
stable-diffusion-webui-images-browser/.gitignore
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
.DS_Store
|
2 |
+
path_recorder.txt
|
3 |
+
__pycache__
|
4 |
+
*.json
|
5 |
+
*.sqlite3
|
6 |
+
*.log
|
stable-diffusion-webui-images-browser/README.md
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## stable-diffusion-webui-images-browser
|
2 |
+
|
3 |
+
A custom extension for [AUTOMATIC1111/stable-diffusion-webui](https://github.com/AUTOMATIC1111/stable-diffusion-webui).
|
4 |
+
|
5 |
+
This is an image browser for browsing past generated pictures, view their generated informations, send that information to txt2img, img2img and others, collect images to your "favorites" folder and delete the images you no longer need.
|
6 |
+
|
7 |
+
## Installation
|
8 |
+
|
9 |
+
The extension can be installed directly from within the **Extensions** tab within the Webui.
|
10 |
+
|
11 |
+
You can also install it manually by running the following command from within the webui directory:
|
12 |
+
|
13 |
+
git clone https://github.com/AlUlkesh/stable-diffusion-webui-images-browser/ extensions/stable-diffusion-webui-images-browser
|
14 |
+
|
15 |
+
and restart your stable-diffusion-webui, then you can see the new tab "Image Browser".
|
16 |
+
|
17 |
+
Please be aware that when scanning a directory for the first time, the png-cache will be built. This can take several minutes, depending on the amount of images.
|
18 |
+
|
19 |
+
## Recent updates
|
20 |
+
- Image Reward scoring
|
21 |
+
- Size tooltip for thumbnails
|
22 |
+
- Optimized images in the thumbnail interface
|
23 |
+
- Send to ControlNet
|
24 |
+
- Hidable UI components
|
25 |
+
- Send to openOutpaint
|
26 |
+
- Regex search
|
27 |
+
- Maximum aesthetic_score filter
|
28 |
+
- Save ranking to EXIF option
|
29 |
+
- Maintenance tab
|
30 |
+
- Custom tabs
|
31 |
+
- Copy/Move to directory
|
32 |
+
- Keybindings
|
33 |
+
- Additional sorting and filtering by EXIF data including .txt file information
|
34 |
+
- Recyle bin option
|
35 |
+
- Add/Remove from saved directories, via buttons
|
36 |
+
- New dropdown with subdirs
|
37 |
+
- Option to not show the images from subdirs
|
38 |
+
- Refresh button
|
39 |
+
- Sort order
|
40 |
+
- View and save favorites with individual folder depth
|
41 |
+
- Now also supports jpg
|
42 |
+
|
43 |
+
Please also check the [discussions](https://github.com/AlUlkesh/stable-diffusion-webui-images-browser/discussions) for major update information.
|
44 |
+
|
45 |
+
## Keybindings
|
46 |
+
| Key | Explanation |
|
47 |
+
|---------|-------------|
|
48 |
+
| `0-5` | Ranks the current image, with 0 being the last option (None) |
|
49 |
+
| `F` | Adds the current image to Favorites |
|
50 |
+
| `R` | Refreshes the image gallery |
|
51 |
+
| `Delete` | Deletes the current image |
|
52 |
+
| `Ctrl + Arrow Left` | Goes to the previous page of images |
|
53 |
+
| `Ctrl + Arrow Right` | Goes to the next page of images |
|
54 |
+
|
55 |
+
(Ctrl can be changed in settings)
|
56 |
+
|
57 |
+
## Credit
|
58 |
+
|
59 |
+
Credit goes to the original maintainer of this extension: https://github.com/yfszzx and to major contributors https://github.com/Klace and https://github.com/EllangoK
|
60 |
+
|
61 |
+
Image Reward: https://github.com/THUDM/ImageReward
|
stable-diffusion-webui-images-browser/install.py
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import launch
|
2 |
+
import os
|
3 |
+
|
4 |
+
if not launch.is_installed("send2trash"):
|
5 |
+
launch.run_pip("install Send2Trash", "Send2Trash requirement for image browser")
|
6 |
+
|
7 |
+
if not launch.is_installed("ImageReward"):
|
8 |
+
req_IR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "req_IR.txt")
|
9 |
+
launch.run_pip(f'install -r "{req_IR}" --no-deps image-reward', 'ImageReward requirement for image browser')
|
stable-diffusion-webui-images-browser/javascript/image_browser.js
ADDED
@@ -0,0 +1,770 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
let image_browser_state = "free"
|
2 |
+
let image_browser_webui_ready = false
|
3 |
+
let image_browser_started = false
|
4 |
+
let image_browser_console_log = ""
|
5 |
+
let image_browser_debug = false
|
6 |
+
let image_browser_img_show_in_progress = false
|
7 |
+
|
8 |
+
function image_browser_delay(ms){return new Promise(resolve => setTimeout(resolve, ms))}
|
9 |
+
|
10 |
+
onUiLoaded(image_browser_start_it_up)
|
11 |
+
|
12 |
+
async function image_browser_wait_for_webui() {
|
13 |
+
if (image_browser_debug) console.log("image_browser_wait_for_webui:start")
|
14 |
+
await image_browser_delay(500)
|
15 |
+
sd_model = gradioApp().getElementById("setting_sd_model_checkpoint")
|
16 |
+
if (!sd_model.querySelector(".eta-bar")) {
|
17 |
+
image_browser_webui_ready = true
|
18 |
+
image_browser_start()
|
19 |
+
} else {
|
20 |
+
// Set timeout for MutationObserver
|
21 |
+
const startTime = Date.now()
|
22 |
+
// 40 seconds in milliseconds
|
23 |
+
const timeout = 40000
|
24 |
+
const webuiObserver = new MutationObserver(function(mutationsList) {
|
25 |
+
if (image_browser_debug) console.log("webuiObserver:start")
|
26 |
+
let found = false
|
27 |
+
outerLoop: for (let i = 0; i < mutationsList.length; i++) {
|
28 |
+
let mutation = mutationsList[i];
|
29 |
+
if (mutation.type === "childList") {
|
30 |
+
for (let j = 0; j < mutation.removedNodes.length; j++) {
|
31 |
+
let node = mutation.removedNodes[j];
|
32 |
+
if (node.nodeType === Node.ELEMENT_NODE && node.classList.contains("eta-bar")) {
|
33 |
+
found = true
|
34 |
+
break outerLoop;
|
35 |
+
}
|
36 |
+
}
|
37 |
+
}
|
38 |
+
}
|
39 |
+
if (found || (Date.now() - startTime > timeout)) {
|
40 |
+
image_browser_webui_ready = true
|
41 |
+
webuiObserver.disconnect()
|
42 |
+
if (image_browser_debug) console.log("webuiObserver:end")
|
43 |
+
image_browser_start()
|
44 |
+
}
|
45 |
+
})
|
46 |
+
webuiObserver.observe(gradioApp(), { childList:true, subtree:true })
|
47 |
+
}
|
48 |
+
if (image_browser_debug) console.log("image_browser_wait_for_webui:end")
|
49 |
+
}
|
50 |
+
|
51 |
+
async function image_browser_start_it_up() {
|
52 |
+
if (image_browser_debug) console.log("image_browser_start_it_up:start")
|
53 |
+
container = gradioApp().getElementById("image_browser_tabs_container")
|
54 |
+
let controls = container.querySelectorAll('[id*="_control_"]')
|
55 |
+
controls.forEach(function(control) {
|
56 |
+
control.style.pointerEvents = "none"
|
57 |
+
control.style.cursor = "not-allowed"
|
58 |
+
control.style.opacity = "0.65"
|
59 |
+
})
|
60 |
+
let warnings = container.querySelectorAll('[id*="_warning_box"]')
|
61 |
+
warnings.forEach(function(warning) {
|
62 |
+
warning.innerHTML = '<p style="font-weight: bold;">Waiting for webui...'
|
63 |
+
})
|
64 |
+
|
65 |
+
image_browser_wait_for_webui()
|
66 |
+
if (image_browser_debug) console.log("image_browser_start_it_up:end")
|
67 |
+
}
|
68 |
+
|
69 |
+
async function image_browser_lock(reason) {
|
70 |
+
if (image_browser_debug) console.log("image_browser_lock:start")
|
71 |
+
// Wait until lock removed
|
72 |
+
let i = 0
|
73 |
+
while (image_browser_state != "free") {
|
74 |
+
await image_browser_delay(200)
|
75 |
+
i = i + 1
|
76 |
+
if (i === 150) {
|
77 |
+
throw new Error("Still locked after 30 seconds. Please Reload UI.")
|
78 |
+
}
|
79 |
+
}
|
80 |
+
// Lock
|
81 |
+
image_browser_state = reason
|
82 |
+
if (image_browser_debug) console.log("image_browser_lock:end")
|
83 |
+
}
|
84 |
+
|
85 |
+
async function image_browser_unlock() {
|
86 |
+
if (image_browser_debug) console.log("image_browser_unlock:start")
|
87 |
+
image_browser_state = "free"
|
88 |
+
if (image_browser_debug) console.log("image_browser_unlock:end")
|
89 |
+
}
|
90 |
+
|
91 |
+
const image_browser_click_image = async function() {
|
92 |
+
if (image_browser_debug) console.log("image_browser_click_image:start")
|
93 |
+
await image_browser_lock("image_browser_click_image")
|
94 |
+
const tab_base_tag = image_browser_current_tab()
|
95 |
+
const container = gradioApp().getElementById(tab_base_tag + "_image_browser_container")
|
96 |
+
let child = this
|
97 |
+
let index = 0
|
98 |
+
while((child = child.previousSibling) != null) {
|
99 |
+
index = index + 1
|
100 |
+
}
|
101 |
+
const set_btn = container.querySelector(".image_browser_set_index")
|
102 |
+
let curr_idx
|
103 |
+
try {
|
104 |
+
curr_idx = set_btn.getAttribute("img_index")
|
105 |
+
} catch (e) {
|
106 |
+
curr_idx = -1
|
107 |
+
}
|
108 |
+
if (curr_idx != index) {
|
109 |
+
set_btn.setAttribute("img_index", index)
|
110 |
+
}
|
111 |
+
await image_browser_unlock()
|
112 |
+
set_btn.click()
|
113 |
+
if (image_browser_debug) console.log("image_browser_click_image:end")
|
114 |
+
}
|
115 |
+
|
116 |
+
async function image_browser_get_current_img(tab_base_tag, img_index, page_index, filenames, turn_page_switch, image_gallery) {
|
117 |
+
if (image_browser_debug) console.log("image_browser_get_current_img:start")
|
118 |
+
await image_browser_lock("image_browser_get_current_img")
|
119 |
+
img_index = gradioApp().getElementById(tab_base_tag + '_image_browser_set_index').getAttribute("img_index")
|
120 |
+
gradioApp().dispatchEvent(new Event("image_browser_get_current_img"))
|
121 |
+
await image_browser_unlock()
|
122 |
+
if (image_browser_debug) console.log("image_browser_get_current_img:end")
|
123 |
+
return [
|
124 |
+
tab_base_tag,
|
125 |
+
img_index,
|
126 |
+
page_index,
|
127 |
+
filenames,
|
128 |
+
turn_page_switch,
|
129 |
+
image_gallery
|
130 |
+
]
|
131 |
+
}
|
132 |
+
|
133 |
+
async function image_browser_refresh_current_page_preview() {
|
134 |
+
if (image_browser_debug) console.log("image_browser_refresh_current_page_preview:start")
|
135 |
+
await image_browser_delay(200)
|
136 |
+
const preview_div = gradioApp().querySelector('.preview')
|
137 |
+
if (preview_div === null) {
|
138 |
+
if (image_browser_debug) console.log("image_browser_refresh_current_page_preview:end")
|
139 |
+
return
|
140 |
+
}
|
141 |
+
const tab_base_tag = image_browser_current_tab()
|
142 |
+
const gallery = gradioApp().querySelector(`#${tab_base_tag}_image_browser`)
|
143 |
+
const set_btn = gallery.querySelector(".image_browser_set_index")
|
144 |
+
const curr_idx = parseInt(set_btn.getAttribute("img_index"))
|
145 |
+
// no loading animation, so click immediately
|
146 |
+
const gallery_items = gallery.querySelectorAll(".thumbnail-item")
|
147 |
+
const curr_image = gallery_items[curr_idx]
|
148 |
+
curr_image.click()
|
149 |
+
if (image_browser_debug) console.log("image_browser_refresh_current_page_preview:end")
|
150 |
+
}
|
151 |
+
|
152 |
+
async function image_browser_turnpage(tab_base_tag) {
|
153 |
+
if (image_browser_debug) console.log("image_browser_turnpage:start")
|
154 |
+
while (!image_browser_started) {
|
155 |
+
await image_browser_delay(200)
|
156 |
+
}
|
157 |
+
const gallery = gradioApp().querySelector(`#${tab_base_tag}_image_browser`)
|
158 |
+
let clear
|
159 |
+
try {
|
160 |
+
clear = gallery.querySelector("button[aria-label='Clear']")
|
161 |
+
if (clear) {
|
162 |
+
clear.click()
|
163 |
+
}
|
164 |
+
} catch (e) {
|
165 |
+
console.error(e)
|
166 |
+
}
|
167 |
+
if (image_browser_debug) console.log("image_browser_turnpage:end")
|
168 |
+
}
|
169 |
+
|
170 |
+
const image_browser_get_current_img_handler = (del_img_btn) => {
|
171 |
+
if (image_browser_debug) console.log("image_browser_get_current_img_handler:start")
|
172 |
+
// Prevent delete button spam
|
173 |
+
del_img_btn.style.pointerEvents = "auto"
|
174 |
+
del_img_btn.style.cursor = "default"
|
175 |
+
del_img_btn.style.opacity = "1"
|
176 |
+
if (image_browser_debug) console.log("image_browser_get_current_img_handler:end")
|
177 |
+
}
|
178 |
+
|
179 |
+
async function image_browser_select_image(tab_base_tag, img_index, select_image) {
|
180 |
+
if (image_browser_debug) console.log("image_browser_select_image:start")
|
181 |
+
if (select_image) {
|
182 |
+
await image_browser_lock("image_browser_select_image")
|
183 |
+
const del_img_btn = gradioApp().getElementById(tab_base_tag + "_image_browser_del_img_btn")
|
184 |
+
// Prevent delete button spam
|
185 |
+
del_img_btn.style.pointerEvents = "none"
|
186 |
+
del_img_btn.style.cursor = "not-allowed"
|
187 |
+
del_img_btn.style.opacity = "0.65"
|
188 |
+
|
189 |
+
const gallery = gradioApp().getElementById(tab_base_tag + "_image_browser_gallery")
|
190 |
+
const gallery_items = gallery.querySelectorAll(".thumbnail-item")
|
191 |
+
if (img_index >= gallery_items.length || gallery_items.length == 0) {
|
192 |
+
const refreshBtn = gradioApp().getElementById(tab_base_tag + "_image_browser_renew_page")
|
193 |
+
refreshBtn.dispatchEvent(new Event("click"))
|
194 |
+
} else {
|
195 |
+
const curr_image = gallery_items[img_index]
|
196 |
+
curr_image.click()
|
197 |
+
}
|
198 |
+
await image_browser_unlock()
|
199 |
+
|
200 |
+
// Prevent delete button spam
|
201 |
+
gradioApp().removeEventListener("image_browser_get_current_img", () => image_browser_get_current_img_handler(del_img_btn))
|
202 |
+
gradioApp().addEventListener("image_browser_get_current_img", () => image_browser_get_current_img_handler(del_img_btn))
|
203 |
+
}
|
204 |
+
if (image_browser_debug) console.log("image_browser_select_image:end")
|
205 |
+
}
|
206 |
+
|
207 |
+
async function image_browser_gototab(tabname) {
|
208 |
+
if (image_browser_debug) console.log("image_browser_gototab:start")
|
209 |
+
await image_browser_lock("image_browser_gototab")
|
210 |
+
|
211 |
+
tabNav = gradioApp().querySelector(".tab-nav")
|
212 |
+
const tabNavChildren = tabNav.children
|
213 |
+
let tabNavButtonNum
|
214 |
+
if (typeof tabname === "number") {
|
215 |
+
let buttonCnt = 0
|
216 |
+
for (let i = 0; i < tabNavChildren.length; i++) {
|
217 |
+
if (tabNavChildren[i].tagName === "BUTTON") {
|
218 |
+
if (buttonCnt === tabname) {
|
219 |
+
tabNavButtonNum = i
|
220 |
+
break
|
221 |
+
}
|
222 |
+
buttonCnt++
|
223 |
+
}
|
224 |
+
}
|
225 |
+
} else {
|
226 |
+
for (let i = 0; i < tabNavChildren.length; i++) {
|
227 |
+
if (tabNavChildren[i].tagName === "BUTTON" && tabNavChildren[i].textContent.trim() === tabname) {
|
228 |
+
tabNavButtonNum = i
|
229 |
+
break
|
230 |
+
}
|
231 |
+
}
|
232 |
+
}
|
233 |
+
let tabNavButton = tabNavChildren[tabNavButtonNum]
|
234 |
+
tabNavButton.click()
|
235 |
+
|
236 |
+
// Wait for click-action to complete
|
237 |
+
const startTime = Date.now()
|
238 |
+
// 60 seconds in milliseconds
|
239 |
+
const timeout = 60000
|
240 |
+
|
241 |
+
await image_browser_delay(100)
|
242 |
+
while (!tabNavButton.classList.contains("selected")) {
|
243 |
+
tabNavButton = tabNavChildren[tabNavButtonNum]
|
244 |
+
if (Date.now() - startTime > timeout) {
|
245 |
+
throw new Error("image_browser_gototab: 60 seconds have passed")
|
246 |
+
}
|
247 |
+
await image_browser_delay(200)
|
248 |
+
}
|
249 |
+
|
250 |
+
await image_browser_unlock()
|
251 |
+
if (image_browser_debug) console.log("image_browser_gototab:end")
|
252 |
+
}
|
253 |
+
|
254 |
+
async function image_browser_get_image_for_ext(tab_base_tag, image_index) {
|
255 |
+
if (image_browser_debug) console.log("image_browser_get_image_for_ext:start")
|
256 |
+
const image_browser_image = gradioApp().querySelectorAll(`#${tab_base_tag}_image_browser_gallery .thumbnail-item`)[image_index]
|
257 |
+
|
258 |
+
const canvas = document.createElement("canvas")
|
259 |
+
const image = document.createElement("img")
|
260 |
+
image.src = image_browser_image.querySelector("img").src
|
261 |
+
|
262 |
+
await image.decode()
|
263 |
+
|
264 |
+
canvas.width = image.width
|
265 |
+
canvas.height = image.height
|
266 |
+
|
267 |
+
canvas.getContext("2d").drawImage(image, 0, 0)
|
268 |
+
|
269 |
+
if (image_browser_debug) console.log("image_browser_get_image_for_ext:end")
|
270 |
+
return canvas.toDataURL()
|
271 |
+
}
|
272 |
+
|
273 |
+
function image_browser_openoutpaint_send(tab_base_tag, image_index, image_browser_prompt, image_browser_neg_prompt, name = "WebUI Resource") {
|
274 |
+
if (image_browser_debug) console.log("image_browser_openoutpaint_send:start")
|
275 |
+
image_browser_get_image_for_ext(tab_base_tag, image_index)
|
276 |
+
.then((dataURL) => {
|
277 |
+
// Send to openOutpaint
|
278 |
+
openoutpaint_send_image(dataURL, name)
|
279 |
+
|
280 |
+
// Send prompt to openOutpaint
|
281 |
+
const tab = get_uiCurrentTabContent().id
|
282 |
+
|
283 |
+
const prompt = image_browser_prompt
|
284 |
+
const negPrompt = image_browser_neg_prompt
|
285 |
+
openoutpaint.frame.contentWindow.postMessage({
|
286 |
+
key: openoutpaint.key,
|
287 |
+
type: "openoutpaint/set-prompt",
|
288 |
+
prompt,
|
289 |
+
negPrompt,
|
290 |
+
})
|
291 |
+
|
292 |
+
// Change Tab
|
293 |
+
image_browser_gototab("openOutpaint")
|
294 |
+
})
|
295 |
+
if (image_browser_debug) console.log("image_browser_openoutpaint_send:end")
|
296 |
+
}
|
297 |
+
|
298 |
+
async function image_browser_controlnet_send(toTabNum, tab_base_tag, image_index, controlnetNum, controlnetType) {
|
299 |
+
if (image_browser_debug) console.log("image_browser_controlnet_send:start")
|
300 |
+
// Logic originally based on github.com/fkunn1326/openpose-editor
|
301 |
+
const dataURL = await image_browser_get_image_for_ext(tab_base_tag, image_index)
|
302 |
+
const blob = await (await fetch(dataURL)).blob()
|
303 |
+
const dt = new DataTransfer()
|
304 |
+
dt.items.add(new File([blob], "ImageBrowser.png", { type: blob.type }))
|
305 |
+
const list = dt.files
|
306 |
+
|
307 |
+
await image_browser_gototab(toTabNum)
|
308 |
+
const current_tabid = image_browser_webui_current_tab()
|
309 |
+
const current_tab = current_tabid.replace("tab_", "")
|
310 |
+
const tab_controlnet = gradioApp().getElementById(current_tab + "_controlnet")
|
311 |
+
let accordion = tab_controlnet.querySelector("#controlnet > .label-wrap > .icon")
|
312 |
+
if (accordion.style.transform.includes("rotate(90deg)")) {
|
313 |
+
accordion.click()
|
314 |
+
// Wait for click-action to complete
|
315 |
+
const startTime = Date.now()
|
316 |
+
// 60 seconds in milliseconds
|
317 |
+
const timeout = 60000
|
318 |
+
|
319 |
+
await image_browser_delay(100)
|
320 |
+
while (accordion.style.transform.includes("rotate(90deg)")) {
|
321 |
+
accordion = tab_controlnet.querySelector("#controlnet > .label-wrap > .icon")
|
322 |
+
if (Date.now() - startTime > timeout) {
|
323 |
+
throw new Error("image_browser_controlnet_send/accordion: 60 seconds have passed")
|
324 |
+
}
|
325 |
+
await image_browser_delay(200)
|
326 |
+
}
|
327 |
+
}
|
328 |
+
|
329 |
+
let inputImage
|
330 |
+
let inputContainer
|
331 |
+
if (controlnetType == "single") {
|
332 |
+
inputImage = gradioApp().getElementById(current_tab + "_controlnet_ControlNet_input_image")
|
333 |
+
} else {
|
334 |
+
const tabs = gradioApp().getElementById(current_tab + "_controlnet_tabs")
|
335 |
+
const tab_num = (parseInt(controlnetNum) + 1).toString()
|
336 |
+
tab_button = tabs.querySelector(".tab-nav > button:nth-child(" + tab_num + ")")
|
337 |
+
tab_button.click()
|
338 |
+
// Wait for click-action to complete
|
339 |
+
const startTime = Date.now()
|
340 |
+
// 60 seconds in milliseconds
|
341 |
+
const timeout = 60000
|
342 |
+
|
343 |
+
await image_browser_delay(100)
|
344 |
+
while (!tab_button.classList.contains("selected")) {
|
345 |
+
tab_button = tabs.querySelector(".tab-nav > button:nth-child(" + tab_num + ")")
|
346 |
+
if (Date.now() - startTime > timeout) {
|
347 |
+
throw new Error("image_browser_controlnet_send/tabs: 60 seconds have passed")
|
348 |
+
}
|
349 |
+
await image_browser_delay(200)
|
350 |
+
}
|
351 |
+
inputImage = gradioApp().getElementById(current_tab + "_controlnet_ControlNet-" + controlnetNum.toString() + "_input_image")
|
352 |
+
}
|
353 |
+
try {
|
354 |
+
inputContainer = inputImage.querySelector('div[data-testid="image"]')
|
355 |
+
} catch (e) {}
|
356 |
+
|
357 |
+
const input = inputContainer.querySelector("input[type='file']")
|
358 |
+
|
359 |
+
let clear
|
360 |
+
try {
|
361 |
+
clear = inputContainer.querySelector("button[aria-label='Clear']")
|
362 |
+
if (clear) {
|
363 |
+
clear.click()
|
364 |
+
}
|
365 |
+
} catch (e) {
|
366 |
+
console.error(e)
|
367 |
+
}
|
368 |
+
|
369 |
+
try {
|
370 |
+
// Wait for click-action to complete
|
371 |
+
const startTime = Date.now()
|
372 |
+
// 60 seconds in milliseconds
|
373 |
+
const timeout = 60000
|
374 |
+
while (clear) {
|
375 |
+
clear = inputContainer.querySelector("button[aria-label='Clear']")
|
376 |
+
if (Date.now() - startTime > timeout) {
|
377 |
+
throw new Error("image_browser_controlnet_send/clear: 60 seconds have passed")
|
378 |
+
}
|
379 |
+
await image_browser_delay(200)
|
380 |
+
}
|
381 |
+
} catch (e) {
|
382 |
+
console.error(e)
|
383 |
+
}
|
384 |
+
|
385 |
+
input.value = ""
|
386 |
+
input.files = list
|
387 |
+
const event = new Event("change", { "bubbles": true, "composed": true })
|
388 |
+
input.dispatchEvent(event)
|
389 |
+
if (image_browser_debug) console.log("image_browser_controlnet_send:end")
|
390 |
+
}
|
391 |
+
|
392 |
+
function image_browser_controlnet_send_txt2img(tab_base_tag, image_index, controlnetNum, controlnetType) {
|
393 |
+
image_browser_controlnet_send(0, tab_base_tag, image_index, controlnetNum, controlnetType)
|
394 |
+
}
|
395 |
+
|
396 |
+
function image_browser_controlnet_send_img2img(tab_base_tag, image_index, controlnetNum, controlnetType) {
|
397 |
+
image_browser_controlnet_send(1, tab_base_tag, image_index, controlnetNum, controlnetType)
|
398 |
+
}
|
399 |
+
|
400 |
+
function image_browser_class_add(tab_base_tag) {
|
401 |
+
gradioApp().getElementById(tab_base_tag + '_image_browser').classList.add("image_browser_container")
|
402 |
+
gradioApp().getElementById(tab_base_tag + '_image_browser_set_index').classList.add("image_browser_set_index")
|
403 |
+
gradioApp().getElementById(tab_base_tag + '_image_browser_del_img_btn').classList.add("image_browser_del_img_btn")
|
404 |
+
gradioApp().getElementById(tab_base_tag + '_image_browser_gallery').classList.add("image_browser_gallery")
|
405 |
+
}
|
406 |
+
|
407 |
+
function btnClickHandler(tab_base_tag, btn) {
|
408 |
+
if (image_browser_debug) console.log("btnClickHandler:start")
|
409 |
+
const tabs_box = gradioApp().getElementById("image_browser_tabs_container")
|
410 |
+
if (!tabs_box.classList.contains(tab_base_tag)) {
|
411 |
+
gradioApp().getElementById(tab_base_tag + "_image_browser_renew_page").click()
|
412 |
+
tabs_box.classList.add(tab_base_tag)
|
413 |
+
}
|
414 |
+
if (image_browser_debug) console.log("btnClickHandler:end")
|
415 |
+
}
|
416 |
+
|
417 |
+
function image_browser_init() {
|
418 |
+
if (image_browser_debug) console.log("image_browser_init:start")
|
419 |
+
const tab_base_tags = gradioApp().getElementById("image_browser_tab_base_tags_list")
|
420 |
+
if (tab_base_tags) {
|
421 |
+
const image_browser_tab_base_tags_list = tab_base_tags.querySelector("textarea").value.split(",")
|
422 |
+
image_browser_tab_base_tags_list.forEach(function(tab_base_tag) {
|
423 |
+
image_browser_class_add(tab_base_tag)
|
424 |
+
})
|
425 |
+
|
426 |
+
const tab_btns = gradioApp().getElementById("image_browser_tabs_container").querySelector("div").querySelectorAll("button")
|
427 |
+
tab_btns.forEach(function(btn, i) {
|
428 |
+
const tab_base_tag = image_browser_tab_base_tags_list[i]
|
429 |
+
btn.setAttribute("tab_base_tag", tab_base_tag)
|
430 |
+
btn.removeEventListener('click', () => btnClickHandler(tab_base_tag, btn))
|
431 |
+
btn.addEventListener('click', () => btnClickHandler(tab_base_tag, btn))
|
432 |
+
})
|
433 |
+
//preload
|
434 |
+
if (gradioApp().getElementById("image_browser_preload").querySelector("input").checked) {
|
435 |
+
setTimeout(function(){tab_btns[0].click()}, 100)
|
436 |
+
}
|
437 |
+
}
|
438 |
+
image_browser_keydown()
|
439 |
+
|
440 |
+
const image_browser_swipe = gradioApp().getElementById("image_browser_swipe").getElementsByTagName("input")[0]
|
441 |
+
if (image_browser_swipe.checked) {
|
442 |
+
image_browser_touch()
|
443 |
+
}
|
444 |
+
if (image_browser_debug) console.log("image_browser_init:end")
|
445 |
+
}
|
446 |
+
|
447 |
+
async function image_browser_wait_for_gallery_btn(tab_base_tag){
|
448 |
+
if (image_browser_debug) console.log("image_browser_wait_for_gallery_btn:start")
|
449 |
+
await image_browser_delay(100)
|
450 |
+
while (!gradioApp().getElementById(image_browser_current_tab() + "_image_browser_gallery").getElementsByClassName("thumbnail-item")) {
|
451 |
+
await image_browser_delay(200)
|
452 |
+
}
|
453 |
+
if (image_browser_debug) console.log("image_browser_wait_for_gallery_btn:end")
|
454 |
+
}
|
455 |
+
|
456 |
+
function image_browser_hijack_console_log() {
|
457 |
+
(function () {
|
458 |
+
const oldLog = console.log
|
459 |
+
console.log = function (message) {
|
460 |
+
const formattedTime = new Date().toISOString().slice(0, -5).replace(/[TZ]/g, ' ').trim().replace(/\s+/g, '-').replace(/:/g, '-')
|
461 |
+
image_browser_console_log = image_browser_console_log + formattedTime + " " + "image_browser.js: " + message + "\n"
|
462 |
+
oldLog.apply(console, arguments)
|
463 |
+
}
|
464 |
+
})()
|
465 |
+
image_browser_debug = true
|
466 |
+
}
|
467 |
+
|
468 |
+
function get_js_logs() {
|
469 |
+
log_to_py = image_browser_console_log
|
470 |
+
image_browser_console_log = ""
|
471 |
+
return log_to_py
|
472 |
+
}
|
473 |
+
|
474 |
+
function isNumeric(str) {
|
475 |
+
if (typeof str != "string") return false
|
476 |
+
return !isNaN(str) && !isNaN(parseFloat(str))
|
477 |
+
}
|
478 |
+
|
479 |
+
function image_browser_start() {
|
480 |
+
if (image_browser_debug) console.log("image_browser_start:start")
|
481 |
+
image_browser_init()
|
482 |
+
const mutationObserver = new MutationObserver(function(mutationsList) {
|
483 |
+
const tab_base_tags = gradioApp().getElementById("image_browser_tab_base_tags_list")
|
484 |
+
if (tab_base_tags) {
|
485 |
+
const image_browser_tab_base_tags_list = tab_base_tags.querySelector("textarea").value.split(",")
|
486 |
+
image_browser_tab_base_tags_list.forEach(function(tab_base_tag) {
|
487 |
+
image_browser_class_add(tab_base_tag)
|
488 |
+
const tab_gallery_items = gradioApp().querySelectorAll('#' + tab_base_tag + '_image_browser .thumbnail-item')
|
489 |
+
|
490 |
+
const image_browser_img_info_json = gradioApp().getElementById(tab_base_tag + "_image_browser_img_info").querySelector('[data-testid="textbox"]').value
|
491 |
+
const image_browser_img_info = JSON.parse(image_browser_img_info_json)
|
492 |
+
const filenames = Object.keys(image_browser_img_info)
|
493 |
+
|
494 |
+
tab_gallery_items.forEach(function(gallery_item, i) {
|
495 |
+
gallery_item.removeEventListener('click', image_browser_click_image, true)
|
496 |
+
gallery_item.addEventListener('click', image_browser_click_image, true)
|
497 |
+
|
498 |
+
const filename = filenames[i]
|
499 |
+
try {
|
500 |
+
let x = image_browser_img_info[filename].x
|
501 |
+
let y = image_browser_img_info[filename].y
|
502 |
+
if (isNumeric(x) && isNumeric(y)) {
|
503 |
+
gallery_item.title = x + "x" + y
|
504 |
+
}
|
505 |
+
} catch (e) {}
|
506 |
+
|
507 |
+
document.onkeyup = async function(e) {
|
508 |
+
if (!image_browser_active()) {
|
509 |
+
if (image_browser_debug) console.log("image_browser_start:end")
|
510 |
+
return
|
511 |
+
}
|
512 |
+
const current_tab = image_browser_current_tab()
|
513 |
+
image_browser_wait_for_gallery_btn(current_tab).then(() => {
|
514 |
+
let gallery_btn
|
515 |
+
gallery_btn = gradioApp().getElementById(current_tab + "_image_browser_gallery").querySelector(".thumbnail-item .selected")
|
516 |
+
gallery_btn = gallery_btn && gallery_btn.length > 0 ? gallery_btn[0] : null
|
517 |
+
if (gallery_btn) {
|
518 |
+
image_browser_click_image.call(gallery_btn)
|
519 |
+
}
|
520 |
+
})
|
521 |
+
}
|
522 |
+
})
|
523 |
+
|
524 |
+
const cls_btn = gradioApp().getElementById(tab_base_tag + '_image_browser_gallery').querySelector("svg")
|
525 |
+
if (cls_btn) {
|
526 |
+
cls_btn.removeEventListener('click', () => image_browser_renew_page(tab_base_tag), false)
|
527 |
+
cls_btn.addEventListener('click', () => image_browser_renew_page(tab_base_tag), false)
|
528 |
+
}
|
529 |
+
})
|
530 |
+
const debug_level_option = gradioApp().getElementById("image_browser_debug_level_option").querySelector("textarea").value
|
531 |
+
if ((debug_level_option == 'javascript' || debug_level_option == 'capture') && !image_browser_debug) {
|
532 |
+
image_browser_hijack_console_log()
|
533 |
+
}
|
534 |
+
}
|
535 |
+
})
|
536 |
+
mutationObserver.observe(gradioApp(), { childList:true, subtree:true })
|
537 |
+
image_browser_started = true
|
538 |
+
image_browser_activate_controls()
|
539 |
+
if (image_browser_debug) console.log("image_browser_start:end")
|
540 |
+
}
|
541 |
+
|
542 |
+
async function image_browser_activate_controls() {
|
543 |
+
if (image_browser_debug) console.log("image_browser_activate_controls:start")
|
544 |
+
await image_browser_delay(500)
|
545 |
+
container = gradioApp().getElementById("image_browser_tabs_container")
|
546 |
+
let controls = container.querySelectorAll('[id*="_control_"]')
|
547 |
+
controls.forEach(function(control) {
|
548 |
+
control.style.pointerEvents = "auto"
|
549 |
+
control.style.cursor = "default"
|
550 |
+
control.style.opacity = "1"
|
551 |
+
})
|
552 |
+
let warnings = container.querySelectorAll('[id*="_warning_box"]')
|
553 |
+
warnings.forEach(function(warning) {
|
554 |
+
warning.innerHTML = "<p> "
|
555 |
+
})
|
556 |
+
if (image_browser_debug) console.log("image_browser_activate_controls:end")
|
557 |
+
}
|
558 |
+
|
559 |
+
function image_browser_img_show_progress_update() {
|
560 |
+
image_browser_img_show_in_progress = false
|
561 |
+
}
|
562 |
+
|
563 |
+
function image_browser_renew_page(tab_base_tag) {
|
564 |
+
if (image_browser_debug) console.log("image_browser_renew_page:start")
|
565 |
+
gradioApp().getElementById(tab_base_tag + '_image_browser_renew_page').click()
|
566 |
+
if (image_browser_debug) console.log("image_browser_renew_page:end")
|
567 |
+
}
|
568 |
+
|
569 |
+
function image_browser_current_tab() {
|
570 |
+
if (image_browser_debug) console.log("image_browser_current_tab:start")
|
571 |
+
const tabs = gradioApp().getElementById("image_browser_tabs_container").querySelectorAll('[id$="_image_browser_container"]')
|
572 |
+
const tab_base_tags = gradioApp().getElementById("image_browser_tab_base_tags_list")
|
573 |
+
const image_browser_tab_base_tags_list = tab_base_tags.querySelector("textarea").value.split(",").sort((a, b) => b.length - a.length)
|
574 |
+
for (const element of tabs) {
|
575 |
+
if (element.style.display === "block") {
|
576 |
+
const id = element.id
|
577 |
+
const tab_base_tag = image_browser_tab_base_tags_list.find(element => id.startsWith(element)) || null
|
578 |
+
if (image_browser_debug) console.log("image_browser_current_tab:end")
|
579 |
+
return tab_base_tag
|
580 |
+
}
|
581 |
+
}
|
582 |
+
if (image_browser_debug) console.log("image_browser_current_tab:end")
|
583 |
+
}
|
584 |
+
|
585 |
+
function image_browser_webui_current_tab() {
|
586 |
+
if (image_browser_debug) console.log("image_browser_webui_current_tab:start")
|
587 |
+
const tabs = gradioApp().getElementById("tabs").querySelectorAll('[id^="tab_"]')
|
588 |
+
let id
|
589 |
+
for (const element of tabs) {
|
590 |
+
if (element.style.display === "block") {
|
591 |
+
id = element.id
|
592 |
+
break
|
593 |
+
}
|
594 |
+
}
|
595 |
+
if (image_browser_debug) console.log("image_browser_webui_current_tab:end")
|
596 |
+
return id
|
597 |
+
}
|
598 |
+
|
599 |
+
function image_browser_active() {
|
600 |
+
if (image_browser_debug) console.log("image_browser_active:start")
|
601 |
+
const ext_active = gradioApp().getElementById("tab_image_browser")
|
602 |
+
if (image_browser_debug) console.log("image_browser_active:end")
|
603 |
+
return ext_active && ext_active.style.display !== "none"
|
604 |
+
}
|
605 |
+
|
606 |
+
async function image_browser_delete_key(tab_base_tag) {
|
607 |
+
// Wait for img_show to end
|
608 |
+
const startTime = Date.now()
|
609 |
+
// 60 seconds in milliseconds
|
610 |
+
const timeout = 60000
|
611 |
+
|
612 |
+
await image_browser_delay(100)
|
613 |
+
while (image_browser_img_show_in_progress) {
|
614 |
+
if (Date.now() - startTime > timeout) {
|
615 |
+
throw new Error("image_browser_delete_key: 60 seconds have passed")
|
616 |
+
}
|
617 |
+
await image_browser_delay(200)
|
618 |
+
}
|
619 |
+
|
620 |
+
const deleteBtn = gradioApp().getElementById(tab_base_tag + "_image_browser_del_img_btn")
|
621 |
+
deleteBtn.dispatchEvent(new Event("click"))
|
622 |
+
}
|
623 |
+
|
624 |
+
function image_browser_keydown() {
|
625 |
+
if (image_browser_debug) console.log("image_browser_keydown:start")
|
626 |
+
gradioApp().addEventListener("keydown", function(event) {
|
627 |
+
// If we are not on the Image Browser Extension, dont listen for keypresses
|
628 |
+
if (!image_browser_active()) {
|
629 |
+
if (image_browser_debug) console.log("image_browser_keydown:end")
|
630 |
+
return
|
631 |
+
}
|
632 |
+
|
633 |
+
// If the user is typing in an input field, dont listen for keypresses
|
634 |
+
let target
|
635 |
+
if (!event.composed) { // We shouldn't get here as the Shadow DOM is always active, but just in case
|
636 |
+
target = event.target
|
637 |
+
} else {
|
638 |
+
target = event.composedPath()[0]
|
639 |
+
}
|
640 |
+
if (!target || target.nodeName === "INPUT" || target.nodeName === "TEXTAREA") {
|
641 |
+
if (image_browser_debug) console.log("image_browser_keydown:end")
|
642 |
+
return
|
643 |
+
}
|
644 |
+
|
645 |
+
const tab_base_tag = image_browser_current_tab()
|
646 |
+
|
647 |
+
// Listens for keypresses 0-5 and updates the corresponding ranking (0 is the last option, None)
|
648 |
+
if (event.code >= "Digit0" && event.code <= "Digit5") {
|
649 |
+
const selectedValue = event.code.charAt(event.code.length - 1)
|
650 |
+
const radioInputs = gradioApp().getElementById(tab_base_tag + "_control_image_browser_ranking").getElementsByTagName("input")
|
651 |
+
for (const input of radioInputs) {
|
652 |
+
if (input.value === selectedValue || (selectedValue === '0' && input === radioInputs[radioInputs.length - 1])) {
|
653 |
+
input.checked = true
|
654 |
+
input.dispatchEvent(new Event("change"))
|
655 |
+
break
|
656 |
+
}
|
657 |
+
}
|
658 |
+
}
|
659 |
+
|
660 |
+
const mod_keys = gradioApp().querySelector(`#${tab_base_tag}_image_browser_mod_keys textarea`).value
|
661 |
+
let modifiers_pressed = false
|
662 |
+
if (mod_keys.indexOf("C") !== -1 && mod_keys.indexOf("S") !== -1) {
|
663 |
+
if (event.ctrlKey && event.shiftKey) {
|
664 |
+
modifiers_pressed = true
|
665 |
+
}
|
666 |
+
} else if (mod_keys.indexOf("S") !== -1) {
|
667 |
+
if (!event.ctrlKey && event.shiftKey) {
|
668 |
+
modifiers_pressed = true
|
669 |
+
}
|
670 |
+
} else {
|
671 |
+
if (event.ctrlKey && !event.shiftKey) {
|
672 |
+
modifiers_pressed = true
|
673 |
+
}
|
674 |
+
}
|
675 |
+
|
676 |
+
let modifiers_none = false
|
677 |
+
if (!event.ctrlKey && !event.shiftKey && !event.altKey && !event.metaKey) {
|
678 |
+
modifiers_none = true
|
679 |
+
}
|
680 |
+
|
681 |
+
if (event.code == "KeyF" && modifiers_none) {
|
682 |
+
if (tab_base_tag == "image_browser_tab_favorites") {
|
683 |
+
if (image_browser_debug) console.log("image_browser_keydown:end")
|
684 |
+
return
|
685 |
+
}
|
686 |
+
const favoriteBtn = gradioApp().getElementById(tab_base_tag + "_image_browser_favorites_btn")
|
687 |
+
favoriteBtn.dispatchEvent(new Event("click"))
|
688 |
+
}
|
689 |
+
|
690 |
+
if (event.code == "KeyR" && modifiers_none) {
|
691 |
+
const refreshBtn = gradioApp().getElementById(tab_base_tag + "_image_browser_renew_page")
|
692 |
+
refreshBtn.dispatchEvent(new Event("click"))
|
693 |
+
}
|
694 |
+
|
695 |
+
if (event.code == "Delete" && modifiers_none) {
|
696 |
+
image_browser_delete_key(tab_base_tag)
|
697 |
+
}
|
698 |
+
|
699 |
+
if (event.code == "ArrowLeft" && modifiers_pressed) {
|
700 |
+
const prevBtn = gradioApp().getElementById(tab_base_tag + "_control_image_browser_prev_page")
|
701 |
+
prevBtn.dispatchEvent(new Event("click"))
|
702 |
+
}
|
703 |
+
|
704 |
+
if (event.code == "ArrowLeft" && modifiers_none) {
|
705 |
+
image_browser_img_show_in_progress = true
|
706 |
+
const tab_base_tag = image_browser_current_tab()
|
707 |
+
const set_btn = gradioApp().querySelector(`#${tab_base_tag}_image_browser .image_browser_set_index`)
|
708 |
+
const curr_idx = parseInt(set_btn.getAttribute("img_index"))
|
709 |
+
set_btn.setAttribute("img_index", curr_idx - 1)
|
710 |
+
image_browser_refresh_current_page_preview()
|
711 |
+
}
|
712 |
+
|
713 |
+
if (event.code == "ArrowRight" && modifiers_pressed) {
|
714 |
+
const nextBtn = gradioApp().getElementById(tab_base_tag + "_control_image_browser_next_page")
|
715 |
+
nextBtn.dispatchEvent(new Event("click"))
|
716 |
+
}
|
717 |
+
|
718 |
+
if (event.code == "ArrowRight" && modifiers_none) {
|
719 |
+
image_browser_img_show_in_progress = true
|
720 |
+
const tab_base_tag = image_browser_current_tab()
|
721 |
+
const set_btn = gradioApp().querySelector(`#${tab_base_tag}_image_browser .image_browser_set_index`)
|
722 |
+
const curr_idx = parseInt(set_btn.getAttribute("img_index"))
|
723 |
+
set_btn.setAttribute("img_index", curr_idx + 1)
|
724 |
+
image_browser_refresh_current_page_preview()
|
725 |
+
}
|
726 |
+
})
|
727 |
+
if (image_browser_debug) console.log("image_browser_keydown:end")
|
728 |
+
}
|
729 |
+
|
730 |
+
function image_browser_touch() {
|
731 |
+
if (image_browser_debug) console.log("image_browser_touch:start")
|
732 |
+
let touchStartX = 0
|
733 |
+
let touchEndX = 0
|
734 |
+
gradioApp().addEventListener("touchstart", function(event) {
|
735 |
+
if (!image_browser_active()) {
|
736 |
+
if (image_browser_debug) console.log("image_browser_touch:end")
|
737 |
+
return
|
738 |
+
}
|
739 |
+
touchStartX = event.touches[0].clientX;
|
740 |
+
})
|
741 |
+
gradioApp().addEventListener("touchend", function(event) {
|
742 |
+
if (!image_browser_active()) {
|
743 |
+
if (image_browser_debug) console.log("image_browser_touch:end")
|
744 |
+
return
|
745 |
+
}
|
746 |
+
touchEndX = event.changedTouches[0].clientX
|
747 |
+
const touchDiffX = touchStartX - touchEndX
|
748 |
+
if (touchDiffX > 50) {
|
749 |
+
const tab_base_tag = image_browser_current_tab()
|
750 |
+
const set_btn = gradioApp().querySelector(`#${tab_base_tag}_image_browser .image_browser_set_index`)
|
751 |
+
const curr_idx = parseInt(set_btn.getAttribute("img_index"))
|
752 |
+
if (curr_idx >= 1) {
|
753 |
+
set_btn.setAttribute("img_index", curr_idx - 1)
|
754 |
+
image_browser_refresh_current_page_preview()
|
755 |
+
}
|
756 |
+
} else if (touchDiffX < -50) {
|
757 |
+
const tab_base_tag = image_browser_current_tab()
|
758 |
+
const gallery = gradioApp().querySelector(`#${tab_base_tag}_image_browser`)
|
759 |
+
const gallery_items = gallery.querySelectorAll(".thumbnail-item")
|
760 |
+
const thumbnails = gallery_items.length / 2
|
761 |
+
const set_btn = gradioApp().querySelector(`#${tab_base_tag}_image_browser .image_browser_set_index`)
|
762 |
+
const curr_idx = parseInt(set_btn.getAttribute("img_index"))
|
763 |
+
if (curr_idx + 1 < thumbnails) {
|
764 |
+
set_btn.setAttribute("img_index", curr_idx + 1)
|
765 |
+
image_browser_refresh_current_page_preview()
|
766 |
+
}
|
767 |
+
}
|
768 |
+
})
|
769 |
+
if (image_browser_debug) console.log("image_browser_touch:end")
|
770 |
+
}
|
stable-diffusion-webui-images-browser/req_IR.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
fairscale
|
stable-diffusion-webui-images-browser/scripts/__pycache__/image_browser.cpython-310.pyc
ADDED
Binary file (56.3 kB). View file
|
|
stable-diffusion-webui-images-browser/scripts/image_browser.py
ADDED
@@ -0,0 +1,1717 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import csv
|
3 |
+
import importlib
|
4 |
+
import json
|
5 |
+
import logging
|
6 |
+
import math
|
7 |
+
import os
|
8 |
+
import platform
|
9 |
+
import random
|
10 |
+
import re
|
11 |
+
import shutil
|
12 |
+
import stat
|
13 |
+
import subprocess as sp
|
14 |
+
import sys
|
15 |
+
import tempfile
|
16 |
+
import time
|
17 |
+
import torch
|
18 |
+
import traceback
|
19 |
+
import hashlib
|
20 |
+
import modules.extras
|
21 |
+
import modules.images
|
22 |
+
import modules.ui
|
23 |
+
from datetime import datetime
|
24 |
+
from modules import paths, shared, script_callbacks, scripts, images
|
25 |
+
from modules.shared import opts, cmd_opts
|
26 |
+
from modules.ui_common import plaintext_to_html
|
27 |
+
from modules.ui_components import ToolButton, DropdownMulti
|
28 |
+
from PIL import Image, UnidentifiedImageError
|
29 |
+
from packaging import version
|
30 |
+
from pathlib import Path
|
31 |
+
from typing import List, Tuple
|
32 |
+
from itertools import chain
|
33 |
+
from io import StringIO
|
34 |
+
|
35 |
+
try:
|
36 |
+
from scripts.wib import wib_db
|
37 |
+
except ModuleNotFoundError:
|
38 |
+
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "scripts")))
|
39 |
+
from wib import wib_db
|
40 |
+
|
41 |
+
try:
|
42 |
+
from send2trash import send2trash
|
43 |
+
send2trash_installed = True
|
44 |
+
except ImportError:
|
45 |
+
print("Image Browser: send2trash is not installed. recycle bin cannot be used.")
|
46 |
+
send2trash_installed = False
|
47 |
+
|
48 |
+
try:
|
49 |
+
import ImageReward
|
50 |
+
image_reward_installed = True
|
51 |
+
except ImportError:
|
52 |
+
print("Image Browser: ImageReward is not installed, cannot be used.")
|
53 |
+
image_reward_installed = False
|
54 |
+
|
55 |
+
# Force reload wib_db, as it doesn't get reloaded otherwise, if an extension update is started from webui
|
56 |
+
importlib.reload(wib_db)
|
57 |
+
|
58 |
+
yappi_do = False
|
59 |
+
|
60 |
+
components_list = ["Sort by", "Filename keyword search", "EXIF keyword search", "Ranking Filter", "Aesthestic Score", "Generation Info", "File Name", "File Time", "Open Folder", "Send to buttons", "Copy to directory", "Gallery Controls Bar", "Ranking Bar", "Delete Bar", "Additional Generation Info"]
|
61 |
+
|
62 |
+
num_of_imgs_per_page = 0
|
63 |
+
loads_files_num = 0
|
64 |
+
image_ext_list = [".png", ".jpg", ".jpeg", ".bmp", ".gif", ".webp", ".svg"]
|
65 |
+
finfo_aes = {}
|
66 |
+
finfo_image_reward = {}
|
67 |
+
exif_cache = {}
|
68 |
+
finfo_exif = {}
|
69 |
+
aes_cache = {}
|
70 |
+
image_reward_cache = {}
|
71 |
+
none_select = "Nothing selected"
|
72 |
+
refresh_symbol = '\U0001f504' # 🔄
|
73 |
+
up_symbol = '\U000025b2' # ▲
|
74 |
+
down_symbol = '\U000025bc' # ▼
|
75 |
+
caution_symbol = '\U000026a0' # ⚠
|
76 |
+
folder_symbol = '\U0001f4c2' # 📂
|
77 |
+
current_depth = 0
|
78 |
+
init = True
|
79 |
+
copy_move = ["Move", "Copy"]
|
80 |
+
copied_moved = ["Moved", "Copied"]
|
81 |
+
np = "negative_prompt: "
|
82 |
+
openoutpaint = False
|
83 |
+
controlnet = False
|
84 |
+
js_dummy_return = None
|
85 |
+
log_file = os.path.join(scripts.basedir(), "image_browser.log")
|
86 |
+
image_reward_model = None
|
87 |
+
|
88 |
+
def check_image_browser_active_tabs():
|
89 |
+
# Check if Maintenance tab has been added to settings in addition to as a mandatory tab. If so, remove.
|
90 |
+
if hasattr(opts, "image_browser_active_tabs"):
|
91 |
+
active_tabs_no_maint = re.sub(r",\s*Maintenance", "", opts.image_browser_active_tabs)
|
92 |
+
if len(active_tabs_no_maint) != len(opts.image_browser_active_tabs):
|
93 |
+
shared.opts.__setattr__("image_browser_active_tabs", active_tabs_no_maint)
|
94 |
+
shared.opts.save(shared.config_filename)
|
95 |
+
|
96 |
+
favorite_tab_name = "Favorites"
|
97 |
+
default_tab_options = ["txt2img", "img2img", "txt2img-grids", "img2img-grids", "Extras", favorite_tab_name, "Others"]
|
98 |
+
check_image_browser_active_tabs()
|
99 |
+
tabs_list = [tab.strip() for tab in chain.from_iterable(csv.reader(StringIO(opts.image_browser_active_tabs))) if tab] if hasattr(opts, "image_browser_active_tabs") else default_tab_options
|
100 |
+
try:
|
101 |
+
if opts.image_browser_enable_maint:
|
102 |
+
tabs_list.append("Maintenance") # mandatory tab
|
103 |
+
except AttributeError:
|
104 |
+
tabs_list.append("Maintenance") # mandatory tab
|
105 |
+
|
106 |
+
path_maps = {
|
107 |
+
"txt2img": opts.outdir_samples or opts.outdir_txt2img_samples,
|
108 |
+
"img2img": opts.outdir_samples or opts.outdir_img2img_samples,
|
109 |
+
"txt2img-grids": opts.outdir_grids or opts.outdir_txt2img_grids,
|
110 |
+
"img2img-grids": opts.outdir_grids or opts.outdir_img2img_grids,
|
111 |
+
"Extras": opts.outdir_samples or opts.outdir_extras_samples,
|
112 |
+
favorite_tab_name: opts.outdir_save
|
113 |
+
}
|
114 |
+
|
115 |
+
class ImageBrowserTab():
|
116 |
+
|
117 |
+
seen_base_tags = set()
|
118 |
+
|
119 |
+
def __init__(self, name: str):
|
120 |
+
self.name: str = os.path.basename(name) if os.path.isdir(name) else name
|
121 |
+
self.path: str = os.path.realpath(path_maps.get(name, name))
|
122 |
+
self.base_tag: str = f"image_browser_tab_{self.get_unique_base_tag(self.remove_invalid_html_tag_chars(self.name).lower())}"
|
123 |
+
|
124 |
+
def remove_invalid_html_tag_chars(self, tag: str) -> str:
|
125 |
+
# Removes any character that is not a letter, a digit, a hyphen, or an underscore
|
126 |
+
removed = re.sub(r'[^a-zA-Z0-9\-_]', '', tag)
|
127 |
+
return removed
|
128 |
+
|
129 |
+
def get_unique_base_tag(self, base_tag: str) -> str:
|
130 |
+
counter = 1
|
131 |
+
while base_tag in self.seen_base_tags:
|
132 |
+
match = re.search(r'_(\d+)$', base_tag)
|
133 |
+
if match:
|
134 |
+
counter = int(match.group(1)) + 1
|
135 |
+
base_tag = re.sub(r'_(\d+)$', f"_{counter}", base_tag)
|
136 |
+
else:
|
137 |
+
base_tag = f"{base_tag}_{counter}"
|
138 |
+
counter += 1
|
139 |
+
self.seen_base_tags.add(base_tag)
|
140 |
+
return base_tag
|
141 |
+
|
142 |
+
def __str__(self):
|
143 |
+
return f"Name: {self.name} / Path: {self.path} / Base tag: {self.base_tag} / Seen base tags: {self.seen_base_tags}"
|
144 |
+
|
145 |
+
tabs_list = [ImageBrowserTab(tab) for tab in tabs_list]
|
146 |
+
|
147 |
+
debug_level_types = ["none", "warning log", "debug log", "javascript log", "capture logs to file"]
|
148 |
+
|
149 |
+
debug_levels_list = []
|
150 |
+
for i in range(len(debug_level_types)):
|
151 |
+
level = debug_level_types[i].split(" ")[0]
|
152 |
+
text = str(i) + " - " + debug_level_types[i]
|
153 |
+
debug_levels_list.append((level, text))
|
154 |
+
|
155 |
+
def debug_levels(arg_value=None, arg_level=None, arg_text=None):
|
156 |
+
if arg_value is not None:
|
157 |
+
return arg_value, debug_levels_list[arg_value]
|
158 |
+
elif arg_level is not None:
|
159 |
+
for i, (level, text) in enumerate(debug_levels_list):
|
160 |
+
if level == arg_level:
|
161 |
+
return i, debug_levels_list[i]
|
162 |
+
elif arg_text is not None:
|
163 |
+
for i, (level, text) in enumerate(debug_levels_list):
|
164 |
+
if text == arg_text:
|
165 |
+
return i, debug_levels_list[i]
|
166 |
+
|
167 |
+
# Logging
|
168 |
+
logger = None
|
169 |
+
def restart_debug(parameter):
|
170 |
+
global logger
|
171 |
+
logger = logging.getLogger(__name__)
|
172 |
+
logger.disabled = False
|
173 |
+
logger_mode = logging.ERROR
|
174 |
+
level_value = 0
|
175 |
+
capture_level_value = 99
|
176 |
+
if hasattr(opts, "image_browser_debug_level"):
|
177 |
+
warning_level_value, (warning_level, warning_level_text) = debug_levels(arg_level="warning")
|
178 |
+
debug_level_value, (debug_level, debug_level_text) = debug_levels(arg_level="debug")
|
179 |
+
capture_level_value, (capture_level, capture_level_text) = debug_levels(arg_level="capture")
|
180 |
+
level_value, (level, level_text) = debug_levels(arg_text=opts.image_browser_debug_level)
|
181 |
+
if level_value >= debug_level_value:
|
182 |
+
logger_mode = logging.DEBUG
|
183 |
+
elif level_value >= warning_level_value:
|
184 |
+
logger_mode = logging.WARNING
|
185 |
+
logger.setLevel(logger_mode)
|
186 |
+
if (logger.hasHandlers()):
|
187 |
+
logger.handlers.clear()
|
188 |
+
console_handler = logging.StreamHandler()
|
189 |
+
console_handler.setLevel(logger_mode)
|
190 |
+
formatter = logging.Formatter(f'%(asctime)s image_browser.py: %(message)s', datefmt='%Y-%m-%d-%H:%M:%S')
|
191 |
+
console_handler.setFormatter(formatter)
|
192 |
+
logger.addHandler(console_handler)
|
193 |
+
if level_value >= capture_level_value:
|
194 |
+
try:
|
195 |
+
os.unlink(log_file)
|
196 |
+
except FileNotFoundError:
|
197 |
+
pass
|
198 |
+
file_handler = logging.FileHandler(log_file)
|
199 |
+
file_handler.setLevel(logger_mode)
|
200 |
+
file_handler.setFormatter(formatter)
|
201 |
+
logger.addHandler(file_handler)
|
202 |
+
logger.warning(f"debug_level: {level_value}")
|
203 |
+
# Debug logging
|
204 |
+
if logger.getEffectiveLevel() == logging.DEBUG:
|
205 |
+
if parameter != "startup":
|
206 |
+
logging.disable(logging.NOTSET)
|
207 |
+
|
208 |
+
logger.debug(f"{sys.executable} {sys.version}")
|
209 |
+
logger.debug(f"{platform.system()} {platform.version()}")
|
210 |
+
try:
|
211 |
+
git = os.environ.get('GIT', "git")
|
212 |
+
webui_commit_hash = os.popen(f"{git} rev-parse HEAD").read().strip()
|
213 |
+
sm_hashes = os.popen(f"{git} submodule").read()
|
214 |
+
sm_hashes_lines = sm_hashes.splitlines()
|
215 |
+
image_browser_commit_hash = f"image_browser_commit_hash not found: {sm_hashes}"
|
216 |
+
for sm_hashes_line in sm_hashes_lines:
|
217 |
+
if "images-browser" in sm_hashes_line.lower():
|
218 |
+
image_browser_commit_hash = sm_hashes_line[1:41]
|
219 |
+
break
|
220 |
+
except Exception as e:
|
221 |
+
webui_commit_hash = e
|
222 |
+
image_browser_commit_hash = e
|
223 |
+
logger.debug(f"Webui {webui_commit_hash}")
|
224 |
+
logger.debug(f"Image Browser {image_browser_commit_hash}")
|
225 |
+
logger.debug(f"Gradio {gr.__version__}")
|
226 |
+
logger.debug(f"{paths.script_path}")
|
227 |
+
with open(cmd_opts.ui_config_file, "r") as f:
|
228 |
+
logger.debug(f.read())
|
229 |
+
with open(cmd_opts.ui_settings_file, "r") as f:
|
230 |
+
logger.debug(f.read())
|
231 |
+
logger.debug(os.path.realpath(__file__))
|
232 |
+
logger.debug([str(tab) for tab in tabs_list])
|
233 |
+
maint_last_msg = "Debug restarted"
|
234 |
+
|
235 |
+
return parameter, maint_last_msg
|
236 |
+
|
237 |
+
restart_debug("startup")
|
238 |
+
|
239 |
+
def delete_recycle(filename):
|
240 |
+
if opts.image_browser_delete_recycle and send2trash_installed:
|
241 |
+
send2trash(filename)
|
242 |
+
else:
|
243 |
+
file = Path(filename)
|
244 |
+
file.unlink()
|
245 |
+
return
|
246 |
+
|
247 |
+
def img_path_subdirs_get(img_path):
|
248 |
+
subdirs = []
|
249 |
+
subdirs.append(none_select)
|
250 |
+
for item in os.listdir(img_path):
|
251 |
+
item_path = os.path.join(img_path, item)
|
252 |
+
if os.path.isdir(item_path):
|
253 |
+
subdirs.append(item_path)
|
254 |
+
return gr.update(choices=subdirs)
|
255 |
+
|
256 |
+
def img_path_add_remove(img_dir, path_recorder, add_remove, img_path_depth):
|
257 |
+
img_dir = os.path.realpath(img_dir)
|
258 |
+
if add_remove == "add" or (add_remove == "remove" and img_dir in path_recorder):
|
259 |
+
if add_remove == "add":
|
260 |
+
path_recorder[img_dir] = {
|
261 |
+
"depth": int(img_path_depth),
|
262 |
+
"path_display": f"{img_dir} [{int(img_path_depth)}]"
|
263 |
+
}
|
264 |
+
wib_db.update_path_recorder(img_dir, path_recorder[img_dir]["depth"], path_recorder[img_dir]["path_display"])
|
265 |
+
else:
|
266 |
+
del path_recorder[img_dir]
|
267 |
+
wib_db.delete_path_recorder(img_dir)
|
268 |
+
path_recorder_formatted = [value.get("path_display") for key, value in path_recorder.items()]
|
269 |
+
path_recorder_formatted = sorted(path_recorder_formatted, key=lambda x: natural_keys(x.lower()))
|
270 |
+
|
271 |
+
if add_remove == "remove":
|
272 |
+
selected = path_recorder[list(path_recorder.keys())[0]]["path_display"]
|
273 |
+
else:
|
274 |
+
selected = path_recorder[img_dir]["path_display"]
|
275 |
+
return path_recorder, gr.update(choices=path_recorder_formatted, value=selected)
|
276 |
+
|
277 |
+
def sort_order_flip(turn_page_switch, sort_order):
|
278 |
+
if sort_order == up_symbol:
|
279 |
+
sort_order = down_symbol
|
280 |
+
else:
|
281 |
+
sort_order = up_symbol
|
282 |
+
return 1, -turn_page_switch, sort_order
|
283 |
+
|
284 |
+
def read_path_recorder():
|
285 |
+
path_recorder = wib_db.load_path_recorder()
|
286 |
+
path_recorder_formatted = [value.get("path_display") for key, value in path_recorder.items()]
|
287 |
+
path_recorder_formatted = sorted(path_recorder_formatted, key=lambda x: natural_keys(x.lower()))
|
288 |
+
path_recorder_unformatted = list(path_recorder.keys())
|
289 |
+
path_recorder_unformatted = sorted(path_recorder_unformatted, key=lambda x: natural_keys(x.lower()))
|
290 |
+
|
291 |
+
return path_recorder, path_recorder_formatted, path_recorder_unformatted
|
292 |
+
|
293 |
+
def pure_path(path):
|
294 |
+
if path == []:
|
295 |
+
return path, 0
|
296 |
+
match = re.search(r" \[(\d+)\]$", path)
|
297 |
+
if match:
|
298 |
+
path = path[:match.start()]
|
299 |
+
depth = int(match.group(1))
|
300 |
+
else:
|
301 |
+
depth = 0
|
302 |
+
path = os.path.realpath(path)
|
303 |
+
return path, depth
|
304 |
+
|
305 |
+
def browser2path(img_path_browser):
|
306 |
+
img_path, _ = pure_path(img_path_browser)
|
307 |
+
return img_path
|
308 |
+
|
309 |
+
def totxt(file):
|
310 |
+
base, _ = os.path.splitext(file)
|
311 |
+
file_txt = base + '.txt'
|
312 |
+
|
313 |
+
return file_txt
|
314 |
+
|
315 |
+
def tab_select():
|
316 |
+
path_recorder, path_recorder_formatted, path_recorder_unformatted = read_path_recorder()
|
317 |
+
return path_recorder, gr.update(choices=path_recorder_unformatted)
|
318 |
+
|
319 |
+
def js_logs_output(js_log):
|
320 |
+
logger.debug(f"js_log: {js_log}")
|
321 |
+
return js_log
|
322 |
+
|
323 |
+
def ranking_filter_settings(page_index, turn_page_switch, ranking_filter):
|
324 |
+
if ranking_filter == "Min-max":
|
325 |
+
interactive = True
|
326 |
+
else:
|
327 |
+
interactive = False
|
328 |
+
page_index = 1
|
329 |
+
turn_page_switch = -turn_page_switch
|
330 |
+
return page_index, turn_page_switch, gr.update(interactive=interactive), gr.update(interactive=interactive)
|
331 |
+
|
332 |
+
def reduplicative_file_move(src, dst):
|
333 |
+
def same_name_file(basename, path):
|
334 |
+
name, ext = os.path.splitext(basename)
|
335 |
+
f_list = os.listdir(path)
|
336 |
+
max_num = 0
|
337 |
+
for f in f_list:
|
338 |
+
if len(f) <= len(basename):
|
339 |
+
continue
|
340 |
+
f_ext = f[-len(ext):] if len(ext) > 0 else ""
|
341 |
+
if f[:len(name)] == name and f_ext == ext:
|
342 |
+
if f[len(name)] == "(" and f[-len(ext)-1] == ")":
|
343 |
+
number = f[len(name)+1:-len(ext)-1]
|
344 |
+
if number.isdigit():
|
345 |
+
if int(number) > max_num:
|
346 |
+
max_num = int(number)
|
347 |
+
return f"{name}({max_num + 1}){ext}"
|
348 |
+
name = os.path.basename(src)
|
349 |
+
save_name = os.path.join(dst, name)
|
350 |
+
src_txt_exists = False
|
351 |
+
if opts.image_browser_txt_files:
|
352 |
+
src_txt = totxt(src)
|
353 |
+
if os.path.exists(src_txt):
|
354 |
+
src_txt_exists = True
|
355 |
+
if not os.path.exists(save_name):
|
356 |
+
if opts.image_browser_copy_image:
|
357 |
+
shutil.copy2(src, dst)
|
358 |
+
if opts.image_browser_txt_files and src_txt_exists:
|
359 |
+
shutil.copy2(src_txt, dst)
|
360 |
+
else:
|
361 |
+
shutil.move(src, dst)
|
362 |
+
if opts.image_browser_txt_files and src_txt_exists:
|
363 |
+
shutil.move(src_txt, dst)
|
364 |
+
else:
|
365 |
+
name = same_name_file(name, dst)
|
366 |
+
if opts.image_browser_copy_image:
|
367 |
+
shutil.copy2(src, os.path.join(dst, name))
|
368 |
+
if opts.image_browser_txt_files and src_txt_exists:
|
369 |
+
shutil.copy2(src_txt, totxt(os.path.join(dst, name)))
|
370 |
+
else:
|
371 |
+
shutil.move(src, os.path.join(dst, name))
|
372 |
+
if opts.image_browser_txt_files and src_txt_exists:
|
373 |
+
shutil.move(src_txt, totxt(os.path.join(dst, name)))
|
374 |
+
|
375 |
+
def save_image(file_name, filenames, page_index, turn_page_switch, dest_path):
|
376 |
+
if file_name is not None and os.path.exists(file_name):
|
377 |
+
reduplicative_file_move(file_name, dest_path)
|
378 |
+
message = f"<div style='color:#999'>{copied_moved[opts.image_browser_copy_image]} to {dest_path}</div>"
|
379 |
+
if not opts.image_browser_copy_image:
|
380 |
+
# Force page refresh with checking filenames
|
381 |
+
filenames = []
|
382 |
+
turn_page_switch = -turn_page_switch
|
383 |
+
else:
|
384 |
+
message = "<div style='color:#999'>Image not found (may have been already moved)</div>"
|
385 |
+
|
386 |
+
return message, filenames, page_index, turn_page_switch
|
387 |
+
|
388 |
+
def delete_image(tab_base_tag_box, delete_num, name, filenames, image_index, visible_num, delete_confirm, turn_page_switch, image_page_list):
|
389 |
+
logger.debug("delete_image")
|
390 |
+
refresh = False
|
391 |
+
delete_num = int(delete_num)
|
392 |
+
image_index = int(image_index)
|
393 |
+
visible_num = int(visible_num)
|
394 |
+
image_page_list = json.loads(image_page_list)
|
395 |
+
new_file_list = []
|
396 |
+
new_image_page_list = []
|
397 |
+
if name == "":
|
398 |
+
refresh = True
|
399 |
+
else:
|
400 |
+
try:
|
401 |
+
index_files = list(filenames).index(name)
|
402 |
+
|
403 |
+
index_on_page = image_page_list.index(name)
|
404 |
+
except ValueError as e:
|
405 |
+
print(traceback.format_exc(), file=sys.stderr)
|
406 |
+
# Something went wrong, force a page refresh
|
407 |
+
refresh = True
|
408 |
+
if not refresh:
|
409 |
+
if not delete_confirm:
|
410 |
+
delete_num = min(visible_num - index_on_page, delete_num)
|
411 |
+
new_file_list = filenames[:index_files] + filenames[index_files + delete_num:]
|
412 |
+
new_image_page_list = image_page_list[:index_on_page] + image_page_list[index_on_page + delete_num:]
|
413 |
+
|
414 |
+
for i in range(index_files, index_files + delete_num):
|
415 |
+
if os.path.exists(filenames[i]):
|
416 |
+
if opts.image_browser_delete_message:
|
417 |
+
print(f"Deleting file {filenames[i]}")
|
418 |
+
delete_recycle(filenames[i])
|
419 |
+
visible_num -= 1
|
420 |
+
if opts.image_browser_txt_files:
|
421 |
+
txt_file = totxt(filenames[i])
|
422 |
+
if os.path.exists(txt_file):
|
423 |
+
delete_recycle(txt_file)
|
424 |
+
else:
|
425 |
+
print(f"File does not exist {filenames[i]}")
|
426 |
+
# If we reach this point (which we shouldn't), things are messed up, better force a page refresh
|
427 |
+
refresh = True
|
428 |
+
|
429 |
+
if refresh:
|
430 |
+
turn_page_switch = -turn_page_switch
|
431 |
+
select_image = False
|
432 |
+
else:
|
433 |
+
select_image = True
|
434 |
+
|
435 |
+
return new_file_list, 1, turn_page_switch, visible_num, new_image_page_list, select_image, json.dumps(new_image_page_list)
|
436 |
+
|
437 |
+
def traverse_all_files(curr_path, image_list, tab_base_tag_box, img_path_depth) -> List[Tuple[str, os.stat_result, str, int]]:
|
438 |
+
global current_depth
|
439 |
+
logger.debug(f"curr_path: {curr_path}")
|
440 |
+
if curr_path == "":
|
441 |
+
return image_list
|
442 |
+
f_list = [(os.path.join(curr_path, entry.name), entry.stat()) for entry in os.scandir(curr_path)]
|
443 |
+
for f_info in f_list:
|
444 |
+
fname, fstat = f_info
|
445 |
+
if os.path.splitext(fname)[1] in image_ext_list:
|
446 |
+
image_list.append(f_info)
|
447 |
+
elif stat.S_ISDIR(fstat.st_mode):
|
448 |
+
if (opts.image_browser_with_subdirs and tab_base_tag_box != "image_browser_tab_others") or (tab_base_tag_box == "image_browser_tab_others" and img_path_depth != 0 and (current_depth < img_path_depth or img_path_depth < 0)):
|
449 |
+
current_depth = current_depth + 1
|
450 |
+
image_list = traverse_all_files(fname, image_list, tab_base_tag_box, img_path_depth)
|
451 |
+
current_depth = current_depth - 1
|
452 |
+
return image_list
|
453 |
+
|
454 |
+
def cache_exif(fileinfos):
|
455 |
+
global finfo_exif, exif_cache, finfo_aes, aes_cache, finfo_image_reward, image_reward_cache
|
456 |
+
|
457 |
+
if yappi_do:
|
458 |
+
import yappi
|
459 |
+
import pandas as pd
|
460 |
+
yappi.set_clock_type("wall")
|
461 |
+
yappi.start()
|
462 |
+
|
463 |
+
cache_exif_start = time.time()
|
464 |
+
new_exif = 0
|
465 |
+
new_aes = 0
|
466 |
+
conn, cursor = wib_db.transaction_begin()
|
467 |
+
for fi_info in fileinfos:
|
468 |
+
if any(fi_info[0].endswith(ext) for ext in image_ext_list):
|
469 |
+
found_exif = False
|
470 |
+
found_aes = False
|
471 |
+
if fi_info[0] in exif_cache:
|
472 |
+
finfo_exif[fi_info[0]] = exif_cache[fi_info[0]]
|
473 |
+
found_exif = True
|
474 |
+
if fi_info[0] in aes_cache:
|
475 |
+
finfo_aes[fi_info[0]] = aes_cache[fi_info[0]]
|
476 |
+
found_aes = True
|
477 |
+
if fi_info[0] in image_reward_cache:
|
478 |
+
finfo_image_reward[fi_info[0]] = image_reward_cache[fi_info[0]]
|
479 |
+
if not found_exif or not found_aes:
|
480 |
+
finfo_exif[fi_info[0]] = "0"
|
481 |
+
exif_cache[fi_info[0]] = "0"
|
482 |
+
finfo_aes[fi_info[0]] = "0"
|
483 |
+
aes_cache[fi_info[0]] = "0"
|
484 |
+
try:
|
485 |
+
image = Image.open(fi_info[0])
|
486 |
+
(_, allExif, allExif_html) = modules.extras.run_pnginfo(image)
|
487 |
+
image.close()
|
488 |
+
except SyntaxError:
|
489 |
+
allExif = False
|
490 |
+
logger.warning(f"Extension and content don't match: {fi_info[0]}")
|
491 |
+
except UnidentifiedImageError as e:
|
492 |
+
allExif = False
|
493 |
+
logger.warning(f"UnidentifiedImageError: {e}")
|
494 |
+
except Image.DecompressionBombError as e:
|
495 |
+
allExif = False
|
496 |
+
logger.warning(f"DecompressionBombError: {e}: {fi_info[0]}")
|
497 |
+
except PermissionError as e:
|
498 |
+
allExif = False
|
499 |
+
logger.warning(f"PermissionError: {e}: {fi_info[0]}")
|
500 |
+
except FileNotFoundError as e:
|
501 |
+
allExif = False
|
502 |
+
logger.warning(f"FileNotFoundError: {e}: {fi_info[0]}")
|
503 |
+
except OSError as e:
|
504 |
+
if e.errno == 22:
|
505 |
+
logger.warning(f"Caught OSError with error code 22: {fi_info[0]}")
|
506 |
+
else:
|
507 |
+
raise
|
508 |
+
if allExif:
|
509 |
+
finfo_exif[fi_info[0]] = allExif
|
510 |
+
exif_cache[fi_info[0]] = allExif
|
511 |
+
wib_db.update_exif_data(conn, fi_info[0], allExif)
|
512 |
+
new_exif = new_exif + 1
|
513 |
+
|
514 |
+
m = re.search("(?:aesthetic_score:|Score:) (\d+.\d+)", allExif)
|
515 |
+
if m:
|
516 |
+
aes_value = m.group(1)
|
517 |
+
else:
|
518 |
+
aes_value = "0"
|
519 |
+
finfo_aes[fi_info[0]] = aes_value
|
520 |
+
aes_cache[fi_info[0]] = aes_value
|
521 |
+
wib_db.update_exif_data_by_key(conn, fi_info[0], "aesthetic_score", aes_value)
|
522 |
+
new_aes = new_aes + 1
|
523 |
+
else:
|
524 |
+
try:
|
525 |
+
filename = os.path.splitext(fi_info[0])[0] + ".txt"
|
526 |
+
geninfo = ""
|
527 |
+
with open(filename) as f:
|
528 |
+
for line in f:
|
529 |
+
geninfo += line
|
530 |
+
finfo_exif[fi_info[0]] = geninfo
|
531 |
+
exif_cache[fi_info[0]] = geninfo
|
532 |
+
wib_db.update_exif_data_by_key(conn, fi_info[0], geninfo)
|
533 |
+
new_exif = new_exif + 1
|
534 |
+
|
535 |
+
m = re.search("(?:aesthetic_score:|Score:) (\d+.\d+)", geninfo)
|
536 |
+
if m:
|
537 |
+
aes_value = m.group(1)
|
538 |
+
else:
|
539 |
+
aes_value = "0"
|
540 |
+
finfo_aes[fi_info[0]] = aes_value
|
541 |
+
aes_cache[fi_info[0]] = aes_value
|
542 |
+
wib_db.update_exif_data_by_key(conn, fi_info[0], "aesthetic_score", aes_value)
|
543 |
+
new_aes = new_aes + 1
|
544 |
+
except Exception:
|
545 |
+
logger.warning(f"cache_exif: No EXIF in image or txt file for {fi_info[0]}")
|
546 |
+
# Saved with defaults to not scan it again next time
|
547 |
+
finfo_exif[fi_info[0]] = "0"
|
548 |
+
exif_cache[fi_info[0]] = "0"
|
549 |
+
allExif = "0"
|
550 |
+
wib_db.update_exif_data(conn, fi_info[0], allExif)
|
551 |
+
new_exif = new_exif + 1
|
552 |
+
|
553 |
+
aes_value = "0"
|
554 |
+
finfo_aes[fi_info[0]] = aes_value
|
555 |
+
aes_cache[fi_info[0]] = aes_value
|
556 |
+
wib_db.update_exif_data_by_key(conn, fi_info[0], "aesthetic_score", aes_value)
|
557 |
+
new_aes = new_aes + 1
|
558 |
+
wib_db.transaction_end(conn, cursor)
|
559 |
+
|
560 |
+
if yappi_do:
|
561 |
+
yappi.stop()
|
562 |
+
pd.set_option('display.float_format', lambda x: '%.6f' % x)
|
563 |
+
yappi_stats = yappi.get_func_stats().strip_dirs()
|
564 |
+
data = [(s.name, s.ncall, s.tsub, s.ttot, s.ttot/s.ncall) for s in yappi_stats]
|
565 |
+
df = pd.DataFrame(data, columns=['name', 'ncall', 'tsub', 'ttot', 'tavg'])
|
566 |
+
print(df.to_string(index=False))
|
567 |
+
yappi.get_thread_stats().print_all()
|
568 |
+
|
569 |
+
cache_exif_end = time.time()
|
570 |
+
logger.debug(f"cache_exif: {new_exif}/{len(fileinfos)} cache_aes: {new_aes}/{len(fileinfos)} {round(cache_exif_end - cache_exif_start, 1)} seconds")
|
571 |
+
|
572 |
+
def exif_rebuild(maint_wait):
|
573 |
+
global finfo_exif, exif_cache, finfo_aes, aes_cache, finfo_image_reward, image_reward_cache
|
574 |
+
if opts.image_browser_scan_exif:
|
575 |
+
logger.debug("Rebuild start")
|
576 |
+
exif_dirs = wib_db.get_exif_dirs()
|
577 |
+
finfo_aes = {}
|
578 |
+
finfo_image_reward = {}
|
579 |
+
exif_cache = {}
|
580 |
+
finfo_exif = {}
|
581 |
+
aes_cache = {}
|
582 |
+
image_reward_cache = {}
|
583 |
+
for key, value in exif_dirs.items():
|
584 |
+
if os.path.exists(key):
|
585 |
+
print(f"Rebuilding {key}")
|
586 |
+
fileinfos = traverse_all_files(key, [], "", 0)
|
587 |
+
cache_exif(fileinfos)
|
588 |
+
logger.debug("Rebuild end")
|
589 |
+
maint_last_msg = "Rebuild finished"
|
590 |
+
else:
|
591 |
+
maint_last_msg = "Exif cache not enabled in settings"
|
592 |
+
|
593 |
+
return maint_wait, maint_last_msg
|
594 |
+
|
595 |
+
def exif_delete_0(maint_wait):
|
596 |
+
global finfo_exif, exif_cache, finfo_aes, aes_cache
|
597 |
+
if opts.image_browser_scan_exif:
|
598 |
+
conn, cursor = wib_db.transaction_begin()
|
599 |
+
wib_db.delete_exif_0(cursor)
|
600 |
+
wib_db.transaction_end(conn, cursor)
|
601 |
+
finfo_aes = {}
|
602 |
+
finfo_exif = {}
|
603 |
+
exif_cache = wib_db.load_exif_data(exif_cache)
|
604 |
+
aes_cache = wib_db.load_aes_data(aes_cache)
|
605 |
+
maint_last_msg = "Delete finished"
|
606 |
+
else:
|
607 |
+
maint_last_msg = "Exif cache not enabled in settings"
|
608 |
+
|
609 |
+
return maint_wait, maint_last_msg
|
610 |
+
|
611 |
+
def exif_update_dirs(maint_update_dirs_from, maint_update_dirs_to, maint_wait):
|
612 |
+
global exif_cache, aes_cache, image_reward_cache
|
613 |
+
if maint_update_dirs_from == "":
|
614 |
+
maint_last_msg = "From is empty"
|
615 |
+
elif maint_update_dirs_to == "":
|
616 |
+
maint_last_msg = "To is empty"
|
617 |
+
else:
|
618 |
+
maint_update_dirs_from = os.path.realpath(maint_update_dirs_from)
|
619 |
+
maint_update_dirs_to = os.path.realpath(maint_update_dirs_to)
|
620 |
+
rows = 0
|
621 |
+
conn, cursor = wib_db.transaction_begin()
|
622 |
+
wib_db.update_path_recorder_mult(cursor, maint_update_dirs_from, maint_update_dirs_to)
|
623 |
+
rows = rows + cursor.rowcount
|
624 |
+
wib_db.update_exif_data_mult(cursor, maint_update_dirs_from, maint_update_dirs_to)
|
625 |
+
rows = rows + cursor.rowcount
|
626 |
+
wib_db.update_ranking_mult(cursor, maint_update_dirs_from, maint_update_dirs_to)
|
627 |
+
rows = rows + cursor.rowcount
|
628 |
+
wib_db.transaction_end(conn, cursor)
|
629 |
+
if rows == 0:
|
630 |
+
maint_last_msg = "No rows updated"
|
631 |
+
else:
|
632 |
+
maint_last_msg = f"{rows} rows updated. Please reload UI!"
|
633 |
+
|
634 |
+
return maint_wait, maint_last_msg
|
635 |
+
|
636 |
+
def reapply_ranking(path_recorder, maint_wait):
|
637 |
+
dirs = {}
|
638 |
+
|
639 |
+
for tab in tabs_list:
|
640 |
+
if os.path.exists(tab.path):
|
641 |
+
dirs[tab.path] = tab.path
|
642 |
+
|
643 |
+
for key in path_recorder:
|
644 |
+
if os.path.exists(key):
|
645 |
+
dirs[key] = key
|
646 |
+
|
647 |
+
conn, cursor = wib_db.transaction_begin()
|
648 |
+
|
649 |
+
# Traverse all known dirs, check if missing rankings are due to moved files
|
650 |
+
for key in dirs.keys():
|
651 |
+
fileinfos = traverse_all_files(key, [], "", 0)
|
652 |
+
for (file, _) in fileinfos:
|
653 |
+
# Is there a ranking for this full filepath
|
654 |
+
ranking_by_file = wib_db.get_ranking_by_file(cursor, file)
|
655 |
+
if ranking_by_file is None:
|
656 |
+
name = os.path.basename(file)
|
657 |
+
(ranking_by_name, alternate_hash) = wib_db.get_ranking_by_name(cursor, name)
|
658 |
+
# Is there a ranking only for the filename
|
659 |
+
if ranking_by_name is not None:
|
660 |
+
hash = wib_db.get_hash(file)
|
661 |
+
(alternate_file, alternate_ranking) = ranking_by_name
|
662 |
+
if alternate_ranking is not None:
|
663 |
+
(alternate_hash,) = alternate_hash
|
664 |
+
# Does the found filename's file have no hash or the same hash?
|
665 |
+
if alternate_hash is None or hash == alternate_hash:
|
666 |
+
if os.path.exists(alternate_file):
|
667 |
+
# Insert ranking as a copy of the found filename's ranking
|
668 |
+
wib_db.insert_ranking(cursor, file, alternate_ranking, hash)
|
669 |
+
else:
|
670 |
+
# Replace ranking of the found filename
|
671 |
+
wib_db.replace_ranking(cursor, file, alternate_file, hash)
|
672 |
+
|
673 |
+
wib_db.transaction_end(conn, cursor)
|
674 |
+
maint_last_msg = "Rankings reapplied"
|
675 |
+
|
676 |
+
return maint_wait, maint_last_msg
|
677 |
+
|
678 |
+
def atof(text):
|
679 |
+
try:
|
680 |
+
retval = float(text)
|
681 |
+
except ValueError:
|
682 |
+
retval = text
|
683 |
+
return retval
|
684 |
+
|
685 |
+
def natural_keys(text):
|
686 |
+
'''
|
687 |
+
alist.sort(key=natural_keys) sorts in human order
|
688 |
+
http://nedbatchelder.com/blog/200712/human_sorting.html
|
689 |
+
(See Toothy's implementation in the comments)
|
690 |
+
float regex comes from https://stackoverflow.com/a/12643073/190597
|
691 |
+
'''
|
692 |
+
return [ atof(c) for c in re.split(r'[+-]?([0-9]+(?:[.][0-9]*)?|[.][0-9]+)', text) ]
|
693 |
+
|
694 |
+
def open_folder(path):
|
695 |
+
if os.path.exists(path):
|
696 |
+
# Code from ui_common.py
|
697 |
+
if not shared.cmd_opts.hide_ui_dir_config:
|
698 |
+
if platform.system() == "Windows":
|
699 |
+
os.startfile(path)
|
700 |
+
elif platform.system() == "Darwin":
|
701 |
+
sp.Popen(["open", path])
|
702 |
+
elif "microsoft-standard-WSL2" in platform.uname().release:
|
703 |
+
sp.Popen(["wsl-open", path])
|
704 |
+
else:
|
705 |
+
sp.Popen(["xdg-open", path])
|
706 |
+
|
707 |
+
def check_ext(ext):
|
708 |
+
found = False
|
709 |
+
scripts_list = scripts.list_scripts("scripts", ".py")
|
710 |
+
for scriptfile in scripts_list:
|
711 |
+
if ext in scriptfile.basedir.lower():
|
712 |
+
found = True
|
713 |
+
break
|
714 |
+
return found
|
715 |
+
|
716 |
+
def exif_search(needle, haystack, use_regex, case_sensitive):
|
717 |
+
found = False
|
718 |
+
if use_regex:
|
719 |
+
if case_sensitive:
|
720 |
+
pattern = re.compile(needle, re.DOTALL)
|
721 |
+
else:
|
722 |
+
pattern = re.compile(needle, re.DOTALL | re.IGNORECASE)
|
723 |
+
if pattern.search(haystack) is not None:
|
724 |
+
found = True
|
725 |
+
else:
|
726 |
+
if not case_sensitive:
|
727 |
+
haystack = haystack.lower()
|
728 |
+
needle = needle.lower()
|
729 |
+
if needle in haystack:
|
730 |
+
found = True
|
731 |
+
return found
|
732 |
+
|
733 |
+
def get_all_images(dir_name, sort_by, sort_order, keyword, tab_base_tag_box, img_path_depth, ranking_filter, ranking_filter_min, ranking_filter_max, aes_filter_min, aes_filter_max, score_type, exif_keyword, negative_prompt_search, use_regex, case_sensitive):
|
734 |
+
global current_depth
|
735 |
+
logger.debug("get_all_images")
|
736 |
+
current_depth = 0
|
737 |
+
fileinfos = traverse_all_files(dir_name, [], tab_base_tag_box, img_path_depth)
|
738 |
+
keyword = keyword.strip(" ")
|
739 |
+
|
740 |
+
if opts.image_browser_scan_exif:
|
741 |
+
cache_exif(fileinfos)
|
742 |
+
|
743 |
+
if len(keyword) != 0:
|
744 |
+
fileinfos = [x for x in fileinfos if keyword.lower() in x[0].lower()]
|
745 |
+
filenames = [finfo[0] for finfo in fileinfos]
|
746 |
+
|
747 |
+
if opts.image_browser_scan_exif:
|
748 |
+
conn, cursor = wib_db.transaction_begin()
|
749 |
+
if len(exif_keyword) != 0:
|
750 |
+
if use_regex:
|
751 |
+
regex_error = False
|
752 |
+
try:
|
753 |
+
test_re = re.compile(exif_keyword, re.DOTALL)
|
754 |
+
except re.error as e:
|
755 |
+
regex_error = True
|
756 |
+
print(f"Regex error: {e}")
|
757 |
+
if (use_regex and not regex_error) or not use_regex:
|
758 |
+
if negative_prompt_search == "Yes":
|
759 |
+
fileinfos = [x for x in fileinfos if exif_search(exif_keyword, finfo_exif[x[0]], use_regex, case_sensitive)]
|
760 |
+
else:
|
761 |
+
result = []
|
762 |
+
for file_info in fileinfos:
|
763 |
+
file_name = file_info[0]
|
764 |
+
file_exif = finfo_exif[file_name]
|
765 |
+
file_exif_lc = file_exif.lower()
|
766 |
+
start_index = file_exif_lc.find(np)
|
767 |
+
end_index = file_exif.find("\n", start_index)
|
768 |
+
if negative_prompt_search == "Only":
|
769 |
+
start_index = start_index + len(np)
|
770 |
+
sub_string = file_exif[start_index:end_index].strip()
|
771 |
+
if exif_search(exif_keyword, sub_string, use_regex, case_sensitive):
|
772 |
+
result.append(file_info)
|
773 |
+
else:
|
774 |
+
sub_string = file_exif[start_index:end_index].strip()
|
775 |
+
file_exif = file_exif.replace(sub_string, "")
|
776 |
+
|
777 |
+
if exif_search(exif_keyword, file_exif, use_regex, case_sensitive):
|
778 |
+
result.append(file_info)
|
779 |
+
fileinfos = result
|
780 |
+
filenames = [finfo[0] for finfo in fileinfos]
|
781 |
+
wib_db.fill_work_files(cursor, fileinfos)
|
782 |
+
if len(aes_filter_min) != 0 or len(aes_filter_max) != 0:
|
783 |
+
try:
|
784 |
+
aes_filter_min_num = float(aes_filter_min)
|
785 |
+
except ValueError:
|
786 |
+
aes_filter_min_num = sys.float_info.min
|
787 |
+
try:
|
788 |
+
aes_filter_max_num = float(aes_filter_max)
|
789 |
+
except ValueError:
|
790 |
+
aes_filter_max_num = sys.float_info.max
|
791 |
+
|
792 |
+
fileinfos = wib_db.filter_aes(cursor, fileinfos, aes_filter_min_num, aes_filter_max_num, score_type)
|
793 |
+
filenames = [finfo[0] for finfo in fileinfos]
|
794 |
+
if ranking_filter != "All":
|
795 |
+
ranking_filter_min_num = 1
|
796 |
+
ranking_filter_max_num = 5
|
797 |
+
if ranking_filter == "Min-max":
|
798 |
+
try:
|
799 |
+
ranking_filter_min_num = int(ranking_filter_min)
|
800 |
+
except ValueError:
|
801 |
+
ranking_filter_min_num = 0
|
802 |
+
try:
|
803 |
+
ranking_filter_max_num = int(ranking_filter_max)
|
804 |
+
except ValueError:
|
805 |
+
ranking_filter_max_num = 0
|
806 |
+
if ranking_filter_min_num < 1:
|
807 |
+
ranking_filter_min_num = 1
|
808 |
+
if ranking_filter_max_num < 1 or ranking_filter_max_num > 5:
|
809 |
+
ranking_filter_max_num = 5
|
810 |
+
|
811 |
+
fileinfos = wib_db.filter_ranking(cursor, fileinfos, ranking_filter, ranking_filter_min_num, ranking_filter_max_num)
|
812 |
+
filenames = [finfo[0] for finfo in fileinfos]
|
813 |
+
|
814 |
+
wib_db.transaction_end(conn, cursor)
|
815 |
+
|
816 |
+
if sort_by == "date":
|
817 |
+
if sort_order == up_symbol:
|
818 |
+
fileinfos = sorted(fileinfos, key=lambda x: x[1].st_mtime)
|
819 |
+
else:
|
820 |
+
fileinfos = sorted(fileinfos, key=lambda x: -x[1].st_mtime)
|
821 |
+
filenames = [finfo[0] for finfo in fileinfos]
|
822 |
+
elif sort_by == "path name":
|
823 |
+
if sort_order == up_symbol:
|
824 |
+
fileinfos = sorted(fileinfos)
|
825 |
+
else:
|
826 |
+
fileinfos = sorted(fileinfos, reverse=True)
|
827 |
+
filenames = [finfo[0] for finfo in fileinfos]
|
828 |
+
elif sort_by == "random":
|
829 |
+
random.shuffle(fileinfos)
|
830 |
+
filenames = [finfo[0] for finfo in fileinfos]
|
831 |
+
elif sort_by == "ranking":
|
832 |
+
finfo_ranked = {}
|
833 |
+
for fi_info in fileinfos:
|
834 |
+
finfo_ranked[fi_info[0]], _ = get_ranking(fi_info[0])
|
835 |
+
if sort_order == up_symbol:
|
836 |
+
fileinfos = dict(sorted(finfo_ranked.items(), key=lambda x: (x[1], x[0])))
|
837 |
+
else:
|
838 |
+
fileinfos = dict(reversed(sorted(finfo_ranked.items(), key=lambda x: (x[1], x[0]))))
|
839 |
+
filenames = [finfo for finfo in fileinfos]
|
840 |
+
else:
|
841 |
+
sort_values = {}
|
842 |
+
exif_info = dict(finfo_exif)
|
843 |
+
if exif_info:
|
844 |
+
for k, v in exif_info.items():
|
845 |
+
match = re.search(r'(?<='+ sort_by + ":" ').*?(?=(,|$))', v, flags=re.DOTALL|re.IGNORECASE)
|
846 |
+
if match:
|
847 |
+
sort_values[k] = match.group().strip()
|
848 |
+
else:
|
849 |
+
sort_values[k] = "0"
|
850 |
+
if sort_by == "aesthetic_score" or sort_by == "ImageRewardScore" or sort_by == "cfg scale":
|
851 |
+
sort_float = True
|
852 |
+
else:
|
853 |
+
sort_float = False
|
854 |
+
|
855 |
+
if sort_order == down_symbol:
|
856 |
+
if sort_float:
|
857 |
+
fileinfos = [x for x in fileinfos if sort_values[x[0]] != "0"]
|
858 |
+
fileinfos.sort(key=lambda x: float(sort_values[x[0]]), reverse=True)
|
859 |
+
fileinfos = dict(fileinfos)
|
860 |
+
else:
|
861 |
+
fileinfos = dict(reversed(sorted(fileinfos, key=lambda x: natural_keys(sort_values[x[0]]))))
|
862 |
+
else:
|
863 |
+
if sort_float:
|
864 |
+
fileinfos = [x for x in fileinfos if sort_values[x[0]] != "0"]
|
865 |
+
fileinfos.sort(key=lambda x: float(sort_values[x[0]]))
|
866 |
+
fileinfos = dict(fileinfos)
|
867 |
+
else:
|
868 |
+
fileinfos = dict(sorted(fileinfos, key=lambda x: natural_keys(sort_values[x[0]])))
|
869 |
+
filenames = [finfo for finfo in fileinfos]
|
870 |
+
else:
|
871 |
+
filenames = [finfo for finfo in fileinfos]
|
872 |
+
return filenames
|
873 |
+
|
874 |
+
def get_image_thumbnail(image_list):
|
875 |
+
logger.debug("get_image_thumbnail")
|
876 |
+
optimized_cache = os.path.join(tempfile.gettempdir(),"optimized")
|
877 |
+
os.makedirs(optimized_cache,exist_ok=True)
|
878 |
+
thumbnail_list = []
|
879 |
+
for image_path in image_list:
|
880 |
+
image_path_hash = hashlib.md5(image_path.encode("utf-8")).hexdigest()
|
881 |
+
cache_image_path = os.path.join(optimized_cache, image_path_hash + ".jpg")
|
882 |
+
if os.path.isfile(cache_image_path):
|
883 |
+
thumbnail_list.append(cache_image_path)
|
884 |
+
else:
|
885 |
+
try:
|
886 |
+
image = Image.open(image_path)
|
887 |
+
except OSError:
|
888 |
+
# If PIL cannot open the image, use the original path
|
889 |
+
thumbnail_list.append(image_path)
|
890 |
+
continue
|
891 |
+
width, height = image.size
|
892 |
+
left = (width - min(width, height)) / 2
|
893 |
+
top = (height - min(width, height)) / 2
|
894 |
+
right = (width + min(width, height)) / 2
|
895 |
+
bottom = (height + min(width, height)) / 2
|
896 |
+
thumbnail = image.crop((left, top, right, bottom))
|
897 |
+
thumbnail.thumbnail((opts.image_browser_thumbnail_size, opts.image_browser_thumbnail_size))
|
898 |
+
if thumbnail.mode != "RGB":
|
899 |
+
thumbnail = thumbnail.convert("RGB")
|
900 |
+
try:
|
901 |
+
thumbnail.save(cache_image_path, "JPEG")
|
902 |
+
thumbnail_list.append(cache_image_path)
|
903 |
+
except FileNotFoundError:
|
904 |
+
# Cannot save cache, use PIL object
|
905 |
+
thumbnail_list.append(thumbnail)
|
906 |
+
return thumbnail_list
|
907 |
+
|
908 |
+
def set_tooltip_info(image_list):
|
909 |
+
image_browser_img_info = {}
|
910 |
+
conn, cursor = wib_db.transaction_begin()
|
911 |
+
for filename in image_list:
|
912 |
+
x, y = wib_db.select_x_y(cursor, filename)
|
913 |
+
image_browser_img_info[filename] = {"x": x, "y": y}
|
914 |
+
wib_db.transaction_end(conn, cursor)
|
915 |
+
image_browser_img_info_json = json.dumps(image_browser_img_info)
|
916 |
+
return image_browser_img_info_json
|
917 |
+
|
918 |
+
def get_image_page(img_path, page_index, filenames, keyword, sort_by, sort_order, tab_base_tag_box, img_path_depth, ranking_filter, ranking_filter_min, ranking_filter_max, aes_filter_min, aes_filter_max, score_type, exif_keyword, negative_prompt_search, use_regex, case_sensitive, image_reward_button):
|
919 |
+
logger.debug("get_image_page")
|
920 |
+
if img_path == "":
|
921 |
+
return [], page_index, [], "", "", "", 0, "", None, "", "[]", image_reward_button
|
922 |
+
|
923 |
+
# Set temp_dir from webui settings, so gradio uses it
|
924 |
+
if shared.opts.temp_dir != "":
|
925 |
+
tempfile.tempdir = shared.opts.temp_dir
|
926 |
+
|
927 |
+
img_path, _ = pure_path(img_path)
|
928 |
+
filenames = get_all_images(img_path, sort_by, sort_order, keyword, tab_base_tag_box, img_path_depth, ranking_filter, ranking_filter_min, ranking_filter_max, aes_filter_min, aes_filter_max, score_type, exif_keyword, negative_prompt_search, use_regex, case_sensitive)
|
929 |
+
page_index = int(page_index)
|
930 |
+
length = len(filenames)
|
931 |
+
max_page_index = math.ceil(length / num_of_imgs_per_page)
|
932 |
+
page_index = max_page_index if page_index == -1 else page_index
|
933 |
+
page_index = 1 if page_index < 1 else page_index
|
934 |
+
page_index = max_page_index if page_index > max_page_index else page_index
|
935 |
+
idx_frm = (page_index - 1) * num_of_imgs_per_page
|
936 |
+
image_list = filenames[idx_frm:idx_frm + num_of_imgs_per_page]
|
937 |
+
|
938 |
+
if opts.image_browser_scan_exif and opts.image_browser_img_tooltips:
|
939 |
+
image_browser_img_info = set_tooltip_info(image_list)
|
940 |
+
else:
|
941 |
+
image_browser_img_info = "[]"
|
942 |
+
|
943 |
+
if opts.image_browser_use_thumbnail:
|
944 |
+
thumbnail_list = get_image_thumbnail(image_list)
|
945 |
+
else:
|
946 |
+
thumbnail_list = image_list
|
947 |
+
|
948 |
+
visible_num = num_of_imgs_per_page if idx_frm + num_of_imgs_per_page < length else length % num_of_imgs_per_page
|
949 |
+
visible_num = num_of_imgs_per_page if visible_num == 0 else visible_num
|
950 |
+
|
951 |
+
load_info = "<div style='color:#999' align='center'>"
|
952 |
+
load_info += f"{length} images in this directory, divided into {int((length + 1) // num_of_imgs_per_page + 1)} pages"
|
953 |
+
load_info += "</div>"
|
954 |
+
|
955 |
+
return filenames, gr.update(value=page_index, label=f"Page Index ({page_index}/{max_page_index})"), thumbnail_list, "", "", "", visible_num, load_info, None, json.dumps(image_list), image_browser_img_info, gr.update(visible=True)
|
956 |
+
|
957 |
+
def get_current_file(tab_base_tag_box, num, page_index, filenames):
|
958 |
+
file = filenames[int(num) + int((page_index - 1) * num_of_imgs_per_page)]
|
959 |
+
return file
|
960 |
+
|
961 |
+
def show_image_info(tab_base_tag_box, num, page_index, filenames, turn_page_switch, image_gallery):
|
962 |
+
logger.debug(f"show_image_info: tab_base_tag_box, num, page_index, len(filenames), num_of_imgs_per_page: {tab_base_tag_box}, {num}, {page_index}, {len(filenames)}, {num_of_imgs_per_page}")
|
963 |
+
if len(filenames) == 0:
|
964 |
+
# This should only happen if webui was stopped and started again and the user clicks on one of the still displayed images.
|
965 |
+
# The state with the filenames will be empty then. In that case we return None to prevent further errors and force a page refresh.
|
966 |
+
turn_page_switch = -turn_page_switch
|
967 |
+
file = None
|
968 |
+
tm = None
|
969 |
+
info = ""
|
970 |
+
else:
|
971 |
+
file_num = int(num) + int(
|
972 |
+
(page_index - 1) * num_of_imgs_per_page)
|
973 |
+
if file_num >= len(filenames):
|
974 |
+
# Last image to the right is deleted, page refresh
|
975 |
+
turn_page_switch = -turn_page_switch
|
976 |
+
file = None
|
977 |
+
tm = None
|
978 |
+
info = ""
|
979 |
+
else:
|
980 |
+
file = filenames[file_num]
|
981 |
+
tm = "<div style='color:#999' align='right'>" + time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(os.path.getmtime(file))) + "</div>"
|
982 |
+
try:
|
983 |
+
with Image.open(file) as image:
|
984 |
+
_, geninfo, info = modules.extras.run_pnginfo(image)
|
985 |
+
except UnidentifiedImageError as e:
|
986 |
+
info = ""
|
987 |
+
logger.warning(f"UnidentifiedImageError: {e}")
|
988 |
+
if opts.image_browser_use_thumbnail:
|
989 |
+
image_gallery = [image['name'] for image in image_gallery]
|
990 |
+
image_gallery[int(num)] = filenames[file_num]
|
991 |
+
return file, tm, num, file, turn_page_switch, info, image_gallery
|
992 |
+
else:
|
993 |
+
return file, tm, num, file, turn_page_switch, info
|
994 |
+
|
995 |
+
def change_dir(img_dir, path_recorder, load_switch, img_path_browser, img_path_depth, img_path):
|
996 |
+
warning = None
|
997 |
+
img_path, _ = pure_path(img_path)
|
998 |
+
img_path_depth_org = img_path_depth
|
999 |
+
if img_dir == none_select:
|
1000 |
+
return warning, gr.update(visible=False), img_path_browser, path_recorder, load_switch, img_path, img_path_depth
|
1001 |
+
else:
|
1002 |
+
img_dir, img_path_depth = pure_path(img_dir)
|
1003 |
+
if warning is None:
|
1004 |
+
try:
|
1005 |
+
if os.path.exists(img_dir):
|
1006 |
+
try:
|
1007 |
+
f = os.listdir(img_dir)
|
1008 |
+
except:
|
1009 |
+
warning = f"'{img_dir} is not a directory"
|
1010 |
+
else:
|
1011 |
+
warning = "The directory does not exist"
|
1012 |
+
except:
|
1013 |
+
warning = "The format of the directory is incorrect"
|
1014 |
+
if warning is None:
|
1015 |
+
return "", gr.update(visible=True), img_path_browser, path_recorder, img_dir, img_dir, img_path_depth
|
1016 |
+
else:
|
1017 |
+
return warning, gr.update(visible=False), img_path_browser, path_recorder, load_switch, img_path, img_path_depth_org
|
1018 |
+
|
1019 |
+
def update_move_text_one(btn):
|
1020 |
+
btn_text = " ".join(btn.split()[1:])
|
1021 |
+
return f"{copy_move[opts.image_browser_copy_image]} {btn_text}"
|
1022 |
+
|
1023 |
+
def update_move_text(favorites_btn, to_dir_btn):
|
1024 |
+
return update_move_text_one(favorites_btn), update_move_text_one(to_dir_btn)
|
1025 |
+
|
1026 |
+
def get_ranking(filename):
|
1027 |
+
ranking_value = wib_db.select_ranking(filename)
|
1028 |
+
return ranking_value, None
|
1029 |
+
|
1030 |
+
def img_file_name_changed(img_file_name, favorites_btn, to_dir_btn):
|
1031 |
+
ranking_current, ranking = get_ranking(img_file_name)
|
1032 |
+
favorites_btn, to_dir_btn = update_move_text(favorites_btn, to_dir_btn)
|
1033 |
+
|
1034 |
+
return ranking_current, ranking, "", favorites_btn, to_dir_btn
|
1035 |
+
|
1036 |
+
def update_exif(img_file_name, key, value):
|
1037 |
+
image = Image.open(img_file_name)
|
1038 |
+
geninfo, items = images.read_info_from_image(image)
|
1039 |
+
if geninfo is not None:
|
1040 |
+
if f"{key}: " in geninfo:
|
1041 |
+
if value == "None":
|
1042 |
+
geninfo = re.sub(f', {key}: \d+(\.\d+)*', '', geninfo)
|
1043 |
+
else:
|
1044 |
+
geninfo = re.sub(f'{key}: \d+(\.\d+)*', f'{key}: {value}', geninfo)
|
1045 |
+
else:
|
1046 |
+
geninfo = f'{geninfo}, {key}: {value}'
|
1047 |
+
|
1048 |
+
original_time = os.path.getmtime(img_file_name)
|
1049 |
+
images.save_image(image, os.path.dirname(img_file_name), "", extension=os.path.splitext(img_file_name)[1][1:], info=geninfo, forced_filename=os.path.splitext(os.path.basename(img_file_name))[0], save_to_dirs=False)
|
1050 |
+
os.utime(img_file_name, (original_time, original_time))
|
1051 |
+
return geninfo
|
1052 |
+
|
1053 |
+
def update_ranking(img_file_name, ranking_current, ranking, img_file_info):
|
1054 |
+
# ranking = None is different than ranking = "None"! None means no radio button selected. "None" means radio button called "None" selected.
|
1055 |
+
if ranking is None:
|
1056 |
+
return ranking_current, None, img_file_info
|
1057 |
+
|
1058 |
+
saved_ranking, _ = get_ranking(img_file_name)
|
1059 |
+
if saved_ranking != ranking:
|
1060 |
+
wib_db.update_ranking(img_file_name, ranking)
|
1061 |
+
if opts.image_browser_ranking_pnginfo and any(img_file_name.endswith(ext) for ext in image_ext_list):
|
1062 |
+
img_file_info = update_exif(img_file_name, "Ranking", ranking)
|
1063 |
+
return ranking, None, img_file_info
|
1064 |
+
|
1065 |
+
def generate_image_reward(filenames, turn_page_switch, aes_filter_min, aes_filter_max):
|
1066 |
+
global image_reward_model
|
1067 |
+
if image_reward_model is None:
|
1068 |
+
image_reward_model = ImageReward.load("ImageReward-v1.0")
|
1069 |
+
conn, cursor = wib_db.transaction_begin()
|
1070 |
+
for filename in filenames:
|
1071 |
+
saved_image_reward_score, saved_image_reward_prompt = wib_db.select_image_reward_score(cursor, filename)
|
1072 |
+
if saved_image_reward_score is None and saved_image_reward_prompt is not None:
|
1073 |
+
try:
|
1074 |
+
with torch.no_grad():
|
1075 |
+
image_reward_score = image_reward_model.score(saved_image_reward_prompt, filename)
|
1076 |
+
image_reward_score = f"{image_reward_score:.2f}"
|
1077 |
+
try:
|
1078 |
+
logger.warning(f"Generated ImageRewardScore: {image_reward_score} for {filename}")
|
1079 |
+
except UnicodeEncodeError:
|
1080 |
+
pass
|
1081 |
+
wib_db.update_image_reward_score(cursor, filename, image_reward_score)
|
1082 |
+
if any(filename.endswith(ext) for ext in image_ext_list):
|
1083 |
+
img_file_info = update_exif(filename, "ImageRewardScore", image_reward_score)
|
1084 |
+
except UnidentifiedImageError as e:
|
1085 |
+
logger.warning(f"UnidentifiedImageError: {e}")
|
1086 |
+
wib_db.transaction_end(conn, cursor)
|
1087 |
+
return -turn_page_switch, aes_filter_min, aes_filter_max
|
1088 |
+
|
1089 |
+
def create_tab(tab: ImageBrowserTab, current_gr_tab: gr.Tab):
|
1090 |
+
global init, exif_cache, aes_cache, image_reward_cache, openoutpaint, controlnet, js_dummy_return
|
1091 |
+
dir_name = None
|
1092 |
+
others_dir = False
|
1093 |
+
maint = False
|
1094 |
+
standard_ui = True
|
1095 |
+
path_recorder = {}
|
1096 |
+
path_recorder_formatted = []
|
1097 |
+
path_recorder_unformatted = []
|
1098 |
+
|
1099 |
+
if init:
|
1100 |
+
db_version = wib_db.check()
|
1101 |
+
logger.debug(f"db_version: {db_version}")
|
1102 |
+
exif_cache = wib_db.load_exif_data(exif_cache)
|
1103 |
+
aes_cache = wib_db.load_exif_data_by_key(aes_cache, "aesthetic_score", "Score")
|
1104 |
+
image_reward_cache = wib_db.load_exif_data_by_key(image_reward_cache, "ImageRewardScore", "ImageRewardScore")
|
1105 |
+
init = False
|
1106 |
+
|
1107 |
+
path_recorder, path_recorder_formatted, path_recorder_unformatted = read_path_recorder()
|
1108 |
+
openoutpaint = check_ext("openoutpaint")
|
1109 |
+
controlnet = check_ext("controlnet")
|
1110 |
+
|
1111 |
+
if tab.name == "Others":
|
1112 |
+
others_dir = True
|
1113 |
+
standard_ui = False
|
1114 |
+
elif tab.name == "Maintenance":
|
1115 |
+
maint = True
|
1116 |
+
standard_ui = False
|
1117 |
+
else:
|
1118 |
+
dir_name = tab.path
|
1119 |
+
|
1120 |
+
if standard_ui:
|
1121 |
+
dir_name = str(Path(dir_name))
|
1122 |
+
if not os.path.exists(dir_name):
|
1123 |
+
os.makedirs(dir_name)
|
1124 |
+
|
1125 |
+
with gr.Row():
|
1126 |
+
path_recorder = gr.State(path_recorder)
|
1127 |
+
with gr.Column(scale=10):
|
1128 |
+
warning_box = gr.HTML("<p> ", elem_id=f"{tab.base_tag}_image_browser_warning_box")
|
1129 |
+
with gr.Column(scale=5, visible=(tab.name==favorite_tab_name)):
|
1130 |
+
gr.HTML(f"<p>Favorites path from settings: {opts.outdir_save}")
|
1131 |
+
|
1132 |
+
with gr.Row(visible=others_dir):
|
1133 |
+
with gr.Column(scale=10):
|
1134 |
+
suffix = "" if others_dir else tab.name
|
1135 |
+
img_path = gr.Textbox(dir_name, label="Images directory"+suffix, placeholder="Input images directory", interactive=others_dir)
|
1136 |
+
with gr.Column(scale=1):
|
1137 |
+
img_path_depth = gr.Number(value="0", label="Sub directory depth")
|
1138 |
+
with gr.Column(scale=1):
|
1139 |
+
img_path_save_button = gr.Button(value="Add to / replace in saved directories")
|
1140 |
+
|
1141 |
+
with gr.Row(visible=others_dir):
|
1142 |
+
with gr.Column(scale=10):
|
1143 |
+
img_path_browser = gr.Dropdown(choices=path_recorder_formatted, label="Saved directories")
|
1144 |
+
with gr.Column(scale=1):
|
1145 |
+
img_path_remove_button = gr.Button(value="Remove from saved directories")
|
1146 |
+
|
1147 |
+
with gr.Row(visible=others_dir):
|
1148 |
+
with gr.Column(scale=10):
|
1149 |
+
img_path_subdirs = gr.Dropdown(choices=[none_select], value=none_select, label="Sub directories", interactive=True, elem_id=f"{tab.base_tag}_img_path_subdirs")
|
1150 |
+
with gr.Column(scale=1):
|
1151 |
+
img_path_subdirs_button = gr.Button(value="Get sub directories")
|
1152 |
+
|
1153 |
+
with gr.Row(visible=standard_ui, elem_id=f"{tab.base_tag}_image_browser") as main_panel:
|
1154 |
+
with gr.Column():
|
1155 |
+
with gr.Row():
|
1156 |
+
with gr.Column(scale=2):
|
1157 |
+
with gr.Row(elem_id=f"{tab.base_tag}_image_browser_gallery_controls") as gallery_controls_panel:
|
1158 |
+
with gr.Column(scale=2, min_width=20):
|
1159 |
+
first_page = gr.Button("First Page", elem_id=f"{tab.base_tag}_control_image_browser_first_page")
|
1160 |
+
with gr.Column(scale=2, min_width=20):
|
1161 |
+
prev_page = gr.Button("Prev Page", elem_id=f"{tab.base_tag}_control_image_browser_prev_page")
|
1162 |
+
with gr.Column(scale=2, min_width=20):
|
1163 |
+
page_index = gr.Number(value=1, label="Page Index", elem_id=f"{tab.base_tag}_control_image_browser_page_index")
|
1164 |
+
with gr.Column(scale=1, min_width=20):
|
1165 |
+
refresh_index_button = ToolButton(value=refresh_symbol, elem_id=f"{tab.base_tag}_control_image_browser_refresh_index")
|
1166 |
+
with gr.Column(scale=2, min_width=20):
|
1167 |
+
next_page = gr.Button("Next Page", elem_id=f"{tab.base_tag}_control_image_browser_next_page")
|
1168 |
+
with gr.Column(scale=2, min_width=20):
|
1169 |
+
end_page = gr.Button("End Page", elem_id=f"{tab.base_tag}_control_image_browser_end_page")
|
1170 |
+
with gr.Row(visible=False) as ranking_panel:
|
1171 |
+
with gr.Column(scale=1, min_width=20):
|
1172 |
+
ranking_current = gr.Textbox(value="None", label="Current ranking", interactive=False)
|
1173 |
+
with gr.Column(scale=4, min_width=20):
|
1174 |
+
ranking = gr.Radio(choices=["1", "2", "3", "4", "5", "None"], label="Set ranking to", elem_id=f"{tab.base_tag}_control_image_browser_ranking", interactive=True)
|
1175 |
+
with gr.Row():
|
1176 |
+
image_gallery = gr.Gallery(show_label=False, elem_id=f"{tab.base_tag}_image_browser_gallery").style(grid=opts.image_browser_page_columns)
|
1177 |
+
with gr.Row() as delete_panel:
|
1178 |
+
with gr.Column(scale=1):
|
1179 |
+
delete_num = gr.Number(value=1, interactive=True, label="delete next", elem_id=f"{tab.base_tag}_image_browser_del_num")
|
1180 |
+
delete_confirm = gr.Checkbox(value=False, label="also delete off-screen images")
|
1181 |
+
with gr.Column(scale=3):
|
1182 |
+
delete = gr.Button('Delete', elem_id=f"{tab.base_tag}_image_browser_del_img_btn")
|
1183 |
+
with gr.Row() as info_add_panel:
|
1184 |
+
with gr.Accordion("Additional Generation Info", open=False):
|
1185 |
+
img_file_info_add = gr.HTML()
|
1186 |
+
|
1187 |
+
with gr.Column(scale=1):
|
1188 |
+
with gr.Row() as sort_panel:
|
1189 |
+
sort_by = gr.Dropdown(value="date", choices=["path name", "date", "aesthetic_score", "ImageRewardScore", "random", "cfg scale", "steps", "seed", "sampler", "size", "model", "model hash", "ranking"], label="Sort by")
|
1190 |
+
sort_order = ToolButton(value=down_symbol)
|
1191 |
+
with gr.Row() as filename_search_panel:
|
1192 |
+
filename_keyword_search = gr.Textbox(value="", label="Filename keyword search")
|
1193 |
+
with gr.Box() as exif_search_panel:
|
1194 |
+
with gr.Row():
|
1195 |
+
exif_keyword_search = gr.Textbox(value="", label="EXIF keyword search")
|
1196 |
+
negative_prompt_search = gr.Radio(value="No", choices=["No", "Yes", "Only"], label="Search negative prompt", interactive=True)
|
1197 |
+
with gr.Row():
|
1198 |
+
case_sensitive = gr.Checkbox(value=False, label="case sensitive")
|
1199 |
+
use_regex = gr.Checkbox(value=False, label=r"regex - e.g. ^(?!.*Hires).*$")
|
1200 |
+
with gr.Box() as ranking_filter_panel:
|
1201 |
+
with gr.Row():
|
1202 |
+
ranking_filter = gr.Radio(value="All", choices=["All", "1", "2", "3", "4", "5", "None", "Min-max"], label="Ranking filter", interactive=True)
|
1203 |
+
with gr.Row():
|
1204 |
+
with gr.Column(scale=2, min_width=20):
|
1205 |
+
ranking_filter_min = gr.Textbox(value="1", label="Minimum ranking", interactive=False)
|
1206 |
+
with gr.Column(scale=2, min_width=20):
|
1207 |
+
ranking_filter_max = gr.Textbox(value="5", label="Maximum ranking", interactive=False)
|
1208 |
+
with gr.Column(scale=4, min_width=20):
|
1209 |
+
gr.Textbox(value="Choose Min-max to activate these controls", label="", interactive=False)
|
1210 |
+
with gr.Box() as aesthetic_score_filter_panel:
|
1211 |
+
with gr.Row():
|
1212 |
+
with gr.Column(scale=4, min_width=20):
|
1213 |
+
score_type = gr.Dropdown(value=opts.image_browser_scoring_type, choices=["aesthetic_score", "ImageReward Score"], label="Scoring type", interactive=True)
|
1214 |
+
with gr.Column(scale=2, min_width=20):
|
1215 |
+
image_reward_button = gr.Button(value="Generate ImageReward Scores for all images", interactive=image_reward_installed, visible=False)
|
1216 |
+
with gr.Row():
|
1217 |
+
aes_filter_min = gr.Textbox(value="", label="Minimum score")
|
1218 |
+
aes_filter_max = gr.Textbox(value="", label="Maximum score")
|
1219 |
+
with gr.Row() as generation_info_panel:
|
1220 |
+
img_file_info = gr.Textbox(label="Generation Info", interactive=False, lines=6,elem_id=f"{tab.base_tag}_image_browser_file_info")
|
1221 |
+
with gr.Row() as filename_panel:
|
1222 |
+
img_file_name = gr.Textbox(value="", label="File Name", interactive=False)
|
1223 |
+
with gr.Row() as filetime_panel:
|
1224 |
+
img_file_time= gr.HTML()
|
1225 |
+
with gr.Row() as open_folder_panel:
|
1226 |
+
open_folder_button = gr.Button(folder_symbol, visible=standard_ui or others_dir)
|
1227 |
+
gr.HTML(" ")
|
1228 |
+
gr.HTML(" ")
|
1229 |
+
gr.HTML(" ")
|
1230 |
+
with gr.Row(elem_id=f"{tab.base_tag}_image_browser_button_panel", visible=False) as button_panel:
|
1231 |
+
with gr.Column():
|
1232 |
+
with gr.Row():
|
1233 |
+
if tab.name == favorite_tab_name:
|
1234 |
+
favorites_btn_show = False
|
1235 |
+
else:
|
1236 |
+
favorites_btn_show = True
|
1237 |
+
favorites_btn = gr.Button(f'{copy_move[opts.image_browser_copy_image]} to favorites', elem_id=f"{tab.base_tag}_image_browser_favorites_btn", visible=favorites_btn_show)
|
1238 |
+
try:
|
1239 |
+
send_to_buttons = modules.generation_parameters_copypaste.create_buttons(["txt2img", "img2img", "inpaint", "extras"])
|
1240 |
+
except:
|
1241 |
+
pass
|
1242 |
+
sendto_openoutpaint = gr.Button("Send to openOutpaint", elem_id=f"{tab.base_tag}_image_browser_openoutpaint_btn", visible=openoutpaint)
|
1243 |
+
with gr.Row(visible=controlnet):
|
1244 |
+
sendto_controlnet_txt2img = gr.Button("Send to txt2img ControlNet", visible=controlnet)
|
1245 |
+
sendto_controlnet_img2img = gr.Button("Send to img2img ControlNet", visible=controlnet)
|
1246 |
+
controlnet_max = opts.data.get("control_net_max_models_num", 1)
|
1247 |
+
sendto_controlnet_num = gr.Dropdown([str(i) for i in range(controlnet_max)], label="ControlNet number", value="0", interactive=True, visible=(controlnet and controlnet_max > 1))
|
1248 |
+
if controlnet_max is None:
|
1249 |
+
sendto_controlnet_type = gr.Textbox(value="none", visible=False)
|
1250 |
+
elif controlnet_max == 1:
|
1251 |
+
sendto_controlnet_type = gr.Textbox(value="single", visible=False)
|
1252 |
+
else:
|
1253 |
+
sendto_controlnet_type = gr.Textbox(value="multiple", visible=False)
|
1254 |
+
with gr.Row(elem_id=f"{tab.base_tag}_image_browser_to_dir_panel", visible=False) as to_dir_panel:
|
1255 |
+
with gr.Box():
|
1256 |
+
with gr.Row():
|
1257 |
+
to_dir_path = gr.Textbox(label="Directory path")
|
1258 |
+
with gr.Row():
|
1259 |
+
to_dir_saved = gr.Dropdown(choices=path_recorder_unformatted, label="Saved directories")
|
1260 |
+
with gr.Row():
|
1261 |
+
to_dir_btn = gr.Button(f'{copy_move[opts.image_browser_copy_image]} to directory', elem_id=f"{tab.base_tag}_image_browser_to_dir_btn")
|
1262 |
+
|
1263 |
+
with gr.Row():
|
1264 |
+
collected_warning = gr.HTML()
|
1265 |
+
|
1266 |
+
with gr.Row(visible=False):
|
1267 |
+
renew_page = gr.Button("Renew Page", elem_id=f"{tab.base_tag}_image_browser_renew_page")
|
1268 |
+
visible_img_num = gr.Number()
|
1269 |
+
tab_base_tag_box = gr.Textbox(tab.base_tag)
|
1270 |
+
image_index = gr.Textbox(value=-1, elem_id=f"{tab.base_tag}_image_browser_image_index")
|
1271 |
+
set_index = gr.Button('set_index', elem_id=f"{tab.base_tag}_image_browser_set_index")
|
1272 |
+
filenames = gr.State([])
|
1273 |
+
hidden = gr.Image(type="pil", elem_id=f"{tab.base_tag}_image_browser_hidden_image")
|
1274 |
+
image_page_list = gr.Textbox(elem_id=f"{tab.base_tag}_image_browser_image_page_list")
|
1275 |
+
info1 = gr.Textbox()
|
1276 |
+
info2 = gr.Textbox()
|
1277 |
+
load_switch = gr.Textbox(value="load_switch", label="load_switch")
|
1278 |
+
to_dir_load_switch = gr.Textbox(value="to dir load_switch", label="to_dir_load_switch")
|
1279 |
+
turn_page_switch = gr.Number(value=1, label="turn_page_switch")
|
1280 |
+
select_image = gr.Number(value=1)
|
1281 |
+
img_path_add = gr.Textbox(value="add")
|
1282 |
+
img_path_remove = gr.Textbox(value="remove")
|
1283 |
+
favorites_path = gr.Textbox(value=opts.outdir_save)
|
1284 |
+
mod_keys = ""
|
1285 |
+
if opts.image_browser_mod_ctrl_shift:
|
1286 |
+
mod_keys = f"{mod_keys}CS"
|
1287 |
+
elif opts.image_browser_mod_shift:
|
1288 |
+
mod_keys = f"{mod_keys}S"
|
1289 |
+
image_browser_mod_keys = gr.Textbox(value=mod_keys, elem_id=f"{tab.base_tag}_image_browser_mod_keys")
|
1290 |
+
image_browser_prompt = gr.Textbox(elem_id=f"{tab.base_tag}_image_browser_prompt")
|
1291 |
+
image_browser_neg_prompt = gr.Textbox(elem_id=f"{tab.base_tag}_image_browser_neg_prompt")
|
1292 |
+
js_logs = gr.Textbox()
|
1293 |
+
image_browser_img_info = gr.Textbox(value="[]", elem_id=f"{tab.base_tag}_image_browser_img_info")
|
1294 |
+
|
1295 |
+
# Maintenance tab
|
1296 |
+
with gr.Row(visible=maint):
|
1297 |
+
with gr.Column(scale=4):
|
1298 |
+
gr.HTML(f"{caution_symbol} Caution: You should only use these options if you know what you are doing. {caution_symbol}")
|
1299 |
+
with gr.Column(scale=3):
|
1300 |
+
maint_wait = gr.HTML("Status:")
|
1301 |
+
with gr.Column(scale=7):
|
1302 |
+
gr.HTML(" ")
|
1303 |
+
with gr.Row(visible=maint):
|
1304 |
+
maint_last_msg = gr.Textbox(label="Last message", interactive=False)
|
1305 |
+
with gr.Row(visible=maint):
|
1306 |
+
with gr.Column(scale=1):
|
1307 |
+
maint_exif_rebuild = gr.Button(value="Rebuild exif cache")
|
1308 |
+
with gr.Column(scale=1):
|
1309 |
+
maint_exif_delete_0 = gr.Button(value="Delete 0-entries from exif cache")
|
1310 |
+
with gr.Column(scale=10):
|
1311 |
+
gr.HTML(visible=False)
|
1312 |
+
with gr.Row(visible=maint):
|
1313 |
+
with gr.Column(scale=1):
|
1314 |
+
maint_update_dirs = gr.Button(value="Update directory names in database")
|
1315 |
+
with gr.Column(scale=10):
|
1316 |
+
maint_update_dirs_from = gr.Textbox(label="From (full path)")
|
1317 |
+
with gr.Column(scale=10):
|
1318 |
+
maint_update_dirs_to = gr.Textbox(label="to (full path)")
|
1319 |
+
with gr.Row(visible=maint):
|
1320 |
+
with gr.Column(scale=1):
|
1321 |
+
maint_reapply_ranking = gr.Button(value="Reapply ranking after moving files")
|
1322 |
+
with gr.Column(scale=10):
|
1323 |
+
gr.HTML(visible=False)
|
1324 |
+
with gr.Row(visible=maint):
|
1325 |
+
with gr.Column(scale=1):
|
1326 |
+
maint_restart_debug = gr.Button(value="Restart debug")
|
1327 |
+
with gr.Column(scale=10):
|
1328 |
+
gr.HTML(visible=False)
|
1329 |
+
with gr.Row(visible=maint):
|
1330 |
+
with gr.Column(scale=1):
|
1331 |
+
maint_get_js_logs = gr.Button(value="Get javascript logs")
|
1332 |
+
with gr.Column(scale=10):
|
1333 |
+
maint_show_logs = gr.Textbox(label="Javascript logs", lines=10, interactive=False)
|
1334 |
+
with gr.Row(visible=False):
|
1335 |
+
with gr.Column(scale=1):
|
1336 |
+
maint_rebuild_ranking = gr.Button(value="Rebuild ranking from exif info")
|
1337 |
+
with gr.Column(scale=10):
|
1338 |
+
gr.HTML(visible=False)
|
1339 |
+
|
1340 |
+
# Hide components based on opts.image_browser_hidden_components
|
1341 |
+
hidden_component_map = {
|
1342 |
+
"Sort by": sort_panel,
|
1343 |
+
"Filename keyword search": filename_search_panel,
|
1344 |
+
"EXIF keyword search": exif_search_panel,
|
1345 |
+
"Ranking Filter": ranking_filter_panel,
|
1346 |
+
"Aesthestic Score": aesthetic_score_filter_panel,
|
1347 |
+
"Generation Info": generation_info_panel,
|
1348 |
+
"File Name": filename_panel,
|
1349 |
+
"File Time": filetime_panel,
|
1350 |
+
"Open Folder": open_folder_panel,
|
1351 |
+
"Send to buttons": button_panel,
|
1352 |
+
"Copy to directory": to_dir_panel,
|
1353 |
+
"Gallery Controls Bar": gallery_controls_panel,
|
1354 |
+
"Ranking Bar": ranking_panel,
|
1355 |
+
"Delete Bar": delete_panel,
|
1356 |
+
"Additional Generation Info": info_add_panel
|
1357 |
+
}
|
1358 |
+
|
1359 |
+
if set(hidden_component_map.keys()) != set(components_list):
|
1360 |
+
logger.warning(f"Invalid items present in either hidden_component_map or components_list. Make sure when adding new components they are added to both.")
|
1361 |
+
|
1362 |
+
override_hidden = set()
|
1363 |
+
if hasattr(opts, "image_browser_hidden_components"):
|
1364 |
+
for item in opts.image_browser_hidden_components:
|
1365 |
+
hidden_component_map[item].visible = False
|
1366 |
+
override_hidden.add(hidden_component_map[item])
|
1367 |
+
|
1368 |
+
change_dir_outputs = [warning_box, main_panel, img_path_browser, path_recorder, load_switch, img_path, img_path_depth]
|
1369 |
+
img_path.submit(change_dir, inputs=[img_path, path_recorder, load_switch, img_path_browser, img_path_depth, img_path], outputs=change_dir_outputs, show_progress=opts.image_browser_show_progress)
|
1370 |
+
img_path_browser.change(change_dir, inputs=[img_path_browser, path_recorder, load_switch, img_path_browser, img_path_depth, img_path], outputs=change_dir_outputs, show_progress=opts.image_browser_show_progress)
|
1371 |
+
# img_path_browser.change(browser2path, inputs=[img_path_browser], outputs=[img_path])
|
1372 |
+
to_dir_saved.change(change_dir, inputs=[to_dir_saved, path_recorder, to_dir_load_switch, to_dir_saved, img_path_depth, to_dir_path], outputs=[warning_box, main_panel, to_dir_saved, path_recorder, to_dir_load_switch, to_dir_path, img_path_depth], show_progress=opts.image_browser_show_progress)
|
1373 |
+
|
1374 |
+
#delete
|
1375 |
+
delete.click(
|
1376 |
+
fn=delete_image,
|
1377 |
+
inputs=[tab_base_tag_box, delete_num, img_file_name, filenames, image_index, visible_img_num, delete_confirm, turn_page_switch, image_page_list],
|
1378 |
+
outputs=[filenames, delete_num, turn_page_switch, visible_img_num, image_gallery, select_image, image_page_list],
|
1379 |
+
show_progress=opts.image_browser_show_progress
|
1380 |
+
).then(
|
1381 |
+
fn=None,
|
1382 |
+
_js="image_browser_select_image",
|
1383 |
+
inputs=[tab_base_tag_box, image_index, select_image],
|
1384 |
+
outputs=[js_dummy_return],
|
1385 |
+
show_progress=opts.image_browser_show_progress
|
1386 |
+
)
|
1387 |
+
|
1388 |
+
to_dir_btn.click(save_image, inputs=[img_file_name, filenames, page_index, turn_page_switch, to_dir_path], outputs=[collected_warning, filenames, page_index, turn_page_switch], show_progress=opts.image_browser_show_progress)
|
1389 |
+
#turn page
|
1390 |
+
first_page.click(lambda s:(1, -s) , inputs=[turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress)
|
1391 |
+
next_page.click(lambda p, s: (p + 1, -s), inputs=[page_index, turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress)
|
1392 |
+
prev_page.click(lambda p, s: (p - 1, -s), inputs=[page_index, turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress)
|
1393 |
+
end_page.click(lambda s: (-1, -s), inputs=[turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress)
|
1394 |
+
load_switch.change(lambda s:(1, -s), inputs=[turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress)
|
1395 |
+
filename_keyword_search.submit(lambda s:(1, -s), inputs=[turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress)
|
1396 |
+
exif_keyword_search.submit(lambda s:(1, -s), inputs=[turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress)
|
1397 |
+
ranking_filter_min.submit(lambda s:(1, -s), inputs=[turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress)
|
1398 |
+
ranking_filter_max.submit(lambda s:(1, -s), inputs=[turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress)
|
1399 |
+
aes_filter_min.submit(lambda s:(1, -s), inputs=[turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress)
|
1400 |
+
aes_filter_max.submit(lambda s:(1, -s), inputs=[turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress)
|
1401 |
+
sort_by.change(lambda s:(1, -s), inputs=[turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress)
|
1402 |
+
page_index.submit(lambda s: -s, inputs=[turn_page_switch], outputs=[turn_page_switch], show_progress=opts.image_browser_show_progress)
|
1403 |
+
renew_page.click(lambda s: -s, inputs=[turn_page_switch], outputs=[turn_page_switch], show_progress=opts.image_browser_show_progress)
|
1404 |
+
refresh_index_button.click(lambda p, s:(p, -s), inputs=[page_index, turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress)
|
1405 |
+
img_path_depth.change(lambda s: -s, inputs=[turn_page_switch], outputs=[turn_page_switch], show_progress=opts.image_browser_show_progress)
|
1406 |
+
|
1407 |
+
hide_on_thumbnail_view = [delete_panel, button_panel, ranking_panel, to_dir_panel, info_add_panel]
|
1408 |
+
|
1409 |
+
sort_order.click(
|
1410 |
+
fn=sort_order_flip,
|
1411 |
+
inputs=[turn_page_switch, sort_order],
|
1412 |
+
outputs=[page_index, turn_page_switch, sort_order],
|
1413 |
+
show_progress=opts.image_browser_show_progress
|
1414 |
+
)
|
1415 |
+
ranking_filter.change(
|
1416 |
+
fn=ranking_filter_settings,
|
1417 |
+
inputs=[page_index, turn_page_switch, ranking_filter],
|
1418 |
+
outputs=[page_index, turn_page_switch, ranking_filter_min, ranking_filter_max],
|
1419 |
+
show_progress=opts.image_browser_show_progress
|
1420 |
+
)
|
1421 |
+
|
1422 |
+
# Others
|
1423 |
+
img_path_subdirs_button.click(
|
1424 |
+
fn=img_path_subdirs_get,
|
1425 |
+
inputs=[img_path],
|
1426 |
+
outputs=[img_path_subdirs],
|
1427 |
+
show_progress=opts.image_browser_show_progress
|
1428 |
+
)
|
1429 |
+
img_path_subdirs.change(
|
1430 |
+
fn=change_dir,
|
1431 |
+
inputs=[img_path_subdirs, path_recorder, load_switch, img_path_browser, img_path_depth, img_path],
|
1432 |
+
outputs=change_dir_outputs,
|
1433 |
+
show_progress=opts.image_browser_show_progress
|
1434 |
+
)
|
1435 |
+
img_path_save_button.click(
|
1436 |
+
fn=img_path_add_remove,
|
1437 |
+
inputs=[img_path, path_recorder, img_path_add, img_path_depth],
|
1438 |
+
outputs=[path_recorder, img_path_browser],
|
1439 |
+
show_progress=opts.image_browser_show_progress
|
1440 |
+
)
|
1441 |
+
img_path_remove_button.click(
|
1442 |
+
fn=img_path_add_remove,
|
1443 |
+
inputs=[img_path, path_recorder, img_path_remove, img_path_depth],
|
1444 |
+
outputs=[path_recorder, img_path_browser],
|
1445 |
+
show_progress=opts.image_browser_show_progress
|
1446 |
+
)
|
1447 |
+
maint_exif_rebuild.click(
|
1448 |
+
fn=exif_rebuild,
|
1449 |
+
inputs=[maint_wait],
|
1450 |
+
outputs=[maint_wait, maint_last_msg],
|
1451 |
+
show_progress=True
|
1452 |
+
)
|
1453 |
+
maint_exif_delete_0.click(
|
1454 |
+
fn=exif_delete_0,
|
1455 |
+
inputs=[maint_wait],
|
1456 |
+
outputs=[maint_wait, maint_last_msg],
|
1457 |
+
show_progress=True
|
1458 |
+
)
|
1459 |
+
maint_update_dirs.click(
|
1460 |
+
fn=exif_update_dirs,
|
1461 |
+
inputs=[maint_update_dirs_from, maint_update_dirs_to, maint_wait],
|
1462 |
+
outputs=[maint_wait, maint_last_msg],
|
1463 |
+
show_progress=True
|
1464 |
+
)
|
1465 |
+
maint_reapply_ranking.click(
|
1466 |
+
fn=reapply_ranking,
|
1467 |
+
inputs=[path_recorder, maint_wait],
|
1468 |
+
outputs=[maint_wait, maint_last_msg],
|
1469 |
+
show_progress=True
|
1470 |
+
)
|
1471 |
+
maint_restart_debug.click(
|
1472 |
+
fn=restart_debug,
|
1473 |
+
inputs=[maint_wait],
|
1474 |
+
outputs=[maint_wait, maint_last_msg],
|
1475 |
+
show_progress=True
|
1476 |
+
)
|
1477 |
+
maint_get_js_logs.click(
|
1478 |
+
fn=js_logs_output,
|
1479 |
+
_js="get_js_logs",
|
1480 |
+
inputs=[js_logs],
|
1481 |
+
outputs=[maint_show_logs],
|
1482 |
+
show_progress=True
|
1483 |
+
)
|
1484 |
+
|
1485 |
+
# other functions
|
1486 |
+
if opts.image_browser_use_thumbnail:
|
1487 |
+
set_index_outputs = [img_file_name, img_file_time, image_index, hidden, turn_page_switch, img_file_info_add, image_gallery]
|
1488 |
+
else:
|
1489 |
+
set_index_outputs = [img_file_name, img_file_time, image_index, hidden, turn_page_switch, img_file_info_add]
|
1490 |
+
set_index.click(
|
1491 |
+
fn=show_image_info,
|
1492 |
+
_js="image_browser_get_current_img",
|
1493 |
+
inputs=[tab_base_tag_box, image_index, page_index, filenames, turn_page_switch, image_gallery],
|
1494 |
+
outputs=set_index_outputs,
|
1495 |
+
show_progress=opts.image_browser_show_progress
|
1496 |
+
).then(
|
1497 |
+
fn=None,
|
1498 |
+
_js="image_browser_img_show_progress_update",
|
1499 |
+
inputs=[],
|
1500 |
+
outputs=[js_dummy_return],
|
1501 |
+
show_progress=opts.image_browser_show_progress
|
1502 |
+
)
|
1503 |
+
|
1504 |
+
set_index.click(fn=lambda:(gr.update(visible=delete_panel not in override_hidden), gr.update(visible=button_panel not in override_hidden), gr.update(visible=ranking_panel not in override_hidden), gr.update(visible=to_dir_panel not in override_hidden), gr.update(visible=info_add_panel not in override_hidden)), inputs=None, outputs=hide_on_thumbnail_view, show_progress=opts.image_browser_show_progress)
|
1505 |
+
|
1506 |
+
favorites_btn.click(save_image, inputs=[img_file_name, filenames, page_index, turn_page_switch, favorites_path], outputs=[collected_warning, filenames, page_index, turn_page_switch], show_progress=opts.image_browser_show_progress)
|
1507 |
+
img_file_name.change(img_file_name_changed, inputs=[img_file_name, favorites_btn, to_dir_btn], outputs=[ranking_current, ranking, collected_warning, favorites_btn, to_dir_btn], show_progress=opts.image_browser_show_progress)
|
1508 |
+
|
1509 |
+
hidden.change(fn=run_pnginfo, inputs=[hidden, img_path, img_file_name], outputs=[info1, img_file_info, info2, image_browser_prompt, image_browser_neg_prompt], show_progress=opts.image_browser_show_progress)
|
1510 |
+
|
1511 |
+
#ranking
|
1512 |
+
ranking.change(update_ranking, inputs=[img_file_name, ranking_current, ranking, img_file_info], outputs=[ranking_current, ranking, img_file_info], show_progress=opts.image_browser_show_progress)
|
1513 |
+
|
1514 |
+
try:
|
1515 |
+
modules.generation_parameters_copypaste.bind_buttons(send_to_buttons, hidden, img_file_info)
|
1516 |
+
except:
|
1517 |
+
pass
|
1518 |
+
|
1519 |
+
if standard_ui:
|
1520 |
+
current_gr_tab.select(
|
1521 |
+
fn=tab_select,
|
1522 |
+
inputs=[],
|
1523 |
+
outputs=[path_recorder, to_dir_saved],
|
1524 |
+
show_progress=opts.image_browser_show_progress
|
1525 |
+
)
|
1526 |
+
open_folder_button.click(
|
1527 |
+
fn=lambda: open_folder(dir_name),
|
1528 |
+
inputs=[],
|
1529 |
+
outputs=[],
|
1530 |
+
show_progress=opts.image_browser_show_progress
|
1531 |
+
)
|
1532 |
+
elif others_dir:
|
1533 |
+
open_folder_button.click(
|
1534 |
+
fn=open_folder,
|
1535 |
+
inputs=[img_path],
|
1536 |
+
outputs=[],
|
1537 |
+
show_progress=opts.image_browser_show_progress
|
1538 |
+
)
|
1539 |
+
if standard_ui or others_dir:
|
1540 |
+
turn_page_switch.change(
|
1541 |
+
fn=get_image_page,
|
1542 |
+
inputs=[img_path, page_index, filenames, filename_keyword_search, sort_by, sort_order, tab_base_tag_box, img_path_depth, ranking_filter, ranking_filter_min, ranking_filter_max, aes_filter_min, aes_filter_max, score_type, exif_keyword_search, negative_prompt_search, use_regex, case_sensitive, image_reward_button],
|
1543 |
+
outputs=[filenames, page_index, image_gallery, img_file_name, img_file_time, img_file_info, visible_img_num, warning_box, hidden, image_page_list, image_browser_img_info, image_reward_button],
|
1544 |
+
show_progress=opts.image_browser_show_progress
|
1545 |
+
).then(
|
1546 |
+
fn=None,
|
1547 |
+
_js="image_browser_turnpage",
|
1548 |
+
inputs=[tab_base_tag_box],
|
1549 |
+
outputs=[js_dummy_return],
|
1550 |
+
show_progress=opts.image_browser_show_progress
|
1551 |
+
)
|
1552 |
+
turn_page_switch.change(fn=lambda:(gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)), inputs=None, outputs=hide_on_thumbnail_view, show_progress=opts.image_browser_show_progress)
|
1553 |
+
sendto_openoutpaint.click(
|
1554 |
+
fn=None,
|
1555 |
+
inputs=[tab_base_tag_box, image_index, image_browser_prompt, image_browser_neg_prompt],
|
1556 |
+
outputs=[js_dummy_return],
|
1557 |
+
_js="image_browser_openoutpaint_send",
|
1558 |
+
show_progress=opts.image_browser_show_progress )
|
1559 |
+
sendto_controlnet_txt2img.click(
|
1560 |
+
fn=None,
|
1561 |
+
inputs=[tab_base_tag_box, image_index, sendto_controlnet_num, sendto_controlnet_type],
|
1562 |
+
outputs=[js_dummy_return],
|
1563 |
+
_js="image_browser_controlnet_send_txt2img",
|
1564 |
+
show_progress=opts.image_browser_show_progress
|
1565 |
+
)
|
1566 |
+
sendto_controlnet_img2img.click(
|
1567 |
+
fn=None,
|
1568 |
+
inputs=[tab_base_tag_box, image_index, sendto_controlnet_num, sendto_controlnet_type],
|
1569 |
+
outputs=[js_dummy_return],
|
1570 |
+
_js="image_browser_controlnet_send_img2img",
|
1571 |
+
show_progress=opts.image_browser_show_progress
|
1572 |
+
)
|
1573 |
+
image_reward_button.click(
|
1574 |
+
fn=generate_image_reward,
|
1575 |
+
inputs=[filenames, turn_page_switch, aes_filter_min, aes_filter_max],
|
1576 |
+
outputs=[turn_page_switch, aes_filter_min, aes_filter_max],
|
1577 |
+
show_progress=True
|
1578 |
+
)
|
1579 |
+
|
1580 |
+
def run_pnginfo(image, image_path, image_file_name):
|
1581 |
+
if image is None:
|
1582 |
+
return '', '', '', '', ''
|
1583 |
+
try:
|
1584 |
+
geninfo, items = images.read_info_from_image(image)
|
1585 |
+
items = {**{'parameters': geninfo}, **items}
|
1586 |
+
|
1587 |
+
info = ''
|
1588 |
+
for key, text in items.items():
|
1589 |
+
info += f"""
|
1590 |
+
<div>
|
1591 |
+
<p><b>{plaintext_to_html(str(key))}</b></p>
|
1592 |
+
<p>{plaintext_to_html(str(text))}</p>
|
1593 |
+
</div>
|
1594 |
+
""".strip()+"\n"
|
1595 |
+
except UnidentifiedImageError as e:
|
1596 |
+
geninfo = None
|
1597 |
+
info = ""
|
1598 |
+
|
1599 |
+
if geninfo is None:
|
1600 |
+
try:
|
1601 |
+
filename = os.path.splitext(image_file_name)[0] + ".txt"
|
1602 |
+
geninfo = ""
|
1603 |
+
with open(filename) as f:
|
1604 |
+
for line in f:
|
1605 |
+
geninfo += line
|
1606 |
+
except Exception:
|
1607 |
+
logger.warning(f"run_pnginfo: No EXIF in image or txt file")
|
1608 |
+
|
1609 |
+
if openoutpaint:
|
1610 |
+
prompt, neg_prompt = wib_db.select_prompts(image_file_name)
|
1611 |
+
if prompt == "0":
|
1612 |
+
prompt = ""
|
1613 |
+
if neg_prompt == "0":
|
1614 |
+
neg_prompt = ""
|
1615 |
+
else:
|
1616 |
+
prompt = ""
|
1617 |
+
neg_prompt = ""
|
1618 |
+
|
1619 |
+
return '', geninfo, info, prompt, neg_prompt
|
1620 |
+
|
1621 |
+
|
1622 |
+
def on_ui_tabs():
|
1623 |
+
global num_of_imgs_per_page, loads_files_num, js_dummy_return
|
1624 |
+
num_of_imgs_per_page = int(opts.image_browser_page_columns * opts.image_browser_page_rows)
|
1625 |
+
loads_files_num = int(opts.image_browser_pages_perload * num_of_imgs_per_page)
|
1626 |
+
with gr.Blocks(analytics_enabled=False) as image_browser:
|
1627 |
+
gradio_needed = "3.23.0"
|
1628 |
+
if version.parse(gr.__version__) < version.parse(gradio_needed):
|
1629 |
+
gr.HTML(f'<p style="color: red; font-weight: bold;">You are running Gradio version {gr.__version__}. This version of the extension requires at least Gradio version {gradio_needed}.</p><p style="color: red; font-weight: bold;">For more details see <a href="https://github.com/AlUlkesh/stable-diffusion-webui-images-browser/issues/116#issuecomment-1493259585" target="_blank">https://github.com/AlUlkesh/stable-diffusion-webui-images-browser/issues/116#issuecomment-1493259585</a></p>')
|
1630 |
+
else:
|
1631 |
+
with gr.Tabs(elem_id="image_browser_tabs_container") as tabs:
|
1632 |
+
js_dummy_return = gr.Textbox(interactive=False, visible=False)
|
1633 |
+
for i, tab in enumerate(tabs_list):
|
1634 |
+
with gr.Tab(tab.name, elem_id=f"{tab.base_tag}_image_browser_container") as current_gr_tab:
|
1635 |
+
with gr.Blocks(analytics_enabled=False):
|
1636 |
+
create_tab(tab, current_gr_tab)
|
1637 |
+
gr.Checkbox(value=opts.image_browser_preload, elem_id="image_browser_preload", visible=False)
|
1638 |
+
gr.Textbox(",".join( [tab.base_tag for tab in tabs_list] ), elem_id="image_browser_tab_base_tags_list", visible=False)
|
1639 |
+
gr.Checkbox(value=opts.image_browser_swipe, elem_id=f"image_browser_swipe", visible=False)
|
1640 |
+
|
1641 |
+
javascript_level_value, (javascript_level, javascript_level_text) = debug_levels(arg_level="javascript")
|
1642 |
+
level_value, (level, level_text) = debug_levels(arg_text=opts.image_browser_debug_level)
|
1643 |
+
if level_value >= javascript_level_value:
|
1644 |
+
debug_level_option = level
|
1645 |
+
else:
|
1646 |
+
debug_level_option = ""
|
1647 |
+
gr.Textbox(value=debug_level_option, elem_id="image_browser_debug_level_option", visible=False)
|
1648 |
+
|
1649 |
+
return (image_browser, "Image Browser", "image_browser"),
|
1650 |
+
|
1651 |
+
def move_setting(cur_setting_name, old_setting_name, option_info, section, added):
|
1652 |
+
try:
|
1653 |
+
old_value = shared.opts.__getattr__(old_setting_name)
|
1654 |
+
except AttributeError:
|
1655 |
+
old_value = None
|
1656 |
+
try:
|
1657 |
+
new_value = shared.opts.__getattr__(cur_setting_name)
|
1658 |
+
except AttributeError:
|
1659 |
+
new_value = None
|
1660 |
+
if old_value is not None and new_value is None:
|
1661 |
+
# Add new option
|
1662 |
+
shared.opts.add_option(cur_setting_name, shared.OptionInfo(*option_info, section=section))
|
1663 |
+
shared.opts.__setattr__(cur_setting_name, old_value)
|
1664 |
+
added = added + 1
|
1665 |
+
# Remove old option
|
1666 |
+
shared.opts.data.pop(old_setting_name, None)
|
1667 |
+
|
1668 |
+
return added
|
1669 |
+
|
1670 |
+
def on_ui_settings():
|
1671 |
+
# [current setting_name], [old setting_name], [default], [label], [component], [component_args]
|
1672 |
+
active_tabs_description = f"List of active tabs (separated by commas). Available options are {', '.join(default_tab_options)}. Custom folders are also supported by specifying their path."
|
1673 |
+
debug_level_choices = []
|
1674 |
+
for i in range(len(debug_level_types)):
|
1675 |
+
level_value, (level, level_text) = debug_levels(arg_value=i)
|
1676 |
+
debug_level_choices.append(level_text)
|
1677 |
+
|
1678 |
+
image_browser_options = [
|
1679 |
+
("image_browser_active_tabs", None, ", ".join(default_tab_options), active_tabs_description),
|
1680 |
+
("image_browser_hidden_components", None, [], "Select components to hide", DropdownMulti, lambda: {"choices": components_list}),
|
1681 |
+
("image_browser_with_subdirs", "images_history_with_subdirs", True, "Include images in sub directories"),
|
1682 |
+
("image_browser_preload", "images_history_preload", False, "Preload images at startup for first tab"),
|
1683 |
+
("image_browser_copy_image", "images_copy_image", False, "Move buttons copy instead of move"),
|
1684 |
+
("image_browser_delete_message", "images_delete_message", True, "Print image deletion messages to the console"),
|
1685 |
+
("image_browser_txt_files", "images_txt_files", True, "Move/Copy/Delete matching .txt files"),
|
1686 |
+
("image_browser_debug_level", None, debug_level_choices[0], "Debug level", gr.Dropdown, lambda: {"choices": debug_level_choices}),
|
1687 |
+
("image_browser_delete_recycle", "images_delete_recycle", True, "Use recycle bin when deleting images"),
|
1688 |
+
("image_browser_scan_exif", "images_scan_exif", True, "Scan Exif-/.txt-data (initially slower, but required for many features to work)"),
|
1689 |
+
("image_browser_mod_shift", None, False, "Change CTRL keybindings to SHIFT"),
|
1690 |
+
("image_browser_mod_ctrl_shift", None, False, "or to CTRL+SHIFT"),
|
1691 |
+
("image_browser_enable_maint", None, True, "Enable Maintenance tab"),
|
1692 |
+
("image_browser_ranking_pnginfo", None, False, "Save ranking in image's pnginfo"),
|
1693 |
+
("image_browser_page_columns", "images_history_page_columns", 6, "Number of columns on the page"),
|
1694 |
+
("image_browser_page_rows", "images_history_page_rows", 6, "Number of rows on the page"),
|
1695 |
+
("image_browser_pages_perload", "images_history_pages_perload", 20, "Minimum number of pages per load"),
|
1696 |
+
("image_browser_use_thumbnail", None, False, "Use optimized images in the thumbnail interface (significantly reduces the amount of data transferred)"),
|
1697 |
+
("image_browser_thumbnail_size", None, 200, "Size of the thumbnails (px)"),
|
1698 |
+
("image_browser_swipe", None, False, "Swipe left/right navigates to the next image"),
|
1699 |
+
("image_browser_img_tooltips", None, True, "Enable thumbnail tooltips"),
|
1700 |
+
("image_browser_scoring_type", None, "aesthetic_score", "Default scoring type", gr.Dropdown, lambda: {"choices": ["aesthetic_score", "ImageReward Score"]}),
|
1701 |
+
("image_browser_show_progress", None, True, "Show progress indicator"),
|
1702 |
+
]
|
1703 |
+
|
1704 |
+
section = ('image-browser', "Image Browser")
|
1705 |
+
# Move historic setting names to current names
|
1706 |
+
added = 0
|
1707 |
+
for cur_setting_name, old_setting_name, *option_info in image_browser_options:
|
1708 |
+
if old_setting_name is not None:
|
1709 |
+
added = move_setting(cur_setting_name, old_setting_name, option_info, section, added)
|
1710 |
+
if added > 0:
|
1711 |
+
shared.opts.save(shared.config_filename)
|
1712 |
+
|
1713 |
+
for cur_setting_name, _, *option_info in image_browser_options:
|
1714 |
+
shared.opts.add_option(cur_setting_name, shared.OptionInfo(*option_info, section=section))
|
1715 |
+
|
1716 |
+
script_callbacks.on_ui_settings(on_ui_settings)
|
1717 |
+
script_callbacks.on_ui_tabs(on_ui_tabs)
|
stable-diffusion-webui-images-browser/scripts/wib/__pycache__/wib_db.cpython-310.pyc
ADDED
Binary file (21.8 kB). View file
|
|
stable-diffusion-webui-images-browser/scripts/wib/wib_db.py
ADDED
@@ -0,0 +1,888 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import hashlib
|
2 |
+
import json
|
3 |
+
import os
|
4 |
+
import sqlite3
|
5 |
+
from modules import scripts
|
6 |
+
from PIL import Image
|
7 |
+
|
8 |
+
version = 6
|
9 |
+
|
10 |
+
path_recorder_file = os.path.join(scripts.basedir(), "path_recorder.txt")
|
11 |
+
aes_cache_file = os.path.join(scripts.basedir(), "aes_scores.json")
|
12 |
+
exif_cache_file = os.path.join(scripts.basedir(), "exif_data.json")
|
13 |
+
ranking_file = os.path.join(scripts.basedir(), "ranking.json")
|
14 |
+
archive = os.path.join(scripts.basedir(), "archive")
|
15 |
+
db_file = os.path.join(scripts.basedir(), "wib.sqlite3")
|
16 |
+
np = "Negative prompt: "
|
17 |
+
st = "Steps: "
|
18 |
+
timeout = 30
|
19 |
+
|
20 |
+
def create_filehash(cursor):
|
21 |
+
cursor.execute('''
|
22 |
+
CREATE TABLE IF NOT EXISTS filehash (
|
23 |
+
file TEXT PRIMARY KEY,
|
24 |
+
hash TEXT,
|
25 |
+
created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
26 |
+
updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
27 |
+
)
|
28 |
+
''')
|
29 |
+
|
30 |
+
cursor.execute('''
|
31 |
+
CREATE TRIGGER filehash_tr
|
32 |
+
AFTER UPDATE ON filehash
|
33 |
+
BEGIN
|
34 |
+
UPDATE filehash SET updated = CURRENT_TIMESTAMP WHERE file = OLD.file;
|
35 |
+
END;
|
36 |
+
''')
|
37 |
+
|
38 |
+
return
|
39 |
+
|
40 |
+
def create_work_files(cursor):
|
41 |
+
cursor.execute('''
|
42 |
+
CREATE TABLE IF NOT EXISTS work_files (
|
43 |
+
file TEXT PRIMARY KEY
|
44 |
+
)
|
45 |
+
''')
|
46 |
+
|
47 |
+
return
|
48 |
+
|
49 |
+
def create_db(cursor):
|
50 |
+
cursor.execute('''
|
51 |
+
CREATE TABLE IF NOT EXISTS db_data (
|
52 |
+
key TEXT PRIMARY KEY,
|
53 |
+
value TEXT
|
54 |
+
)
|
55 |
+
''')
|
56 |
+
|
57 |
+
cursor.execute('''
|
58 |
+
CREATE TABLE IF NOT EXISTS path_recorder (
|
59 |
+
path TEXT PRIMARY KEY,
|
60 |
+
depth INT,
|
61 |
+
path_display TEXT,
|
62 |
+
created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
63 |
+
updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
64 |
+
)
|
65 |
+
''')
|
66 |
+
|
67 |
+
cursor.execute('''
|
68 |
+
CREATE TRIGGER path_recorder_tr
|
69 |
+
AFTER UPDATE ON path_recorder
|
70 |
+
BEGIN
|
71 |
+
UPDATE path_recorder SET updated = CURRENT_TIMESTAMP WHERE path = OLD.path;
|
72 |
+
END;
|
73 |
+
''')
|
74 |
+
|
75 |
+
cursor.execute('''
|
76 |
+
CREATE TABLE IF NOT EXISTS exif_data (
|
77 |
+
file TEXT,
|
78 |
+
key TEXT,
|
79 |
+
value TEXT,
|
80 |
+
created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
81 |
+
updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
82 |
+
PRIMARY KEY (file, key)
|
83 |
+
)
|
84 |
+
''')
|
85 |
+
|
86 |
+
cursor.execute('''
|
87 |
+
CREATE INDEX IF NOT EXISTS exif_data_key ON exif_data (key)
|
88 |
+
''')
|
89 |
+
|
90 |
+
cursor.execute('''
|
91 |
+
CREATE TRIGGER exif_data_tr
|
92 |
+
AFTER UPDATE ON exif_data
|
93 |
+
BEGIN
|
94 |
+
UPDATE exif_data SET updated = CURRENT_TIMESTAMP WHERE file = OLD.file AND key = OLD.key;
|
95 |
+
END;
|
96 |
+
''')
|
97 |
+
|
98 |
+
cursor.execute('''
|
99 |
+
CREATE TABLE IF NOT EXISTS ranking (
|
100 |
+
file TEXT PRIMARY KEY,
|
101 |
+
name TEXT,
|
102 |
+
ranking TEXT,
|
103 |
+
created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
104 |
+
updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
105 |
+
)
|
106 |
+
''')
|
107 |
+
|
108 |
+
cursor.execute('''
|
109 |
+
CREATE INDEX IF NOT EXISTS ranking_name ON ranking (name)
|
110 |
+
''')
|
111 |
+
|
112 |
+
cursor.execute('''
|
113 |
+
CREATE TRIGGER ranking_tr
|
114 |
+
AFTER UPDATE ON ranking
|
115 |
+
BEGIN
|
116 |
+
UPDATE ranking SET updated = CURRENT_TIMESTAMP WHERE file = OLD.file;
|
117 |
+
END;
|
118 |
+
''')
|
119 |
+
|
120 |
+
create_filehash(cursor)
|
121 |
+
create_work_files(cursor)
|
122 |
+
|
123 |
+
return
|
124 |
+
|
125 |
+
def migrate_path_recorder(cursor):
|
126 |
+
if os.path.exists(path_recorder_file):
|
127 |
+
try:
|
128 |
+
with open(path_recorder_file) as f:
|
129 |
+
# json-version
|
130 |
+
path_recorder = json.load(f)
|
131 |
+
for path, values in path_recorder.items():
|
132 |
+
path = os.path.realpath(path)
|
133 |
+
depth = values["depth"]
|
134 |
+
path_display = f"{path} [{depth}]"
|
135 |
+
cursor.execute('''
|
136 |
+
INSERT INTO path_recorder (path, depth, path_display)
|
137 |
+
VALUES (?, ?, ?)
|
138 |
+
''', (path, depth, path_display))
|
139 |
+
except json.JSONDecodeError:
|
140 |
+
with open(path_recorder_file) as f:
|
141 |
+
# old txt-version
|
142 |
+
path = f.readline().rstrip("\n")
|
143 |
+
while len(path) > 0:
|
144 |
+
path = os.path.realpath(path)
|
145 |
+
cursor.execute('''
|
146 |
+
INSERT INTO path_recorder (path, depth, path_display)
|
147 |
+
VALUES (?, ?, ?)
|
148 |
+
''', (path, 0, f"{path} [0]"))
|
149 |
+
path = f.readline().rstrip("\n")
|
150 |
+
|
151 |
+
return
|
152 |
+
|
153 |
+
def update_exif_data(cursor, file, info):
|
154 |
+
prompt = "0"
|
155 |
+
negative_prompt = "0"
|
156 |
+
key_values = "0: 0"
|
157 |
+
if info != "0":
|
158 |
+
info_list = info.split("\n")
|
159 |
+
prompt = ""
|
160 |
+
negative_prompt = ""
|
161 |
+
key_values = ""
|
162 |
+
for info_item in info_list:
|
163 |
+
if info_item.startswith(st):
|
164 |
+
key_values = info_item
|
165 |
+
elif info_item.startswith(np):
|
166 |
+
negative_prompt = info_item.replace(np, "")
|
167 |
+
else:
|
168 |
+
if prompt == "":
|
169 |
+
prompt = info_item
|
170 |
+
else:
|
171 |
+
# multiline prompts
|
172 |
+
prompt = f"{prompt}\n{info_item}"
|
173 |
+
if key_values != "":
|
174 |
+
key_value_pairs = []
|
175 |
+
key_value = ""
|
176 |
+
quote_open = False
|
177 |
+
for char in key_values + ",":
|
178 |
+
key_value += char
|
179 |
+
if char == '"':
|
180 |
+
quote_open = not quote_open
|
181 |
+
if char == "," and not quote_open:
|
182 |
+
try:
|
183 |
+
k, v = key_value.strip(" ,").split(": ")
|
184 |
+
except ValueError:
|
185 |
+
k = key_value.strip(" ,").split(": ")[0]
|
186 |
+
v = ""
|
187 |
+
key_value_pairs.append((k, v))
|
188 |
+
key_value = ""
|
189 |
+
|
190 |
+
try:
|
191 |
+
cursor.execute('''
|
192 |
+
INSERT INTO exif_data (file, key, value)
|
193 |
+
VALUES (?, ?, ?)
|
194 |
+
''', (file, "prompt", prompt))
|
195 |
+
except sqlite3.IntegrityError:
|
196 |
+
# Duplicate, delete all "file" entries and try again
|
197 |
+
cursor.execute('''
|
198 |
+
DELETE FROM exif_data
|
199 |
+
WHERE file = ?
|
200 |
+
''', (file,))
|
201 |
+
|
202 |
+
cursor.execute('''
|
203 |
+
INSERT INTO exif_data (file, key, value)
|
204 |
+
VALUES (?, ?, ?)
|
205 |
+
''', (file, "prompt", prompt))
|
206 |
+
|
207 |
+
cursor.execute('''
|
208 |
+
INSERT INTO exif_data (file, key, value)
|
209 |
+
VALUES (?, ?, ?)
|
210 |
+
''', (file, "negative_prompt", negative_prompt))
|
211 |
+
|
212 |
+
for (key, value) in key_value_pairs:
|
213 |
+
try:
|
214 |
+
cursor.execute('''
|
215 |
+
INSERT INTO exif_data (file, key, value)
|
216 |
+
VALUES (?, ?, ?)
|
217 |
+
''', (file, key, value))
|
218 |
+
except sqlite3.IntegrityError:
|
219 |
+
pass
|
220 |
+
|
221 |
+
return
|
222 |
+
|
223 |
+
def migrate_exif_data(cursor):
|
224 |
+
if os.path.exists(exif_cache_file):
|
225 |
+
with open(exif_cache_file, 'r') as file:
|
226 |
+
exif_cache = json.load(file)
|
227 |
+
|
228 |
+
for file, info in exif_cache.items():
|
229 |
+
file = os.path.realpath(file)
|
230 |
+
update_exif_data(cursor, file, info)
|
231 |
+
|
232 |
+
return
|
233 |
+
|
234 |
+
def migrate_ranking(cursor):
|
235 |
+
if os.path.exists(ranking_file):
|
236 |
+
with open(ranking_file, 'r') as file:
|
237 |
+
ranking = json.load(file)
|
238 |
+
for file, info in ranking.items():
|
239 |
+
if info != "None":
|
240 |
+
file = os.path.realpath(file)
|
241 |
+
name = os.path.basename(file)
|
242 |
+
cursor.execute('''
|
243 |
+
INSERT INTO ranking (file, name, ranking)
|
244 |
+
VALUES (?, ?, ?)
|
245 |
+
''', (file, name, info))
|
246 |
+
|
247 |
+
return
|
248 |
+
|
249 |
+
def get_hash(file):
|
250 |
+
# Get filehash without exif info
|
251 |
+
try:
|
252 |
+
image = Image.open(file)
|
253 |
+
except Exception as e:
|
254 |
+
print(e)
|
255 |
+
|
256 |
+
hash = hashlib.sha512(image.tobytes()).hexdigest()
|
257 |
+
image.close()
|
258 |
+
|
259 |
+
return hash
|
260 |
+
|
261 |
+
def migrate_filehash(cursor, version):
|
262 |
+
if version <= "4":
|
263 |
+
create_filehash(cursor)
|
264 |
+
|
265 |
+
cursor.execute('''
|
266 |
+
SELECT file
|
267 |
+
FROM ranking
|
268 |
+
''')
|
269 |
+
for (file,) in cursor.fetchall():
|
270 |
+
if os.path.exists(file):
|
271 |
+
hash = get_hash(file)
|
272 |
+
cursor.execute('''
|
273 |
+
INSERT INTO filehash (file, hash)
|
274 |
+
VALUES (?, ?)
|
275 |
+
''', (file, hash))
|
276 |
+
|
277 |
+
return
|
278 |
+
|
279 |
+
def migrate_work_files(cursor):
|
280 |
+
create_work_files(cursor)
|
281 |
+
|
282 |
+
return
|
283 |
+
|
284 |
+
def update_db_data(cursor, key, value):
|
285 |
+
cursor.execute('''
|
286 |
+
INSERT OR REPLACE
|
287 |
+
INTO db_data (key, value)
|
288 |
+
VALUES (?, ?)
|
289 |
+
''', (key, value))
|
290 |
+
|
291 |
+
return
|
292 |
+
|
293 |
+
def get_version():
|
294 |
+
with sqlite3.connect(db_file, timeout=timeout) as conn:
|
295 |
+
cursor = conn.cursor()
|
296 |
+
cursor.execute('''
|
297 |
+
SELECT value
|
298 |
+
FROM db_data
|
299 |
+
WHERE key = 'version'
|
300 |
+
''',)
|
301 |
+
db_version = cursor.fetchone()
|
302 |
+
|
303 |
+
return db_version
|
304 |
+
|
305 |
+
def migrate_path_recorder_dirs(cursor):
|
306 |
+
cursor.execute('''
|
307 |
+
SELECT path, path_display
|
308 |
+
FROM path_recorder
|
309 |
+
''')
|
310 |
+
for (path, path_display) in cursor.fetchall():
|
311 |
+
real_path = os.path.realpath(path)
|
312 |
+
if path != real_path:
|
313 |
+
update_from = path
|
314 |
+
update_to = real_path
|
315 |
+
try:
|
316 |
+
cursor.execute('''
|
317 |
+
UPDATE path_recorder
|
318 |
+
SET path = ?,
|
319 |
+
path_display = ? || SUBSTR(path_display, LENGTH(?) + 1)
|
320 |
+
WHERE path = ?
|
321 |
+
''', (update_to, update_to, update_from, update_from))
|
322 |
+
except sqlite3.IntegrityError as e:
|
323 |
+
# these are double keys, because the same file can be in the db with different path notations
|
324 |
+
(e_msg,) = e.args
|
325 |
+
if e_msg.startswith("UNIQUE constraint"):
|
326 |
+
cursor.execute('''
|
327 |
+
DELETE FROM path_recorder
|
328 |
+
WHERE path = ?
|
329 |
+
''', (update_from,))
|
330 |
+
else:
|
331 |
+
raise
|
332 |
+
|
333 |
+
return
|
334 |
+
|
335 |
+
def migrate_exif_data_dirs(cursor):
|
336 |
+
cursor.execute('''
|
337 |
+
SELECT file
|
338 |
+
FROM exif_data
|
339 |
+
''')
|
340 |
+
for (filepath,) in cursor.fetchall():
|
341 |
+
(path, file) = os.path.split(filepath)
|
342 |
+
real_path = os.path.realpath(path)
|
343 |
+
if path != real_path:
|
344 |
+
update_from = filepath
|
345 |
+
update_to = os.path.join(real_path, file)
|
346 |
+
try:
|
347 |
+
cursor.execute('''
|
348 |
+
UPDATE exif_data
|
349 |
+
SET file = ?
|
350 |
+
WHERE file = ?
|
351 |
+
''', (update_to, update_from))
|
352 |
+
except sqlite3.IntegrityError as e:
|
353 |
+
# these are double keys, because the same file can be in the db with different path notations
|
354 |
+
(e_msg,) = e.args
|
355 |
+
if e_msg.startswith("UNIQUE constraint"):
|
356 |
+
cursor.execute('''
|
357 |
+
DELETE FROM exif_data
|
358 |
+
WHERE file = ?
|
359 |
+
''', (update_from,))
|
360 |
+
else:
|
361 |
+
raise
|
362 |
+
|
363 |
+
return
|
364 |
+
|
365 |
+
def migrate_ranking_dirs(cursor, db_version):
|
366 |
+
if db_version == "1":
|
367 |
+
cursor.execute('''
|
368 |
+
ALTER TABLE ranking
|
369 |
+
ADD COLUMN name TEXT
|
370 |
+
''')
|
371 |
+
|
372 |
+
cursor.execute('''
|
373 |
+
CREATE INDEX IF NOT EXISTS ranking_name ON ranking (name)
|
374 |
+
''')
|
375 |
+
|
376 |
+
cursor.execute('''
|
377 |
+
SELECT file, ranking
|
378 |
+
FROM ranking
|
379 |
+
''')
|
380 |
+
for (filepath, ranking) in cursor.fetchall():
|
381 |
+
if filepath == "" or ranking == "None":
|
382 |
+
cursor.execute('''
|
383 |
+
DELETE FROM ranking
|
384 |
+
WHERE file = ?
|
385 |
+
''', (filepath,))
|
386 |
+
else:
|
387 |
+
(path, file) = os.path.split(filepath)
|
388 |
+
real_path = os.path.realpath(path)
|
389 |
+
name = file
|
390 |
+
update_from = filepath
|
391 |
+
update_to = os.path.join(real_path, file)
|
392 |
+
try:
|
393 |
+
cursor.execute('''
|
394 |
+
UPDATE ranking
|
395 |
+
SET file = ?,
|
396 |
+
name = ?
|
397 |
+
WHERE file = ?
|
398 |
+
''', (update_to, name, update_from))
|
399 |
+
except sqlite3.IntegrityError as e:
|
400 |
+
# these are double keys, because the same file can be in the db with different path notations
|
401 |
+
(e_msg,) = e.args
|
402 |
+
if e_msg.startswith("UNIQUE constraint"):
|
403 |
+
cursor.execute('''
|
404 |
+
DELETE FROM ranking
|
405 |
+
WHERE file = ?
|
406 |
+
''', (update_from,))
|
407 |
+
else:
|
408 |
+
raise
|
409 |
+
|
410 |
+
return
|
411 |
+
|
412 |
+
def check():
|
413 |
+
if not os.path.exists(db_file):
|
414 |
+
conn, cursor = transaction_begin()
|
415 |
+
print("Image Browser: Creating database")
|
416 |
+
create_db(cursor)
|
417 |
+
update_db_data(cursor, "version", version)
|
418 |
+
migrate_path_recorder(cursor)
|
419 |
+
migrate_exif_data(cursor)
|
420 |
+
migrate_ranking(cursor)
|
421 |
+
migrate_filehash(cursor, str(version))
|
422 |
+
transaction_end(conn, cursor)
|
423 |
+
print("Image Browser: Database created")
|
424 |
+
db_version = get_version()
|
425 |
+
conn, cursor = transaction_begin()
|
426 |
+
if db_version[0] <= "2":
|
427 |
+
# version 1 database had mixed path notations, changed them all to abspath
|
428 |
+
# version 2 database still had mixed path notations, because of windows short name, changed them all to realpath
|
429 |
+
print(f"Image Browser: Upgrading database from version {db_version[0]} to version {version}")
|
430 |
+
migrate_path_recorder_dirs(cursor)
|
431 |
+
migrate_exif_data_dirs(cursor)
|
432 |
+
migrate_ranking_dirs(cursor, db_version[0])
|
433 |
+
if db_version[0] <= "4":
|
434 |
+
migrate_filehash(cursor, db_version[0])
|
435 |
+
if db_version[0] <= "5":
|
436 |
+
migrate_work_files(cursor)
|
437 |
+
update_db_data(cursor, "version", version)
|
438 |
+
print(f"Image Browser: Database upgraded from version {db_version[0]} to version {version}")
|
439 |
+
transaction_end(conn, cursor)
|
440 |
+
|
441 |
+
return version
|
442 |
+
|
443 |
+
def load_path_recorder():
|
444 |
+
with sqlite3.connect(db_file, timeout=timeout) as conn:
|
445 |
+
cursor = conn.cursor()
|
446 |
+
cursor.execute('''
|
447 |
+
SELECT path, depth, path_display
|
448 |
+
FROM path_recorder
|
449 |
+
''')
|
450 |
+
path_recorder = {path: {"depth": depth, "path_display": path_display} for path, depth, path_display in cursor.fetchall()}
|
451 |
+
|
452 |
+
return path_recorder
|
453 |
+
|
454 |
+
def select_ranking(file):
|
455 |
+
with sqlite3.connect(db_file, timeout=timeout) as conn:
|
456 |
+
cursor = conn.cursor()
|
457 |
+
cursor.execute('''
|
458 |
+
SELECT ranking
|
459 |
+
FROM ranking
|
460 |
+
WHERE file = ?
|
461 |
+
''', (file,))
|
462 |
+
ranking_value = cursor.fetchone()
|
463 |
+
|
464 |
+
if ranking_value is None:
|
465 |
+
return_ranking = "None"
|
466 |
+
else:
|
467 |
+
(return_ranking,) = ranking_value
|
468 |
+
|
469 |
+
return return_ranking
|
470 |
+
|
471 |
+
def update_ranking(file, ranking):
|
472 |
+
name = os.path.basename(file)
|
473 |
+
with sqlite3.connect(db_file, timeout=timeout) as conn:
|
474 |
+
cursor = conn.cursor()
|
475 |
+
if ranking == "None":
|
476 |
+
cursor.execute('''
|
477 |
+
DELETE FROM ranking
|
478 |
+
WHERE file = ?
|
479 |
+
''', (file,))
|
480 |
+
else:
|
481 |
+
cursor.execute('''
|
482 |
+
INSERT OR REPLACE
|
483 |
+
INTO ranking (file, name, ranking)
|
484 |
+
VALUES (?, ?, ?)
|
485 |
+
''', (file, name, ranking))
|
486 |
+
|
487 |
+
hash = get_hash(file)
|
488 |
+
cursor.execute('''
|
489 |
+
INSERT OR REPLACE
|
490 |
+
INTO filehash (file, hash)
|
491 |
+
VALUES (?, ?)
|
492 |
+
''', (file, hash))
|
493 |
+
|
494 |
+
return
|
495 |
+
|
496 |
+
def select_image_reward_score(cursor, file):
|
497 |
+
cursor.execute('''
|
498 |
+
SELECT value
|
499 |
+
FROM exif_data
|
500 |
+
WHERE file = ?
|
501 |
+
AND key = 'ImageRewardScore'
|
502 |
+
''', (file,))
|
503 |
+
image_reward_score = cursor.fetchone()
|
504 |
+
if image_reward_score is None:
|
505 |
+
return_image_reward_score = None
|
506 |
+
else:
|
507 |
+
(return_image_reward_score,) = image_reward_score
|
508 |
+
cursor.execute('''
|
509 |
+
SELECT value
|
510 |
+
FROM exif_data
|
511 |
+
WHERE file = ?
|
512 |
+
AND key = 'prompt'
|
513 |
+
''', (file,))
|
514 |
+
image_reward_prompt = cursor.fetchone()
|
515 |
+
if image_reward_prompt is None:
|
516 |
+
return_image_reward_prompt = None
|
517 |
+
else:
|
518 |
+
(return_image_reward_prompt,) = image_reward_prompt
|
519 |
+
|
520 |
+
return return_image_reward_score, return_image_reward_prompt
|
521 |
+
|
522 |
+
def update_image_reward_score(cursor, file, image_reward_score):
|
523 |
+
cursor.execute('''
|
524 |
+
INSERT OR REPLACE
|
525 |
+
INTO exif_data (file, key, value)
|
526 |
+
VALUES (?, ?, ?)
|
527 |
+
''', (file, "ImageRewardScore", image_reward_score))
|
528 |
+
|
529 |
+
return
|
530 |
+
|
531 |
+
def update_path_recorder(path, depth, path_display):
|
532 |
+
with sqlite3.connect(db_file, timeout=timeout) as conn:
|
533 |
+
cursor = conn.cursor()
|
534 |
+
cursor.execute('''
|
535 |
+
INSERT OR REPLACE
|
536 |
+
INTO path_recorder (path, depth, path_display)
|
537 |
+
VALUES (?, ?, ?)
|
538 |
+
''', (path, depth, path_display))
|
539 |
+
|
540 |
+
return
|
541 |
+
|
542 |
+
def update_path_recorder(path, depth, path_display):
|
543 |
+
with sqlite3.connect(db_file, timeout=timeout) as conn:
|
544 |
+
cursor = conn.cursor()
|
545 |
+
cursor.execute('''
|
546 |
+
INSERT OR REPLACE
|
547 |
+
INTO path_recorder (path, depth, path_display)
|
548 |
+
VALUES (?, ?, ?)
|
549 |
+
''', (path, depth, path_display))
|
550 |
+
|
551 |
+
return
|
552 |
+
|
553 |
+
def delete_path_recorder(path):
|
554 |
+
with sqlite3.connect(db_file, timeout=timeout) as conn:
|
555 |
+
cursor = conn.cursor()
|
556 |
+
cursor.execute('''
|
557 |
+
DELETE FROM path_recorder
|
558 |
+
WHERE path = ?
|
559 |
+
''', (path,))
|
560 |
+
|
561 |
+
return
|
562 |
+
|
563 |
+
def update_path_recorder_mult(cursor, update_from, update_to):
|
564 |
+
cursor.execute('''
|
565 |
+
UPDATE path_recorder
|
566 |
+
SET path = ?,
|
567 |
+
path_display = ? || SUBSTR(path_display, LENGTH(?) + 1)
|
568 |
+
WHERE path = ?
|
569 |
+
''', (update_to, update_to, update_from, update_from))
|
570 |
+
|
571 |
+
return
|
572 |
+
|
573 |
+
def update_exif_data_mult(cursor, update_from, update_to):
|
574 |
+
update_from = update_from + os.path.sep
|
575 |
+
update_to = update_to + os.path.sep
|
576 |
+
cursor.execute('''
|
577 |
+
UPDATE exif_data
|
578 |
+
SET file = ? || SUBSTR(file, LENGTH(?) + 1)
|
579 |
+
WHERE file like ? || '%'
|
580 |
+
''', (update_to, update_from, update_from))
|
581 |
+
|
582 |
+
return
|
583 |
+
|
584 |
+
def update_ranking_mult(cursor, update_from, update_to):
|
585 |
+
update_from = update_from + os.path.sep
|
586 |
+
update_to = update_to + os.path.sep
|
587 |
+
cursor.execute('''
|
588 |
+
UPDATE ranking
|
589 |
+
SET file = ? || SUBSTR(file, LENGTH(?) + 1)
|
590 |
+
WHERE file like ? || '%'
|
591 |
+
''', (update_to, update_from, update_from))
|
592 |
+
|
593 |
+
return
|
594 |
+
|
595 |
+
def delete_exif_0(cursor):
|
596 |
+
cursor.execute('''
|
597 |
+
DELETE FROM exif_data
|
598 |
+
WHERE file IN (
|
599 |
+
SELECT file FROM exif_data a
|
600 |
+
WHERE value = '0'
|
601 |
+
GROUP BY file
|
602 |
+
HAVING COUNT(*) = (SELECT COUNT(*) FROM exif_data WHERE file = a.file)
|
603 |
+
)
|
604 |
+
''')
|
605 |
+
|
606 |
+
return
|
607 |
+
|
608 |
+
def get_ranking_by_file(cursor, file):
|
609 |
+
cursor.execute('''
|
610 |
+
SELECT ranking
|
611 |
+
FROM ranking
|
612 |
+
WHERE file = ?
|
613 |
+
''', (file,))
|
614 |
+
ranking_value = cursor.fetchone()
|
615 |
+
|
616 |
+
return ranking_value
|
617 |
+
|
618 |
+
def get_ranking_by_name(cursor, name):
|
619 |
+
cursor.execute('''
|
620 |
+
SELECT file, ranking
|
621 |
+
FROM ranking
|
622 |
+
WHERE name = ?
|
623 |
+
''', (name,))
|
624 |
+
ranking_value = cursor.fetchone()
|
625 |
+
|
626 |
+
if ranking_value is not None:
|
627 |
+
(file, _) = ranking_value
|
628 |
+
cursor.execute('''
|
629 |
+
SELECT hash
|
630 |
+
FROM filehash
|
631 |
+
WHERE file = ?
|
632 |
+
''', (file,))
|
633 |
+
hash_value = cursor.fetchone()
|
634 |
+
else:
|
635 |
+
hash_value = None
|
636 |
+
|
637 |
+
return ranking_value, hash_value
|
638 |
+
|
639 |
+
def insert_ranking(cursor, file, ranking, hash):
|
640 |
+
name = os.path.basename(file)
|
641 |
+
cursor.execute('''
|
642 |
+
INSERT INTO ranking (file, name, ranking)
|
643 |
+
VALUES (?, ?, ?)
|
644 |
+
''', (file, name, ranking))
|
645 |
+
|
646 |
+
cursor.execute('''
|
647 |
+
INSERT OR REPLACE
|
648 |
+
INTO filehash (file, hash)
|
649 |
+
VALUES (?, ?)
|
650 |
+
''', (file, hash))
|
651 |
+
|
652 |
+
return
|
653 |
+
|
654 |
+
def replace_ranking(cursor, file, alternate_file, hash):
|
655 |
+
name = os.path.basename(file)
|
656 |
+
cursor.execute('''
|
657 |
+
UPDATE ranking
|
658 |
+
SET file = ?
|
659 |
+
WHERE file = ?
|
660 |
+
''', (file, alternate_file))
|
661 |
+
|
662 |
+
cursor.execute('''
|
663 |
+
INSERT OR REPLACE
|
664 |
+
INTO filehash (file, hash)
|
665 |
+
VALUES (?, ?)
|
666 |
+
''', (file, hash))
|
667 |
+
|
668 |
+
return
|
669 |
+
|
670 |
+
def transaction_begin():
|
671 |
+
conn = sqlite3.connect(db_file, timeout=timeout)
|
672 |
+
conn.isolation_level = None
|
673 |
+
cursor = conn.cursor()
|
674 |
+
cursor.execute("BEGIN")
|
675 |
+
return conn, cursor
|
676 |
+
|
677 |
+
def transaction_end(conn, cursor):
|
678 |
+
cursor.execute("COMMIT")
|
679 |
+
conn.close()
|
680 |
+
return
|
681 |
+
|
682 |
+
def update_exif_data_by_key(cursor, file, key, value):
|
683 |
+
cursor.execute('''
|
684 |
+
INSERT OR REPLACE
|
685 |
+
INTO exif_data (file, key, value)
|
686 |
+
VALUES (?, ?, ?)
|
687 |
+
''', (file, key, value))
|
688 |
+
|
689 |
+
return
|
690 |
+
|
691 |
+
def select_prompts(file):
|
692 |
+
with sqlite3.connect(db_file, timeout=timeout) as conn:
|
693 |
+
cursor = conn.cursor()
|
694 |
+
cursor.execute('''
|
695 |
+
SELECT key, value
|
696 |
+
FROM exif_data
|
697 |
+
WHERE file = ?
|
698 |
+
AND KEY in ('prompt', 'negative_prompt')
|
699 |
+
''', (file,))
|
700 |
+
|
701 |
+
rows = cursor.fetchall()
|
702 |
+
prompt = ""
|
703 |
+
neg_prompt = ""
|
704 |
+
for row in rows:
|
705 |
+
(key, value) = row
|
706 |
+
if key == 'prompt':
|
707 |
+
prompt = value
|
708 |
+
elif key == 'negative_prompt':
|
709 |
+
neg_prompt = value
|
710 |
+
|
711 |
+
return prompt, neg_prompt
|
712 |
+
|
713 |
+
def load_exif_data(exif_cache):
|
714 |
+
with sqlite3.connect(db_file, timeout=timeout) as conn:
|
715 |
+
cursor = conn.cursor()
|
716 |
+
cursor.execute('''
|
717 |
+
SELECT file, group_concat(
|
718 |
+
case when key = 'prompt' or key = 'negative_prompt' then key || ': ' || value || '\n'
|
719 |
+
else key || ': ' || value
|
720 |
+
end, ', ') AS string
|
721 |
+
FROM (
|
722 |
+
SELECT *
|
723 |
+
FROM exif_data
|
724 |
+
ORDER BY
|
725 |
+
CASE WHEN key = 'prompt' THEN 0
|
726 |
+
WHEN key = 'negative_prompt' THEN 1
|
727 |
+
ELSE 2 END,
|
728 |
+
key
|
729 |
+
)
|
730 |
+
GROUP BY file
|
731 |
+
''')
|
732 |
+
|
733 |
+
rows = cursor.fetchall()
|
734 |
+
for row in rows:
|
735 |
+
exif_cache[row[0]] = row[1]
|
736 |
+
|
737 |
+
return exif_cache
|
738 |
+
|
739 |
+
def load_exif_data_by_key(cache, key1, key2):
|
740 |
+
with sqlite3.connect(db_file, timeout=timeout) as conn:
|
741 |
+
cursor = conn.cursor()
|
742 |
+
cursor.execute('''
|
743 |
+
SELECT file, value
|
744 |
+
FROM exif_data
|
745 |
+
WHERE key IN (?, ?)
|
746 |
+
''', (key1, key2))
|
747 |
+
|
748 |
+
rows = cursor.fetchall()
|
749 |
+
for row in rows:
|
750 |
+
cache[row[0]] = row[1]
|
751 |
+
|
752 |
+
return cache
|
753 |
+
|
754 |
+
def get_exif_dirs():
|
755 |
+
with sqlite3.connect(db_file, timeout=timeout) as conn:
|
756 |
+
cursor = conn.cursor()
|
757 |
+
cursor.execute('''
|
758 |
+
SELECT file
|
759 |
+
FROM exif_data
|
760 |
+
''')
|
761 |
+
|
762 |
+
rows = cursor.fetchall()
|
763 |
+
|
764 |
+
dirs = {}
|
765 |
+
for row in rows:
|
766 |
+
dir = os.path.dirname(row[0])
|
767 |
+
dirs[dir] = dir
|
768 |
+
|
769 |
+
return dirs
|
770 |
+
|
771 |
+
def fill_work_files(cursor, fileinfos):
|
772 |
+
filenames = [x[0] for x in fileinfos]
|
773 |
+
|
774 |
+
cursor.execute('''
|
775 |
+
DELETE
|
776 |
+
FROM work_files
|
777 |
+
''')
|
778 |
+
|
779 |
+
sql = '''
|
780 |
+
INSERT INTO work_files (file)
|
781 |
+
VALUES (?)
|
782 |
+
'''
|
783 |
+
|
784 |
+
cursor.executemany(sql, [(x,) for x in filenames])
|
785 |
+
|
786 |
+
return
|
787 |
+
|
788 |
+
def filter_aes(cursor, fileinfos, aes_filter_min_num, aes_filter_max_num, score_type):
|
789 |
+
if score_type == "aesthetic_score":
|
790 |
+
key = "aesthetic_score"
|
791 |
+
else:
|
792 |
+
key = "ImageRewardScore"
|
793 |
+
|
794 |
+
cursor.execute('''
|
795 |
+
DELETE
|
796 |
+
FROM work_files
|
797 |
+
WHERE file not in (
|
798 |
+
SELECT file
|
799 |
+
FROM exif_data b
|
800 |
+
WHERE file = b.file
|
801 |
+
AND b.key = ?
|
802 |
+
AND CAST(b.value AS REAL) between ? and ?
|
803 |
+
)
|
804 |
+
''', (key, aes_filter_min_num, aes_filter_max_num))
|
805 |
+
|
806 |
+
cursor.execute('''
|
807 |
+
SELECT file
|
808 |
+
FROM work_files
|
809 |
+
''')
|
810 |
+
|
811 |
+
rows = cursor.fetchall()
|
812 |
+
|
813 |
+
fileinfos_dict = {pair[0]: pair[1] for pair in fileinfos}
|
814 |
+
fileinfos_new = []
|
815 |
+
for (file,) in rows:
|
816 |
+
if fileinfos_dict.get(file) is not None:
|
817 |
+
fileinfos_new.append((file, fileinfos_dict[file]))
|
818 |
+
|
819 |
+
return fileinfos_new
|
820 |
+
|
821 |
+
def filter_ranking(cursor, fileinfos, ranking_filter, ranking_filter_min_num, ranking_filter_max_num):
|
822 |
+
if ranking_filter == "None":
|
823 |
+
cursor.execute('''
|
824 |
+
DELETE
|
825 |
+
FROM work_files
|
826 |
+
WHERE file IN (
|
827 |
+
SELECT file
|
828 |
+
FROM ranking b
|
829 |
+
WHERE file = b.file
|
830 |
+
)
|
831 |
+
''')
|
832 |
+
elif ranking_filter == "Min-max":
|
833 |
+
cursor.execute('''
|
834 |
+
DELETE
|
835 |
+
FROM work_files
|
836 |
+
WHERE file NOT IN (
|
837 |
+
SELECT file
|
838 |
+
FROM ranking b
|
839 |
+
WHERE file = b.file
|
840 |
+
AND b.ranking BETWEEN ? AND ?
|
841 |
+
)
|
842 |
+
''', (ranking_filter_min_num, ranking_filter_max_num))
|
843 |
+
else:
|
844 |
+
cursor.execute('''
|
845 |
+
DELETE
|
846 |
+
FROM work_files
|
847 |
+
WHERE file NOT IN (
|
848 |
+
SELECT file
|
849 |
+
FROM ranking b
|
850 |
+
WHERE file = b.file
|
851 |
+
AND b.ranking = ?
|
852 |
+
)
|
853 |
+
''', (ranking_filter,))
|
854 |
+
|
855 |
+
cursor.execute('''
|
856 |
+
SELECT file
|
857 |
+
FROM work_files
|
858 |
+
''')
|
859 |
+
|
860 |
+
rows = cursor.fetchall()
|
861 |
+
|
862 |
+
fileinfos_dict = {pair[0]: pair[1] for pair in fileinfos}
|
863 |
+
fileinfos_new = []
|
864 |
+
for (file,) in rows:
|
865 |
+
if fileinfos_dict.get(file) is not None:
|
866 |
+
fileinfos_new.append((file, fileinfos_dict[file]))
|
867 |
+
|
868 |
+
return fileinfos_new
|
869 |
+
|
870 |
+
def select_x_y(cursor, file):
|
871 |
+
cursor.execute('''
|
872 |
+
SELECT value
|
873 |
+
FROM exif_data
|
874 |
+
WHERE file = ?
|
875 |
+
AND key = 'Size'
|
876 |
+
''', (file,))
|
877 |
+
size_value = cursor.fetchone()
|
878 |
+
|
879 |
+
if size_value is None:
|
880 |
+
x = "?"
|
881 |
+
y = "?"
|
882 |
+
else:
|
883 |
+
(size,) = size_value
|
884 |
+
parts = size.split("x")
|
885 |
+
x = parts[0]
|
886 |
+
y = parts[1]
|
887 |
+
|
888 |
+
return x, y
|
stable-diffusion-webui-images-browser/style.css
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
.thumbnails.svelte-1tkea93.svelte-1tkea93 {
|
2 |
+
justify-content: initial;
|
3 |
+
}
|
4 |
+
|
5 |
+
.thumbnails.scroll-hide.svelte-g4rw9 {
|
6 |
+
justify-content: initial;
|
7 |
+
}
|
8 |
+
|
9 |
+
div[id^="image_browser_tab"][id$="image_browser_gallery"].hide_loading > .svelte-gjihhp {
|
10 |
+
display: none;
|
11 |
+
}
|
12 |
+
|
13 |
+
.image_browser_gallery img {
|
14 |
+
object-fit: scale-down !important;
|
15 |
+
}
|
16 |
+
|
17 |
+
/* Workaround until gradio version is updated to a version that fixes it
|
18 |
+
see https://github.com/gradio-app/gradio/issues/1590
|
19 |
+
*/
|
20 |
+
#tab_image_browser .thumbnail-item > img {
|
21 |
+
width: auto !important;
|
22 |
+
height: auto !important;
|
23 |
+
}
|
stable-diffusion-webui-images-browser/wib.sqlite3
ADDED
Binary file (61.4 kB). View file
|
|
ultimate-upscale-for-automatic1111/.gitignore
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
.vscode
|
ultimate-upscale-for-automatic1111/LICENSE
ADDED
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 29 June 2007
|
3 |
+
|
4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
6 |
+
of this license document, but changing it is not allowed.
|
7 |
+
|
8 |
+
Preamble
|
9 |
+
|
10 |
+
The GNU General Public License is a free, copyleft license for
|
11 |
+
software and other kinds of works.
|
12 |
+
|
13 |
+
The licenses for most software and other practical works are designed
|
14 |
+
to take away your freedom to share and change the works. By contrast,
|
15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
16 |
+
share and change all versions of a program--to make sure it remains free
|
17 |
+
software for all its users. We, the Free Software Foundation, use the
|
18 |
+
GNU General Public License for most of our software; it applies also to
|
19 |
+
any other work released this way by its authors. You can apply it to
|
20 |
+
your programs, too.
|
21 |
+
|
22 |
+
When we speak of free software, we are referring to freedom, not
|
23 |
+
price. Our General Public Licenses are designed to make sure that you
|
24 |
+
have the freedom to distribute copies of free software (and charge for
|
25 |
+
them if you wish), that you receive source code or can get it if you
|
26 |
+
want it, that you can change the software or use pieces of it in new
|
27 |
+
free programs, and that you know you can do these things.
|
28 |
+
|
29 |
+
To protect your rights, we need to prevent others from denying you
|
30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
31 |
+
certain responsibilities if you distribute copies of the software, or if
|
32 |
+
you modify it: responsibilities to respect the freedom of others.
|
33 |
+
|
34 |
+
For example, if you distribute copies of such a program, whether
|
35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
36 |
+
freedoms that you received. You must make sure that they, too, receive
|
37 |
+
or can get the source code. And you must show them these terms so they
|
38 |
+
know their rights.
|
39 |
+
|
40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
43 |
+
|
44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
45 |
+
that there is no warranty for this free software. For both users' and
|
46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
47 |
+
changed, so that their problems will not be attributed erroneously to
|
48 |
+
authors of previous versions.
|
49 |
+
|
50 |
+
Some devices are designed to deny users access to install or run
|
51 |
+
modified versions of the software inside them, although the manufacturer
|
52 |
+
can do so. This is fundamentally incompatible with the aim of
|
53 |
+
protecting users' freedom to change the software. The systematic
|
54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
56 |
+
have designed this version of the GPL to prohibit the practice for those
|
57 |
+
products. If such problems arise substantially in other domains, we
|
58 |
+
stand ready to extend this provision to those domains in future versions
|
59 |
+
of the GPL, as needed to protect the freedom of users.
|
60 |
+
|
61 |
+
Finally, every program is threatened constantly by software patents.
|
62 |
+
States should not allow patents to restrict development and use of
|
63 |
+
software on general-purpose computers, but in those that do, we wish to
|
64 |
+
avoid the special danger that patents applied to a free program could
|
65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
66 |
+
patents cannot be used to render the program non-free.
|
67 |
+
|
68 |
+
The precise terms and conditions for copying, distribution and
|
69 |
+
modification follow.
|
70 |
+
|
71 |
+
TERMS AND CONDITIONS
|
72 |
+
|
73 |
+
0. Definitions.
|
74 |
+
|
75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
76 |
+
|
77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
78 |
+
works, such as semiconductor masks.
|
79 |
+
|
80 |
+
"The Program" refers to any copyrightable work licensed under this
|
81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
82 |
+
"recipients" may be individuals or organizations.
|
83 |
+
|
84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
85 |
+
in a fashion requiring copyright permission, other than the making of an
|
86 |
+
exact copy. The resulting work is called a "modified version" of the
|
87 |
+
earlier work or a work "based on" the earlier work.
|
88 |
+
|
89 |
+
A "covered work" means either the unmodified Program or a work based
|
90 |
+
on the Program.
|
91 |
+
|
92 |
+
To "propagate" a work means to do anything with it that, without
|
93 |
+
permission, would make you directly or secondarily liable for
|
94 |
+
infringement under applicable copyright law, except executing it on a
|
95 |
+
computer or modifying a private copy. Propagation includes copying,
|
96 |
+
distribution (with or without modification), making available to the
|
97 |
+
public, and in some countries other activities as well.
|
98 |
+
|
99 |
+
To "convey" a work means any kind of propagation that enables other
|
100 |
+
parties to make or receive copies. Mere interaction with a user through
|
101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
102 |
+
|
103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
104 |
+
to the extent that it includes a convenient and prominently visible
|
105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
106 |
+
tells the user that there is no warranty for the work (except to the
|
107 |
+
extent that warranties are provided), that licensees may convey the
|
108 |
+
work under this License, and how to view a copy of this License. If
|
109 |
+
the interface presents a list of user commands or options, such as a
|
110 |
+
menu, a prominent item in the list meets this criterion.
|
111 |
+
|
112 |
+
1. Source Code.
|
113 |
+
|
114 |
+
The "source code" for a work means the preferred form of the work
|
115 |
+
for making modifications to it. "Object code" means any non-source
|
116 |
+
form of a work.
|
117 |
+
|
118 |
+
A "Standard Interface" means an interface that either is an official
|
119 |
+
standard defined by a recognized standards body, or, in the case of
|
120 |
+
interfaces specified for a particular programming language, one that
|
121 |
+
is widely used among developers working in that language.
|
122 |
+
|
123 |
+
The "System Libraries" of an executable work include anything, other
|
124 |
+
than the work as a whole, that (a) is included in the normal form of
|
125 |
+
packaging a Major Component, but which is not part of that Major
|
126 |
+
Component, and (b) serves only to enable use of the work with that
|
127 |
+
Major Component, or to implement a Standard Interface for which an
|
128 |
+
implementation is available to the public in source code form. A
|
129 |
+
"Major Component", in this context, means a major essential component
|
130 |
+
(kernel, window system, and so on) of the specific operating system
|
131 |
+
(if any) on which the executable work runs, or a compiler used to
|
132 |
+
produce the work, or an object code interpreter used to run it.
|
133 |
+
|
134 |
+
The "Corresponding Source" for a work in object code form means all
|
135 |
+
the source code needed to generate, install, and (for an executable
|
136 |
+
work) run the object code and to modify the work, including scripts to
|
137 |
+
control those activities. However, it does not include the work's
|
138 |
+
System Libraries, or general-purpose tools or generally available free
|
139 |
+
programs which are used unmodified in performing those activities but
|
140 |
+
which are not part of the work. For example, Corresponding Source
|
141 |
+
includes interface definition files associated with source files for
|
142 |
+
the work, and the source code for shared libraries and dynamically
|
143 |
+
linked subprograms that the work is specifically designed to require,
|
144 |
+
such as by intimate data communication or control flow between those
|
145 |
+
subprograms and other parts of the work.
|
146 |
+
|
147 |
+
The Corresponding Source need not include anything that users
|
148 |
+
can regenerate automatically from other parts of the Corresponding
|
149 |
+
Source.
|
150 |
+
|
151 |
+
The Corresponding Source for a work in source code form is that
|
152 |
+
same work.
|
153 |
+
|
154 |
+
2. Basic Permissions.
|
155 |
+
|
156 |
+
All rights granted under this License are granted for the term of
|
157 |
+
copyright on the Program, and are irrevocable provided the stated
|
158 |
+
conditions are met. This License explicitly affirms your unlimited
|
159 |
+
permission to run the unmodified Program. The output from running a
|
160 |
+
covered work is covered by this License only if the output, given its
|
161 |
+
content, constitutes a covered work. This License acknowledges your
|
162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
163 |
+
|
164 |
+
You may make, run and propagate covered works that you do not
|
165 |
+
convey, without conditions so long as your license otherwise remains
|
166 |
+
in force. You may convey covered works to others for the sole purpose
|
167 |
+
of having them make modifications exclusively for you, or provide you
|
168 |
+
with facilities for running those works, provided that you comply with
|
169 |
+
the terms of this License in conveying all material for which you do
|
170 |
+
not control copyright. Those thus making or running the covered works
|
171 |
+
for you must do so exclusively on your behalf, under your direction
|
172 |
+
and control, on terms that prohibit them from making any copies of
|
173 |
+
your copyrighted material outside their relationship with you.
|
174 |
+
|
175 |
+
Conveying under any other circumstances is permitted solely under
|
176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
177 |
+
makes it unnecessary.
|
178 |
+
|
179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
180 |
+
|
181 |
+
No covered work shall be deemed part of an effective technological
|
182 |
+
measure under any applicable law fulfilling obligations under article
|
183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
184 |
+
similar laws prohibiting or restricting circumvention of such
|
185 |
+
measures.
|
186 |
+
|
187 |
+
When you convey a covered work, you waive any legal power to forbid
|
188 |
+
circumvention of technological measures to the extent such circumvention
|
189 |
+
is effected by exercising rights under this License with respect to
|
190 |
+
the covered work, and you disclaim any intention to limit operation or
|
191 |
+
modification of the work as a means of enforcing, against the work's
|
192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
193 |
+
technological measures.
|
194 |
+
|
195 |
+
4. Conveying Verbatim Copies.
|
196 |
+
|
197 |
+
You may convey verbatim copies of the Program's source code as you
|
198 |
+
receive it, in any medium, provided that you conspicuously and
|
199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
200 |
+
keep intact all notices stating that this License and any
|
201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
202 |
+
keep intact all notices of the absence of any warranty; and give all
|
203 |
+
recipients a copy of this License along with the Program.
|
204 |
+
|
205 |
+
You may charge any price or no price for each copy that you convey,
|
206 |
+
and you may offer support or warranty protection for a fee.
|
207 |
+
|
208 |
+
5. Conveying Modified Source Versions.
|
209 |
+
|
210 |
+
You may convey a work based on the Program, or the modifications to
|
211 |
+
produce it from the Program, in the form of source code under the
|
212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
213 |
+
|
214 |
+
a) The work must carry prominent notices stating that you modified
|
215 |
+
it, and giving a relevant date.
|
216 |
+
|
217 |
+
b) The work must carry prominent notices stating that it is
|
218 |
+
released under this License and any conditions added under section
|
219 |
+
7. This requirement modifies the requirement in section 4 to
|
220 |
+
"keep intact all notices".
|
221 |
+
|
222 |
+
c) You must license the entire work, as a whole, under this
|
223 |
+
License to anyone who comes into possession of a copy. This
|
224 |
+
License will therefore apply, along with any applicable section 7
|
225 |
+
additional terms, to the whole of the work, and all its parts,
|
226 |
+
regardless of how they are packaged. This License gives no
|
227 |
+
permission to license the work in any other way, but it does not
|
228 |
+
invalidate such permission if you have separately received it.
|
229 |
+
|
230 |
+
d) If the work has interactive user interfaces, each must display
|
231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
233 |
+
work need not make them do so.
|
234 |
+
|
235 |
+
A compilation of a covered work with other separate and independent
|
236 |
+
works, which are not by their nature extensions of the covered work,
|
237 |
+
and which are not combined with it such as to form a larger program,
|
238 |
+
in or on a volume of a storage or distribution medium, is called an
|
239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
240 |
+
used to limit the access or legal rights of the compilation's users
|
241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
242 |
+
in an aggregate does not cause this License to apply to the other
|
243 |
+
parts of the aggregate.
|
244 |
+
|
245 |
+
6. Conveying Non-Source Forms.
|
246 |
+
|
247 |
+
You may convey a covered work in object code form under the terms
|
248 |
+
of sections 4 and 5, provided that you also convey the
|
249 |
+
machine-readable Corresponding Source under the terms of this License,
|
250 |
+
in one of these ways:
|
251 |
+
|
252 |
+
a) Convey the object code in, or embodied in, a physical product
|
253 |
+
(including a physical distribution medium), accompanied by the
|
254 |
+
Corresponding Source fixed on a durable physical medium
|
255 |
+
customarily used for software interchange.
|
256 |
+
|
257 |
+
b) Convey the object code in, or embodied in, a physical product
|
258 |
+
(including a physical distribution medium), accompanied by a
|
259 |
+
written offer, valid for at least three years and valid for as
|
260 |
+
long as you offer spare parts or customer support for that product
|
261 |
+
model, to give anyone who possesses the object code either (1) a
|
262 |
+
copy of the Corresponding Source for all the software in the
|
263 |
+
product that is covered by this License, on a durable physical
|
264 |
+
medium customarily used for software interchange, for a price no
|
265 |
+
more than your reasonable cost of physically performing this
|
266 |
+
conveying of source, or (2) access to copy the
|
267 |
+
Corresponding Source from a network server at no charge.
|
268 |
+
|
269 |
+
c) Convey individual copies of the object code with a copy of the
|
270 |
+
written offer to provide the Corresponding Source. This
|
271 |
+
alternative is allowed only occasionally and noncommercially, and
|
272 |
+
only if you received the object code with such an offer, in accord
|
273 |
+
with subsection 6b.
|
274 |
+
|
275 |
+
d) Convey the object code by offering access from a designated
|
276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
277 |
+
Corresponding Source in the same way through the same place at no
|
278 |
+
further charge. You need not require recipients to copy the
|
279 |
+
Corresponding Source along with the object code. If the place to
|
280 |
+
copy the object code is a network server, the Corresponding Source
|
281 |
+
may be on a different server (operated by you or a third party)
|
282 |
+
that supports equivalent copying facilities, provided you maintain
|
283 |
+
clear directions next to the object code saying where to find the
|
284 |
+
Corresponding Source. Regardless of what server hosts the
|
285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
286 |
+
available for as long as needed to satisfy these requirements.
|
287 |
+
|
288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
289 |
+
you inform other peers where the object code and Corresponding
|
290 |
+
Source of the work are being offered to the general public at no
|
291 |
+
charge under subsection 6d.
|
292 |
+
|
293 |
+
A separable portion of the object code, whose source code is excluded
|
294 |
+
from the Corresponding Source as a System Library, need not be
|
295 |
+
included in conveying the object code work.
|
296 |
+
|
297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
298 |
+
tangible personal property which is normally used for personal, family,
|
299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
302 |
+
product received by a particular user, "normally used" refers to a
|
303 |
+
typical or common use of that class of product, regardless of the status
|
304 |
+
of the particular user or of the way in which the particular user
|
305 |
+
actually uses, or expects or is expected to use, the product. A product
|
306 |
+
is a consumer product regardless of whether the product has substantial
|
307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
308 |
+
the only significant mode of use of the product.
|
309 |
+
|
310 |
+
"Installation Information" for a User Product means any methods,
|
311 |
+
procedures, authorization keys, or other information required to install
|
312 |
+
and execute modified versions of a covered work in that User Product from
|
313 |
+
a modified version of its Corresponding Source. The information must
|
314 |
+
suffice to ensure that the continued functioning of the modified object
|
315 |
+
code is in no case prevented or interfered with solely because
|
316 |
+
modification has been made.
|
317 |
+
|
318 |
+
If you convey an object code work under this section in, or with, or
|
319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
320 |
+
part of a transaction in which the right of possession and use of the
|
321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
322 |
+
fixed term (regardless of how the transaction is characterized), the
|
323 |
+
Corresponding Source conveyed under this section must be accompanied
|
324 |
+
by the Installation Information. But this requirement does not apply
|
325 |
+
if neither you nor any third party retains the ability to install
|
326 |
+
modified object code on the User Product (for example, the work has
|
327 |
+
been installed in ROM).
|
328 |
+
|
329 |
+
The requirement to provide Installation Information does not include a
|
330 |
+
requirement to continue to provide support service, warranty, or updates
|
331 |
+
for a work that has been modified or installed by the recipient, or for
|
332 |
+
the User Product in which it has been modified or installed. Access to a
|
333 |
+
network may be denied when the modification itself materially and
|
334 |
+
adversely affects the operation of the network or violates the rules and
|
335 |
+
protocols for communication across the network.
|
336 |
+
|
337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
338 |
+
in accord with this section must be in a format that is publicly
|
339 |
+
documented (and with an implementation available to the public in
|
340 |
+
source code form), and must require no special password or key for
|
341 |
+
unpacking, reading or copying.
|
342 |
+
|
343 |
+
7. Additional Terms.
|
344 |
+
|
345 |
+
"Additional permissions" are terms that supplement the terms of this
|
346 |
+
License by making exceptions from one or more of its conditions.
|
347 |
+
Additional permissions that are applicable to the entire Program shall
|
348 |
+
be treated as though they were included in this License, to the extent
|
349 |
+
that they are valid under applicable law. If additional permissions
|
350 |
+
apply only to part of the Program, that part may be used separately
|
351 |
+
under those permissions, but the entire Program remains governed by
|
352 |
+
this License without regard to the additional permissions.
|
353 |
+
|
354 |
+
When you convey a copy of a covered work, you may at your option
|
355 |
+
remove any additional permissions from that copy, or from any part of
|
356 |
+
it. (Additional permissions may be written to require their own
|
357 |
+
removal in certain cases when you modify the work.) You may place
|
358 |
+
additional permissions on material, added by you to a covered work,
|
359 |
+
for which you have or can give appropriate copyright permission.
|
360 |
+
|
361 |
+
Notwithstanding any other provision of this License, for material you
|
362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
363 |
+
that material) supplement the terms of this License with terms:
|
364 |
+
|
365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
366 |
+
terms of sections 15 and 16 of this License; or
|
367 |
+
|
368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
369 |
+
author attributions in that material or in the Appropriate Legal
|
370 |
+
Notices displayed by works containing it; or
|
371 |
+
|
372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
373 |
+
requiring that modified versions of such material be marked in
|
374 |
+
reasonable ways as different from the original version; or
|
375 |
+
|
376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
377 |
+
authors of the material; or
|
378 |
+
|
379 |
+
e) Declining to grant rights under trademark law for use of some
|
380 |
+
trade names, trademarks, or service marks; or
|
381 |
+
|
382 |
+
f) Requiring indemnification of licensors and authors of that
|
383 |
+
material by anyone who conveys the material (or modified versions of
|
384 |
+
it) with contractual assumptions of liability to the recipient, for
|
385 |
+
any liability that these contractual assumptions directly impose on
|
386 |
+
those licensors and authors.
|
387 |
+
|
388 |
+
All other non-permissive additional terms are considered "further
|
389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
390 |
+
received it, or any part of it, contains a notice stating that it is
|
391 |
+
governed by this License along with a term that is a further
|
392 |
+
restriction, you may remove that term. If a license document contains
|
393 |
+
a further restriction but permits relicensing or conveying under this
|
394 |
+
License, you may add to a covered work material governed by the terms
|
395 |
+
of that license document, provided that the further restriction does
|
396 |
+
not survive such relicensing or conveying.
|
397 |
+
|
398 |
+
If you add terms to a covered work in accord with this section, you
|
399 |
+
must place, in the relevant source files, a statement of the
|
400 |
+
additional terms that apply to those files, or a notice indicating
|
401 |
+
where to find the applicable terms.
|
402 |
+
|
403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
404 |
+
form of a separately written license, or stated as exceptions;
|
405 |
+
the above requirements apply either way.
|
406 |
+
|
407 |
+
8. Termination.
|
408 |
+
|
409 |
+
You may not propagate or modify a covered work except as expressly
|
410 |
+
provided under this License. Any attempt otherwise to propagate or
|
411 |
+
modify it is void, and will automatically terminate your rights under
|
412 |
+
this License (including any patent licenses granted under the third
|
413 |
+
paragraph of section 11).
|
414 |
+
|
415 |
+
However, if you cease all violation of this License, then your
|
416 |
+
license from a particular copyright holder is reinstated (a)
|
417 |
+
provisionally, unless and until the copyright holder explicitly and
|
418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
419 |
+
holder fails to notify you of the violation by some reasonable means
|
420 |
+
prior to 60 days after the cessation.
|
421 |
+
|
422 |
+
Moreover, your license from a particular copyright holder is
|
423 |
+
reinstated permanently if the copyright holder notifies you of the
|
424 |
+
violation by some reasonable means, this is the first time you have
|
425 |
+
received notice of violation of this License (for any work) from that
|
426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
427 |
+
your receipt of the notice.
|
428 |
+
|
429 |
+
Termination of your rights under this section does not terminate the
|
430 |
+
licenses of parties who have received copies or rights from you under
|
431 |
+
this License. If your rights have been terminated and not permanently
|
432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
433 |
+
material under section 10.
|
434 |
+
|
435 |
+
9. Acceptance Not Required for Having Copies.
|
436 |
+
|
437 |
+
You are not required to accept this License in order to receive or
|
438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
440 |
+
to receive a copy likewise does not require acceptance. However,
|
441 |
+
nothing other than this License grants you permission to propagate or
|
442 |
+
modify any covered work. These actions infringe copyright if you do
|
443 |
+
not accept this License. Therefore, by modifying or propagating a
|
444 |
+
covered work, you indicate your acceptance of this License to do so.
|
445 |
+
|
446 |
+
10. Automatic Licensing of Downstream Recipients.
|
447 |
+
|
448 |
+
Each time you convey a covered work, the recipient automatically
|
449 |
+
receives a license from the original licensors, to run, modify and
|
450 |
+
propagate that work, subject to this License. You are not responsible
|
451 |
+
for enforcing compliance by third parties with this License.
|
452 |
+
|
453 |
+
An "entity transaction" is a transaction transferring control of an
|
454 |
+
organization, or substantially all assets of one, or subdividing an
|
455 |
+
organization, or merging organizations. If propagation of a covered
|
456 |
+
work results from an entity transaction, each party to that
|
457 |
+
transaction who receives a copy of the work also receives whatever
|
458 |
+
licenses to the work the party's predecessor in interest had or could
|
459 |
+
give under the previous paragraph, plus a right to possession of the
|
460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
461 |
+
the predecessor has it or can get it with reasonable efforts.
|
462 |
+
|
463 |
+
You may not impose any further restrictions on the exercise of the
|
464 |
+
rights granted or affirmed under this License. For example, you may
|
465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
466 |
+
rights granted under this License, and you may not initiate litigation
|
467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
468 |
+
any patent claim is infringed by making, using, selling, offering for
|
469 |
+
sale, or importing the Program or any portion of it.
|
470 |
+
|
471 |
+
11. Patents.
|
472 |
+
|
473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
474 |
+
License of the Program or a work on which the Program is based. The
|
475 |
+
work thus licensed is called the contributor's "contributor version".
|
476 |
+
|
477 |
+
A contributor's "essential patent claims" are all patent claims
|
478 |
+
owned or controlled by the contributor, whether already acquired or
|
479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
480 |
+
by this License, of making, using, or selling its contributor version,
|
481 |
+
but do not include claims that would be infringed only as a
|
482 |
+
consequence of further modification of the contributor version. For
|
483 |
+
purposes of this definition, "control" includes the right to grant
|
484 |
+
patent sublicenses in a manner consistent with the requirements of
|
485 |
+
this License.
|
486 |
+
|
487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
488 |
+
patent license under the contributor's essential patent claims, to
|
489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
490 |
+
propagate the contents of its contributor version.
|
491 |
+
|
492 |
+
In the following three paragraphs, a "patent license" is any express
|
493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
494 |
+
(such as an express permission to practice a patent or covenant not to
|
495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
496 |
+
party means to make such an agreement or commitment not to enforce a
|
497 |
+
patent against the party.
|
498 |
+
|
499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
500 |
+
and the Corresponding Source of the work is not available for anyone
|
501 |
+
to copy, free of charge and under the terms of this License, through a
|
502 |
+
publicly available network server or other readily accessible means,
|
503 |
+
then you must either (1) cause the Corresponding Source to be so
|
504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
506 |
+
consistent with the requirements of this License, to extend the patent
|
507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
508 |
+
actual knowledge that, but for the patent license, your conveying the
|
509 |
+
covered work in a country, or your recipient's use of the covered work
|
510 |
+
in a country, would infringe one or more identifiable patents in that
|
511 |
+
country that you have reason to believe are valid.
|
512 |
+
|
513 |
+
If, pursuant to or in connection with a single transaction or
|
514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
515 |
+
covered work, and grant a patent license to some of the parties
|
516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
517 |
+
or convey a specific copy of the covered work, then the patent license
|
518 |
+
you grant is automatically extended to all recipients of the covered
|
519 |
+
work and works based on it.
|
520 |
+
|
521 |
+
A patent license is "discriminatory" if it does not include within
|
522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
524 |
+
specifically granted under this License. You may not convey a covered
|
525 |
+
work if you are a party to an arrangement with a third party that is
|
526 |
+
in the business of distributing software, under which you make payment
|
527 |
+
to the third party based on the extent of your activity of conveying
|
528 |
+
the work, and under which the third party grants, to any of the
|
529 |
+
parties who would receive the covered work from you, a discriminatory
|
530 |
+
patent license (a) in connection with copies of the covered work
|
531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
532 |
+
for and in connection with specific products or compilations that
|
533 |
+
contain the covered work, unless you entered into that arrangement,
|
534 |
+
or that patent license was granted, prior to 28 March 2007.
|
535 |
+
|
536 |
+
Nothing in this License shall be construed as excluding or limiting
|
537 |
+
any implied license or other defenses to infringement that may
|
538 |
+
otherwise be available to you under applicable patent law.
|
539 |
+
|
540 |
+
12. No Surrender of Others' Freedom.
|
541 |
+
|
542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
543 |
+
otherwise) that contradict the conditions of this License, they do not
|
544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
546 |
+
License and any other pertinent obligations, then as a consequence you may
|
547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
548 |
+
to collect a royalty for further conveying from those to whom you convey
|
549 |
+
the Program, the only way you could satisfy both those terms and this
|
550 |
+
License would be to refrain entirely from conveying the Program.
|
551 |
+
|
552 |
+
13. Use with the GNU Affero General Public License.
|
553 |
+
|
554 |
+
Notwithstanding any other provision of this License, you have
|
555 |
+
permission to link or combine any covered work with a work licensed
|
556 |
+
under version 3 of the GNU Affero General Public License into a single
|
557 |
+
combined work, and to convey the resulting work. The terms of this
|
558 |
+
License will continue to apply to the part which is the covered work,
|
559 |
+
but the special requirements of the GNU Affero General Public License,
|
560 |
+
section 13, concerning interaction through a network will apply to the
|
561 |
+
combination as such.
|
562 |
+
|
563 |
+
14. Revised Versions of this License.
|
564 |
+
|
565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
566 |
+
the GNU General Public License from time to time. Such new versions will
|
567 |
+
be similar in spirit to the present version, but may differ in detail to
|
568 |
+
address new problems or concerns.
|
569 |
+
|
570 |
+
Each version is given a distinguishing version number. If the
|
571 |
+
Program specifies that a certain numbered version of the GNU General
|
572 |
+
Public License "or any later version" applies to it, you have the
|
573 |
+
option of following the terms and conditions either of that numbered
|
574 |
+
version or of any later version published by the Free Software
|
575 |
+
Foundation. If the Program does not specify a version number of the
|
576 |
+
GNU General Public License, you may choose any version ever published
|
577 |
+
by the Free Software Foundation.
|
578 |
+
|
579 |
+
If the Program specifies that a proxy can decide which future
|
580 |
+
versions of the GNU General Public License can be used, that proxy's
|
581 |
+
public statement of acceptance of a version permanently authorizes you
|
582 |
+
to choose that version for the Program.
|
583 |
+
|
584 |
+
Later license versions may give you additional or different
|
585 |
+
permissions. However, no additional obligations are imposed on any
|
586 |
+
author or copyright holder as a result of your choosing to follow a
|
587 |
+
later version.
|
588 |
+
|
589 |
+
15. Disclaimer of Warranty.
|
590 |
+
|
591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
599 |
+
|
600 |
+
16. Limitation of Liability.
|
601 |
+
|
602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
610 |
+
SUCH DAMAGES.
|
611 |
+
|
612 |
+
17. Interpretation of Sections 15 and 16.
|
613 |
+
|
614 |
+
If the disclaimer of warranty and limitation of liability provided
|
615 |
+
above cannot be given local legal effect according to their terms,
|
616 |
+
reviewing courts shall apply local law that most closely approximates
|
617 |
+
an absolute waiver of all civil liability in connection with the
|
618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
619 |
+
copy of the Program in return for a fee.
|
620 |
+
|
621 |
+
END OF TERMS AND CONDITIONS
|
622 |
+
|
623 |
+
How to Apply These Terms to Your New Programs
|
624 |
+
|
625 |
+
If you develop a new program, and you want it to be of the greatest
|
626 |
+
possible use to the public, the best way to achieve this is to make it
|
627 |
+
free software which everyone can redistribute and change under these terms.
|
628 |
+
|
629 |
+
To do so, attach the following notices to the program. It is safest
|
630 |
+
to attach them to the start of each source file to most effectively
|
631 |
+
state the exclusion of warranty; and each file should have at least
|
632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
633 |
+
|
634 |
+
ultimate-upscale-for-automatic1111
|
635 |
+
Copyright (C) 2023 Mirzam
|
636 |
+
|
637 |
+
This program is free software: you can redistribute it and/or modify
|
638 |
+
it under the terms of the GNU General Public License as published by
|
639 |
+
the Free Software Foundation, either version 3 of the License, or
|
640 |
+
(at your option) any later version.
|
641 |
+
|
642 |
+
This program is distributed in the hope that it will be useful,
|
643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
645 |
+
GNU General Public License for more details.
|
646 |
+
|
647 |
+
You should have received a copy of the GNU General Public License
|
648 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
649 |
+
|
650 |
+
Also add information on how to contact you by electronic and paper mail.
|
651 |
+
|
652 |
+
If the program does terminal interaction, make it output a short
|
653 |
+
notice like this when it starts in an interactive mode:
|
654 |
+
|
655 |
+
<program> Copyright (C) 2023 Mirzam
|
656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
657 |
+
This is free software, and you are welcome to redistribute it
|
658 |
+
under certain conditions; type `show c' for details.
|
659 |
+
|
660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
661 |
+
parts of the General Public License. Of course, your program's commands
|
662 |
+
might be different; for a GUI interface, you would use an "about box".
|
663 |
+
|
664 |
+
You should also get your employer (if you work as a programmer) or school,
|
665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
667 |
+
<https://www.gnu.org/licenses/>.
|
668 |
+
|
669 |
+
The GNU General Public License does not permit incorporating your program
|
670 |
+
into proprietary programs. If your program is a subroutine library, you
|
671 |
+
may consider it more useful to permit linking proprietary applications with
|
672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
673 |
+
Public License instead of this License. But first, please read
|
674 |
+
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
ultimate-upscale-for-automatic1111/README.md
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ultimate SD Upscale extension for [AUTOMATIC1111 Stable Diffusion web UI](https://github.com/AUTOMATIC1111/stable-diffusion-webui)
|
2 |
+
Now you have the opportunity to use a large denoise (0.3-0.5) and not spawn many artifacts. Works on any video card, since you can use a 512x512 tile size and the image will converge.
|
3 |
+
|
4 |
+
News channel: https://t.me/usdunews
|
5 |
+
|
6 |
+
# Instructions
|
7 |
+
All instructions can be found on the project's [wiki](https://github.com/Coyote-A/ultimate-upscale-for-automatic1111/wiki).
|
8 |
+
|
9 |
+
# Examples
|
10 |
+
More on [wiki page](https://github.com/Coyote-A/ultimate-upscale-for-automatic1111/wiki/Examples)
|
11 |
+
|
12 |
+
<details>
|
13 |
+
<summary>E1</summary>
|
14 |
+
Original image
|
15 |
+
|
16 |
+

|
17 |
+
|
18 |
+
2k upscaled. **Tile size**: 512, **Padding**: 32, **Mask blur**: 16, **Denoise**: 0.4
|
19 |
+

|
20 |
+
</details>
|
21 |
+
|
22 |
+
<details>
|
23 |
+
<summary>E2</summary>
|
24 |
+
Original image
|
25 |
+
|
26 |
+

|
27 |
+
|
28 |
+
2k upscaled. **Tile size**: 768, **Padding**: 55, **Mask blur**: 20, **Denoise**: 0.35
|
29 |
+

|
30 |
+
|
31 |
+
4k upscaled. **Tile size**: 768, **Padding**: 55, **Mask blur**: 20, **Denoise**: 0.35
|
32 |
+

|
33 |
+
</details>
|
34 |
+
|
35 |
+
<details>
|
36 |
+
<summary>E3</summary>
|
37 |
+
Original image
|
38 |
+
|
39 |
+

|
40 |
+
|
41 |
+
4k upscaled. **Tile size**: 768, **Padding**: 55, **Mask blur**: 20, **Denoise**: 0.4
|
42 |
+

|
43 |
+
</details>
|
ultimate-upscale-for-automatic1111/scripts/__pycache__/ultimate-upscale.cpython-310.pyc
ADDED
Binary file (16.1 kB). View file
|
|
ultimate-upscale-for-automatic1111/scripts/ultimate-upscale.py
ADDED
@@ -0,0 +1,557 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import gradio as gr
|
3 |
+
from PIL import Image, ImageDraw, ImageOps
|
4 |
+
from modules import processing, shared, images, devices, scripts
|
5 |
+
from modules.processing import StableDiffusionProcessing
|
6 |
+
from modules.processing import Processed
|
7 |
+
from modules.shared import opts, state
|
8 |
+
from enum import Enum
|
9 |
+
|
10 |
+
class USDUMode(Enum):
|
11 |
+
LINEAR = 0
|
12 |
+
CHESS = 1
|
13 |
+
NONE = 2
|
14 |
+
|
15 |
+
class USDUSFMode(Enum):
|
16 |
+
NONE = 0
|
17 |
+
BAND_PASS = 1
|
18 |
+
HALF_TILE = 2
|
19 |
+
HALF_TILE_PLUS_INTERSECTIONS = 3
|
20 |
+
|
21 |
+
class USDUpscaler():
|
22 |
+
|
23 |
+
def __init__(self, p, image, upscaler_index:int, save_redraw, save_seams_fix, tile_width, tile_height) -> None:
|
24 |
+
self.p:StableDiffusionProcessing = p
|
25 |
+
self.image:Image = image
|
26 |
+
self.scale_factor = math.ceil(max(p.width, p.height) / max(image.width, image.height))
|
27 |
+
self.upscaler = shared.sd_upscalers[upscaler_index]
|
28 |
+
self.redraw = USDURedraw()
|
29 |
+
self.redraw.save = save_redraw
|
30 |
+
self.redraw.tile_width = tile_width if tile_width > 0 else tile_height
|
31 |
+
self.redraw.tile_height = tile_height if tile_height > 0 else tile_width
|
32 |
+
self.seams_fix = USDUSeamsFix()
|
33 |
+
self.seams_fix.save = save_seams_fix
|
34 |
+
self.seams_fix.tile_width = tile_width if tile_width > 0 else tile_height
|
35 |
+
self.seams_fix.tile_height = tile_height if tile_height > 0 else tile_width
|
36 |
+
self.initial_info = None
|
37 |
+
self.rows = math.ceil(self.p.height / self.redraw.tile_height)
|
38 |
+
self.cols = math.ceil(self.p.width / self.redraw.tile_width)
|
39 |
+
|
40 |
+
def get_factor(self, num):
|
41 |
+
# Its just return, don't need elif
|
42 |
+
if num == 1:
|
43 |
+
return 2
|
44 |
+
if num % 4 == 0:
|
45 |
+
return 4
|
46 |
+
if num % 3 == 0:
|
47 |
+
return 3
|
48 |
+
if num % 2 == 0:
|
49 |
+
return 2
|
50 |
+
return 0
|
51 |
+
|
52 |
+
def get_factors(self):
|
53 |
+
scales = []
|
54 |
+
current_scale = 1
|
55 |
+
current_scale_factor = self.get_factor(self.scale_factor)
|
56 |
+
while current_scale_factor == 0:
|
57 |
+
self.scale_factor += 1
|
58 |
+
current_scale_factor = self.get_factor(self.scale_factor)
|
59 |
+
while current_scale < self.scale_factor:
|
60 |
+
current_scale_factor = self.get_factor(self.scale_factor // current_scale)
|
61 |
+
scales.append(current_scale_factor)
|
62 |
+
current_scale = current_scale * current_scale_factor
|
63 |
+
if current_scale_factor == 0:
|
64 |
+
break
|
65 |
+
self.scales = enumerate(scales)
|
66 |
+
|
67 |
+
def upscale(self):
|
68 |
+
# Log info
|
69 |
+
print(f"Canva size: {self.p.width}x{self.p.height}")
|
70 |
+
print(f"Image size: {self.image.width}x{self.image.height}")
|
71 |
+
print(f"Scale factor: {self.scale_factor}")
|
72 |
+
# Check upscaler is not empty
|
73 |
+
if self.upscaler.name == "None":
|
74 |
+
self.image = self.image.resize((self.p.width, self.p.height), resample=Image.LANCZOS)
|
75 |
+
return
|
76 |
+
# Get list with scale factors
|
77 |
+
self.get_factors()
|
78 |
+
# Upscaling image over all factors
|
79 |
+
for index, value in self.scales:
|
80 |
+
print(f"Upscaling iteration {index+1} with scale factor {value}")
|
81 |
+
self.image = self.upscaler.scaler.upscale(self.image, value, self.upscaler.data_path)
|
82 |
+
# Resize image to set values
|
83 |
+
self.image = self.image.resize((self.p.width, self.p.height), resample=Image.LANCZOS)
|
84 |
+
|
85 |
+
def setup_redraw(self, redraw_mode, padding, mask_blur):
|
86 |
+
self.redraw.mode = USDUMode(redraw_mode)
|
87 |
+
self.redraw.enabled = self.redraw.mode != USDUMode.NONE
|
88 |
+
self.redraw.padding = padding
|
89 |
+
self.p.mask_blur = mask_blur
|
90 |
+
|
91 |
+
def setup_seams_fix(self, padding, denoise, mask_blur, width, mode):
|
92 |
+
self.seams_fix.padding = padding
|
93 |
+
self.seams_fix.denoise = denoise
|
94 |
+
self.seams_fix.mask_blur = mask_blur
|
95 |
+
self.seams_fix.width = width
|
96 |
+
self.seams_fix.mode = USDUSFMode(mode)
|
97 |
+
self.seams_fix.enabled = self.seams_fix.mode != USDUSFMode.NONE
|
98 |
+
|
99 |
+
def save_image(self):
|
100 |
+
if type(self.p.prompt) != list:
|
101 |
+
images.save_image(self.image, self.p.outpath_samples, "", self.p.seed, self.p.prompt, opts.samples_format, info=self.initial_info, p=self.p)
|
102 |
+
else:
|
103 |
+
images.save_image(self.image, self.p.outpath_samples, "", self.p.seed, self.p.prompt[0], opts.samples_format, info=self.initial_info, p=self.p)
|
104 |
+
|
105 |
+
def calc_jobs_count(self):
|
106 |
+
redraw_job_count = (self.rows * self.cols) if self.redraw.enabled else 0
|
107 |
+
seams_job_count = 0
|
108 |
+
if self.seams_fix.mode == USDUSFMode.BAND_PASS:
|
109 |
+
seams_job_count = self.rows + self.cols - 2
|
110 |
+
elif self.seams_fix.mode == USDUSFMode.HALF_TILE:
|
111 |
+
seams_job_count = self.rows * (self.cols - 1) + (self.rows - 1) * self.cols
|
112 |
+
elif self.seams_fix.mode == USDUSFMode.HALF_TILE_PLUS_INTERSECTIONS:
|
113 |
+
seams_job_count = self.rows * (self.cols - 1) + (self.rows - 1) * self.cols + (self.rows - 1) * (self.cols - 1)
|
114 |
+
|
115 |
+
state.job_count = redraw_job_count + seams_job_count
|
116 |
+
|
117 |
+
def print_info(self):
|
118 |
+
print(f"Tile size: {self.redraw.tile_width}x{self.redraw.tile_height}")
|
119 |
+
print(f"Tiles amount: {self.rows * self.cols}")
|
120 |
+
print(f"Grid: {self.rows}x{self.cols}")
|
121 |
+
print(f"Redraw enabled: {self.redraw.enabled}")
|
122 |
+
print(f"Seams fix mode: {self.seams_fix.mode.name}")
|
123 |
+
|
124 |
+
def add_extra_info(self):
|
125 |
+
self.p.extra_generation_params["Ultimate SD upscale upscaler"] = self.upscaler.name
|
126 |
+
self.p.extra_generation_params["Ultimate SD upscale tile_width"] = self.redraw.tile_width
|
127 |
+
self.p.extra_generation_params["Ultimate SD upscale tile_height"] = self.redraw.tile_height
|
128 |
+
self.p.extra_generation_params["Ultimate SD upscale mask_blur"] = self.p.mask_blur
|
129 |
+
self.p.extra_generation_params["Ultimate SD upscale padding"] = self.redraw.padding
|
130 |
+
|
131 |
+
def process(self):
|
132 |
+
state.begin()
|
133 |
+
self.calc_jobs_count()
|
134 |
+
self.result_images = []
|
135 |
+
if self.redraw.enabled:
|
136 |
+
self.image = self.redraw.start(self.p, self.image, self.rows, self.cols)
|
137 |
+
self.initial_info = self.redraw.initial_info
|
138 |
+
self.result_images.append(self.image)
|
139 |
+
if self.redraw.save:
|
140 |
+
self.save_image()
|
141 |
+
|
142 |
+
if self.seams_fix.enabled:
|
143 |
+
self.image = self.seams_fix.start(self.p, self.image, self.rows, self.cols)
|
144 |
+
self.initial_info = self.seams_fix.initial_info
|
145 |
+
self.result_images.append(self.image)
|
146 |
+
if self.seams_fix.save:
|
147 |
+
self.save_image()
|
148 |
+
state.end()
|
149 |
+
|
150 |
+
class USDURedraw():
|
151 |
+
|
152 |
+
def init_draw(self, p, width, height):
|
153 |
+
p.inpaint_full_res = True
|
154 |
+
p.inpaint_full_res_padding = self.padding
|
155 |
+
p.width = math.ceil((self.tile_width+self.padding) / 64) * 64
|
156 |
+
p.height = math.ceil((self.tile_height+self.padding) / 64) * 64
|
157 |
+
mask = Image.new("L", (width, height), "black")
|
158 |
+
draw = ImageDraw.Draw(mask)
|
159 |
+
return mask, draw
|
160 |
+
|
161 |
+
def calc_rectangle(self, xi, yi):
|
162 |
+
x1 = xi * self.tile_width
|
163 |
+
y1 = yi * self.tile_height
|
164 |
+
x2 = xi * self.tile_width + self.tile_width
|
165 |
+
y2 = yi * self.tile_height + self.tile_height
|
166 |
+
|
167 |
+
return x1, y1, x2, y2
|
168 |
+
|
169 |
+
def linear_process(self, p, image, rows, cols):
|
170 |
+
mask, draw = self.init_draw(p, image.width, image.height)
|
171 |
+
for yi in range(rows):
|
172 |
+
for xi in range(cols):
|
173 |
+
if state.interrupted:
|
174 |
+
break
|
175 |
+
draw.rectangle(self.calc_rectangle(xi, yi), fill="white")
|
176 |
+
p.init_images = [image]
|
177 |
+
p.image_mask = mask
|
178 |
+
processed = processing.process_images(p)
|
179 |
+
draw.rectangle(self.calc_rectangle(xi, yi), fill="black")
|
180 |
+
if (len(processed.images) > 0):
|
181 |
+
image = processed.images[0]
|
182 |
+
|
183 |
+
p.width = image.width
|
184 |
+
p.height = image.height
|
185 |
+
self.initial_info = processed.infotext(p, 0)
|
186 |
+
|
187 |
+
return image
|
188 |
+
|
189 |
+
def chess_process(self, p, image, rows, cols):
|
190 |
+
mask, draw = self.init_draw(p, image.width, image.height)
|
191 |
+
tiles = []
|
192 |
+
# calc tiles colors
|
193 |
+
for yi in range(rows):
|
194 |
+
for xi in range(cols):
|
195 |
+
if state.interrupted:
|
196 |
+
break
|
197 |
+
if xi == 0:
|
198 |
+
tiles.append([])
|
199 |
+
color = xi % 2 == 0
|
200 |
+
if yi > 0 and yi % 2 != 0:
|
201 |
+
color = not color
|
202 |
+
tiles[yi].append(color)
|
203 |
+
|
204 |
+
for yi in range(len(tiles)):
|
205 |
+
for xi in range(len(tiles[yi])):
|
206 |
+
if state.interrupted:
|
207 |
+
break
|
208 |
+
if not tiles[yi][xi]:
|
209 |
+
tiles[yi][xi] = not tiles[yi][xi]
|
210 |
+
continue
|
211 |
+
tiles[yi][xi] = not tiles[yi][xi]
|
212 |
+
draw.rectangle(self.calc_rectangle(xi, yi), fill="white")
|
213 |
+
p.init_images = [image]
|
214 |
+
p.image_mask = mask
|
215 |
+
processed = processing.process_images(p)
|
216 |
+
draw.rectangle(self.calc_rectangle(xi, yi), fill="black")
|
217 |
+
if (len(processed.images) > 0):
|
218 |
+
image = processed.images[0]
|
219 |
+
|
220 |
+
for yi in range(len(tiles)):
|
221 |
+
for xi in range(len(tiles[yi])):
|
222 |
+
if state.interrupted:
|
223 |
+
break
|
224 |
+
if not tiles[yi][xi]:
|
225 |
+
continue
|
226 |
+
draw.rectangle(self.calc_rectangle(xi, yi), fill="white")
|
227 |
+
p.init_images = [image]
|
228 |
+
p.image_mask = mask
|
229 |
+
processed = processing.process_images(p)
|
230 |
+
draw.rectangle(self.calc_rectangle(xi, yi), fill="black")
|
231 |
+
if (len(processed.images) > 0):
|
232 |
+
image = processed.images[0]
|
233 |
+
|
234 |
+
p.width = image.width
|
235 |
+
p.height = image.height
|
236 |
+
self.initial_info = processed.infotext(p, 0)
|
237 |
+
|
238 |
+
return image
|
239 |
+
|
240 |
+
def start(self, p, image, rows, cols):
|
241 |
+
self.initial_info = None
|
242 |
+
if self.mode == USDUMode.LINEAR:
|
243 |
+
return self.linear_process(p, image, rows, cols)
|
244 |
+
if self.mode == USDUMode.CHESS:
|
245 |
+
return self.chess_process(p, image, rows, cols)
|
246 |
+
|
247 |
+
class USDUSeamsFix():
|
248 |
+
|
249 |
+
def init_draw(self, p):
|
250 |
+
self.initial_info = None
|
251 |
+
p.width = math.ceil((self.tile_width+self.padding) / 64) * 64
|
252 |
+
p.height = math.ceil((self.tile_height+self.padding) / 64) * 64
|
253 |
+
|
254 |
+
def half_tile_process(self, p, image, rows, cols):
|
255 |
+
|
256 |
+
self.init_draw(p)
|
257 |
+
processed = None
|
258 |
+
|
259 |
+
gradient = Image.linear_gradient("L")
|
260 |
+
row_gradient = Image.new("L", (self.tile_width, self.tile_height), "black")
|
261 |
+
row_gradient.paste(gradient.resize(
|
262 |
+
(self.tile_width, self.tile_height//2), resample=Image.BICUBIC), (0, 0))
|
263 |
+
row_gradient.paste(gradient.rotate(180).resize(
|
264 |
+
(self.tile_width, self.tile_height//2), resample=Image.BICUBIC),
|
265 |
+
(0, self.tile_height//2))
|
266 |
+
col_gradient = Image.new("L", (self.tile_width, self.tile_height), "black")
|
267 |
+
col_gradient.paste(gradient.rotate(90).resize(
|
268 |
+
(self.tile_width//2, self.tile_height), resample=Image.BICUBIC), (0, 0))
|
269 |
+
col_gradient.paste(gradient.rotate(270).resize(
|
270 |
+
(self.tile_width//2, self.tile_height), resample=Image.BICUBIC), (self.tile_width//2, 0))
|
271 |
+
|
272 |
+
p.denoising_strength = self.denoise
|
273 |
+
p.mask_blur = self.mask_blur
|
274 |
+
|
275 |
+
for yi in range(rows-1):
|
276 |
+
for xi in range(cols):
|
277 |
+
if state.interrupted:
|
278 |
+
break
|
279 |
+
p.width = self.tile_width
|
280 |
+
p.height = self.tile_height
|
281 |
+
p.inpaint_full_res = True
|
282 |
+
p.inpaint_full_res_padding = self.padding
|
283 |
+
mask = Image.new("L", (image.width, image.height), "black")
|
284 |
+
mask.paste(row_gradient, (xi*self.tile_width, yi*self.tile_height + self.tile_height//2))
|
285 |
+
|
286 |
+
p.init_images = [image]
|
287 |
+
p.image_mask = mask
|
288 |
+
processed = processing.process_images(p)
|
289 |
+
if (len(processed.images) > 0):
|
290 |
+
image = processed.images[0]
|
291 |
+
|
292 |
+
for yi in range(rows):
|
293 |
+
for xi in range(cols-1):
|
294 |
+
if state.interrupted:
|
295 |
+
break
|
296 |
+
p.width = self.tile_width
|
297 |
+
p.height = self.tile_height
|
298 |
+
p.inpaint_full_res = True
|
299 |
+
p.inpaint_full_res_padding = self.padding
|
300 |
+
mask = Image.new("L", (image.width, image.height), "black")
|
301 |
+
mask.paste(col_gradient, (xi*self.tile_width+self.tile_width//2, yi*self.tile_height))
|
302 |
+
|
303 |
+
p.init_images = [image]
|
304 |
+
p.image_mask = mask
|
305 |
+
processed = processing.process_images(p)
|
306 |
+
if (len(processed.images) > 0):
|
307 |
+
image = processed.images[0]
|
308 |
+
|
309 |
+
p.width = image.width
|
310 |
+
p.height = image.height
|
311 |
+
if processed is not None:
|
312 |
+
self.initial_info = processed.infotext(p, 0)
|
313 |
+
|
314 |
+
return image
|
315 |
+
|
316 |
+
def half_tile_process_corners(self, p, image, rows, cols):
|
317 |
+
fixed_image = self.half_tile_process(p, image, rows, cols)
|
318 |
+
processed = None
|
319 |
+
self.init_draw(p)
|
320 |
+
gradient = Image.radial_gradient("L").resize(
|
321 |
+
(self.tile_width, self.tile_height), resample=Image.BICUBIC)
|
322 |
+
gradient = ImageOps.invert(gradient)
|
323 |
+
p.denoising_strength = self.denoise
|
324 |
+
#p.mask_blur = 0
|
325 |
+
p.mask_blur = self.mask_blur
|
326 |
+
|
327 |
+
for yi in range(rows-1):
|
328 |
+
for xi in range(cols-1):
|
329 |
+
if state.interrupted:
|
330 |
+
break
|
331 |
+
p.width = self.tile_width
|
332 |
+
p.height = self.tile_height
|
333 |
+
p.inpaint_full_res = True
|
334 |
+
p.inpaint_full_res_padding = 0
|
335 |
+
mask = Image.new("L", (fixed_image.width, fixed_image.height), "black")
|
336 |
+
mask.paste(gradient, (xi*self.tile_width + self.tile_width//2,
|
337 |
+
yi*self.tile_height + self.tile_height//2))
|
338 |
+
|
339 |
+
p.init_images = [fixed_image]
|
340 |
+
p.image_mask = mask
|
341 |
+
processed = processing.process_images(p)
|
342 |
+
if (len(processed.images) > 0):
|
343 |
+
fixed_image = processed.images[0]
|
344 |
+
|
345 |
+
p.width = fixed_image.width
|
346 |
+
p.height = fixed_image.height
|
347 |
+
if processed is not None:
|
348 |
+
self.initial_info = processed.infotext(p, 0)
|
349 |
+
|
350 |
+
return fixed_image
|
351 |
+
|
352 |
+
def band_pass_process(self, p, image, cols, rows):
|
353 |
+
|
354 |
+
self.init_draw(p)
|
355 |
+
processed = None
|
356 |
+
|
357 |
+
p.denoising_strength = self.denoise
|
358 |
+
p.mask_blur = 0
|
359 |
+
|
360 |
+
gradient = Image.linear_gradient("L")
|
361 |
+
mirror_gradient = Image.new("L", (256, 256), "black")
|
362 |
+
mirror_gradient.paste(gradient.resize((256, 128), resample=Image.BICUBIC), (0, 0))
|
363 |
+
mirror_gradient.paste(gradient.rotate(180).resize((256, 128), resample=Image.BICUBIC), (0, 128))
|
364 |
+
|
365 |
+
row_gradient = mirror_gradient.resize((image.width, self.width), resample=Image.BICUBIC)
|
366 |
+
col_gradient = mirror_gradient.rotate(90).resize((self.width, image.height), resample=Image.BICUBIC)
|
367 |
+
|
368 |
+
for xi in range(1, rows):
|
369 |
+
if state.interrupted:
|
370 |
+
break
|
371 |
+
p.width = self.width + self.padding * 2
|
372 |
+
p.height = image.height
|
373 |
+
p.inpaint_full_res = True
|
374 |
+
p.inpaint_full_res_padding = self.padding
|
375 |
+
mask = Image.new("L", (image.width, image.height), "black")
|
376 |
+
mask.paste(col_gradient, (xi * self.tile_width - self.width // 2, 0))
|
377 |
+
|
378 |
+
p.init_images = [image]
|
379 |
+
p.image_mask = mask
|
380 |
+
processed = processing.process_images(p)
|
381 |
+
if (len(processed.images) > 0):
|
382 |
+
image = processed.images[0]
|
383 |
+
for yi in range(1, cols):
|
384 |
+
if state.interrupted:
|
385 |
+
break
|
386 |
+
p.width = image.width
|
387 |
+
p.height = self.width + self.padding * 2
|
388 |
+
p.inpaint_full_res = True
|
389 |
+
p.inpaint_full_res_padding = self.padding
|
390 |
+
mask = Image.new("L", (image.width, image.height), "black")
|
391 |
+
mask.paste(row_gradient, (0, yi * self.tile_height - self.width // 2))
|
392 |
+
|
393 |
+
p.init_images = [image]
|
394 |
+
p.image_mask = mask
|
395 |
+
processed = processing.process_images(p)
|
396 |
+
if (len(processed.images) > 0):
|
397 |
+
image = processed.images[0]
|
398 |
+
|
399 |
+
p.width = image.width
|
400 |
+
p.height = image.height
|
401 |
+
if processed is not None:
|
402 |
+
self.initial_info = processed.infotext(p, 0)
|
403 |
+
|
404 |
+
return image
|
405 |
+
|
406 |
+
def start(self, p, image, rows, cols):
|
407 |
+
if USDUSFMode(self.mode) == USDUSFMode.BAND_PASS:
|
408 |
+
return self.band_pass_process(p, image, rows, cols)
|
409 |
+
elif USDUSFMode(self.mode) == USDUSFMode.HALF_TILE:
|
410 |
+
return self.half_tile_process(p, image, rows, cols)
|
411 |
+
elif USDUSFMode(self.mode) == USDUSFMode.HALF_TILE_PLUS_INTERSECTIONS:
|
412 |
+
return self.half_tile_process_corners(p, image, rows, cols)
|
413 |
+
else:
|
414 |
+
return image
|
415 |
+
|
416 |
+
class Script(scripts.Script):
|
417 |
+
def title(self):
|
418 |
+
return "Ultimate SD upscale"
|
419 |
+
|
420 |
+
def show(self, is_img2img):
|
421 |
+
return is_img2img
|
422 |
+
|
423 |
+
def ui(self, is_img2img):
|
424 |
+
|
425 |
+
target_size_types = [
|
426 |
+
"From img2img2 settings",
|
427 |
+
"Custom size",
|
428 |
+
"Scale from image size"
|
429 |
+
]
|
430 |
+
|
431 |
+
seams_fix_types = [
|
432 |
+
"None",
|
433 |
+
"Band pass",
|
434 |
+
"Half tile offset pass",
|
435 |
+
"Half tile offset pass + intersections"
|
436 |
+
]
|
437 |
+
|
438 |
+
redrow_modes = [
|
439 |
+
"Linear",
|
440 |
+
"Chess",
|
441 |
+
"None"
|
442 |
+
]
|
443 |
+
|
444 |
+
info = gr.HTML(
|
445 |
+
"<p style=\"margin-bottom:0.75em\">Will upscale the image depending on the selected target size type</p>")
|
446 |
+
|
447 |
+
with gr.Row():
|
448 |
+
target_size_type = gr.Dropdown(label="Target size type", choices=[k for k in target_size_types], type="index",
|
449 |
+
value=next(iter(target_size_types)))
|
450 |
+
|
451 |
+
custom_width = gr.Slider(label='Custom width', minimum=64, maximum=8192, step=64, value=2048, visible=False, interactive=True)
|
452 |
+
custom_height = gr.Slider(label='Custom height', minimum=64, maximum=8192, step=64, value=2048, visible=False, interactive=True)
|
453 |
+
custom_scale = gr.Slider(label='Scale', minimum=1, maximum=16, step=0.01, value=2, visible=False, interactive=True)
|
454 |
+
|
455 |
+
gr.HTML("<p style=\"margin-bottom:0.75em\">Redraw options:</p>")
|
456 |
+
with gr.Row():
|
457 |
+
upscaler_index = gr.Radio(label='Upscaler', choices=[x.name for x in shared.sd_upscalers],
|
458 |
+
value=shared.sd_upscalers[0].name, type="index")
|
459 |
+
with gr.Row():
|
460 |
+
redraw_mode = gr.Dropdown(label="Type", choices=[k for k in redrow_modes], type="index", value=next(iter(redrow_modes)))
|
461 |
+
tile_width = gr.Slider(minimum=0, maximum=2048, step=64, label='Tile width', value=512)
|
462 |
+
tile_height = gr.Slider(minimum=0, maximum=2048, step=64, label='Tile height', value=0)
|
463 |
+
mask_blur = gr.Slider(label='Mask blur', minimum=0, maximum=64, step=1, value=8)
|
464 |
+
padding = gr.Slider(label='Padding', minimum=0, maximum=128, step=1, value=32)
|
465 |
+
gr.HTML("<p style=\"margin-bottom:0.75em\">Seams fix:</p>")
|
466 |
+
with gr.Row():
|
467 |
+
seams_fix_type = gr.Dropdown(label="Type", choices=[k for k in seams_fix_types], type="index", value=next(iter(seams_fix_types)))
|
468 |
+
seams_fix_denoise = gr.Slider(label='Denoise', minimum=0, maximum=1, step=0.01, value=0.35, visible=False, interactive=True)
|
469 |
+
seams_fix_width = gr.Slider(label='Width', minimum=0, maximum=128, step=1, value=64, visible=False, interactive=True)
|
470 |
+
seams_fix_mask_blur = gr.Slider(label='Mask blur', minimum=0, maximum=64, step=1, value=4, visible=False, interactive=True)
|
471 |
+
seams_fix_padding = gr.Slider(label='Padding', minimum=0, maximum=128, step=1, value=16, visible=False, interactive=True)
|
472 |
+
gr.HTML("<p style=\"margin-bottom:0.75em\">Save options:</p>")
|
473 |
+
with gr.Row():
|
474 |
+
save_upscaled_image = gr.Checkbox(label="Upscaled", value=True)
|
475 |
+
save_seams_fix_image = gr.Checkbox(label="Seams fix", value=False)
|
476 |
+
|
477 |
+
def select_fix_type(fix_index):
|
478 |
+
all_visible = fix_index != 0
|
479 |
+
mask_blur_visible = fix_index == 2 or fix_index == 3
|
480 |
+
width_visible = fix_index == 1
|
481 |
+
|
482 |
+
return [gr.update(visible=all_visible),
|
483 |
+
gr.update(visible=width_visible),
|
484 |
+
gr.update(visible=mask_blur_visible),
|
485 |
+
gr.update(visible=all_visible)]
|
486 |
+
|
487 |
+
seams_fix_type.change(
|
488 |
+
fn=select_fix_type,
|
489 |
+
inputs=seams_fix_type,
|
490 |
+
outputs=[seams_fix_denoise, seams_fix_width, seams_fix_mask_blur, seams_fix_padding]
|
491 |
+
)
|
492 |
+
|
493 |
+
def select_scale_type(scale_index):
|
494 |
+
is_custom_size = scale_index == 1
|
495 |
+
is_custom_scale = scale_index == 2
|
496 |
+
|
497 |
+
return [gr.update(visible=is_custom_size),
|
498 |
+
gr.update(visible=is_custom_size),
|
499 |
+
gr.update(visible=is_custom_scale),
|
500 |
+
]
|
501 |
+
|
502 |
+
target_size_type.change(
|
503 |
+
fn=select_scale_type,
|
504 |
+
inputs=target_size_type,
|
505 |
+
outputs=[custom_width, custom_height, custom_scale]
|
506 |
+
)
|
507 |
+
|
508 |
+
return [info, tile_width, tile_height, mask_blur, padding, seams_fix_width, seams_fix_denoise, seams_fix_padding,
|
509 |
+
upscaler_index, save_upscaled_image, redraw_mode, save_seams_fix_image, seams_fix_mask_blur,
|
510 |
+
seams_fix_type, target_size_type, custom_width, custom_height, custom_scale]
|
511 |
+
|
512 |
+
def run(self, p, _, tile_width, tile_height, mask_blur, padding, seams_fix_width, seams_fix_denoise, seams_fix_padding,
|
513 |
+
upscaler_index, save_upscaled_image, redraw_mode, save_seams_fix_image, seams_fix_mask_blur,
|
514 |
+
seams_fix_type, target_size_type, custom_width, custom_height, custom_scale):
|
515 |
+
|
516 |
+
# Init
|
517 |
+
processing.fix_seed(p)
|
518 |
+
devices.torch_gc()
|
519 |
+
|
520 |
+
p.do_not_save_grid = True
|
521 |
+
p.do_not_save_samples = True
|
522 |
+
p.inpaint_full_res = False
|
523 |
+
|
524 |
+
p.inpainting_fill = 1
|
525 |
+
p.n_iter = 1
|
526 |
+
p.batch_size = 1
|
527 |
+
|
528 |
+
seed = p.seed
|
529 |
+
|
530 |
+
# Init image
|
531 |
+
init_img = p.init_images[0]
|
532 |
+
if init_img == None:
|
533 |
+
return Processed(p, [], seed, "Empty image")
|
534 |
+
init_img = images.flatten(init_img, opts.img2img_background_color)
|
535 |
+
|
536 |
+
#override size
|
537 |
+
if target_size_type == 1:
|
538 |
+
p.width = custom_width
|
539 |
+
p.height = custom_height
|
540 |
+
if target_size_type == 2:
|
541 |
+
p.width = math.ceil((init_img.width * custom_scale) / 64) * 64
|
542 |
+
p.height = math.ceil((init_img.height * custom_scale) / 64) * 64
|
543 |
+
|
544 |
+
# Upscaling
|
545 |
+
upscaler = USDUpscaler(p, init_img, upscaler_index, save_upscaled_image, save_seams_fix_image, tile_width, tile_height)
|
546 |
+
upscaler.upscale()
|
547 |
+
|
548 |
+
# Drawing
|
549 |
+
upscaler.setup_redraw(redraw_mode, padding, mask_blur)
|
550 |
+
upscaler.setup_seams_fix(seams_fix_padding, seams_fix_denoise, seams_fix_mask_blur, seams_fix_width, seams_fix_type)
|
551 |
+
upscaler.print_info()
|
552 |
+
upscaler.add_extra_info()
|
553 |
+
upscaler.process()
|
554 |
+
result_images = upscaler.result_images
|
555 |
+
|
556 |
+
return Processed(p, result_images, seed, upscaler.initial_info if upscaler.initial_info is not None else "")
|
557 |
+
|