mirror of
https://github.com/AUTOMATIC1111/stable-diffusion-webui.git
synced 2025-04-05 20:29:02 +08:00
Compare commits
3318 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
82a973c043 | ||
|
1d7e9eca09 | ||
|
c19d044364 | ||
|
8b3d98c5a5 | ||
|
5bbbda473f | ||
|
9f5a98d576 | ||
|
986c31dcfe | ||
|
5096c163c1 | ||
|
7b99e14ab1 | ||
|
7c8a4ccecb | ||
|
5d26c6ae89 | ||
|
5a10bb9aa6 | ||
|
fa0ba939a7 | ||
|
fc7b25ac67 | ||
|
e09104a126 | ||
|
141d4b71b1 | ||
|
ea903819cb | ||
|
24a23e1225 | ||
|
8749540602 | ||
|
9de7084884 | ||
|
94275b115c | ||
|
e285af6e48 | ||
|
f6f055a93d | ||
|
3a5a66775c | ||
|
7e1bd3e3c3 | ||
|
964fc13a99 | ||
|
a5f66b5003 | ||
|
2abc628899 | ||
|
2b50233f3f | ||
|
f5866199c4 | ||
|
7e5cdaab4b | ||
|
b2453d280a | ||
|
b4d62a05af | ||
|
589dda3cf2 | ||
|
3d2dbefcde | ||
|
b1695c1b68 | ||
|
d57ff884ed | ||
|
26cccd8faa | ||
|
9cc7142dd7 | ||
|
5a5fe7494a | ||
|
6a7042fe2f | ||
|
72cfa2829d | ||
|
4debd4d3ef | ||
|
3f6dcda3e5 | ||
|
27d96fa608 | ||
|
dd4f798b97 | ||
|
27947a79d6 | ||
|
11f827c58b | ||
|
48dd4d9eae | ||
|
93c00b2af7 | ||
|
7d7f7f4b49 | ||
|
1b0823db94 | ||
|
6ca7a453d4 | ||
|
bad47dcfeb | ||
|
c3d8b78b47 | ||
|
21e72d1a5e | ||
|
7b2917255a | ||
|
11cfe0dd05 | ||
|
780c70f6ea | ||
|
b5481c6195 | ||
|
1da4907927 | ||
|
ec580374e5 | ||
|
340a9108ca | ||
|
74069addc3 | ||
|
477869c044 | ||
|
ffead92d4e | ||
|
0a6628bad0 | ||
|
eb112c6f88 | ||
|
ace00a1fe8 | ||
|
2fec94710b | ||
|
74b56fef3d | ||
|
8058eed6a5 | ||
|
3bd4a08119 | ||
|
68df28176c | ||
|
4cc3add770 | ||
|
50514ce414 | ||
|
edebe4d4de | ||
|
b9c3f4ec2c | ||
|
41ac13996e | ||
|
76a19c089a | ||
|
372a8e0658 | ||
|
b8c3664934 | ||
|
9414309f15 | ||
|
9cbde7938a | ||
|
019df53a31 | ||
|
af3ccee5c8 | ||
|
a6c384b9f7 | ||
|
b282b47b85 | ||
|
c02e3a5549 | ||
|
b82caf1322 | ||
|
bfbca31074 | ||
|
f8640662c5 | ||
|
f8fb74b93a | ||
|
32fdf18203 | ||
|
3971c01562 | ||
|
fd16393465 | ||
|
957185f7eb | ||
|
6ddcd8914b | ||
|
9e404c3154 | ||
|
ebe8be9028 | ||
|
1394ecaf36 | ||
|
7e4b06fcd0 | ||
|
d67348a0a5 | ||
|
179ae47d64 | ||
|
0b64633584 | ||
|
0c7bdcc1b1 | ||
|
fc8b126673 | ||
|
06fe174c74 | ||
|
afaf120bc2 | ||
|
42ca30d6c1 | ||
|
d686e73daa | ||
|
ec3c31e7a1 | ||
|
9e60cdbc3f | ||
|
5d9f1e6a43 | ||
|
a8fba9af35 | ||
|
a65dd315ad | ||
|
731eb72774 | ||
|
c3ef381cd8 | ||
|
775fa7696b | ||
|
109bbda709 | ||
|
0f40c4b9b1 | ||
|
bd85b3f19b | ||
|
13f22974a4 | ||
|
a772fd9804 | ||
|
663a4d80df | ||
|
34b4443cc3 | ||
|
d4b814aed6 | ||
|
58dc35a64a | ||
|
06d0a5ab4d | ||
|
80f618ea95 | ||
|
b443fdcf76 | ||
|
7ee2114cd9 | ||
|
79de09c3df | ||
|
5b2a60b8e2 | ||
|
a7116aa9a1 | ||
|
9e0f6d2012 | ||
|
a30b19dd55 | ||
|
f1e0bfebfc | ||
|
c803e11505 | ||
|
1f8f3a6e8b | ||
|
d5e26274c8 | ||
|
91ecc750be | ||
|
00e09382cd | ||
|
123582b00f | ||
|
abacb735f4 | ||
|
e33bb8febe | ||
|
17e846150c | ||
|
a84000c285 | ||
|
74ee8fd1e3 | ||
|
d2097dbdd9 | ||
|
99e65ec618 | ||
|
1d0bb39797 | ||
|
57e6d05a43 | ||
|
aafbb5b403 | ||
|
e368cd2810 | ||
|
981abbb1f2 | ||
|
6214aa7d2a | ||
|
6447ff49d3 | ||
|
41ee2db5a8 | ||
|
f89b5dbbd2 | ||
|
d875cda565 | ||
|
d52a1e1a22 | ||
|
39a6d5655f | ||
|
428975e1d3 | ||
|
58b24eae30 | ||
|
547778b10f | ||
|
194c2620d6 | ||
|
5ecfc20d97 | ||
|
2dbc7aa688 | ||
|
6d8d2723a0 | ||
|
3ef9f2748d | ||
|
30461bef98 | ||
|
569f17c6c6 | ||
|
a184e5dd87 | ||
|
9e5103124a | ||
|
41b24d350f | ||
|
742bfbe0ec | ||
|
a1130c26e5 | ||
|
b9dfc50a1b | ||
|
74b1fc6256 | ||
|
4aebfe9844 | ||
|
debc6dddeb | ||
|
1a7ffa2c76 | ||
|
64783dd9cc | ||
|
c1c4b3fb34 | ||
|
5abdf5191d | ||
|
64ebb245ad | ||
|
07cf95c76e | ||
|
9905341602 | ||
|
88a5001e06 | ||
|
7b940e3879 | ||
|
b4723bb8c1 | ||
|
6450d24afe | ||
|
64bf57b5ea | ||
|
816bc424c4 | ||
|
371cb60945 | ||
|
603509ec90 | ||
|
ad229fae43 | ||
|
510f025a01 | ||
|
5977cb0946 | ||
|
04164a83c4 | ||
|
96f907ee09 | ||
|
c3c90deec0 | ||
|
cbac72d8ee | ||
|
616013fd7a | ||
|
93b53dc116 | ||
|
ebfc9f6d09 | ||
|
33b73c473c | ||
|
ba54c747e2 | ||
|
cd9e9e4049 | ||
|
15245d9d5e | ||
|
5429e4cff5 | ||
|
b150b3a3a4 | ||
|
9e1fc80c48 | ||
|
0edc04d126 | ||
|
e21b1e3716 | ||
|
00f37ad73f | ||
|
0769aa318a | ||
|
de7f5cdc62 | ||
|
0c0d71a4e4 | ||
|
6de733c91e | ||
|
46bcfbe37c | ||
|
3c7384ab60 | ||
|
53f62674ae | ||
|
25bbf31f57 | ||
|
10f8d0f842 | ||
|
8d6f741738 | ||
|
feee37d75f | ||
|
801b72b92b | ||
|
759f396a2e | ||
|
6dd53ce63d | ||
|
a63946233b | ||
|
344eda55d4 | ||
|
5867be2914 | ||
|
51e7122f25 | ||
|
1e696b028a | ||
|
1f392517f8 | ||
|
82884da18c | ||
|
24a59ad3d2 | ||
|
969a462ac9 | ||
|
501ac016da | ||
|
feeb6802aa | ||
|
281e0a007b | ||
|
1d74482817 | ||
|
b57a70f373 | ||
|
dca9007ac7 | ||
|
cc9ca67664 | ||
|
53d67088ee | ||
|
10f2407f48 | ||
|
01491d303c | ||
|
47f1d42a7e | ||
|
2a8a60c2c5 | ||
|
58eec83a54 | ||
|
221ac0b9ab | ||
|
b2ae4490b9 | ||
|
51b13a8c54 | ||
|
f015b94176 | ||
|
41f66849c7 | ||
|
9c8075ba8e | ||
|
3e20b36e8f | ||
|
6a48476502 | ||
|
9eb2f78631 | ||
|
0e98529365 | ||
|
022d835565 | ||
|
5ab7d08a0a | ||
|
ef7713fbb2 | ||
|
d44f241317 | ||
|
d6b4444069 | ||
|
73d1caf8f2 | ||
|
d2cc8ccb11 | ||
|
5fbac49791 | ||
|
f7e349cea4 | ||
|
e736c3b36b | ||
|
dbda59e58a | ||
|
dd93c47abf | ||
|
f12886aefa | ||
|
7195c4d42c | ||
|
5d5224b322 | ||
|
0e0e41eabc | ||
|
89103b4747 | ||
|
9d39380705 | ||
|
c8336c45b9 | ||
|
4c7b22d37d | ||
|
579f1ef278 | ||
|
3d3fc81f48 | ||
|
3a215deff2 | ||
|
9d964d3fc3 | ||
|
60c0799958 | ||
|
44afb48447 | ||
|
c5ae225418 | ||
|
c5b7559856 | ||
|
8dc920228e | ||
|
3902aa222b | ||
|
d5f6fdb3c4 | ||
|
e85e327ae0 | ||
|
1091e3a37e | ||
|
8fa3fa76c3 | ||
|
50bb6e1179 | ||
|
029adbe531 | ||
|
33cbbf9f8b | ||
|
6e9b69a338 | ||
|
83182d2799 | ||
|
83266205d0 | ||
|
8016d78a4b | ||
|
a1aa0af8a4 | ||
|
c69773d7e8 | ||
|
246c269af8 | ||
|
4bc39d234d | ||
|
2b717bb195 | ||
|
ddb28b33a3 | ||
|
1c0a0c4c26 | ||
|
7dfe959f4b | ||
|
8f64dad282 | ||
|
821adc3041 | ||
|
e2b177c508 | ||
|
e837124f4b | ||
|
3fdc3cfbbf | ||
|
e9809de651 | ||
|
61f6479ea9 | ||
|
e84703b253 | ||
|
e4aa0c362e | ||
|
a183ea4ba7 | ||
|
6c7c176dc9 | ||
|
e6a8d0b4e6 | ||
|
db263df5d5 | ||
|
d1998d747d | ||
|
c0eaeb15af | ||
|
9bcfb92a00 | ||
|
d74fc56fa5 | ||
|
a44ed231c2 | ||
|
daae17851a | ||
|
ce19a7baef | ||
|
8d6e72dbfa | ||
|
6f4f6bff6b | ||
|
367b823466 | ||
|
c8ac42aad1 | ||
|
449bc7bcf3 | ||
|
3810413c00 | ||
|
f8f5d6cea2 | ||
|
cde35bebe9 | ||
|
49fee7c8db | ||
|
b5b1487f6a | ||
|
5cb567c138 | ||
|
d212fb59fe | ||
|
71314e47b1 | ||
|
ba2a737cce | ||
|
909c3dfe83 | ||
|
9d4fdc45d3 | ||
|
63fd38a04f | ||
|
50190ca669 | ||
|
0980fdfe8c | ||
|
bba306d414 | ||
|
a95326bec4 | ||
|
0f82948e4f | ||
|
8e1c3561be | ||
|
ff6f4680c4 | ||
|
adadb4e3c7 | ||
|
d282d24800 | ||
|
a196319edf | ||
|
3fadb4fc85 | ||
|
592e40ebe9 | ||
|
4068429ac7 | ||
|
88f70ce63c | ||
|
ac8ffb34e3 | ||
|
ef83f6831f | ||
|
600f339c4c | ||
|
7f691612ca | ||
|
a976f4dff9 | ||
|
696d6813e0 | ||
|
c48b6bf6bd | ||
|
2580235c72 | ||
|
3786f3742f | ||
|
d9708c92b4 | ||
|
e3aabe6959 | ||
|
1e1176b6eb | ||
|
219e64489c | ||
|
47ed9b2d39 | ||
|
6efdfe3234 | ||
|
e1640314df | ||
|
c16a27caa9 | ||
|
2ad17a6100 | ||
|
23c06a51cc | ||
|
badb70da48 | ||
|
447198f21b | ||
|
acb20338b1 | ||
|
73f7812045 | ||
|
989b89b12a | ||
|
20123d427b | ||
|
a05d89b1e5 | ||
|
92e6aa3653 | ||
|
b372fb6165 | ||
|
0cb2bbd01a | ||
|
a669b8a6bc | ||
|
719296133d | ||
|
86861f8379 | ||
|
e73a7e4006 | ||
|
aa4a45187e | ||
|
0a7d1e756f | ||
|
859f0f6b19 | ||
|
23ef5027c6 | ||
|
4ccbae320e | ||
|
ea83180761 | ||
|
f1a6c5fe17 | ||
|
bfa20d2758 | ||
|
dcd4f880a8 | ||
|
7f3ce06de9 | ||
|
8bebfde701 | ||
|
98096195dd | ||
|
642bca4c3d | ||
|
80b87107de | ||
|
c4c8a64111 | ||
|
470d402b17 | ||
|
1dc8cc1bce | ||
|
8687163f7f | ||
|
4e2bb7250f | ||
|
5461b00e89 | ||
|
16522cb0e3 | ||
|
c321680b3d | ||
|
f4633cb9c0 | ||
|
f62217b65d | ||
|
dfbdb5a135 | ||
|
b0b90dc0d7 | ||
|
9aa9e980a9 | ||
|
c4402500c7 | ||
|
755d2cb2e5 | ||
|
0affa24ce2 | ||
|
bf2f7b3af4 | ||
|
db61b876d6 | ||
|
f3ca6a92ad | ||
|
2941e1f1f3 | ||
|
721c4309c2 | ||
|
57727e554d | ||
|
b80b1cf92c | ||
|
5c5594ff16 | ||
|
65075896f2 | ||
|
32ba757501 | ||
|
4e6e2574ab | ||
|
41907b25f0 | ||
|
4bc2963320 | ||
|
4eb5e09873 | ||
|
b5b04912b5 | ||
|
f010dfffb9 | ||
|
5fd9a40b92 | ||
|
e0cad0f87a | ||
|
8ec8901921 | ||
|
702edb288e | ||
|
31306ce672 | ||
|
ac9aa44cb8 | ||
|
76f8436bfa | ||
|
61f488302f | ||
|
25cd53d775 | ||
|
060e55dfe3 | ||
|
b5c33341a1 | ||
|
6e420c7be2 | ||
|
d7f48472cc | ||
|
49779413aa | ||
|
8f450321fe | ||
|
86276832e0 | ||
|
61f321756f | ||
|
d44b8aa8c1 | ||
|
a6b5a513f9 | ||
|
c4a00affc5 | ||
|
522121be7e | ||
|
3fa1ebed62 | ||
|
7ac7600dc3 | ||
|
e9d4da7b56 | ||
|
c4664b5a9c | ||
|
203afa39c4 | ||
|
51cb20ec39 | ||
|
2a6054f836 | ||
|
8ac4a207f3 | ||
|
df4da02ab0 | ||
|
f1b090e9e0 | ||
|
611faaddef | ||
|
daa1b33247 | ||
|
fd83d4eec3 | ||
|
81be357925 | ||
|
79cbc92abf | ||
|
06c5dd0907 | ||
|
908d522057 | ||
|
4ce2e25c0b | ||
|
ef35619325 | ||
|
b1cd0189bc | ||
|
c95c46004a | ||
|
c3f75d1d85 | ||
|
c12ba58433 | ||
|
66355b4775 | ||
|
e9b8a89b3c | ||
|
93c7b9d7fc | ||
|
6d8b7ec188 | ||
|
446cd5a58b | ||
|
83a9dd82db | ||
|
3da13f0cc9 | ||
|
df8c09bcb3 | ||
|
8dcb8faf5d | ||
|
199c51d688 | ||
|
1792e193b1 | ||
|
bf35c66183 | ||
|
cb09e1ef7d | ||
|
0283826179 | ||
|
2f9d1c33e2 | ||
|
874809e0ca | ||
|
c364b60776 | ||
|
7598a92436 | ||
|
eb2ea8df1d | ||
|
9142ce8188 | ||
|
79514e5b8e | ||
|
bb9df5cdc9 | ||
|
e8613dbc93 | ||
|
cc8ea32501 | ||
|
38a7dc5488 | ||
|
5bd2724765 | ||
|
9fd693272f | ||
|
f7bad19e00 | ||
|
03ea0f3bfc | ||
|
2fc47b44c2 | ||
|
446e49d6db | ||
|
8bc9978909 | ||
|
1282bceeba | ||
|
d38b390ed4 | ||
|
63c3c4dbc3 | ||
|
afb9296e0d | ||
|
c9244ef83a | ||
|
a072c1997d | ||
|
3cb698ac15 | ||
|
0cc3647c1c | ||
|
3ffe47c6b7 | ||
|
c5aa7b65f7 | ||
|
01ba5ad213 | ||
|
a3a648bf6b | ||
|
887a512208 | ||
|
6f51e05553 | ||
|
5f4203bf9b | ||
|
8eaa7e9f04 | ||
|
76fd487818 | ||
|
07805cbeee | ||
|
c40f33ca04 | ||
|
4e17fc36d8 | ||
|
fd71b761ff | ||
|
d18eb10ecd | ||
|
9f2ae1cb85 | ||
|
32f0b5dbaf | ||
|
2efc7c1b05 | ||
|
9fbfb8ad32 | ||
|
74e2e5279c | ||
|
b980c8140b | ||
|
994e08aac1 | ||
|
8262cd71c4 | ||
|
2e3a0f39f6 | ||
|
4079b17dd9 | ||
|
1a1205f601 | ||
|
2d57a2df66 | ||
|
eb10da8bb7 | ||
|
3e0146f9bd | ||
|
1bbc8a153b | ||
|
3670b4f49e | ||
|
2f55d669a2 | ||
|
edc56202c1 | ||
|
7e5e67330b | ||
|
9fd0cd6a80 | ||
|
9b842e9ec7 | ||
|
0411eced89 | ||
|
2e93bdce0c | ||
|
8076100e14 | ||
|
fb62f1fb40 | ||
|
0085e719a9 | ||
|
6136db1409 | ||
|
110e3d7033 | ||
|
0dc179ee72 | ||
|
4c9a7b8a75 | ||
|
1770b887ec | ||
|
18d801a13d | ||
|
851c3d51ed | ||
|
5251733c0d | ||
|
c50b7e4eff | ||
|
d318f1b5e1 | ||
|
02a4ceabdd | ||
|
7d1368c51c | ||
|
758e8d7b41 | ||
|
530fea2bc4 | ||
|
3bd75adb1c | ||
|
01f531e9b1 | ||
|
a551a43164 | ||
|
a43ce7eabb | ||
|
9409419afb | ||
|
e0c9361b7d | ||
|
8b96f3d036 | ||
|
5ab5405b6f | ||
|
766f6e3eca | ||
|
12bcacf413 | ||
|
58f7410c9d | ||
|
ea3aae9c39 | ||
|
8904e00842 | ||
|
7d59b3b564 | ||
|
7f766cd762 | ||
|
73e635ce6e | ||
|
ecd5fa9c42 | ||
|
14215beb48 | ||
|
11ef1a9302 | ||
|
c1deec64cb | ||
|
2bb296531d | ||
|
ed386c84b6 | ||
|
7785d484ae | ||
|
706f63adfa | ||
|
ecffe8513e | ||
|
801461eea2 | ||
|
eee46a5094 | ||
|
09b5ce68a9 | ||
|
5625ce1b1a | ||
|
58278aa71c | ||
|
33fbe943e2 | ||
|
0dc12861ef | ||
|
67d8dafe44 | ||
|
3fb1c2e58d | ||
|
92d77e3fa8 | ||
|
48a677c4ac | ||
|
e3fa46f26f | ||
|
e2a8745abc | ||
|
3c0177a24b | ||
|
0103365697 | ||
|
45b8a499a7 | ||
|
bb24c13ed7 | ||
|
aabedcbcc7 | ||
|
f4cb21bb8a | ||
|
6044a9723a | ||
|
9189ea20b0 | ||
|
95d143eafe | ||
|
bef51aed03 | ||
|
1398485789 | ||
|
141a17e969 | ||
|
da67afe5f6 | ||
|
28bc85a20a | ||
|
978c7fadb3 | ||
|
d558cb69b0 | ||
|
0b07a6cf26 | ||
|
024a32a09b | ||
|
b47756385d | ||
|
ee470cc6a3 | ||
|
1a51b166a0 | ||
|
06b9200e91 | ||
|
f04e76811a | ||
|
817d9b15f7 | ||
|
150b603770 | ||
|
eb0b84c564 | ||
|
bb99f52712 | ||
|
bce09eb987 | ||
|
51cc1ff2c9 | ||
|
b4c44e659b | ||
|
de7604fa77 | ||
|
44bce3c74e | ||
|
3ba575216a | ||
|
4dae91a1fe | ||
|
94f23d00a7 | ||
|
e2cd92ea23 | ||
|
3a618e3d24 | ||
|
dd4b0b95d5 | ||
|
c8a5322d1f | ||
|
ca0308b60d | ||
|
6e6cc2922d | ||
|
eaf5e0289a | ||
|
f97e3548e5 | ||
|
e651ca8adb | ||
|
78e421e4ea | ||
|
a10c8df876 | ||
|
648f6a8e0c | ||
|
2b7ddcbb5c | ||
|
e3a8dc6e23 | ||
|
ca8dc2bde2 | ||
|
900419e85e | ||
|
3a99824638 | ||
|
bab918f049 | ||
|
ed594d7ba6 | ||
|
9211febbfc | ||
|
3069716510 | ||
|
dfab42c949 | ||
|
18819723c1 | ||
|
6bc35be10a | ||
|
b53989b195 | ||
|
726aaea0fe | ||
|
3f18a09c86 | ||
|
58985e6b37 | ||
|
ab1e0fa9bf | ||
|
85abbbb8fa | ||
|
ba66cf8d69 | ||
|
052fbde3ac | ||
|
1da05297ea | ||
|
f537e5a519 | ||
|
c4afdb7895 | ||
|
64179c3221 | ||
|
b7aa425344 | ||
|
9c1ece8978 | ||
|
bf348032bc | ||
|
25eeeaa65f | ||
|
09d2e58811 | ||
|
f4869f8de3 | ||
|
591470d86d | ||
|
a5436a3ac0 | ||
|
140d58b512 | ||
|
0a271938d8 | ||
|
33c8fe1221 | ||
|
532c340829 | ||
|
92ab0ef7d6 | ||
|
6e4fc5e1a8 | ||
|
4eb949625c | ||
|
9d5dc582be | ||
|
5a8dd0c549 | ||
|
c7808825b1 | ||
|
cb52279c3e | ||
|
9d5becb4de | ||
|
71072f5620 | ||
|
a18e54ecd7 | ||
|
3345218439 | ||
|
4ff1fabc86 | ||
|
4652fc5ac3 | ||
|
4573195894 | ||
|
310d6b9075 | ||
|
db19c46d6d | ||
|
1466daeafc | ||
|
dd1641ecc4 | ||
|
7dae6bb3b5 | ||
|
2e1b61e590 | ||
|
f293dbbf97 | ||
|
bf08a5b75e | ||
|
48ce0379bc | ||
|
d235aa068d | ||
|
ce57a6c6db | ||
|
d70632a7cf | ||
|
4333ecc43f | ||
|
a56125b0a8 | ||
|
23f03d4796 | ||
|
06ab10a1be | ||
|
6ee4012c0a | ||
|
46988af636 | ||
|
18ec22bffe | ||
|
1142201a3a | ||
|
69f9564a6d | ||
|
90441294db | ||
|
13fd466c18 | ||
|
b7f45e67dc | ||
|
02ab75b86a | ||
|
f6e476d7a8 | ||
|
b531b0bbef | ||
|
e2b19900ec | ||
|
3732cf2f97 | ||
|
2f1e2c492f | ||
|
860534399b | ||
|
4d46f8c25c | ||
|
5ddd5d29e5 | ||
|
440fff64a2 | ||
|
d2246df160 | ||
|
c04c4b95de | ||
|
7583351760 | ||
|
82e2e25325 | ||
|
2ba0277b52 | ||
|
542611cce4 | ||
|
c3c88ca8b4 | ||
|
6b3f7039b6 | ||
|
6b8458eb9f | ||
|
0bc7867ccd | ||
|
d69a7944c9 | ||
|
eb6f2df826 | ||
|
613b0d9548 | ||
|
325eaeb584 | ||
|
2f1073dc6e | ||
|
81c16c965e | ||
|
a4668a16b6 | ||
|
9588721197 | ||
|
99c6c4a51b | ||
|
321b2db067 | ||
|
1ff1c5be64 | ||
|
5084b39ea5 | ||
|
5904e3f6b3 | ||
|
db4632f4ba | ||
|
2600370659 | ||
|
9f3ba38314 | ||
|
b594f518b7 | ||
|
bbe8e02d74 | ||
|
652a7bbf80 | ||
|
1b0931fd92 | ||
|
96b550430a | ||
|
74b214a92a | ||
|
cc3f604310 | ||
|
c4255d12f7 | ||
|
74ff85a1a1 | ||
|
ce168ab5db | ||
|
f9ba7e648a | ||
|
d243e24f53 | ||
|
6e7f0860f7 | ||
|
750dd6014a | ||
|
6484053037 | ||
|
ec124607f4 | ||
|
baaf39b6f9 | ||
|
2cb1b65309 | ||
|
757dda9ade | ||
|
e717eaff86 | ||
|
eae0bb89fd | ||
|
0a3a83382f | ||
|
486aeda3a7 | ||
|
7ea0859362 | ||
|
2996e43ff7 | ||
|
36d1fefc19 | ||
|
4d5db58a3e | ||
|
47cf92039b | ||
|
c6c9d12275 | ||
|
0466ee2a83 | ||
|
19c95de8eb | ||
|
358e9e2847 | ||
|
c17f7ee694 | ||
|
de5a8c5cb4 | ||
|
bac30eb3e7 | ||
|
695e24dbce | ||
|
94d4b3c8e7 | ||
|
f4e931f18f | ||
|
569dc1919c | ||
|
fd383140cf | ||
|
26e1cd7ec4 | ||
|
d7d3166a27 | ||
|
2974b9cee9 | ||
|
8a6a4ad894 | ||
|
e36827af32 | ||
|
3a5196de1b | ||
|
4aa99f77ab | ||
|
f190b85182 | ||
|
8459015017 | ||
|
d0b65e148b | ||
|
25e8273d2f | ||
|
b67a49441f | ||
|
2310cd66e5 | ||
|
f939bce845 | ||
|
ed383eb5a0 | ||
|
c1713bfeac | ||
|
4a66d2fb22 | ||
|
81126027f5 | ||
|
1dbee391b4 | ||
|
56676ff923 | ||
|
a06ae54a18 | ||
|
58a142b56b | ||
|
0f2de4cfbe | ||
|
cfa326bbcc | ||
|
7581da5d92 | ||
|
41c2121e51 | ||
|
5df56b3980 | ||
|
9cdd161160 | ||
|
7c30c5eec4 | ||
|
5cbda43d63 | ||
|
30f31d23c6 | ||
|
bcdcc8be7d | ||
|
4dde96109b | ||
|
d31dc7a739 | ||
|
1ddb886a80 | ||
|
2e7efe47b6 | ||
|
a97147bc8a | ||
|
69f4f148dc | ||
|
50e444fa1d | ||
|
0181c1f76b | ||
|
f25c81a744 | ||
|
2cf23099eb | ||
|
e1dfd452c0 | ||
|
6916de5c0b | ||
|
45a51c07e2 | ||
|
d224fed0ce | ||
|
6acd8e28fc | ||
|
0b83f4c263 | ||
|
ccee26b065 | ||
|
4f96267033 | ||
|
315e40a49c | ||
|
a75dfe1c0d | ||
|
14b9762bca | ||
|
c1e04c63b3 | ||
|
1fdc18e6a0 | ||
|
f49c220c03 | ||
|
e280eb4055 | ||
|
d88424ef2a | ||
|
019f6e3c5a | ||
|
261972f929 | ||
|
39db1d09d1 | ||
|
92032f2da8 | ||
|
208ccfbe7c | ||
|
ee9d487081 | ||
|
cfb90a938e | ||
|
92501d4f80 | ||
|
02e6963325 | ||
|
b6dc307c99 | ||
|
47b52d9b28 | ||
|
541881e318 | ||
|
036500223d | ||
|
0726a6e12e | ||
|
cb5b335acd | ||
|
0011640ab1 | ||
|
3db6938caa | ||
|
85bf2eb441 | ||
|
4d9f2c3ec8 | ||
|
abb630108e | ||
|
9dd2534824 | ||
|
3cc7572f5d | ||
|
751d014cd6 | ||
|
639f22ea7c | ||
|
905b14237f | ||
|
ca671e5d7b | ||
|
58d5b042cd | ||
|
1fd69655fe | ||
|
e00365962b | ||
|
c2c05fcca8 | ||
|
42e6df723c | ||
|
209c26a1cb | ||
|
8d986727b3 | ||
|
46413b20a4 | ||
|
34fc215249 | ||
|
67a70ad112 | ||
|
df8aa69a99 | ||
|
8e292373ec | ||
|
6869d95890 | ||
|
37906e429a | ||
|
f56cebf5ba | ||
|
425507bd10 | ||
|
2f98a35fc4 | ||
|
30aa5e0a7c | ||
|
cab1d839b5 | ||
|
71e0057137 | ||
|
a183de04e3 | ||
|
818d6a11e7 | ||
|
73786c047f | ||
|
b00b429477 | ||
|
ec9acb3145 | ||
|
16b4d2cf3f | ||
|
8b6848c6db | ||
|
a4ee64050a | ||
|
942617f828 | ||
|
233c66b36e | ||
|
88ba095fd0 | ||
|
44744d6005 | ||
|
18ca987c92 | ||
|
f8f38c7c28 | ||
|
a06dab8d7a | ||
|
6ffbff0857 | ||
|
6fa42e919f | ||
|
9805f35c6f | ||
|
15ec54dd96 | ||
|
f903b4dda3 | ||
|
3f7f61e541 | ||
|
1e7a8ce5e4 | ||
|
397251ba0c | ||
|
df62ffbd25 | ||
|
149c9d2234 | ||
|
320a217b78 | ||
|
420f56c2e8 | ||
|
d9034b48a5 | ||
|
50158a1fc9 | ||
|
62470ee234 | ||
|
3d31d5c27b | ||
|
dfdc51246c | ||
|
bfc48fbc24 | ||
|
04a005f0e9 | ||
|
fccd0b00c2 | ||
|
9c6ea5386b | ||
|
7ad6899bf9 | ||
|
e4dcdcc955 | ||
|
62bd7624d2 | ||
|
7c3ab416ad | ||
|
2cacbc124c | ||
|
51f1cca852 | ||
|
cf14a6a7aa | ||
|
980970d390 | ||
|
80873b1538 | ||
|
1341b22081 | ||
|
6f9fcfdbb7 | ||
|
a5b6a5a3ad | ||
|
c2ea571005 | ||
|
ac3cc1adc5 | ||
|
c32c51a0fc | ||
|
501993ebf2 | ||
|
5d7d1823af | ||
|
1ffdedc11d | ||
|
c507d7b252 | ||
|
7ba02e0b7c | ||
|
15156cde18 | ||
|
0aa7c53c0b | ||
|
2a7ad70db5 | ||
|
dfd6438221 | ||
|
0ce67cb618 | ||
|
cba6fba123 | ||
|
ac0ecf3b4b | ||
|
0743ee9b3e | ||
|
c352008c95 | ||
|
d8126be578 | ||
|
45b7bba3d0 | ||
|
267fd5d76b | ||
|
d613cd17c7 | ||
|
d859cec696 | ||
|
c5496c7646 | ||
|
003b91f083 | ||
|
5692bf1517 | ||
|
e55fec9d9a | ||
|
00901bfbe0 | ||
|
a70dfb64a8 | ||
|
be5f1acc8f | ||
|
f3af8c8d04 | ||
|
b6f74e936e | ||
|
d4945f4422 | ||
|
5768afc776 | ||
|
a84e842189 | ||
|
6f86b62a1b | ||
|
ce21840a04 | ||
|
ae124439c4 | ||
|
777af661a2 | ||
|
c0ca6348e8 | ||
|
3be9074031 | ||
|
a2f23f9d22 | ||
|
bc5ae74c7d | ||
|
8100e901ab | ||
|
c2fd7c0344 | ||
|
7c13ffdbb1 | ||
|
a86f4411cb | ||
|
393a5b82ba | ||
|
af050dcaa7 | ||
|
5fbb13e0da | ||
|
16848f950b | ||
|
48a2a1a437 | ||
|
1465dab715 | ||
|
79c9151802 | ||
|
f651405427 | ||
|
b58ed1b243 | ||
|
c9174253fb | ||
|
91560e98c4 | ||
|
f476649c02 | ||
|
cd12c0e15c | ||
|
05230c0260 | ||
|
4ad0c0c0a8 | ||
|
c756133541 | ||
|
b621a63cf6 | ||
|
b0f5934234 | ||
|
e472383acb | ||
|
12c6f37f8e | ||
|
7aa27b000a | ||
|
31992eff9b | ||
|
d05f9e8124 | ||
|
c069c2c562 | ||
|
adcd65ba34 | ||
|
f0e2e8b930 | ||
|
83c0758d90 | ||
|
1d603eb5a8 | ||
|
4b6eb8072b | ||
|
908fb4ea71 | ||
|
c9c105c7db | ||
|
a79890efd6 | ||
|
32862e4379 | ||
|
8f18263759 | ||
|
11a435b469 | ||
|
0aacd4c72b | ||
|
8b08b78c03 | ||
|
ba92135a2b | ||
|
59d060fd5e | ||
|
bb07cb6a0d | ||
|
dc57ec0296 | ||
|
892e703b59 | ||
|
af2951ed53 | ||
|
de04573438 | ||
|
bfe418a58d | ||
|
00d4a4d4ac | ||
|
edfae95d90 | ||
|
de1809bd14 | ||
|
9feb034e34 | ||
|
3e068de0dc | ||
|
0d5941edbc | ||
|
fe4d084390 | ||
|
f586f4973a | ||
|
e4b4a9c4ac | ||
|
10945aa41a | ||
|
de03882d6c | ||
|
3d9a0d9e4b | ||
|
98c5fa9201 | ||
|
7428ce52ab | ||
|
a978320334 | ||
|
4f5281a92e | ||
|
86b3aa94e2 | ||
|
5b7d86d42b | ||
|
93eae69895 | ||
|
cd9ce2e31c | ||
|
c121f8c315 | ||
|
8edb9144cc | ||
|
60186c7b9d | ||
|
7745db6fc0 | ||
|
ea272152e0 | ||
|
e9c6325fc6 | ||
|
7504f14503 | ||
|
cf2772fab0 | ||
|
0dfffe53ec | ||
|
c16fcb7f46 | ||
|
6d7e57ba6a | ||
|
da45e73b4f | ||
|
d859de37d9 | ||
|
1242ba08e1 | ||
|
0c5427960b | ||
|
3c0c277579 | ||
|
0fb34b57b8 | ||
|
2be85f8fe0 | ||
|
eb52c803b8 | ||
|
f8871dedcf | ||
|
b7e0d4a7e1 | ||
|
5cb1ce470d | ||
|
888b928f0d | ||
|
b55f09c4e1 | ||
|
c7cd9b441d | ||
|
6ef0ff39f2 | ||
|
aeaf1c510f | ||
|
097140ac1a | ||
|
778a30a95e | ||
|
96c393a7a7 | ||
|
09013b357c | ||
|
d45f790f58 | ||
|
8c32594d3b | ||
|
f3cc5f8382 | ||
|
28bafffdc2 | ||
|
5db09d1865 | ||
|
c5631aa90d | ||
|
206de1a6b0 | ||
|
b943eebb1d | ||
|
3772a82a70 | ||
|
8fc67f3851 | ||
|
265bc26c21 | ||
|
735c9e8059 | ||
|
89cfbc3bbe | ||
|
bda86f0fd9 | ||
|
cc41cc4349 | ||
|
6513470f0d | ||
|
cee1a40651 | ||
|
1d42babd32 | ||
|
6b8143a84e | ||
|
8b74389e76 | ||
|
23a0e60b9b | ||
|
5381405eaa | ||
|
1a79a5049b | ||
|
9c201550dd | ||
|
39ec4cfea9 | ||
|
049d5642e5 | ||
|
5942979344 | ||
|
f1ff932caf | ||
|
b2414476ef | ||
|
16bdcce92d | ||
|
659f62e120 | ||
|
fc3e246c0f | ||
|
f284ae23bc | ||
|
0ef4a4cb23 | ||
|
56604f08a1 | ||
|
8dbacc7d01 | ||
|
2abc417834 | ||
|
39ebd5684b | ||
|
ac45789123 | ||
|
4608f6236f | ||
|
e90d4334ad | ||
|
9d2cbf8e97 | ||
|
746783f7a4 | ||
|
c2bdbb67b6 | ||
|
4d56383025 | ||
|
294ec5ac37 | ||
|
672dc4efa8 | ||
|
895456c4a2 | ||
|
120a84bd2f | ||
|
f92d61497a | ||
|
38864816fa | ||
|
49bbf11407 | ||
|
6fc12428e3 | ||
|
b32a334e3d | ||
|
60c602232f | ||
|
57f29bd61d | ||
|
1455159cf4 | ||
|
976c1053ef | ||
|
854f8c318c | ||
|
368d66c9cc | ||
|
22e23dbf29 | ||
|
81105ee013 | ||
|
883d6a2b34 | ||
|
24dae9bc4c | ||
|
15322e1b1a | ||
|
259d33c3c8 | ||
|
f5f89780cc | ||
|
aaacf48232 | ||
|
48fae7ccdc | ||
|
9e1f3feb12 | ||
|
208760f348 | ||
|
06725af40b | ||
|
639ccf254b | ||
|
552f8bc832 | ||
|
28a2b5b4aa | ||
|
334298d473 | ||
|
2d5507fce5 | ||
|
d92ce145bb | ||
|
d3fdc4af61 | ||
|
b4776ea3a2 | ||
|
3bd3a09160 | ||
|
bb04d400c9 | ||
|
73ab982d1b | ||
|
fed5b1d55c | ||
|
9a15ae2a92 | ||
|
609dea36ea | ||
|
9528d66c94 | ||
|
78acdcf677 | ||
|
dc1adeecdd | ||
|
4a43334376 | ||
|
83e8c32276 | ||
|
81c4ddf6eb | ||
|
309a606c2f | ||
|
ac02216e54 | ||
|
af5f0734c9 | ||
|
a5f61aa8c5 | ||
|
11d23e8ca5 | ||
|
50a21cb09f | ||
|
96871e4f74 | ||
|
4a666381bf | ||
|
110485d5bb | ||
|
87cd07b3af | ||
|
0bb6e00ba3 | ||
|
87d973e389 | ||
|
ef6b8123dc | ||
|
5ed7daa3d9 | ||
|
ef1723ef41 | ||
|
7547d7c791 | ||
|
88736b5557 | ||
|
9eadc4f146 | ||
|
97c8e7e0c7 | ||
|
e12a26c253 | ||
|
600036d158 | ||
|
4125552752 | ||
|
e294e46d46 | ||
|
7499148ad4 | ||
|
b58d061e41 | ||
|
6080045b2a | ||
|
293f44e6c1 | ||
|
01c8f1803a | ||
|
c2ed413203 | ||
|
8b40f475a3 | ||
|
668ae34e21 | ||
|
de79597ab9 | ||
|
ffa7f8201d | ||
|
ec6ee5c13b | ||
|
6d0a8dcd89 | ||
|
588a52891d | ||
|
b25c126ccd | ||
|
c7a1ff8720 | ||
|
284fd8f415 | ||
|
c5c7fa06aa | ||
|
debf836fcc | ||
|
a6e5846453 | ||
|
e715e46b6a | ||
|
bbba133f05 | ||
|
dec791d35d | ||
|
81c00728b8 | ||
|
a0096c5897 | ||
|
39eae9f009 | ||
|
d608926f81 | ||
|
03ee297aa2 | ||
|
3cd6e1d0a0 | ||
|
ec78354efa | ||
|
524d6a4dba | ||
|
f207eb7a0d | ||
|
601a7b4ce5 | ||
|
0cd5b0ed54 | ||
|
23c36f59b4 | ||
|
26a0c29587 | ||
|
a75314b41f | ||
|
1c64bb7140 | ||
|
9621ca4d64 | ||
|
8a6e4bda21 | ||
|
b30cc87b78 | ||
|
1f6844eb7e | ||
|
f0f100e67b | ||
|
500de919ed | ||
|
a15dd151ff | ||
|
2a40d3c603 | ||
|
3d341ebc7d | ||
|
29f04149b6 | ||
|
e44103264d | ||
|
6955c210b7 | ||
|
d1750e5eca | ||
|
c5a0c59a83 | ||
|
f7f015e84b | ||
|
f85b74763d | ||
|
fd8674a4bc | ||
|
d2e0c1ca13 | ||
|
3a9bf4ac10 | ||
|
40ac134c55 | ||
|
5cedc8f9b2 | ||
|
86b99b1e98 | ||
|
ac2a981c4f | ||
|
066afda2f6 | ||
|
8fe1e19522 | ||
|
f5d719d1f1 | ||
|
370a77f8e7 | ||
|
8aa51f682c | ||
|
58c19545c8 | ||
|
314ae1535e | ||
|
5f36f6ab21 | ||
|
1463cea949 | ||
|
73a0b4bba6 | ||
|
9b471436b2 | ||
|
b2e039d07b | ||
|
411da7c281 | ||
|
6d337bf23d | ||
|
dea5e43c83 | ||
|
043d2edcf6 | ||
|
f383af2729 | ||
|
890181e1d4 | ||
|
598da5cd49 | ||
|
b60e1088db | ||
|
bde439ef67 | ||
|
fc83af4432 | ||
|
337bc4a2fb | ||
|
6fac65f334 | ||
|
5a031d9233 | ||
|
e4e875fffe | ||
|
b945ba716b | ||
|
2207ef363a | ||
|
3a13b0e762 | ||
|
6429c3db11 | ||
|
5a9dc1c0ca | ||
|
4f2a4a3615 | ||
|
97431f29fe | ||
|
ffd0f8ddc3 | ||
|
c0725ba2d0 | ||
|
c40be2252a | ||
|
7021cdb1de | ||
|
cdb60a690d | ||
|
236eb82c3a | ||
|
cd12256575 | ||
|
472c22cc8a | ||
|
bcfaf3979a | ||
|
eb667e715a | ||
|
d6d0b22e66 | ||
|
af45872fdb | ||
|
b29fc6d4de | ||
|
a292d2c47f | ||
|
c1c816006e | ||
|
94e9669566 | ||
|
8048f36072 | ||
|
f6762d2ad9 | ||
|
3bb32befe9 | ||
|
48d6102b31 | ||
|
520e52f846 | ||
|
7af576e745 | ||
|
294f8a514f | ||
|
bc1a450124 | ||
|
0d1924c48b | ||
|
0fc7dc1c04 | ||
|
3a4a6c43a4 | ||
|
5432d93013 | ||
|
6a86b3ad9b | ||
|
7ff54005fe | ||
|
66767e3876 | ||
|
6d77a6e1c6 | ||
|
42dbcad3ef | ||
|
98fc525a2c | ||
|
ff2952f105 | ||
|
9aa4d098f0 | ||
|
a625a7bb81 | ||
|
816096e642 | ||
|
6b9795849d | ||
|
f9c14a8c8c | ||
|
5e80d9ee99 | ||
|
47bccbebae | ||
|
9ba991cad8 | ||
|
9c1c0da026 | ||
|
656437e0a5 | ||
|
6ad666e479 | ||
|
80d639a440 | ||
|
96ee3eff6c | ||
|
ff805d8d0e | ||
|
c3699d4fd1 | ||
|
4d4a9e7332 | ||
|
44c5097375 | ||
|
44db35fb1a | ||
|
ff1609f91e | ||
|
d9499f4301 | ||
|
16ab174290 | ||
|
046c7b053a | ||
|
6b8c661c49 | ||
|
2b06cefe66 | ||
|
7edd50f304 | ||
|
bbf00a96af | ||
|
329c8bacce | ||
|
c3facab495 | ||
|
1dd25be037 | ||
|
f6c8201e56 | ||
|
fe1967a4c4 | ||
|
452ab8fe72 | ||
|
399baa54c2 | ||
|
21d561885e | ||
|
73c74baa6a | ||
|
1f373a2baa | ||
|
4afaaf8a02 | ||
|
bda2ecdbf5 | ||
|
4c423f6d37 | ||
|
cc80a09d82 | ||
|
8052a4971e | ||
|
759515316e | ||
|
d727ddfccd | ||
|
65ccd6305f | ||
|
a2fad6ee05 | ||
|
fbc5c531b9 | ||
|
be31e7e71a | ||
|
844c23975f | ||
|
f2b83517aa | ||
|
ddc2a3499b | ||
|
d4d3134f6d | ||
|
5121846d34 | ||
|
0beb131c7f | ||
|
dda067f64d | ||
|
bf5067f50c | ||
|
4830b25136 | ||
|
1df6c8bfec | ||
|
9c1eba2af3 | ||
|
eaa9f5162f | ||
|
dfc4c27b24 | ||
|
88b2ef3b04 | ||
|
6523edb8a4 | ||
|
3b8515d2c9 | ||
|
4a50c9638c | ||
|
de8ee92ed8 | ||
|
76f5abdbdb | ||
|
fce86ab7d7 | ||
|
7683547728 | ||
|
2d8c894b27 | ||
|
236dd55dbe | ||
|
443ca983ad | ||
|
464fbcd921 | ||
|
384fab9627 | ||
|
0550659ce6 | ||
|
d10c4db57e | ||
|
321680ccd0 | ||
|
5f9ddfa46f | ||
|
7c128bbdac | ||
|
eb01d7f0e0 | ||
|
853e21d98e | ||
|
1c6efdbba7 | ||
|
ec718f76b5 | ||
|
3d15e58b0a | ||
|
8aa13d5dce | ||
|
861cbd5636 | ||
|
d33cb2b812 | ||
|
3e223523ce | ||
|
d295e97a0d | ||
|
77bd953da2 | ||
|
2f6ea8b103 | ||
|
a3d9b011a3 | ||
|
282903bb67 | ||
|
0d65d0eabd | ||
|
f00eaa4d00 | ||
|
d4255506ff | ||
|
117ec71994 | ||
|
4be7b620c2 | ||
|
a8cbe50c9f | ||
|
19f5795c27 | ||
|
6fe16a9e1a | ||
|
eadef35512 | ||
|
771dac9c5f | ||
|
0619df9835 | ||
|
7cc96429f2 | ||
|
26500b8c1b | ||
|
a109c7aeb8 | ||
|
27fdc26a74 | ||
|
3a66c3c9e1 | ||
|
499543cf1d | ||
|
902afa6b4c | ||
|
fff1a0c74f | ||
|
954499a494 | ||
|
44d14bc32e | ||
|
fbc8d21354 | ||
|
906d1179e9 | ||
|
dbb10fbd8c | ||
|
891ccb767c | ||
|
81e94de318 | ||
|
2282eb8dd5 | ||
|
3d8b1af6be | ||
|
2aa485b5af | ||
|
9821625a76 | ||
|
3562b0dc74 | ||
|
fd51b8501e | ||
|
09a2da835e | ||
|
770ee23f18 | ||
|
76010a51ef | ||
|
e34949be52 | ||
|
35fd24e857 | ||
|
7d60076b8b | ||
|
77171923f8 | ||
|
c4ffeb857e | ||
|
e5381320b9 | ||
|
86a46e8189 | ||
|
c2279da522 | ||
|
dc2074c46d | ||
|
362675e75b | ||
|
6ab0b65ed1 | ||
|
3f763d41e8 | ||
|
f71e919ecb | ||
|
e3c849da06 | ||
|
c0113872c5 | ||
|
deeec0b343 | ||
|
c7e810a985 | ||
|
2d947175b9 | ||
|
7026b96476 | ||
|
56ef5e9d48 | ||
|
0eb5fde2fd | ||
|
0935d2c304 | ||
|
b2f9709538 | ||
|
5cc7bf3876 | ||
|
416fbde726 | ||
|
1cc7c4bfb3 | ||
|
951842d785 | ||
|
591ad1dbc3 | ||
|
fcfe5c179b | ||
|
a0e979badb | ||
|
3aa9f01bdc | ||
|
4e5d2526cb | ||
|
ab63054f95 | ||
|
0c71967a53 | ||
|
b20cd352d9 | ||
|
3a4290f833 | ||
|
df48222f3e | ||
|
ee8e98711b | ||
|
87b50397a6 | ||
|
e309583f29 | ||
|
7ce1f3a142 | ||
|
db63cf7d24 | ||
|
cdafbcaad2 | ||
|
34055f9d0c | ||
|
9b17416580 | ||
|
833b9b62b5 | ||
|
3b0be0f12f | ||
|
4083639c3c | ||
|
8a758383d2 | ||
|
ad3b8a1c41 | ||
|
1b9ca01e4f | ||
|
30f4f25b2e | ||
|
a69daae012 | ||
|
99aa702015 | ||
|
d00f6dca28 | ||
|
fdecf813b6 | ||
|
f8f4ff2bb8 | ||
|
702a1e1cc7 | ||
|
8e355fbd75 | ||
|
701feabf49 | ||
|
d2878a8b0b | ||
|
663fb87976 | ||
|
d9d94141dc | ||
|
813535d38b | ||
|
afd0624587 | ||
|
ab3d3528a1 | ||
|
0ad38a9b87 | ||
|
cf1edc2b54 | ||
|
5b761b49ad | ||
|
102b6617da | ||
|
93015964c7 | ||
|
6fb2194d9c | ||
|
74b80e7211 | ||
|
59544321aa | ||
|
e785402b6a | ||
|
c485a7d12e | ||
|
413123f08a | ||
|
7d4d871d46 | ||
|
26d0d87f5b | ||
|
d6478a60aa | ||
|
ab57417175 | ||
|
f8042cb323 | ||
|
f5959c1c30 | ||
|
25de9a785c | ||
|
924642331b | ||
|
c9c457eda8 | ||
|
73c2a03d49 | ||
|
06af73bd1d | ||
|
9cebe308e9 | ||
|
558808c748 | ||
|
c68aabc852 | ||
|
46ef185709 | ||
|
46375f0592 | ||
|
558baffa2c | ||
|
4ebed495ed | ||
|
e6d41b54cd | ||
|
e06c16e884 | ||
|
72bc69e741 | ||
|
b33ffc11aa | ||
|
0a2c24003c | ||
|
9e58e11ad4 | ||
|
4c4d7dd01f | ||
|
adb3f2bcdd | ||
|
8afabae67d | ||
|
fccde0c1f7 | ||
|
3ca4655a18 | ||
|
349f893024 | ||
|
7b44b85730 | ||
|
329c8ab932 | ||
|
259768f27f | ||
|
741e8ecb7d | ||
|
63485b2c55 | ||
|
e4726cccf9 | ||
|
f11eec81e3 | ||
|
c3d51fc696 | ||
|
45881703c5 | ||
|
340fce2113 | ||
|
657404b75b | ||
|
35d1c94549 | ||
|
25189b29af | ||
|
47033afa5c | ||
|
de5bb4ca88 | ||
|
ff7027ffc0 | ||
|
0c1c9e74cd | ||
|
022639a145 | ||
|
5e16914a4e | ||
|
8f3b02f095 | ||
|
f593cbfec4 | ||
|
aab385d01b | ||
|
a51721cb09 | ||
|
061a4a295d | ||
|
ba05e32789 | ||
|
3e67017dfb | ||
|
d7e3ea68b3 | ||
|
bf0b083216 | ||
|
317d00b2a6 | ||
|
737a013377 | ||
|
78c1a74660 | ||
|
bd9b3d15e8 | ||
|
5681bf8016 | ||
|
348c6022f3 | ||
|
76b1ad7daf | ||
|
d39440bfb9 | ||
|
5ef669de08 | ||
|
20158d77d9 | ||
|
e7965a5eb8 | ||
|
3bff988f1e | ||
|
41196ccbf7 | ||
|
541a3db05b | ||
|
ae7291fb49 | ||
|
d43333ff71 | ||
|
0cdbd90d6b | ||
|
d0026da483 | ||
|
8d54739de5 | ||
|
135b61bc0b | ||
|
6adf2b71c2 | ||
|
87cca029d7 | ||
|
ae0b2cc196 | ||
|
1ac11b3dae | ||
|
0ff8b8fb54 | ||
|
c985d23c52 | ||
|
87a083d1b2 | ||
|
644b537014 | ||
|
67cd4ec0aa | ||
|
28b084ca25 | ||
|
503bd3fc0f | ||
|
f874b1bcad | ||
|
9e7de49fc5 | ||
|
06bc1f4f67 | ||
|
338d0b6103 | ||
|
3989d7e88b | ||
|
afea99a72b | ||
|
965c728914 | ||
|
46f3ee9594 | ||
|
323dcadea2 | ||
|
642faa1f65 | ||
|
d156d5bffd | ||
|
edf3ad5aed | ||
|
4aaae3dc65 | ||
|
9a4a1aac81 | ||
|
ee373a737c | ||
|
9e248fb24e | ||
|
08603378e8 | ||
|
834f4c7cd3 | ||
|
549b475be9 | ||
|
7e5fcdaf69 | ||
|
e3939f3339 | ||
|
cb2a4f2424 | ||
|
f564d8ed2c | ||
|
ba7d0d225a | ||
|
04b90328c0 | ||
|
a0af2852b6 | ||
|
b6c1a1bbbf | ||
|
00e393ce10 | ||
|
84d41e49b3 | ||
|
0c9282b84d | ||
|
18ba89863d | ||
|
444f102964 | ||
|
9e8464db1e | ||
|
738e133b24 | ||
|
01a257eb07 | ||
|
6558716018 | ||
|
9c87ae0d9d | ||
|
7ab16e99ee | ||
|
8a7a4275a8 | ||
|
3269572753 | ||
|
5070ab8004 | ||
|
02e7824e6a | ||
|
d83a1ba65b | ||
|
1bb21f3510 | ||
|
739686b1c5 | ||
|
c0f9821c35 | ||
|
cd48308a2a | ||
|
592b0dcfa7 | ||
|
20df81b0cc | ||
|
99acbd5ebe | ||
|
d1c93c3822 | ||
|
9e14cac318 | ||
|
f898833ea3 | ||
|
f3d1631aab | ||
|
8632452627 | ||
|
86708463f1 | ||
|
66146ed72b | ||
|
2b8484a29d | ||
|
18e3e6d6ab | ||
|
bfc5c08109 | ||
|
ad266d795e | ||
|
e422f19ee9 | ||
|
d0d5075914 | ||
|
896fde789e | ||
|
d63117ace5 | ||
|
66d7630705 | ||
|
63d3150dc4 | ||
|
cb81087b59 | ||
|
6139b145f0 | ||
|
f331821b27 | ||
|
5359dc0a10 | ||
|
7989765faa | ||
|
783a5754d5 | ||
|
897312de46 | ||
|
23c6b5f124 | ||
|
c2463b5323 | ||
|
ed2a05fc3f | ||
|
e3174a1a42 | ||
|
07878c6ca8 | ||
|
5e30f737b0 | ||
|
bd5c16e8da | ||
|
f2c55523c0 | ||
|
cb5f0823c6 | ||
|
9dd0c4add5 | ||
|
1b46863f24 | ||
|
3d83683a28 | ||
|
b7f0e81562 | ||
|
9d8d279d0d | ||
|
d888490f85 | ||
|
168eac319d | ||
|
73f69a7453 | ||
|
ec54257cb2 | ||
|
72ee347eab | ||
|
ac1abf3de6 | ||
|
bb90b0ff42 | ||
|
db56bdce33 | ||
|
f3a1027869 | ||
|
dd07b5193e | ||
|
3369fb27df | ||
|
4c6788644a | ||
|
a6cedafb27 | ||
|
e004384e46 | ||
|
e835e61f3a | ||
|
4130e5db3d | ||
|
c8c73eae59 | ||
|
c39efa6ba6 | ||
|
935d9d899c | ||
|
189229bbf9 | ||
|
b6c0217405 | ||
|
995ff5902f | ||
|
b0211ff7f8 | ||
|
0027ce1f6e | ||
|
06f18186dc | ||
|
2c570f641c | ||
|
fa68d66c98 | ||
|
32e790a47e | ||
|
ddf3d1a7ac | ||
|
c9c8485bc1 | ||
|
31f2be3dce | ||
|
250c416474 | ||
|
12171ca961 | ||
|
bae91855f5 | ||
|
f29b4cd7cb | ||
|
0232a987bb | ||
|
6a87e35bef | ||
|
8fd1558179 | ||
|
04cfcf91d9 | ||
|
3ec5ce9416 | ||
|
016554e437 | ||
|
bb7dd7b646 | ||
|
9c82b34be7 | ||
|
54fbdcf467 | ||
|
2e9289bcbf | ||
|
7fd0ccdffc | ||
|
ed49c7c246 | ||
|
0d90064e9e | ||
|
9158d0fd12 | ||
|
c4b11ec54e | ||
|
9e4019c5ff | ||
|
96edfb560b | ||
|
f6c52f4f41 | ||
|
7d94e5f33b | ||
|
e8a9d213e4 | ||
|
0998256fc5 | ||
|
a459075d26 | ||
|
70283a9f4a | ||
|
e1b37a066d | ||
|
d7c9c61420 | ||
|
79fd17ee63 | ||
|
7a3a6e3855 | ||
|
f83996cd9f | ||
|
7da73cbcca | ||
|
299b8096bc | ||
|
aed52d1632 | ||
|
9dce2aa735 | ||
|
953c3eab7b | ||
|
18fb522660 | ||
|
bd6f070882 | ||
|
a3fdef4ed4 | ||
|
dfd6ea3fca | ||
|
71a0f6ef85 | ||
|
d02c4da483 | ||
|
df595ae313 | ||
|
b4d21e7113 | ||
|
d722d6de36 | ||
|
76ae1019b9 | ||
|
a7f18b2297 | ||
|
d3632368e6 | ||
|
5a3fe7a8d1 | ||
|
be301f224d | ||
|
db6c7ff084 | ||
|
268dc9b308 | ||
|
549b0fc526 | ||
|
42b72fe246 | ||
|
f65d0dc081 | ||
|
af5d2e8e5f | ||
|
5159edbf0e | ||
|
4a2bf65fea | ||
|
db5c304e29 | ||
|
a0d721e109 | ||
|
2c10fda399 | ||
|
7ca20adc6d | ||
|
e0e64bcdf6 | ||
|
499cef3c2b | ||
|
2571767204 | ||
|
36ecff71ae | ||
|
a3c8510c05 | ||
|
042e1d5d0b | ||
|
ae17c775dc | ||
|
8ce613bb3a | ||
|
9d2299ed0b | ||
|
35db3665b3 | ||
|
5a5913828c | ||
|
448d6bef37 | ||
|
7056fdf2be | ||
|
3d81fd714b | ||
|
58a9082411 | ||
|
99a64edea8 | ||
|
d75b521af8 | ||
|
296c8f6a4a | ||
|
99cd8de234 | ||
|
5590be7a8c | ||
|
f084e6bbd0 | ||
|
cd719b08bd | ||
|
90e560bb75 | ||
|
9182dd7e5d | ||
|
f739e3e05d | ||
|
e7a044a2d1 | ||
|
ca72db23d2 | ||
|
e4a2a705ad | ||
|
bb91bb5e83 | ||
|
4760c3c0b5 | ||
|
1631e96a98 | ||
|
61c1261e4e | ||
|
956e1d8d90 | ||
|
453a5ac1d0 | ||
|
64d5fa1efd | ||
|
9d1d63afca | ||
|
44d4e7c500 | ||
|
f89f01f9d8 | ||
|
640cb1bb8d | ||
|
a81dc43fcd | ||
|
8a1f32b6a5 | ||
|
f9c2216ffa | ||
|
959f8b32d5 | ||
|
13f1357b7f | ||
|
3ce5fb8e5c | ||
|
46e8898f65 | ||
|
3003b10e0a | ||
|
0dc74545c0 | ||
|
254be4eeb2 | ||
|
541ef9247c | ||
|
e1a29266b2 | ||
|
fc3a57ff96 | ||
|
0cf85b24df | ||
|
eaba3d7349 | ||
|
57e59c14c8 | ||
|
0815c45bcd | ||
|
023a3a98a1 | ||
|
86221269f9 | ||
|
d9ddc5d4cd | ||
|
a7f7701b64 | ||
|
fd563e3274 | ||
|
d09d33bc2d | ||
|
7083391931 | ||
|
0f77139253 | ||
|
5b28b7dbc7 | ||
|
85fcb7b8df | ||
|
8b181c812f | ||
|
f01682ee01 | ||
|
aa57a89a21 | ||
|
7327be97aa | ||
|
63f881a5f0 | ||
|
dc0e63a48a | ||
|
f117bb64fc | ||
|
54209c1639 | ||
|
ec505bac41 | ||
|
2154662826 | ||
|
9ab52caf02 | ||
|
bc61ad9ec8 | ||
|
b0a6d61d73 | ||
|
371b24b17c | ||
|
79d4e81984 | ||
|
7e77a38cbc | ||
|
d6b79b9963 | ||
|
6f86573247 | ||
|
45be87afc6 | ||
|
5daf7983d1 | ||
|
f23e5ce2da | ||
|
e56b7c8419 | ||
|
2359c07ddf | ||
|
bc63339df3 | ||
|
a2e213bc7b | ||
|
6bfd4dfecf | ||
|
99ab3d43a7 | ||
|
353c876172 | ||
|
d61e31bae6 | ||
|
f3b96d4998 | ||
|
abbecb3e73 | ||
|
b39d9364d8 | ||
|
c7c16f805c | ||
|
f37cc5f5e1 | ||
|
3a4bee1096 | ||
|
c1a31ec9f7 | ||
|
f70ded8936 | ||
|
aa26f8eb40 | ||
|
cda2f0a162 | ||
|
aeb76ef174 | ||
|
e7c03ccdce | ||
|
d9cc27cb29 | ||
|
0ea61a74be | ||
|
007ecfbb29 | ||
|
9cd0475c08 | ||
|
8452708560 | ||
|
16781ba09a | ||
|
09ff5b5416 | ||
|
f093c9d39d | ||
|
2035cbbd5d | ||
|
5df535b7c2 | ||
|
232c931f40 | ||
|
f4dbb0c820 | ||
|
9058620cec | ||
|
2489252099 | ||
|
87dd685224 | ||
|
abfa4ad8bc | ||
|
3163d1269a | ||
|
1c6ca09992 | ||
|
d73db17ee3 | ||
|
127ab9114f | ||
|
d53f3b5596 | ||
|
d41a5bb97d | ||
|
551d2fabcc | ||
|
db40d26d08 | ||
|
525b55b1e9 | ||
|
ce0829d711 | ||
|
ac790fc49b | ||
|
f4757032e7 | ||
|
d1a70c3f05 | ||
|
d8419762c1 | ||
|
60a7405165 | ||
|
1ae9dacb4b | ||
|
69f49c8d39 | ||
|
822597db49 | ||
|
7fa5ee54b1 | ||
|
da80d649fd | ||
|
61673451ff | ||
|
599f61a1e0 | ||
|
0e3bac8132 | ||
|
fa9370b741 | ||
|
5881dcb887 | ||
|
a2b8305096 | ||
|
bd4da4474b | ||
|
dc5b5ee9c6 | ||
|
299eb54308 | ||
|
8d9ca46e0a | ||
|
b2080756fc | ||
|
9d0ec13596 | ||
|
6816ad5ed8 | ||
|
4e8690906c | ||
|
f0b72b8121 | ||
|
7a68ac6615 | ||
|
f131f84e13 | ||
|
6aa26a26d5 | ||
|
fd617fad00 | ||
|
d20eb11c9e | ||
|
c8d453e915 | ||
|
b293ed3061 | ||
|
64311faa68 | ||
|
26c92f056a | ||
|
ebc1bafb03 | ||
|
9dae70da79 | ||
|
f57bc1a21b | ||
|
af27b716e5 | ||
|
7c9c19b2a2 | ||
|
3b2f51602d | ||
|
ae6b30907d | ||
|
77c52ea701 | ||
|
3c00e41ec0 | ||
|
340c1cc68d | ||
|
2c79f2af6e | ||
|
4fafc34e49 | ||
|
d456fb797a | ||
|
458eda1321 | ||
|
54f926b11d | ||
|
a75d756a6f | ||
|
863613293e | ||
|
9af5cce4c7 | ||
|
e0906096c5 | ||
|
4549f2a9cc | ||
|
f4979422dd | ||
|
5a705c2468 | ||
|
36762f0eaf | ||
|
ac8a5d18d3 | ||
|
70a01cd444 | ||
|
959404e0e2 | ||
|
887bcfdf65 | ||
|
40ccd26b19 | ||
|
4412398c4b | ||
|
942d7a118a | ||
|
070b034cd5 | ||
|
9d78d317ae | ||
|
045f740892 | ||
|
b13806c150 | ||
|
4f6582cb66 | ||
|
1b3093fe3a | ||
|
237b704172 | ||
|
4d93f48f09 | ||
|
ed01d2ee3b | ||
|
386202895f | ||
|
0883810592 | ||
|
faca86620d | ||
|
6c23061a7d | ||
|
33446acf47 | ||
|
0a0a9d4fe9 | ||
|
9199b6b7eb | ||
|
2c5106ed06 | ||
|
6ed1541ef5 | ||
|
736aaf348b | ||
|
f0edd26998 | ||
|
ff1bfd01ba | ||
|
2ceb4f81e2 | ||
|
259805947e | ||
|
66c32e40e8 | ||
|
edfae9e78a | ||
|
d1ba46b6e1 | ||
|
c7b9394daf | ||
|
ab42f81c75 | ||
|
8b7b99f8d5 | ||
|
4a64d34001 | ||
|
95821f0132 | ||
|
a2a97e57f0 | ||
|
f2ebcee7c4 | ||
|
eed963e972 | ||
|
7ba8f11688 | ||
|
aa10faa591 | ||
|
358f55db6a | ||
|
c8c48640e6 | ||
|
0cac6ab615 | ||
|
2617598b7a | ||
|
8eea891718 | ||
|
386245a264 | ||
|
7d81ecbea6 | ||
|
8cf8fc6794 | ||
|
da0712ee7d | ||
|
a6f840b4dc | ||
|
0d5dc9a6e7 | ||
|
d81d3fa8cd | ||
|
c102780693 | ||
|
7f9dbc45b1 | ||
|
08e538e2e6 | ||
|
bd4b4292ef | ||
|
e12a1be1ca | ||
|
a74c014425 | ||
|
a2360de3f3 | ||
|
0e83c67525 | ||
|
1aefb50259 | ||
|
ec194b6374 | ||
|
f8ff8c0638 | ||
|
54c3e5c913 | ||
|
70c63c1208 | ||
|
bc7906e6d6 | ||
|
ae1bde1aa1 | ||
|
a8a256f9b5 | ||
|
8285a149d8 | ||
|
2a72d76d6f | ||
|
2d8e4a6544 | ||
|
c721884cf5 | ||
|
ee2b8f2e1b | ||
|
a3e27019e4 | ||
|
7e88f57aaa | ||
|
902f8cf292 | ||
|
f17c8c2eff | ||
|
c75bda867b | ||
|
8c200c2156 | ||
|
b0f7f4a991 | ||
|
01997f45ba | ||
|
251140fc88 | ||
|
aea0fa9fd5 | ||
|
912356133a | ||
|
250a95b6fe | ||
|
fd67eafc65 | ||
|
4c72377bbf | ||
|
7d8f55ec7c | ||
|
0ea20a0d52 | ||
|
5cf37ca89f | ||
|
3453710d10 | ||
|
6e7828e1d2 | ||
|
c96e4750d8 | ||
|
7bcfb4654f | ||
|
976963ab6d | ||
|
5a0db84b6c | ||
|
5a38a9c0ee | ||
|
956e69bf3a | ||
|
f1975b0213 | ||
|
e866c35462 | ||
|
57e8a11d17 | ||
|
f9950da3e3 | ||
|
aa42c0ff8e | ||
|
06da34d47a | ||
|
5cae08f2c3 | ||
|
8f31b139b8 | ||
|
ce4be668fe | ||
|
2e8b40004e | ||
|
1e8482356c | ||
|
e9c591b101 | ||
|
ee96a6a588 | ||
|
92b99f3273 | ||
|
ee75416e3e | ||
|
d86d12e911 | ||
|
2844d9597b | ||
|
dd1e2726f3 | ||
|
f18a032190 | ||
|
9cbde6c9fd | ||
|
f4e4992a4a | ||
|
31506f0771 | ||
|
85c2c138d2 | ||
|
c11104fed5 | ||
|
dfc01c68cd | ||
|
496cef956b | ||
|
b315c20756 | ||
|
c6278c15a8 | ||
|
0a0a6b2a4d | ||
|
1f7fc4d7a3 | ||
|
8ece321df3 | ||
|
1d7dcdb6c3 | ||
|
60183eebc3 | ||
|
36ca80d004 | ||
|
3f451f3042 | ||
|
c980dca234 | ||
|
f879cac1e7 | ||
|
ad510b2cd3 | ||
|
c74c708ed8 | ||
|
e053e21af6 | ||
|
7a64601428 | ||
|
b85ec2b9b6 | ||
|
d56a9cfe6a | ||
|
a32f270a47 | ||
|
8197f24dbc | ||
|
ef1698fd6d | ||
|
56888644a6 | ||
|
c613416af3 | ||
|
22ecb78b51 | ||
|
a6b245e46f | ||
|
0ae2767ae6 | ||
|
e64263653a | ||
|
d2b842ce07 | ||
|
d8371d0b3c | ||
|
e7140a36c0 | ||
|
aa744cadc8 | ||
|
63cac3c3cc | ||
|
bcff763b6e | ||
|
9ac2989edd | ||
|
1d60a609a9 | ||
|
4560176640 | ||
|
31a9966b9d | ||
|
c57cb6e89c | ||
|
b6596cdb19 | ||
|
9213d5cb3b | ||
|
682ff8936d | ||
|
f08a69e629 | ||
|
fadbab3781 | ||
|
3ca3c7f1c6 | ||
|
daee41e0d6 | ||
|
21000f13a1 | ||
|
a0e74c4db4 | ||
|
073342c887 | ||
|
6346d8eeaa | ||
|
094c416a80 | ||
|
99f5f8e76b | ||
|
cd4e053e5e | ||
|
2dc2bc4ab5 | ||
|
e219211ff6 | ||
|
df9fd1d3ae | ||
|
2e613a6ffc | ||
|
f5994e84a2 | ||
|
c93857922a | ||
|
6391128b41 | ||
|
7c5480eb96 | ||
|
67312653d7 | ||
|
e81b431701 | ||
|
695300929a | ||
|
82b415c9c1 | ||
|
d89a915b74 | ||
|
ac8dfd9386 | ||
|
1f6bfdea80 | ||
|
70e66e81e5 | ||
|
f0c1063a70 | ||
|
09165916fa | ||
|
c134a48016 | ||
|
75336dfc84 | ||
|
3f9e09a615 | ||
|
01486f6896 | ||
|
56c3f94ba3 | ||
|
073c0ebba3 | ||
|
362789a379 | ||
|
7f1d087cba | ||
|
3bd2c68eb4 | ||
|
71efc5bda8 | ||
|
f4d9297127 | ||
|
220e298417 | ||
|
f7813fad1c | ||
|
8b37734244 | ||
|
bbfff771d7 | ||
|
24f21583cd | ||
|
09c1be9674 | ||
|
af528552d6 | ||
|
20549a50cb | ||
|
8e840e1519 | ||
|
f56a309432 | ||
|
0904df84e2 | ||
|
fca42949a3 | ||
|
a1825ee741 | ||
|
84b6fcd02c | ||
|
ccb9233934 | ||
|
10ff071e33 | ||
|
390bffa81b | ||
|
0c9b1e7969 | ||
|
6a0d498c8e | ||
|
401ba1b879 | ||
|
07be13caa3 | ||
|
6d3a0c9506 | ||
|
0042954490 | ||
|
8a4149accc | ||
|
b98fa1c397 | ||
|
c6b826d796 | ||
|
2860c3be3e | ||
|
4b43480fe8 | ||
|
8b036d8a82 | ||
|
c46525b70b | ||
|
955542a654 | ||
|
2f1d5b6b04 | ||
|
151b8ed3a6 | ||
|
b235022c61 | ||
|
c10633f93a | ||
|
0d577aba26 | ||
|
c09bc2c608 | ||
|
fb87a05fe8 | ||
|
4d9b096663 | ||
|
29d7e31d89 | ||
|
dca121e903 | ||
|
0af4127fd1 | ||
|
a1eb49627a | ||
|
02038036ff | ||
|
f60d9fbe29 | ||
|
cc53db6652 | ||
|
a64fbe8928 | ||
|
eec540b227 | ||
|
77761e7bad | ||
|
40cd59207b | ||
|
3bca90b249 | ||
|
c4ee6d9b73 | ||
|
085c903229 | ||
|
8a40e30d08 | ||
|
63a8861c19 | ||
|
fb44838176 | ||
|
53ccdefc01 | ||
|
9857537053 | ||
|
b95a41ad72 | ||
|
6f0abbb71a | ||
|
4ca9f70b59 | ||
|
e18fc29bbf | ||
|
79d6e9cd32 | ||
|
aefe1325df | ||
|
11dc92dc0a | ||
|
bdeb44aeb2 | ||
|
e1323fc1b7 | ||
|
3ac950248d | ||
|
bef40851af | ||
|
9a52a30d2f | ||
|
fc163218c4 | ||
|
19ac0adf03 | ||
|
ac81c1dd1f | ||
|
6cc5a886ae | ||
|
9cbf3461f7 | ||
|
25004d4eee | ||
|
56236dfd3f | ||
|
68f336bd99 | ||
|
50973ec77c | ||
|
f82e08cf45 | ||
|
91a131aa6c | ||
|
3039925b27 | ||
|
8220cf37da | ||
|
0cb9711a15 | ||
|
055461ae41 | ||
|
89e6dfff71 | ||
|
5c8f91b229 | ||
|
8284ebd94c | ||
|
187323a606 | ||
|
6b877c35da | ||
|
deed8439d5 | ||
|
6305632493 | ||
|
eb6d330bb7 | ||
|
246d1f1f70 | ||
|
5360ae2cc5 | ||
|
e16eb3d0cb | ||
|
ca6f90dc6d | ||
|
835a7dbf0e | ||
|
225eb1b1a0 | ||
|
b8a903efbe | ||
|
7c22bbd3ad | ||
|
13e371af73 | ||
|
ae36e0899f | ||
|
b73c405013 | ||
|
8de6d3ff77 | ||
|
fd43558586 | ||
|
99ef3b6c52 | ||
|
65b6f8d3d5 | ||
|
b57a816038 | ||
|
11f996a096 | ||
|
ce0aab3643 | ||
|
c251e8db8d | ||
|
284822323a | ||
|
1f59be5188 | ||
|
cad87bf4e3 | ||
|
704628b903 | ||
|
636ff513b0 | ||
|
51206edb62 | ||
|
c5934fb6e3 | ||
|
d0bf509fa1 | ||
|
d6ec08ba89 | ||
|
65bf3ba260 | ||
|
bed598ce7f | ||
|
b1a16a298c | ||
|
fee593a07f | ||
|
fc8e23dec5 | ||
|
a3ddf464a2 | ||
|
a68f469030 | ||
|
f7c0a963f1 | ||
|
5b06607476 | ||
|
6b68b59032 | ||
|
0a89cd1a58 | ||
|
ca45ff1ae6 | ||
|
1cbfafafd2 | ||
|
f451994053 | ||
|
2c11e9009e | ||
|
f2a4073aea | ||
|
ec83db8978 | ||
|
a8d4213317 | ||
|
9421c11346 | ||
|
0615b3c532 | ||
|
2d635c0192 | ||
|
88a3e1d306 | ||
|
0674fabd0d | ||
|
c76a30af41 | ||
|
3c26734d60 | ||
|
2a7e34fe79 | ||
|
b2f0040da7 | ||
|
7afe7375e1 | ||
|
90eb731ff1 | ||
|
491d42bb1c | ||
|
45c0f58dc6 | ||
|
1fe2dcaa2a | ||
|
075934a944 | ||
|
ed4d7912c7 | ||
|
16eddc622e | ||
|
bc91f15ed3 | ||
|
118529a6dc | ||
|
33694baea1 | ||
|
f873890298 | ||
|
128d59c9cc | ||
|
2f57a559ac | ||
|
2f98f7c924 | ||
|
1f26815dd3 | ||
|
8218f6cd37 | ||
|
6233268964 | ||
|
ddbf4a73f5 | ||
|
4bf64976c1 | ||
|
23c947ab03 | ||
|
5677296d1b | ||
|
0e47c36a28 | ||
|
4334d25978 | ||
|
05ccb4d0e3 | ||
|
cb75734896 | ||
|
d5c850aab5 | ||
|
0a334b447f | ||
|
c2b9754857 | ||
|
fc3bdf8c11 | ||
|
c8b55f29e2 | ||
|
6094310704 | ||
|
0c4ca5f43e | ||
|
b010eea520 | ||
|
0fae47e974 | ||
|
c278e60131 | ||
|
2b42f73e3d | ||
|
136c8859a4 | ||
|
eb7c9b58fc | ||
|
7f7db1700b | ||
|
b270ded268 | ||
|
be16d274f8 | ||
|
66c5f1bb15 | ||
|
4b5a63aa11 | ||
|
ed82f1c5f1 | ||
|
3c570421d3 | ||
|
420cc8f68e | ||
|
6be5ccb530 | ||
|
a3730bd9be | ||
|
d6668347c8 | ||
|
871b8687a8 | ||
|
20c41364cc | ||
|
7bb0fbed13 | ||
|
37e048a7e2 | ||
|
f0e2098f1a | ||
|
15a94d6cf7 | ||
|
40a18d38a8 | ||
|
3d31caf4a5 | ||
|
17e14ed2d9 | ||
|
a99d5708e6 | ||
|
699108bfbb | ||
|
f97e35929b | ||
|
2164578738 | ||
|
952effa8b1 | ||
|
0dcf6436a8 | ||
|
05d23c7837 | ||
|
95c5c4d64e | ||
|
543ea5730b | ||
|
35510f7529 | ||
|
9251ae3bc7 | ||
|
2e07a8ae6b | ||
|
238adeaffb | ||
|
8941297ceb | ||
|
c03856bfdf | ||
|
7870937c77 | ||
|
46466f09d0 | ||
|
58c3df32f3 | ||
|
ef5dac7786 | ||
|
c2297b89d3 | ||
|
b75b004fe6 | ||
|
643836007f | ||
|
7d26c479ee | ||
|
24bad5dc7b | ||
|
67ea4eabc3 | ||
|
ace0c78373 | ||
|
570f42afd1 | ||
|
0198eaec45 | ||
|
57d61de25c | ||
|
5ef7590324 | ||
|
9d3dd64fe9 | ||
|
690d56f3c1 | ||
|
7b052eb70e | ||
|
ccd97886da | ||
|
f71630edb3 | ||
|
89c3e17c65 | ||
|
d2e64e26e5 | ||
|
57e4422bdb | ||
|
47d9dd0240 | ||
|
a1d6ada69a | ||
|
8c11b126e5 | ||
|
d380f939b5 | ||
|
efceed8c7f | ||
|
11f339733d | ||
|
5decbf184b | ||
|
e5d3ae2bf4 | ||
|
2970d712ee | ||
|
2d9d53be21 | ||
|
c58cf73c80 | ||
|
0aa8d538e1 | ||
|
510e5fc8c6 | ||
|
2b1bae0d75 | ||
|
127635409a | ||
|
b8bd8ce4cf | ||
|
14cf434bc3 | ||
|
5d94088eac | ||
|
95ee0cb188 | ||
|
5dee0fa1f8 | ||
|
ac2d47ff4c | ||
|
471a5a66b7 | ||
|
92a3236161 | ||
|
9893d09b43 | ||
|
62e3263467 | ||
|
9a3f35b028 | ||
|
714c920c20 | ||
|
abb948dab0 | ||
|
b7dbeda0d9 | ||
|
6d8dcdefa0 | ||
|
073e30ee15 | ||
|
a3db187e4f | ||
|
dc39061856 | ||
|
6c5f83b19b | ||
|
ff73841c60 | ||
|
e16ebc917d | ||
|
b8159d0919 | ||
|
6f23da603d | ||
|
066d5edf17 | ||
|
b7c5b30f14 | ||
|
262ec8ecda | ||
|
ed0512c76f | ||
|
cc0a3cc492 | ||
|
e93f582a78 | ||
|
76ebb175ca | ||
|
594c8e7b26 | ||
|
21aec6f567 | ||
|
ac4ccfa136 | ||
|
b717eb7e56 | ||
|
a04c955121 | ||
|
5cf623c58e | ||
|
60397a7800 | ||
|
da464a3fb3 | ||
|
ea49bb0612 | ||
|
e5ca987778 | ||
|
3d524fd3f1 | ||
|
8f6b24ce59 | ||
|
e0218c4f22 | ||
|
6c0d5d1198 | ||
|
3fee3c34f1 | ||
|
af081211ee | ||
|
15adff3d6d | ||
|
3636c2c6ed | ||
|
799760ab95 | ||
|
b85fc7187d | ||
|
14501f56aa | ||
|
10d4e4ace2 | ||
|
7b833291b3 | ||
|
f865d3e116 | ||
|
910d4f61e5 | ||
|
8d0078b6ef | ||
|
44c27ebc73 | ||
|
089a0022ae | ||
|
75f56406ce | ||
|
bcb6ad5fab | ||
|
44d66daaad | ||
|
7dcdf81b84 | ||
|
e3507a1be4 | ||
|
4981c7d370 | ||
|
ee642a2ff4 | ||
|
4da92281f6 | ||
|
da468a585b | ||
|
ed855783ed | ||
|
386f78035b | ||
|
da8916f926 | ||
|
e161b5a025 | ||
|
353031a014 | ||
|
993dd9a892 | ||
|
d7d6e8cfc8 | ||
|
7a6abc59ea | ||
|
12a29a677a | ||
|
274a3e21ba | ||
|
1d71c36de2 | ||
|
9043b91649 | ||
|
b88645d9eb | ||
|
b0419b60a0 | ||
|
ec9bbda3da | ||
|
18256c5f01 | ||
|
211c3398f6 | ||
|
539518292e | ||
|
f0c62688d2 | ||
|
3602602260 | ||
|
53924aeaf0 | ||
|
953147bf6b | ||
|
eb51acb89e | ||
|
6acc4cd7e1 | ||
|
b25925c95b | ||
|
b74f661ed9 | ||
|
7a7fa25d02 | ||
|
d78377ea5d | ||
|
fc049a2fd3 | ||
|
ae74b44c69 | ||
|
9be8903ca9 | ||
|
e338f4142f | ||
|
3a294a08bc | ||
|
d12ccb91a8 | ||
|
2151a9881f | ||
|
19772c3c97 | ||
|
16045d0877 | ||
|
5ed1ae5003 | ||
|
46c2b1e202 | ||
|
7348440524 | ||
|
a369a0cf65 | ||
|
f439179641 | ||
|
c258dd34a8 | ||
|
259967b7c6 | ||
|
daf41a2734 | ||
|
fb661e089f | ||
|
c602471b85 | ||
|
f325783abd | ||
|
f731a728c6 | ||
|
c1c0492859 | ||
|
3278887317 | ||
|
5c6a33b3e1 | ||
|
96f0593c8f | ||
|
b2c574891f | ||
|
08f9b705cd | ||
|
522a8b9f62 | ||
|
e430344347 | ||
|
f44feb6a10 | ||
|
b70001e618 | ||
|
e33e2c5175 | ||
|
5a32d4fcb1 | ||
|
8519d52ef5 | ||
|
74d001bc68 | ||
|
7f46f81dd7 | ||
|
8a07c59baa | ||
|
2ccc832b33 | ||
|
0416a7bfba | ||
|
b1c6e39620 | ||
|
d47324b898 | ||
|
0bc0e652a3 | ||
|
cc9c171978 | ||
|
0b0767939d | ||
|
9c2a7f1e8b | ||
|
f74fb50495 | ||
|
d22eb8a17f | ||
|
45ab7475d6 | ||
|
24d4475bdb | ||
|
b0ec69b360 | ||
|
da14f6a663 | ||
|
9d8af4bd6a | ||
|
fab73f2e7d | ||
|
1bf01b73f4 | ||
|
d06af4e517 | ||
|
a96687682a | ||
|
0b97ae2832 | ||
|
3cd4fd51ef | ||
|
d4f9250c5a | ||
|
24129368f1 | ||
|
14196548c5 | ||
|
d35e246111 | ||
|
4147fd6b2f | ||
|
bedcd2f377 | ||
|
58a9a261c4 | ||
|
2c43dd766d | ||
|
9bb1fcfad4 | ||
|
fa31dd80f5 | ||
|
2b247f3533 | ||
|
3e76ae5f50 | ||
|
f005efae72 | ||
|
394ffa7b0a | ||
|
6ac247317d | ||
|
dbc88c9645 | ||
|
cd7c03e1f6 | ||
|
a9e7a3db3e | ||
|
001cbd369d | ||
|
820bbb5b7b | ||
|
4bd490c28d | ||
|
dd268c48c9 | ||
|
d5a5f2f29f | ||
|
c4c63dd5e4 | ||
|
7ad48120d4 | ||
|
928bd42da4 | ||
|
27e9e3f6fa | ||
|
d2ccdcdc97 | ||
|
f7ae0e68c9 | ||
|
2e1710d88e | ||
|
373ff5a217 | ||
|
41363e0d27 | ||
|
e9bd18c57b | ||
|
f603275d84 | ||
|
8f18e67243 | ||
|
de022c4c80 | ||
|
9ec2ba2d28 | ||
|
d3c86e5178 | ||
|
1d7c51fb9f | ||
|
376f793bde | ||
|
fa9d2ac2ff | ||
|
6091c4e4aa | ||
|
49fb2a3376 | ||
|
6387f0e85d | ||
|
5be6c026f5 | ||
|
3a41d7c551 | ||
|
9b687f013d | ||
|
d807164776 | ||
|
8ce9b36e0f | ||
|
2667f47ffb | ||
|
bf67a5dcf4 | ||
|
e3a973a68d | ||
|
0afbc0c235 | ||
|
89352a2f52 | ||
|
165ab44f03 | ||
|
9a2da597c5 | ||
|
ee029a8cad | ||
|
d80962681a | ||
|
b9664ab615 | ||
|
7e2d39a2d1 | ||
|
9142be0a0d | ||
|
5576a72322 | ||
|
3b11f17a37 | ||
|
59419bd64a | ||
|
cfdd1b9418 | ||
|
89e6c60546 | ||
|
d00139eea8 | ||
|
b8d7506ebe | ||
|
f9606b8826 | ||
|
741bd71873 | ||
|
d75ed52bfc | ||
|
72815c0211 | ||
|
1503af60b0 | ||
|
8ca34ad6d8 | ||
|
46e4777fd6 | ||
|
7f2214aa2b | ||
|
cf28aed1a7 | ||
|
806ea639e6 | ||
|
d9cc0910c8 | ||
|
62860c221e | ||
|
96e446218c | ||
|
8646768801 | ||
|
95d4d650d4 | ||
|
e0d923bdf8 | ||
|
2788ce8c7b | ||
|
8d98532b65 | ||
|
a009fe15fd | ||
|
851bf43520 | ||
|
ba70a220e3 | ||
|
0895c2369c | ||
|
c2808f3040 | ||
|
eaace155ce | ||
|
e89a248e2e | ||
|
1dd8d571a4 | ||
|
46a5bd64ed | ||
|
1411a6e74b | ||
|
18acc0b30d | ||
|
7a7a201d81 | ||
|
2d4c66f7b5 | ||
|
6163b38ad9 | ||
|
afbb0b5f86 | ||
|
68cda4f213 | ||
|
8fd20bd4c3 | ||
|
9781f31f74 | ||
|
baf6946e06 | ||
|
1e7e34337f | ||
|
4faaf3e723 | ||
|
fbf88343de | ||
|
1ca5e76f7b | ||
|
1c6dca9383 | ||
|
56bf522913 | ||
|
2e23c9c568 | ||
|
0819383de0 | ||
|
efc4c79b5e | ||
|
aeba3cadd5 | ||
|
b4b7e6e5f7 | ||
|
7f28e8c445 | ||
|
f98f4f73aa | ||
|
08f93da17c | ||
|
0432e37843 | ||
|
ad3d6d9a22 | ||
|
1a49178330 | ||
|
dc273f7473 | ||
|
0a277ab591 | ||
|
1c9d1b0ee0 | ||
|
f098e726d3 | ||
|
b1a72bc7e2 | ||
|
3e3635b114 | ||
|
30bbb8bce3 | ||
|
68d8423288 | ||
|
b2fa0a921d | ||
|
80ae378f34 | ||
|
8c8c3617a7 | ||
|
31f57455dd | ||
|
cd7ec5f728 | ||
|
7393c1f99c | ||
|
333e63c091 | ||
|
9d953c0e03 | ||
|
e0d8ce3d2b | ||
|
7fd53815d3 | ||
|
b1fd2aaa8b | ||
|
08109b9bc0 | ||
|
58779b289e | ||
|
df5a3cbefe | ||
|
d1bfc86ffc | ||
|
5b682be59a | ||
|
1e0ab4015d | ||
|
9009e25cb1 | ||
|
8d970a4a97 | ||
|
d306d25e56 | ||
|
0dd6bca4f1 | ||
|
51864790fd | ||
|
6f754ab98b | ||
|
8f8405274c | ||
|
2bbe3f5f0a | ||
|
eed7b2776e | ||
|
cbc38a903b | ||
|
eeb685b0e5 | ||
|
b617c634a8 | ||
|
4cc0cede6d | ||
|
7dca8e7698 | ||
|
38aca6f605 | ||
|
68c4beab46 | ||
|
cbe1799797 | ||
|
3e995778fc | ||
|
b6af0a3809 | ||
|
a9674359ca | ||
|
ba110bf093 | ||
|
49f4b4be67 | ||
|
a5e851028e | ||
|
b3390a9840 | ||
|
8c3e64f4f6 | ||
|
3ee1238630 | ||
|
36888092af | ||
|
17a66931da | ||
|
915d1da1cd | ||
|
f1533de982 | ||
|
e980a4bd88 | ||
|
0bf09c30c6 | ||
|
72f6367b9b | ||
|
884435796a | ||
|
8a561d94e6 | ||
|
c5d70fe1d3 | ||
|
3690e4e82c | ||
|
6427ffde4d | ||
|
c63d46ceb8 | ||
|
fae8bdfa48 | ||
|
10dbee0d59 | ||
|
48875af7a1 | ||
|
df02498d03 | ||
|
583fb9f066 | ||
|
05933840f0 | ||
|
d67ef01f62 | ||
|
726f3feb2b | ||
|
e72013ea67 | ||
|
80583263a2 | ||
|
9013559eef | ||
|
177d4b6828 | ||
|
881de0df38 | ||
|
670195d720 | ||
|
003ed0f087 | ||
|
8598587f1c | ||
|
d9bd7ada76 | ||
|
52b8752e62 | ||
|
78a602ae8c | ||
|
2fcd64b9e8 | ||
|
741ab6bed1 | ||
|
11a6a669d1 | ||
|
58dbd0ea4d | ||
|
3e48f7d30c | ||
|
0b0f60f954 | ||
|
69f49a935a | ||
|
fec089d8f1 | ||
|
c3a61425b8 | ||
|
e7439b5cbe | ||
|
fb1cb6d364 | ||
|
f81931c591 | ||
|
c928c228af | ||
|
5fcdaa6a7f | ||
|
baa81126c4 | ||
|
3fc8aeb48d | ||
|
42e020c1c1 | ||
|
8ab4e55fe3 | ||
|
23314a6e27 | ||
|
6c610a8a95 | ||
|
c8e67b6732 | ||
|
4a449375a2 | ||
|
123641e4ec | ||
|
00dfe27f59 | ||
|
77a10c62c9 | ||
|
679e873875 | ||
|
df59b74ced | ||
|
7dfee8a3bd | ||
|
2aca613a61 | ||
|
018f77f0b8 | ||
|
edd766e70a | ||
|
4635f31270 | ||
|
3539885f0e | ||
|
4d7b63f489 | ||
|
f48bce5f68 | ||
|
905c3fe23e | ||
|
bae2fca523 | ||
|
c1a5068ebe | ||
|
cf07983a6e | ||
|
3d42411c3d | ||
|
1013758933 | ||
|
b957dcfece | ||
|
f9809e6e40 | ||
|
9e69009d1b | ||
|
433c70b403 | ||
|
662af75973 | ||
|
20ae71faa8 | ||
|
6095ade147 | ||
|
dd377637ca | ||
|
50906bf78b | ||
|
9bc037d045 | ||
|
d0e8fa627d | ||
|
2fc2fbb4ea | ||
|
5d29672b32 | ||
|
d92a6acf0e | ||
|
348abeb99d | ||
|
ba812b4495 | ||
|
0666f7c597 | ||
|
e8e7fe11e9 | ||
|
654234ec56 | ||
|
633867ecc6 | ||
|
339b531570 | ||
|
1f0fdede17 | ||
|
3829afec36 | ||
|
bdc371983e | ||
|
6645f23c4c | ||
|
43bdaa2f0e | ||
|
b2530c965c | ||
|
09d9c3d287 | ||
|
d29fe44e46 | ||
|
60062b51d8 | ||
|
dc7a1bbb1c | ||
|
bc53ecf298 | ||
|
54696dce05 | ||
|
9574ebe212 | ||
|
f661fb0fd3 | ||
|
7a1bbf99da | ||
|
32b0f7c9bb | ||
|
b82d4a65fe | ||
|
d66c64b9d7 | ||
|
fb5d0ef209 | ||
|
a69b71a37f | ||
|
4b88e24ebe | ||
|
1601fccebc | ||
|
27962ded4a | ||
|
a6e653be26 | ||
|
0e1c41998a | ||
|
72377b0251 | ||
|
b186045fee | ||
|
3f50b7d71c | ||
|
1db7d21283 | ||
|
78aed1fa4a | ||
|
70650f87a4 | ||
|
dafe519363 | ||
|
1846ad36a3 | ||
|
468056958b | ||
|
ec1608308c | ||
|
89c44bbc15 | ||
|
38aaad654b | ||
|
80a723cbcf | ||
|
e1c44267ea | ||
|
809001fe41 | ||
|
d77ba18d5d | ||
|
51d672890d | ||
|
403b304162 | ||
|
65a87ccc9b | ||
|
302d95c726 | ||
|
4365c35bf9 | ||
|
5dfb1f597b | ||
|
7dc9d9e27e | ||
|
7882f76da4 | ||
|
f821051443 | ||
|
e6269cba7f | ||
|
efc9853059 | ||
|
90ec557d60 | ||
|
a104879869 | ||
|
cc2f6e3b7b | ||
|
47b669bc9f | ||
|
ee65e72931 | ||
|
0cbcc4d828 | ||
|
ee2f4fb92d | ||
|
8137bdba61 | ||
|
a862428902 | ||
|
3366e494a1 | ||
|
618c59b01d | ||
|
5ed970b949 | ||
|
8faac8b963 | ||
|
1f3182924b | ||
|
fdaf0147b6 | ||
|
fe73d6439a | ||
|
f9fe5e5f9d | ||
|
4b07984d1b | ||
|
38a2324dc3 | ||
|
6fe85e8d5b | ||
|
696f16e901 | ||
|
8e9188aa5a | ||
|
cd03317c05 | ||
|
40a61f54e6 | ||
|
9a442702d1 | ||
|
31545abe14 | ||
|
0cc05fc492 | ||
|
df004be2fc | ||
|
3605407033 | ||
|
373903d851 | ||
|
05e6fc9aa9 | ||
|
cc6c0fc70a | ||
|
db1ce5aa26 | ||
|
b2b06eee02 | ||
|
6a676cc185 | ||
|
bf5e5f4269 | ||
|
0b6ca8e77b | ||
|
3758744eb6 | ||
|
39ec4f06ff | ||
|
87702febe0 | ||
|
0d84055eb6 | ||
|
9a86932c8b | ||
|
78dd988e12 | ||
|
793a491923 | ||
|
71f4a4afdf | ||
|
0f28aee9cd | ||
|
674e80c625 | ||
|
8a178e6717 | ||
|
8200e0c27b | ||
|
1482c89376 | ||
|
d41a31a508 | ||
|
a6bf4aae30 | ||
|
4897e5277b | ||
|
a0005121ae | ||
|
21ee46eea7 | ||
|
de3abc29ae | ||
|
67d4360453 | ||
|
563e88dd91 | ||
|
3909c2b2a0 | ||
|
247f371d3e | ||
|
958d68fb14 | ||
|
208f066e0e | ||
|
2725dfd8a6 | ||
|
330f14d27a | ||
|
ff6acd35d0 | ||
|
2140bd1c10 | ||
|
994f56c3f9 | ||
|
fe7bcbe340 | ||
|
7b61acbd35 | ||
|
1e5afd4fa9 | ||
|
8c1148b9ea | ||
|
df6fffb054 | ||
|
379fd6204d | ||
|
7569677e9e | ||
|
e38e7dbfb9 | ||
|
e373fd0c00 | ||
|
4dd5559162 | ||
|
8a3d232839 | ||
|
a375acdd26 | ||
|
a6bbc6aa8c | ||
|
4f42acd9ba | ||
|
161b2944b8 | ||
|
3d959f5b49 | ||
|
6837cf6a8d | ||
|
bd877d7b5a | ||
|
2582a0fd3b | ||
|
36791cb6af | ||
|
2e006fa500 | ||
|
b5a0c6da37 | ||
|
57275da903 | ||
|
92902e180e | ||
|
ff0e17174f | ||
|
63c02314cc | ||
|
5ec2c294ee | ||
|
3885f8a63e | ||
|
44c37f94e1 | ||
|
cd8a510ca9 | ||
|
96cba45d71 | ||
|
ae252cd5bc | ||
|
7fd80951ad | ||
|
97e1cf69c0 | ||
|
bb431df52b | ||
|
f9be4dc498 | ||
|
b4b42de9d5 | ||
|
182330ae40 | ||
|
983f2c494a | ||
|
bb80eea9d4 | ||
|
c08f229318 | ||
|
57b75f4a03 | ||
|
f88169a9e7 | ||
|
aa6e98e43c | ||
|
1ceb82bc74 | ||
|
3694379f26 | ||
|
973ae87309 | ||
|
61ee563df9 | ||
|
e5dd4b4ebf | ||
|
1d1b5da4bf | ||
|
04b4508a66 | ||
|
b397f63e00 | ||
|
30410fd355 | ||
|
6a13c416f6 | ||
|
ad3a7f2ab9 | ||
|
f6fc7916c4 | ||
|
8fe9ea7f4d | ||
|
a6b618d072 | ||
|
9c91a86720 | ||
|
6b51cc7530 | ||
|
f6a622bcef | ||
|
987c1f7d9f | ||
|
9fd6c1e343 | ||
|
f5092164e8 | ||
|
f6c06e3ed2 | ||
|
216b0fa6c9 | ||
|
3c81d184c0 | ||
|
76ebf750a4 | ||
|
36c14831b3 | ||
|
95cb492e41 | ||
|
f8ca37b903 | ||
|
9c54b78d9d | ||
|
4f11f285f9 | ||
|
13f4c62ba3 | ||
|
b4703b788b | ||
|
1210548cba | ||
|
875ccc27f6 | ||
|
7a13a3f4ba | ||
|
484948f5c0 | ||
|
b3397c2492 | ||
|
315f109427 | ||
|
875990a232 | ||
|
85b4f89926 | ||
|
9ac85b8b73 | ||
|
85232a5b26 | ||
|
56a2672831 | ||
|
b217ebc490 | ||
|
4b07f2f584 | ||
|
4071fa4a12 | ||
|
0003b29044 | ||
|
54f657ffbc | ||
|
e378590d33 | ||
|
a4d5fdd3c2 | ||
|
0d31f20cbd | ||
|
bbce167305 | ||
|
4fb2cc0f06 | ||
|
ce38ee8f26 | ||
|
6302978ff8 | ||
|
a61cbef02c | ||
|
cdac5ace14 | ||
|
3d76eabbca | ||
|
a47abe1b7b | ||
|
0d2a4b608c | ||
|
0d3a80e269 | ||
|
9e90907532 | ||
|
32af211f4c | ||
|
f517838c75 | ||
|
742da31932 | ||
|
9a9557ecfc | ||
|
38583be7af | ||
|
f6a2a98f1a | ||
|
d7d378eda1 | ||
|
d9968e6108 | ||
|
1b7e787733 | ||
|
a98ae89bde | ||
|
b023940032 | ||
|
f29c41bf6d | ||
|
ef046fae39 | ||
|
efe81620a0 | ||
|
7001e1ed61 | ||
|
89f9faa633 | ||
|
dbd13dee3a | ||
|
b9abdb50a3 | ||
|
1a43524018 | ||
|
5f5435eb1a | ||
|
80adb6979d | ||
|
3ddc763422 | ||
|
a58ae0b717 | ||
|
a00e42556f | ||
|
a423f23d28 | ||
|
ce515b81c5 | ||
|
bd9b9d425a | ||
|
e14b586d04 | ||
|
2cfaffb239 | ||
|
7f6ef764b9 | ||
|
005849331e | ||
|
cb9a3a7809 | ||
|
4051d51caf | ||
|
8abfc95013 | ||
|
3078001439 | ||
|
d7e9ac2aff | ||
|
86ff43b930 | ||
|
e8eea1bb7a | ||
|
2053745c8f | ||
|
27f7fbf35c | ||
|
12c78138dd | ||
|
063848798c | ||
|
7e3539df6f | ||
|
477199357f | ||
|
d70c3a807b | ||
|
cdb1ffb2f4 | ||
|
23b62afc72 | ||
|
cd6990c243 | ||
|
1f57b948b7 | ||
|
c2fdb44880 | ||
|
917faa5325 | ||
|
ac83627a31 | ||
|
cb5f61281a | ||
|
55e52c878a | ||
|
867c8a1083 | ||
|
5afc44aab1 | ||
|
999a03e4a7 | ||
|
2b3fc246b0 | ||
|
4135937876 | ||
|
d274b8297e | ||
|
867be74244 | ||
|
b14e23529f | ||
|
9080af56dd | ||
|
b4ad31ddd4 | ||
|
451d255b58 | ||
|
55d222a9f4 | ||
|
0cab07b2f1 | ||
|
54c84e63b3 | ||
|
681c16dd1e | ||
|
75b3692920 | ||
|
d4bd67bd67 | ||
|
abe32cefa3 | ||
|
b4aaa339d5 | ||
|
da10de022f | ||
|
49a55b410b | ||
|
ba7ae7b948 | ||
|
cb3f8ff59f | ||
|
431bc5a297 | ||
|
098d2fda52 | ||
|
483545252f | ||
|
0bfaf613a8 | ||
|
fb366891ab | ||
|
5b592669f9 | ||
|
c702010e57 | ||
|
dd3ca9adf7 | ||
|
a09e1e6e18 | ||
|
875bc27009 | ||
|
49db24ce27 | ||
|
4445314c68 | ||
|
87c3aa7389 | ||
|
1332c46b71 | ||
|
df7070eca2 | ||
|
16e4d79122 | ||
|
3bb964d806 | ||
|
1dcd672324 | ||
|
ef11c197b3 | ||
|
fe5d988947 | ||
|
b7e160a87d | ||
|
e334758ec2 | ||
|
ae17e97898 | ||
|
c9e5b92106 | ||
|
c8732dfa6f | ||
|
8aa87c564a | ||
|
5abecea34c | ||
|
3ec7b705c7 | ||
|
d25219b7e8 | ||
|
a5121e7a06 | ||
|
550256db1c | ||
|
028d3f6425 | ||
|
e42de4b8a2 | ||
|
57ef617251 | ||
|
837d3a94b7 | ||
|
4b854806d9 | ||
|
f741a98bac | ||
|
96d6ca4199 | ||
|
762265eab5 | ||
|
a617d64882 | ||
|
990ca80cb6 | ||
|
81bbe31d9f | ||
|
749a93295e | ||
|
7fd3a4e6d7 | ||
|
f0efc8c211 | ||
|
e960781511 | ||
|
f08ae96115 | ||
|
dff60e2e74 | ||
|
a9902ca331 | ||
|
c510cfd24b | ||
|
1c11062603 | ||
|
cf5a5773bf | ||
|
ab195ab0da | ||
|
5c8e53d5e9 | ||
|
7201d940a4 | ||
|
c707b7df95 | ||
|
a609bd56b4 | ||
|
8c88bf4006 | ||
|
26ab018253 | ||
|
ef8c044051 | ||
|
56680cd84a | ||
|
8410b1351e | ||
|
cb8c447f0d | ||
|
efac2cf1ab | ||
|
fb72066ef6 | ||
|
e3b9d0e3e8 | ||
|
771ea212de | ||
|
1d096ed145 | ||
|
f6374934db | ||
|
f5e4436453 | ||
|
f6e2737840 | ||
|
b9fdb9f701 | ||
|
e97b83bdbb | ||
|
51f81efb02 | ||
|
c3bd113a0b | ||
|
f4b78e73a4 | ||
|
3ec2eb8bf1 | ||
|
0d834b9394 | ||
![]() |
425eab3464 | ||
![]() |
9beeef6267 | ||
![]() |
6127d2ff1b | ||
![]() |
c92ec3a925 | ||
|
ee3d63b6be | ||
|
44c0e6b993 | ||
![]() |
3bc8ee998d | ||
![]() |
7f62300f7d | ||
![]() |
fccc39834a | ||
![]() |
d261bec1ec | ||
![]() |
1fa777c1d7 | ||
![]() |
2aaee73633 | ||
![]() |
a5c2b5ed89 | ||
![]() |
bbb1e35ea2 | ||
![]() |
b0ae92d605 | ||
![]() |
34f6d66742 | ||
![]() |
125d5c8d96 | ||
![]() |
2ab2bce74d | ||
![]() |
c5d4c87c02 | ||
![]() |
4e0cf7d4ed | ||
![]() |
a9f0e7d536 | ||
![]() |
f774a8d24e | ||
![]() |
81e0723d65 | ||
![]() |
b331ca784a | ||
![]() |
8114959e7e | ||
|
cd14e7e8fd | ||
|
35b4104daf | ||
![]() |
f7b38c4841 | ||
![]() |
0f6862ef30 | ||
![]() |
6cd7bf9f86 | ||
![]() |
3ffe2e768b | ||
![]() |
9e1f49c4e5 | ||
![]() |
8bec3a2aa1 | ||
![]() |
6c0566f937 | ||
![]() |
3bd898b6ce |
4
.eslintignore
Normal file
4
.eslintignore
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
extensions
|
||||||
|
extensions-disabled
|
||||||
|
repositories
|
||||||
|
venv
|
98
.eslintrc.js
Normal file
98
.eslintrc.js
Normal file
@ -0,0 +1,98 @@
|
|||||||
|
/* global module */
|
||||||
|
module.exports = {
|
||||||
|
env: {
|
||||||
|
browser: true,
|
||||||
|
es2021: true,
|
||||||
|
},
|
||||||
|
extends: "eslint:recommended",
|
||||||
|
parserOptions: {
|
||||||
|
ecmaVersion: "latest",
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
"arrow-spacing": "error",
|
||||||
|
"block-spacing": "error",
|
||||||
|
"brace-style": "error",
|
||||||
|
"comma-dangle": ["error", "only-multiline"],
|
||||||
|
"comma-spacing": "error",
|
||||||
|
"comma-style": ["error", "last"],
|
||||||
|
"curly": ["error", "multi-line", "consistent"],
|
||||||
|
"eol-last": "error",
|
||||||
|
"func-call-spacing": "error",
|
||||||
|
"function-call-argument-newline": ["error", "consistent"],
|
||||||
|
"function-paren-newline": ["error", "consistent"],
|
||||||
|
"indent": ["error", 4],
|
||||||
|
"key-spacing": "error",
|
||||||
|
"keyword-spacing": "error",
|
||||||
|
"linebreak-style": ["error", "unix"],
|
||||||
|
"no-extra-semi": "error",
|
||||||
|
"no-mixed-spaces-and-tabs": "error",
|
||||||
|
"no-multi-spaces": "error",
|
||||||
|
"no-redeclare": ["error", {builtinGlobals: false}],
|
||||||
|
"no-trailing-spaces": "error",
|
||||||
|
"no-unused-vars": "off",
|
||||||
|
"no-whitespace-before-property": "error",
|
||||||
|
"object-curly-newline": ["error", {consistent: true, multiline: true}],
|
||||||
|
"object-curly-spacing": ["error", "never"],
|
||||||
|
"operator-linebreak": ["error", "after"],
|
||||||
|
"quote-props": ["error", "consistent-as-needed"],
|
||||||
|
"semi": ["error", "always"],
|
||||||
|
"semi-spacing": "error",
|
||||||
|
"semi-style": ["error", "last"],
|
||||||
|
"space-before-blocks": "error",
|
||||||
|
"space-before-function-paren": ["error", "never"],
|
||||||
|
"space-in-parens": ["error", "never"],
|
||||||
|
"space-infix-ops": "error",
|
||||||
|
"space-unary-ops": "error",
|
||||||
|
"switch-colon-spacing": "error",
|
||||||
|
"template-curly-spacing": ["error", "never"],
|
||||||
|
"unicode-bom": "error",
|
||||||
|
},
|
||||||
|
globals: {
|
||||||
|
//script.js
|
||||||
|
gradioApp: "readonly",
|
||||||
|
executeCallbacks: "readonly",
|
||||||
|
onAfterUiUpdate: "readonly",
|
||||||
|
onOptionsChanged: "readonly",
|
||||||
|
onUiLoaded: "readonly",
|
||||||
|
onUiUpdate: "readonly",
|
||||||
|
uiCurrentTab: "writable",
|
||||||
|
uiElementInSight: "readonly",
|
||||||
|
uiElementIsVisible: "readonly",
|
||||||
|
//ui.js
|
||||||
|
opts: "writable",
|
||||||
|
all_gallery_buttons: "readonly",
|
||||||
|
selected_gallery_button: "readonly",
|
||||||
|
selected_gallery_index: "readonly",
|
||||||
|
switch_to_txt2img: "readonly",
|
||||||
|
switch_to_img2img_tab: "readonly",
|
||||||
|
switch_to_img2img: "readonly",
|
||||||
|
switch_to_sketch: "readonly",
|
||||||
|
switch_to_inpaint: "readonly",
|
||||||
|
switch_to_inpaint_sketch: "readonly",
|
||||||
|
switch_to_extras: "readonly",
|
||||||
|
get_tab_index: "readonly",
|
||||||
|
create_submit_args: "readonly",
|
||||||
|
restart_reload: "readonly",
|
||||||
|
updateInput: "readonly",
|
||||||
|
onEdit: "readonly",
|
||||||
|
//extraNetworks.js
|
||||||
|
requestGet: "readonly",
|
||||||
|
popup: "readonly",
|
||||||
|
// profilerVisualization.js
|
||||||
|
createVisualizationTable: "readonly",
|
||||||
|
// from python
|
||||||
|
localization: "readonly",
|
||||||
|
// progrssbar.js
|
||||||
|
randomId: "readonly",
|
||||||
|
requestProgress: "readonly",
|
||||||
|
// imageviewer.js
|
||||||
|
modalPrevImage: "readonly",
|
||||||
|
modalNextImage: "readonly",
|
||||||
|
// localStorage.js
|
||||||
|
localSet: "readonly",
|
||||||
|
localGet: "readonly",
|
||||||
|
localRemove: "readonly",
|
||||||
|
// resizeHandle.js
|
||||||
|
setupResizeHandle: "writable"
|
||||||
|
}
|
||||||
|
};
|
2
.git-blame-ignore-revs
Normal file
2
.git-blame-ignore-revs
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
# Apply ESlint
|
||||||
|
9c54b78d9dde5601e916f308d9a9d6953ec39430
|
97
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
97
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
@ -1,35 +1,55 @@
|
|||||||
name: Bug Report
|
name: Bug Report
|
||||||
description: You think somethings is broken in the UI
|
description: You think something is broken in the UI
|
||||||
title: "[Bug]: "
|
title: "[Bug]: "
|
||||||
labels: ["bug-report"]
|
labels: ["bug-report"]
|
||||||
|
|
||||||
body:
|
body:
|
||||||
- type: checkboxes
|
|
||||||
attributes:
|
|
||||||
label: Is there an existing issue for this?
|
|
||||||
description: Please search to see if an issue already exists for the bug you encountered, and that it hasn't been fixed in a recent build/commit.
|
|
||||||
options:
|
|
||||||
- label: I have searched the existing issues and checked the recent builds/commits
|
|
||||||
required: true
|
|
||||||
- type: markdown
|
- type: markdown
|
||||||
attributes:
|
attributes:
|
||||||
value: |
|
value: |
|
||||||
*Please fill this form with as much information as possible, don't forget to fill "What OS..." and "What browsers" and *provide screenshots if possible**
|
> The title of the bug report should be short and descriptive.
|
||||||
|
> Use relevant keywords for searchability.
|
||||||
|
> Do not leave it blank, but also do not put an entire error log in it.
|
||||||
|
- type: checkboxes
|
||||||
|
attributes:
|
||||||
|
label: Checklist
|
||||||
|
description: |
|
||||||
|
Please perform basic debugging to see if extensions or configuration is the cause of the issue.
|
||||||
|
Basic debug procedure
|
||||||
|
1. Disable all third-party extensions - check if extension is the cause
|
||||||
|
2. Update extensions and webui - sometimes things just need to be updated
|
||||||
|
3. Backup and remove your config.json and ui-config.json - check if the issue is caused by bad configuration
|
||||||
|
4. Delete venv with third-party extensions disabled - sometimes extensions might cause wrong libraries to be installed
|
||||||
|
5. Try a fresh installation webui in a different directory - see if a clean installation solves the issue
|
||||||
|
Before making a issue report please, check that the issue hasn't been reported recently.
|
||||||
|
options:
|
||||||
|
- label: The issue exists after disabling all extensions
|
||||||
|
- label: The issue exists on a clean installation of webui
|
||||||
|
- label: The issue is caused by an extension, but I believe it is caused by a bug in the webui
|
||||||
|
- label: The issue exists in the current version of the webui
|
||||||
|
- label: The issue has not been reported before recently
|
||||||
|
- label: The issue has been reported before but has not been fixed yet
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
> Please fill this form with as much information as possible. Don't forget to "Upload Sysinfo" and "What browsers" and provide screenshots if possible
|
||||||
- type: textarea
|
- type: textarea
|
||||||
id: what-did
|
id: what-did
|
||||||
attributes:
|
attributes:
|
||||||
label: What happened?
|
label: What happened?
|
||||||
description: Tell us what happened in a very clear and simple way
|
description: Tell us what happened in a very clear and simple way
|
||||||
|
placeholder: |
|
||||||
|
txt2img is not working as intended.
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: true
|
||||||
- type: textarea
|
- type: textarea
|
||||||
id: steps
|
id: steps
|
||||||
attributes:
|
attributes:
|
||||||
label: Steps to reproduce the problem
|
label: Steps to reproduce the problem
|
||||||
description: Please provide us with precise step by step information on how to reproduce the bug
|
description: Please provide us with precise step by step instructions on how to reproduce the bug
|
||||||
value: |
|
placeholder: |
|
||||||
1. Go to ....
|
1. Go to ...
|
||||||
2. Press ....
|
2. Press ...
|
||||||
3. ...
|
3. ...
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: true
|
||||||
@ -37,28 +57,11 @@ body:
|
|||||||
id: what-should
|
id: what-should
|
||||||
attributes:
|
attributes:
|
||||||
label: What should have happened?
|
label: What should have happened?
|
||||||
description: Tell what you think the normal behavior should be
|
description: Tell us what you think the normal behavior should be
|
||||||
|
placeholder: |
|
||||||
|
WebUI should ...
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: true
|
||||||
- type: input
|
|
||||||
id: commit
|
|
||||||
attributes:
|
|
||||||
label: Commit where the problem happens
|
|
||||||
description: Which commit are you running ? (Do not write *Latest version/repo/commit*, as this means nothing and will have changed by the time we read your issue. Rather, copy the **Commit** link at the bottom of the UI, or from the cmd/terminal if you can't launch it.)
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: dropdown
|
|
||||||
id: platforms
|
|
||||||
attributes:
|
|
||||||
label: What platforms do you use to access the UI ?
|
|
||||||
multiple: true
|
|
||||||
options:
|
|
||||||
- Windows
|
|
||||||
- Linux
|
|
||||||
- MacOS
|
|
||||||
- iOS
|
|
||||||
- Android
|
|
||||||
- Other/Cloud
|
|
||||||
- type: dropdown
|
- type: dropdown
|
||||||
id: browsers
|
id: browsers
|
||||||
attributes:
|
attributes:
|
||||||
@ -70,26 +73,25 @@ body:
|
|||||||
- Brave
|
- Brave
|
||||||
- Apple Safari
|
- Apple Safari
|
||||||
- Microsoft Edge
|
- Microsoft Edge
|
||||||
|
- Android
|
||||||
|
- iOS
|
||||||
|
- Other
|
||||||
- type: textarea
|
- type: textarea
|
||||||
id: cmdargs
|
id: sysinfo
|
||||||
attributes:
|
attributes:
|
||||||
label: Command Line Arguments
|
label: Sysinfo
|
||||||
description: Are you using any launching parameters/command line arguments (modified webui-user .bat/.sh) ? If yes, please write them below. Write "No" otherwise.
|
description: System info file, generated by WebUI. You can generate it in settings, on the Sysinfo page. Drag the file into the field to upload it. If you submit your report without including the sysinfo file, the report will be closed. If needed, review the report to make sure it includes no personal information you don't want to share. If you can't start WebUI, you can use --dump-sysinfo commandline argument to generate the file.
|
||||||
render: Shell
|
placeholder: |
|
||||||
validations:
|
1. Go to WebUI Settings -> Sysinfo -> Download system info.
|
||||||
required: true
|
If WebUI fails to launch, use --dump-sysinfo commandline argument to generate the file
|
||||||
- type: textarea
|
2. Upload the Sysinfo as a attached file, Do NOT paste it in as plain text.
|
||||||
id: extensions
|
|
||||||
attributes:
|
|
||||||
label: List of extensions
|
|
||||||
description: Are you using any extensions other than built-ins? If yes, provide a list, you can copy it at "Extensions" tab. Write "No" otherwise.
|
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: true
|
||||||
- type: textarea
|
- type: textarea
|
||||||
id: logs
|
id: logs
|
||||||
attributes:
|
attributes:
|
||||||
label: Console logs
|
label: Console logs
|
||||||
description: Please provide **full** cmd/terminal logs from the moment you started UI to the end of it, after your bug happened. If it's very long, provide a link to pastebin or similar service.
|
description: Please provide **full** cmd/terminal logs from the moment you started UI to the end of it, after the bug occurred. If it's very long, provide a link to pastebin or similar service.
|
||||||
render: Shell
|
render: Shell
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: true
|
||||||
@ -97,4 +99,7 @@ body:
|
|||||||
id: misc
|
id: misc
|
||||||
attributes:
|
attributes:
|
||||||
label: Additional information
|
label: Additional information
|
||||||
description: Please provide us with any relevant additional info or context.
|
description: |
|
||||||
|
Please provide us with any relevant additional info or context.
|
||||||
|
Examples:
|
||||||
|
I have updated my GPU driver recently.
|
||||||
|
33
.github/pull_request_template.md
vendored
33
.github/pull_request_template.md
vendored
@ -1,28 +1,15 @@
|
|||||||
# Please read the [contributing wiki page](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Contributing) before submitting a pull request!
|
## Description
|
||||||
|
|
||||||
If you have a large change, pay special attention to this paragraph:
|
* a simple description of what you're trying to accomplish
|
||||||
|
* a summary of changes in code
|
||||||
|
* which issues it fixes, if any
|
||||||
|
|
||||||
> Before making changes, if you think that your feature will result in more than 100 lines changing, find me and talk to me about the feature you are proposing. It pains me to reject the hard work someone else did, but I won't add everything to the repo, and it's better if the rejection happens before you have to waste time working on the feature.
|
## Screenshots/videos:
|
||||||
|
|
||||||
Otherwise, after making sure you're following the rules described in wiki page, remove this section and continue on.
|
|
||||||
|
|
||||||
**Describe what this pull request is trying to achieve.**
|
## Checklist:
|
||||||
|
|
||||||
A clear and concise description of what you're trying to accomplish with this, so your intent doesn't have to be extracted from your code.
|
- [ ] I have read [contributing wiki page](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Contributing)
|
||||||
|
- [ ] I have performed a self-review of my own code
|
||||||
**Additional notes and description of your changes**
|
- [ ] My code follows the [style guidelines](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Contributing#code-style)
|
||||||
|
- [ ] My code passes [tests](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Tests)
|
||||||
More technical discussion about your changes go here, plus anything that a maintainer might have to specifically take a look at, or be wary of.
|
|
||||||
|
|
||||||
**Environment this was tested in**
|
|
||||||
|
|
||||||
List the environment you have developed / tested this on. As per the contributing page, changes should be able to work on Windows out of the box.
|
|
||||||
- OS: [e.g. Windows, Linux]
|
|
||||||
- Browser: [e.g. chrome, safari]
|
|
||||||
- Graphics card: [e.g. NVIDIA RTX 2080 8GB, AMD RX 6600 8GB]
|
|
||||||
|
|
||||||
**Screenshots or videos of your changes**
|
|
||||||
|
|
||||||
If applicable, screenshots or a video showing off your changes. If it edits an existing UI, it should ideally contain a comparison of what used to be there, before your changes were made.
|
|
||||||
|
|
||||||
This is **required** for anything that touches the user interface.
|
|
||||||
|
57
.github/workflows/on_pull_request.yaml
vendored
57
.github/workflows/on_pull_request.yaml
vendored
@ -1,39 +1,38 @@
|
|||||||
# See https://github.com/actions/starter-workflows/blob/1067f16ad8a1eac328834e4b0ae24f7d206f810d/ci/pylint.yml for original reference file
|
name: Linter
|
||||||
name: Run Linting/Formatting on Pull Requests
|
|
||||||
|
|
||||||
on:
|
on:
|
||||||
- push
|
- push
|
||||||
- pull_request
|
- pull_request
|
||||||
# See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#onpull_requestpull_request_targetbranchesbranches-ignore for syntax docs
|
|
||||||
# if you want to filter out branches, delete the `- pull_request` and uncomment these lines :
|
|
||||||
# pull_request:
|
|
||||||
# branches:
|
|
||||||
# - master
|
|
||||||
# branches-ignore:
|
|
||||||
# - development
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
lint:
|
lint-python:
|
||||||
|
name: ruff
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout Code
|
- name: Checkout Code
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v4
|
||||||
- name: Set up Python 3.10
|
- uses: actions/setup-python@v5
|
||||||
uses: actions/setup-python@v4
|
|
||||||
with:
|
with:
|
||||||
python-version: 3.10.6
|
python-version: 3.11
|
||||||
cache: pip
|
# NB: there's no cache: pip here since we're not installing anything
|
||||||
cache-dependency-path: |
|
# from the requirements.txt file(s) in the repository; it's faster
|
||||||
**/requirements*txt
|
# not to have GHA download an (at the time of writing) 4 GB cache
|
||||||
- name: Install PyLint
|
# of PyTorch and other dependencies.
|
||||||
run: |
|
- name: Install Ruff
|
||||||
python -m pip install --upgrade pip
|
run: pip install ruff==0.3.3
|
||||||
pip install pylint
|
- name: Run Ruff
|
||||||
# This lets PyLint check to see if it can resolve imports
|
run: ruff .
|
||||||
- name: Install dependencies
|
lint-js:
|
||||||
run: |
|
name: eslint
|
||||||
export COMMANDLINE_ARGS="--skip-torch-cuda-test --exit"
|
runs-on: ubuntu-latest
|
||||||
python launch.py
|
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
|
||||||
- name: Analysing the code with pylint
|
steps:
|
||||||
run: |
|
- name: Checkout Code
|
||||||
pylint $(git ls-files '*.py')
|
uses: actions/checkout@v4
|
||||||
|
- name: Install Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 18
|
||||||
|
- run: npm i --ci
|
||||||
|
- run: npm run lint
|
||||||
|
72
.github/workflows/run_tests.yaml
vendored
72
.github/workflows/run_tests.yaml
vendored
@ -1,4 +1,4 @@
|
|||||||
name: Run basic features tests on CPU with empty SD model
|
name: Tests
|
||||||
|
|
||||||
on:
|
on:
|
||||||
- push
|
- push
|
||||||
@ -6,24 +6,76 @@ on:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
|
name: tests on CPU with empty model
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout Code
|
- name: Checkout Code
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v4
|
||||||
- name: Set up Python 3.10
|
- name: Set up Python 3.10
|
||||||
uses: actions/setup-python@v4
|
uses: actions/setup-python@v5
|
||||||
with:
|
with:
|
||||||
python-version: 3.10.6
|
python-version: 3.10.6
|
||||||
cache: pip
|
cache: pip
|
||||||
cache-dependency-path: |
|
cache-dependency-path: |
|
||||||
**/requirements*txt
|
**/requirements*txt
|
||||||
|
launch.py
|
||||||
|
- name: Cache models
|
||||||
|
id: cache-models
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: models
|
||||||
|
key: "2023-12-30"
|
||||||
|
- name: Install test dependencies
|
||||||
|
run: pip install wait-for-it -r requirements-test.txt
|
||||||
|
env:
|
||||||
|
PIP_DISABLE_PIP_VERSION_CHECK: "1"
|
||||||
|
PIP_PROGRESS_BAR: "off"
|
||||||
|
- name: Setup environment
|
||||||
|
run: python launch.py --skip-torch-cuda-test --exit
|
||||||
|
env:
|
||||||
|
PIP_DISABLE_PIP_VERSION_CHECK: "1"
|
||||||
|
PIP_PROGRESS_BAR: "off"
|
||||||
|
TORCH_INDEX_URL: https://download.pytorch.org/whl/cpu
|
||||||
|
WEBUI_LAUNCH_LIVE_OUTPUT: "1"
|
||||||
|
PYTHONUNBUFFERED: "1"
|
||||||
|
- name: Print installed packages
|
||||||
|
run: pip freeze
|
||||||
|
- name: Start test server
|
||||||
|
run: >
|
||||||
|
python -m coverage run
|
||||||
|
--data-file=.coverage.server
|
||||||
|
launch.py
|
||||||
|
--skip-prepare-environment
|
||||||
|
--skip-torch-cuda-test
|
||||||
|
--test-server
|
||||||
|
--do-not-download-clip
|
||||||
|
--no-half
|
||||||
|
--disable-opt-split-attention
|
||||||
|
--use-cpu all
|
||||||
|
--api-server-stop
|
||||||
|
2>&1 | tee output.txt &
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
run: python launch.py --tests test --no-half --disable-opt-split-attention --use-cpu all --skip-torch-cuda-test
|
run: |
|
||||||
- name: Upload main app stdout-stderr
|
wait-for-it --service 127.0.0.1:7860 -t 20
|
||||||
uses: actions/upload-artifact@v3
|
python -m pytest -vv --junitxml=test/results.xml --cov . --cov-report=xml --verify-base-url test
|
||||||
|
- name: Kill test server
|
||||||
|
if: always()
|
||||||
|
run: curl -vv -XPOST http://127.0.0.1:7860/sdapi/v1/server-stop && sleep 10
|
||||||
|
- name: Show coverage
|
||||||
|
run: |
|
||||||
|
python -m coverage combine .coverage*
|
||||||
|
python -m coverage report -i
|
||||||
|
python -m coverage html -i
|
||||||
|
- name: Upload main app output
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
if: always()
|
if: always()
|
||||||
with:
|
with:
|
||||||
name: stdout-stderr
|
name: output
|
||||||
path: |
|
path: output.txt
|
||||||
test/stdout.txt
|
- name: Upload coverage HTML
|
||||||
test/stderr.txt
|
uses: actions/upload-artifact@v4
|
||||||
|
if: always()
|
||||||
|
with:
|
||||||
|
name: htmlcov
|
||||||
|
path: htmlcov
|
||||||
|
19
.github/workflows/warns_merge_master.yml
vendored
Normal file
19
.github/workflows/warns_merge_master.yml
vendored
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
name: Pull requests can't target master branch
|
||||||
|
|
||||||
|
"on":
|
||||||
|
pull_request:
|
||||||
|
types:
|
||||||
|
- opened
|
||||||
|
- synchronize
|
||||||
|
- reopened
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
check:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Warning marge into master
|
||||||
|
run: |
|
||||||
|
echo -e "::warning::This pull request directly merge into \"master\" branch, normally development happens on \"dev\" branch."
|
||||||
|
exit 1
|
8
.gitignore
vendored
8
.gitignore
vendored
@ -2,6 +2,7 @@ __pycache__
|
|||||||
*.ckpt
|
*.ckpt
|
||||||
*.safetensors
|
*.safetensors
|
||||||
*.pth
|
*.pth
|
||||||
|
.DS_Store
|
||||||
/ESRGAN/*
|
/ESRGAN/*
|
||||||
/SwinIR/*
|
/SwinIR/*
|
||||||
/repositories
|
/repositories
|
||||||
@ -34,3 +35,10 @@ notification.mp3
|
|||||||
/test/stderr.txt
|
/test/stderr.txt
|
||||||
/cache.json*
|
/cache.json*
|
||||||
/config_states/
|
/config_states/
|
||||||
|
/node_modules
|
||||||
|
/package-lock.json
|
||||||
|
/.coverage*
|
||||||
|
/test/test_outputs
|
||||||
|
/cache
|
||||||
|
trace.json
|
||||||
|
/sysinfo-????-??-??-??-??.json
|
||||||
|
1052
CHANGELOG.md
1052
CHANGELOG.md
File diff suppressed because it is too large
Load Diff
7
CITATION.cff
Normal file
7
CITATION.cff
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
cff-version: 1.2.0
|
||||||
|
message: "If you use this software, please cite it as below."
|
||||||
|
authors:
|
||||||
|
- given-names: AUTOMATIC1111
|
||||||
|
title: "Stable Diffusion Web UI"
|
||||||
|
date-released: 2022-08-22
|
||||||
|
url: "https://github.com/AUTOMATIC1111/stable-diffusion-webui"
|
71
README.md
71
README.md
@ -1,5 +1,5 @@
|
|||||||
# Stable Diffusion web UI
|
# Stable Diffusion web UI
|
||||||
A browser interface based on Gradio library for Stable Diffusion.
|
A web interface for Stable Diffusion, implemented using Gradio library.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
@ -15,7 +15,7 @@ A browser interface based on Gradio library for Stable Diffusion.
|
|||||||
- Attention, specify parts of text that the model should pay more attention to
|
- Attention, specify parts of text that the model should pay more attention to
|
||||||
- a man in a `((tuxedo))` - will pay more attention to tuxedo
|
- a man in a `((tuxedo))` - will pay more attention to tuxedo
|
||||||
- a man in a `(tuxedo:1.21)` - alternative syntax
|
- a man in a `(tuxedo:1.21)` - alternative syntax
|
||||||
- select text and press `Ctrl+Up` or `Ctrl+Down` to automatically adjust attention to selected text (code contributed by anonymous user)
|
- select text and press `Ctrl+Up` or `Ctrl+Down` (or `Command+Up` or `Command+Down` if you're on a MacOS) to automatically adjust attention to selected text (code contributed by anonymous user)
|
||||||
- Loopback, run img2img processing multiple times
|
- Loopback, run img2img processing multiple times
|
||||||
- X/Y/Z plot, a way to draw a 3 dimensional plot of images with different parameters
|
- X/Y/Z plot, a way to draw a 3 dimensional plot of images with different parameters
|
||||||
- Textual Inversion
|
- Textual Inversion
|
||||||
@ -78,7 +78,7 @@ A browser interface based on Gradio library for Stable Diffusion.
|
|||||||
- Clip skip
|
- Clip skip
|
||||||
- Hypernetworks
|
- Hypernetworks
|
||||||
- Loras (same as Hypernetworks but more pretty)
|
- Loras (same as Hypernetworks but more pretty)
|
||||||
- A sparate UI where you can choose, with preview, which embeddings, hypernetworks or Loras to add to your prompt
|
- A separate UI where you can choose, with preview, which embeddings, hypernetworks or Loras to add to your prompt
|
||||||
- Can select to load a different VAE from settings screen
|
- Can select to load a different VAE from settings screen
|
||||||
- Estimated completion time in progress bar
|
- Estimated completion time in progress bar
|
||||||
- API
|
- API
|
||||||
@ -88,17 +88,28 @@ A browser interface based on Gradio library for Stable Diffusion.
|
|||||||
- [Alt-Diffusion](https://arxiv.org/abs/2211.06679) support - see [wiki](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Features#alt-diffusion) for instructions
|
- [Alt-Diffusion](https://arxiv.org/abs/2211.06679) support - see [wiki](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Features#alt-diffusion) for instructions
|
||||||
- Now without any bad letters!
|
- Now without any bad letters!
|
||||||
- Load checkpoints in safetensors format
|
- Load checkpoints in safetensors format
|
||||||
- Eased resolution restriction: generated image's domension must be a multiple of 8 rather than 64
|
- Eased resolution restriction: generated image's dimensions must be a multiple of 8 rather than 64
|
||||||
- Now with a license!
|
- Now with a license!
|
||||||
- Reorder elements in the UI from settings screen
|
- Reorder elements in the UI from settings screen
|
||||||
|
- [Segmind Stable Diffusion](https://huggingface.co/segmind/SSD-1B) support
|
||||||
|
|
||||||
## Installation and Running
|
## Installation and Running
|
||||||
Make sure the required [dependencies](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Dependencies) are met and follow the instructions available for both [NVidia](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Install-and-Run-on-NVidia-GPUs) (recommended) and [AMD](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Install-and-Run-on-AMD-GPUs) GPUs.
|
Make sure the required [dependencies](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Dependencies) are met and follow the instructions available for:
|
||||||
|
- [NVidia](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Install-and-Run-on-NVidia-GPUs) (recommended)
|
||||||
|
- [AMD](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Install-and-Run-on-AMD-GPUs) GPUs.
|
||||||
|
- [Intel CPUs, Intel GPUs (both integrated and discrete)](https://github.com/openvinotoolkit/stable-diffusion-webui/wiki/Installation-on-Intel-Silicon) (external wiki page)
|
||||||
|
- [Ascend NPUs](https://github.com/wangshuai09/stable-diffusion-webui/wiki/Install-and-run-on-Ascend-NPUs) (external wiki page)
|
||||||
|
|
||||||
Alternatively, use online services (like Google Colab):
|
Alternatively, use online services (like Google Colab):
|
||||||
|
|
||||||
- [List of Online Services](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Online-Services)
|
- [List of Online Services](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Online-Services)
|
||||||
|
|
||||||
|
### Installation on Windows 10/11 with NVidia-GPUs using release package
|
||||||
|
1. Download `sd.webui.zip` from [v1.0.0-pre](https://github.com/AUTOMATIC1111/stable-diffusion-webui/releases/tag/v1.0.0-pre) and extract its contents.
|
||||||
|
2. Run `update.bat`.
|
||||||
|
3. Run `run.bat`.
|
||||||
|
> For more details see [Install-and-Run-on-NVidia-GPUs](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Install-and-Run-on-NVidia-GPUs)
|
||||||
|
|
||||||
### Automatic Installation on Windows
|
### Automatic Installation on Windows
|
||||||
1. Install [Python 3.10.6](https://www.python.org/downloads/release/python-3106/) (Newer version of Python does not support torch), checking "Add Python to PATH".
|
1. Install [Python 3.10.6](https://www.python.org/downloads/release/python-3106/) (Newer version of Python does not support torch), checking "Add Python to PATH".
|
||||||
2. Install [git](https://git-scm.com/download/win).
|
2. Install [git](https://git-scm.com/download/win).
|
||||||
@ -109,16 +120,40 @@ Alternatively, use online services (like Google Colab):
|
|||||||
1. Install the dependencies:
|
1. Install the dependencies:
|
||||||
```bash
|
```bash
|
||||||
# Debian-based:
|
# Debian-based:
|
||||||
sudo apt install wget git python3 python3-venv
|
sudo apt install wget git python3 python3-venv libgl1 libglib2.0-0
|
||||||
# Red Hat-based:
|
# Red Hat-based:
|
||||||
sudo dnf install wget git python3
|
sudo dnf install wget git python3 gperftools-libs libglvnd-glx
|
||||||
|
# openSUSE-based:
|
||||||
|
sudo zypper install wget git python3 libtcmalloc4 libglvnd
|
||||||
# Arch-based:
|
# Arch-based:
|
||||||
sudo pacman -S wget git python3
|
sudo pacman -S wget git python3
|
||||||
```
|
```
|
||||||
|
If your system is very new, you need to install python3.11 or python3.10:
|
||||||
|
```bash
|
||||||
|
# Ubuntu 24.04
|
||||||
|
sudo add-apt-repository ppa:deadsnakes/ppa
|
||||||
|
sudo apt update
|
||||||
|
sudo apt install python3.11
|
||||||
|
|
||||||
|
# Manjaro/Arch
|
||||||
|
sudo pacman -S yay
|
||||||
|
yay -S python311 # do not confuse with python3.11 package
|
||||||
|
|
||||||
|
# Only for 3.11
|
||||||
|
# Then set up env variable in launch script
|
||||||
|
export python_cmd="python3.11"
|
||||||
|
# or in webui-user.sh
|
||||||
|
python_cmd="python3.11"
|
||||||
|
```
|
||||||
2. Navigate to the directory you would like the webui to be installed and execute the following command:
|
2. Navigate to the directory you would like the webui to be installed and execute the following command:
|
||||||
```bash
|
```bash
|
||||||
bash <(wget -qO- https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/master/webui.sh)
|
wget -q https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/master/webui.sh
|
||||||
```
|
```
|
||||||
|
Or just clone the repo wherever you want:
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui
|
||||||
|
```
|
||||||
|
|
||||||
3. Run `webui.sh`.
|
3. Run `webui.sh`.
|
||||||
4. Check `webui-user.sh` for options.
|
4. Check `webui-user.sh` for options.
|
||||||
### Installation on Apple Silicon
|
### Installation on Apple Silicon
|
||||||
@ -129,18 +164,22 @@ Find the instructions [here](https://github.com/AUTOMATIC1111/stable-diffusion-w
|
|||||||
Here's how to add code to this repo: [Contributing](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Contributing)
|
Here's how to add code to this repo: [Contributing](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Contributing)
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
The documentation was moved from this README over to the project's [wiki](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki).
|
The documentation was moved from this README over to the project's [wiki](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki).
|
||||||
|
|
||||||
|
For the purposes of getting Google and other search engines to crawl the wiki, here's a link to the (not for humans) [crawlable wiki](https://github-wiki-see.page/m/AUTOMATIC1111/stable-diffusion-webui/wiki).
|
||||||
|
|
||||||
## Credits
|
## Credits
|
||||||
Licenses for borrowed code can be found in `Settings -> Licenses` screen, and also in `html/licenses.html` file.
|
Licenses for borrowed code can be found in `Settings -> Licenses` screen, and also in `html/licenses.html` file.
|
||||||
|
|
||||||
- Stable Diffusion - https://github.com/CompVis/stable-diffusion, https://github.com/CompVis/taming-transformers
|
- Stable Diffusion - https://github.com/Stability-AI/stablediffusion, https://github.com/CompVis/taming-transformers, https://github.com/mcmonkey4eva/sd3-ref
|
||||||
- k-diffusion - https://github.com/crowsonkb/k-diffusion.git
|
- k-diffusion - https://github.com/crowsonkb/k-diffusion.git
|
||||||
- GFPGAN - https://github.com/TencentARC/GFPGAN.git
|
- Spandrel - https://github.com/chaiNNer-org/spandrel implementing
|
||||||
- CodeFormer - https://github.com/sczhou/CodeFormer
|
- GFPGAN - https://github.com/TencentARC/GFPGAN.git
|
||||||
- ESRGAN - https://github.com/xinntao/ESRGAN
|
- CodeFormer - https://github.com/sczhou/CodeFormer
|
||||||
- SwinIR - https://github.com/JingyunLiang/SwinIR
|
- ESRGAN - https://github.com/xinntao/ESRGAN
|
||||||
- Swin2SR - https://github.com/mv-lab/swin2sr
|
- SwinIR - https://github.com/JingyunLiang/SwinIR
|
||||||
|
- Swin2SR - https://github.com/mv-lab/swin2sr
|
||||||
- LDSR - https://github.com/Hafiidz/latent-diffusion
|
- LDSR - https://github.com/Hafiidz/latent-diffusion
|
||||||
- MiDaS - https://github.com/isl-org/MiDaS
|
- MiDaS - https://github.com/isl-org/MiDaS
|
||||||
- Ideas for optimizations - https://github.com/basujindal/stable-diffusion
|
- Ideas for optimizations - https://github.com/basujindal/stable-diffusion
|
||||||
@ -158,5 +197,9 @@ Licenses for borrowed code can be found in `Settings -> Licenses` screen, and al
|
|||||||
- Instruct pix2pix - Tim Brooks (star), Aleksander Holynski (star), Alexei A. Efros (no star) - https://github.com/timothybrooks/instruct-pix2pix
|
- Instruct pix2pix - Tim Brooks (star), Aleksander Holynski (star), Alexei A. Efros (no star) - https://github.com/timothybrooks/instruct-pix2pix
|
||||||
- Security advice - RyotaK
|
- Security advice - RyotaK
|
||||||
- UniPC sampler - Wenliang Zhao - https://github.com/wl-zhao/UniPC
|
- UniPC sampler - Wenliang Zhao - https://github.com/wl-zhao/UniPC
|
||||||
|
- TAESD - Ollin Boer Bohan - https://github.com/madebyollin/taesd
|
||||||
|
- LyCORIS - KohakuBlueleaf
|
||||||
|
- Restart sampling - lambertae - https://github.com/Newbeeer/diffusion_restart_sampling
|
||||||
|
- Hypertile - tfernd - https://github.com/tfernd/HyperTile
|
||||||
- Initial Gradio script - posted on 4chan by an Anonymous user. Thank you Anonymous user.
|
- Initial Gradio script - posted on 4chan by an Anonymous user. Thank you Anonymous user.
|
||||||
- (You)
|
- (You)
|
||||||
|
5
_typos.toml
Normal file
5
_typos.toml
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
[default.extend-words]
|
||||||
|
# Part of "RGBa" (Pillow's pre-multiplied alpha RGB mode)
|
||||||
|
Ba = "Ba"
|
||||||
|
# HSA is something AMD uses for their GPUs
|
||||||
|
HSA = "HSA"
|
@ -40,7 +40,7 @@ model:
|
|||||||
use_spatial_transformer: True
|
use_spatial_transformer: True
|
||||||
transformer_depth: 1
|
transformer_depth: 1
|
||||||
context_dim: 768
|
context_dim: 768
|
||||||
use_checkpoint: True
|
use_checkpoint: False
|
||||||
legacy: False
|
legacy: False
|
||||||
|
|
||||||
first_stage_config:
|
first_stage_config:
|
||||||
|
73
configs/alt-diffusion-m18-inference.yaml
Normal file
73
configs/alt-diffusion-m18-inference.yaml
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
model:
|
||||||
|
base_learning_rate: 1.0e-04
|
||||||
|
target: ldm.models.diffusion.ddpm.LatentDiffusion
|
||||||
|
params:
|
||||||
|
linear_start: 0.00085
|
||||||
|
linear_end: 0.0120
|
||||||
|
num_timesteps_cond: 1
|
||||||
|
log_every_t: 200
|
||||||
|
timesteps: 1000
|
||||||
|
first_stage_key: "jpg"
|
||||||
|
cond_stage_key: "txt"
|
||||||
|
image_size: 64
|
||||||
|
channels: 4
|
||||||
|
cond_stage_trainable: false # Note: different from the one we trained before
|
||||||
|
conditioning_key: crossattn
|
||||||
|
monitor: val/loss_simple_ema
|
||||||
|
scale_factor: 0.18215
|
||||||
|
use_ema: False
|
||||||
|
|
||||||
|
scheduler_config: # 10000 warmup steps
|
||||||
|
target: ldm.lr_scheduler.LambdaLinearScheduler
|
||||||
|
params:
|
||||||
|
warm_up_steps: [ 10000 ]
|
||||||
|
cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
|
||||||
|
f_start: [ 1.e-6 ]
|
||||||
|
f_max: [ 1. ]
|
||||||
|
f_min: [ 1. ]
|
||||||
|
|
||||||
|
unet_config:
|
||||||
|
target: ldm.modules.diffusionmodules.openaimodel.UNetModel
|
||||||
|
params:
|
||||||
|
image_size: 32 # unused
|
||||||
|
in_channels: 4
|
||||||
|
out_channels: 4
|
||||||
|
model_channels: 320
|
||||||
|
attention_resolutions: [ 4, 2, 1 ]
|
||||||
|
num_res_blocks: 2
|
||||||
|
channel_mult: [ 1, 2, 4, 4 ]
|
||||||
|
num_head_channels: 64
|
||||||
|
use_spatial_transformer: True
|
||||||
|
use_linear_in_transformer: True
|
||||||
|
transformer_depth: 1
|
||||||
|
context_dim: 1024
|
||||||
|
use_checkpoint: False
|
||||||
|
legacy: False
|
||||||
|
|
||||||
|
first_stage_config:
|
||||||
|
target: ldm.models.autoencoder.AutoencoderKL
|
||||||
|
params:
|
||||||
|
embed_dim: 4
|
||||||
|
monitor: val/rec_loss
|
||||||
|
ddconfig:
|
||||||
|
double_z: true
|
||||||
|
z_channels: 4
|
||||||
|
resolution: 256
|
||||||
|
in_channels: 3
|
||||||
|
out_ch: 3
|
||||||
|
ch: 128
|
||||||
|
ch_mult:
|
||||||
|
- 1
|
||||||
|
- 2
|
||||||
|
- 4
|
||||||
|
- 4
|
||||||
|
num_res_blocks: 2
|
||||||
|
attn_resolutions: []
|
||||||
|
dropout: 0.0
|
||||||
|
lossconfig:
|
||||||
|
target: torch.nn.Identity
|
||||||
|
|
||||||
|
cond_stage_config:
|
||||||
|
target: modules.xlmr_m18.BertSeriesModelWithTransformation
|
||||||
|
params:
|
||||||
|
name: "XLMR-Large"
|
@ -45,7 +45,7 @@ model:
|
|||||||
use_spatial_transformer: True
|
use_spatial_transformer: True
|
||||||
transformer_depth: 1
|
transformer_depth: 1
|
||||||
context_dim: 768
|
context_dim: 768
|
||||||
use_checkpoint: True
|
use_checkpoint: False
|
||||||
legacy: False
|
legacy: False
|
||||||
|
|
||||||
first_stage_config:
|
first_stage_config:
|
||||||
|
5
configs/sd3-inference.yaml
Normal file
5
configs/sd3-inference.yaml
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
model:
|
||||||
|
target: modules.models.sd3.sd3_model.SD3Inferencer
|
||||||
|
params:
|
||||||
|
shift: 3
|
||||||
|
state_dict: null
|
98
configs/sd_xl_inpaint.yaml
Normal file
98
configs/sd_xl_inpaint.yaml
Normal file
@ -0,0 +1,98 @@
|
|||||||
|
model:
|
||||||
|
target: sgm.models.diffusion.DiffusionEngine
|
||||||
|
params:
|
||||||
|
scale_factor: 0.13025
|
||||||
|
disable_first_stage_autocast: True
|
||||||
|
|
||||||
|
denoiser_config:
|
||||||
|
target: sgm.modules.diffusionmodules.denoiser.DiscreteDenoiser
|
||||||
|
params:
|
||||||
|
num_idx: 1000
|
||||||
|
|
||||||
|
weighting_config:
|
||||||
|
target: sgm.modules.diffusionmodules.denoiser_weighting.EpsWeighting
|
||||||
|
scaling_config:
|
||||||
|
target: sgm.modules.diffusionmodules.denoiser_scaling.EpsScaling
|
||||||
|
discretization_config:
|
||||||
|
target: sgm.modules.diffusionmodules.discretizer.LegacyDDPMDiscretization
|
||||||
|
|
||||||
|
network_config:
|
||||||
|
target: sgm.modules.diffusionmodules.openaimodel.UNetModel
|
||||||
|
params:
|
||||||
|
adm_in_channels: 2816
|
||||||
|
num_classes: sequential
|
||||||
|
use_checkpoint: False
|
||||||
|
in_channels: 9
|
||||||
|
out_channels: 4
|
||||||
|
model_channels: 320
|
||||||
|
attention_resolutions: [4, 2]
|
||||||
|
num_res_blocks: 2
|
||||||
|
channel_mult: [1, 2, 4]
|
||||||
|
num_head_channels: 64
|
||||||
|
use_spatial_transformer: True
|
||||||
|
use_linear_in_transformer: True
|
||||||
|
transformer_depth: [1, 2, 10] # note: the first is unused (due to attn_res starting at 2) 32, 16, 8 --> 64, 32, 16
|
||||||
|
context_dim: 2048
|
||||||
|
spatial_transformer_attn_type: softmax-xformers
|
||||||
|
legacy: False
|
||||||
|
|
||||||
|
conditioner_config:
|
||||||
|
target: sgm.modules.GeneralConditioner
|
||||||
|
params:
|
||||||
|
emb_models:
|
||||||
|
# crossattn cond
|
||||||
|
- is_trainable: False
|
||||||
|
input_key: txt
|
||||||
|
target: sgm.modules.encoders.modules.FrozenCLIPEmbedder
|
||||||
|
params:
|
||||||
|
layer: hidden
|
||||||
|
layer_idx: 11
|
||||||
|
# crossattn and vector cond
|
||||||
|
- is_trainable: False
|
||||||
|
input_key: txt
|
||||||
|
target: sgm.modules.encoders.modules.FrozenOpenCLIPEmbedder2
|
||||||
|
params:
|
||||||
|
arch: ViT-bigG-14
|
||||||
|
version: laion2b_s39b_b160k
|
||||||
|
freeze: True
|
||||||
|
layer: penultimate
|
||||||
|
always_return_pooled: True
|
||||||
|
legacy: False
|
||||||
|
# vector cond
|
||||||
|
- is_trainable: False
|
||||||
|
input_key: original_size_as_tuple
|
||||||
|
target: sgm.modules.encoders.modules.ConcatTimestepEmbedderND
|
||||||
|
params:
|
||||||
|
outdim: 256 # multiplied by two
|
||||||
|
# vector cond
|
||||||
|
- is_trainable: False
|
||||||
|
input_key: crop_coords_top_left
|
||||||
|
target: sgm.modules.encoders.modules.ConcatTimestepEmbedderND
|
||||||
|
params:
|
||||||
|
outdim: 256 # multiplied by two
|
||||||
|
# vector cond
|
||||||
|
- is_trainable: False
|
||||||
|
input_key: target_size_as_tuple
|
||||||
|
target: sgm.modules.encoders.modules.ConcatTimestepEmbedderND
|
||||||
|
params:
|
||||||
|
outdim: 256 # multiplied by two
|
||||||
|
|
||||||
|
first_stage_config:
|
||||||
|
target: sgm.models.autoencoder.AutoencoderKLInferenceWrapper
|
||||||
|
params:
|
||||||
|
embed_dim: 4
|
||||||
|
monitor: val/rec_loss
|
||||||
|
ddconfig:
|
||||||
|
attn_type: vanilla-xformers
|
||||||
|
double_z: true
|
||||||
|
z_channels: 4
|
||||||
|
resolution: 256
|
||||||
|
in_channels: 3
|
||||||
|
out_ch: 3
|
||||||
|
ch: 128
|
||||||
|
ch_mult: [1, 2, 4, 4]
|
||||||
|
num_res_blocks: 2
|
||||||
|
attn_resolutions: []
|
||||||
|
dropout: 0.0
|
||||||
|
lossconfig:
|
||||||
|
target: torch.nn.Identity
|
@ -40,7 +40,7 @@ model:
|
|||||||
use_spatial_transformer: True
|
use_spatial_transformer: True
|
||||||
transformer_depth: 1
|
transformer_depth: 1
|
||||||
context_dim: 768
|
context_dim: 768
|
||||||
use_checkpoint: True
|
use_checkpoint: False
|
||||||
legacy: False
|
legacy: False
|
||||||
|
|
||||||
first_stage_config:
|
first_stage_config:
|
||||||
|
@ -40,7 +40,7 @@ model:
|
|||||||
use_spatial_transformer: True
|
use_spatial_transformer: True
|
||||||
transformer_depth: 1
|
transformer_depth: 1
|
||||||
context_dim: 768
|
context_dim: 768
|
||||||
use_checkpoint: True
|
use_checkpoint: False
|
||||||
legacy: False
|
legacy: False
|
||||||
|
|
||||||
first_stage_config:
|
first_stage_config:
|
||||||
|
@ -12,7 +12,7 @@ import safetensors.torch
|
|||||||
|
|
||||||
from ldm.models.diffusion.ddim import DDIMSampler
|
from ldm.models.diffusion.ddim import DDIMSampler
|
||||||
from ldm.util import instantiate_from_config, ismap
|
from ldm.util import instantiate_from_config, ismap
|
||||||
from modules import shared, sd_hijack
|
from modules import shared, sd_hijack, devices
|
||||||
|
|
||||||
cached_ldsr_model: torch.nn.Module = None
|
cached_ldsr_model: torch.nn.Module = None
|
||||||
|
|
||||||
@ -88,7 +88,7 @@ class LDSR:
|
|||||||
|
|
||||||
x_t = None
|
x_t = None
|
||||||
logs = None
|
logs = None
|
||||||
for n in range(n_runs):
|
for _ in range(n_runs):
|
||||||
if custom_shape is not None:
|
if custom_shape is not None:
|
||||||
x_t = torch.randn(1, custom_shape[1], custom_shape[2], custom_shape[3]).to(model.device)
|
x_t = torch.randn(1, custom_shape[1], custom_shape[2], custom_shape[3]).to(model.device)
|
||||||
x_t = repeat(x_t, '1 c h w -> b c h w', b=custom_shape[0])
|
x_t = repeat(x_t, '1 c h w -> b c h w', b=custom_shape[0])
|
||||||
@ -110,11 +110,9 @@ class LDSR:
|
|||||||
diffusion_steps = int(steps)
|
diffusion_steps = int(steps)
|
||||||
eta = 1.0
|
eta = 1.0
|
||||||
|
|
||||||
down_sample_method = 'Lanczos'
|
|
||||||
|
|
||||||
gc.collect()
|
gc.collect()
|
||||||
if torch.cuda.is_available:
|
devices.torch_gc()
|
||||||
torch.cuda.empty_cache()
|
|
||||||
|
|
||||||
im_og = image
|
im_og = image
|
||||||
width_og, height_og = im_og.size
|
width_og, height_og = im_og.size
|
||||||
@ -131,11 +129,11 @@ class LDSR:
|
|||||||
im_og = im_og.resize((width_downsampled_pre, height_downsampled_pre), Image.LANCZOS)
|
im_og = im_og.resize((width_downsampled_pre, height_downsampled_pre), Image.LANCZOS)
|
||||||
else:
|
else:
|
||||||
print(f"Down sample rate is 1 from {target_scale} / 4 (Not downsampling)")
|
print(f"Down sample rate is 1 from {target_scale} / 4 (Not downsampling)")
|
||||||
|
|
||||||
# pad width and height to multiples of 64, pads with the edge values of image to avoid artifacts
|
# pad width and height to multiples of 64, pads with the edge values of image to avoid artifacts
|
||||||
pad_w, pad_h = np.max(((2, 2), np.ceil(np.array(im_og.size) / 64).astype(int)), axis=0) * 64 - im_og.size
|
pad_w, pad_h = np.max(((2, 2), np.ceil(np.array(im_og.size) / 64).astype(int)), axis=0) * 64 - im_og.size
|
||||||
im_padded = Image.fromarray(np.pad(np.array(im_og), ((0, pad_h), (0, pad_w), (0, 0)), mode='edge'))
|
im_padded = Image.fromarray(np.pad(np.array(im_og), ((0, pad_h), (0, pad_w), (0, 0)), mode='edge'))
|
||||||
|
|
||||||
logs = self.run(model["model"], im_padded, diffusion_steps, eta)
|
logs = self.run(model["model"], im_padded, diffusion_steps, eta)
|
||||||
|
|
||||||
sample = logs["sample"]
|
sample = logs["sample"]
|
||||||
@ -151,14 +149,13 @@ class LDSR:
|
|||||||
|
|
||||||
del model
|
del model
|
||||||
gc.collect()
|
gc.collect()
|
||||||
if torch.cuda.is_available:
|
devices.torch_gc()
|
||||||
torch.cuda.empty_cache()
|
|
||||||
|
|
||||||
return a
|
return a
|
||||||
|
|
||||||
|
|
||||||
def get_cond(selected_path):
|
def get_cond(selected_path):
|
||||||
example = dict()
|
example = {}
|
||||||
up_f = 4
|
up_f = 4
|
||||||
c = selected_path.convert('RGB')
|
c = selected_path.convert('RGB')
|
||||||
c = torch.unsqueeze(torchvision.transforms.ToTensor()(c), 0)
|
c = torch.unsqueeze(torchvision.transforms.ToTensor()(c), 0)
|
||||||
@ -196,7 +193,7 @@ def convsample_ddim(model, cond, steps, shape, eta=1.0, callback=None, normals_s
|
|||||||
@torch.no_grad()
|
@torch.no_grad()
|
||||||
def make_convolutional_sample(batch, model, custom_steps=None, eta=1.0, quantize_x0=False, custom_shape=None, temperature=1., noise_dropout=0., corrector=None,
|
def make_convolutional_sample(batch, model, custom_steps=None, eta=1.0, quantize_x0=False, custom_shape=None, temperature=1., noise_dropout=0., corrector=None,
|
||||||
corrector_kwargs=None, x_T=None, ddim_use_x0_pred=False):
|
corrector_kwargs=None, x_T=None, ddim_use_x0_pred=False):
|
||||||
log = dict()
|
log = {}
|
||||||
|
|
||||||
z, c, x, xrec, xc = model.get_input(batch, model.first_stage_key,
|
z, c, x, xrec, xc = model.get_input(batch, model.first_stage_key,
|
||||||
return_first_stage_outputs=True,
|
return_first_stage_outputs=True,
|
||||||
@ -244,7 +241,7 @@ def make_convolutional_sample(batch, model, custom_steps=None, eta=1.0, quantize
|
|||||||
x_sample_noquant = model.decode_first_stage(sample, force_not_quantize=True)
|
x_sample_noquant = model.decode_first_stage(sample, force_not_quantize=True)
|
||||||
log["sample_noquant"] = x_sample_noquant
|
log["sample_noquant"] = x_sample_noquant
|
||||||
log["sample_diff"] = torch.abs(x_sample_noquant - x_sample)
|
log["sample_diff"] = torch.abs(x_sample_noquant - x_sample)
|
||||||
except:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
log["sample"] = x_sample
|
log["sample"] = x_sample
|
||||||
|
@ -1,13 +1,11 @@
|
|||||||
import os
|
import os
|
||||||
import sys
|
|
||||||
import traceback
|
|
||||||
|
|
||||||
from basicsr.utils.download_util import load_file_from_url
|
|
||||||
|
|
||||||
|
from modules.modelloader import load_file_from_url
|
||||||
from modules.upscaler import Upscaler, UpscalerData
|
from modules.upscaler import Upscaler, UpscalerData
|
||||||
from ldsr_model_arch import LDSR
|
from ldsr_model_arch import LDSR
|
||||||
from modules import shared, script_callbacks
|
from modules import shared, script_callbacks, errors
|
||||||
import sd_hijack_autoencoder, sd_hijack_ddpm_v1
|
import sd_hijack_autoencoder # noqa: F401
|
||||||
|
import sd_hijack_ddpm_v1 # noqa: F401
|
||||||
|
|
||||||
|
|
||||||
class UpscalerLDSR(Upscaler):
|
class UpscalerLDSR(Upscaler):
|
||||||
@ -44,22 +42,17 @@ class UpscalerLDSR(Upscaler):
|
|||||||
if local_safetensors_path is not None and os.path.exists(local_safetensors_path):
|
if local_safetensors_path is not None and os.path.exists(local_safetensors_path):
|
||||||
model = local_safetensors_path
|
model = local_safetensors_path
|
||||||
else:
|
else:
|
||||||
model = local_ckpt_path if local_ckpt_path is not None else load_file_from_url(url=self.model_url, model_dir=self.model_path, file_name="model.ckpt", progress=True)
|
model = local_ckpt_path or load_file_from_url(self.model_url, model_dir=self.model_download_path, file_name="model.ckpt")
|
||||||
|
|
||||||
yaml = local_yaml_path if local_yaml_path is not None else load_file_from_url(url=self.yaml_url, model_dir=self.model_path, file_name="project.yaml", progress=True)
|
yaml = local_yaml_path or load_file_from_url(self.yaml_url, model_dir=self.model_download_path, file_name="project.yaml")
|
||||||
|
|
||||||
try:
|
return LDSR(model, yaml)
|
||||||
return LDSR(model, yaml)
|
|
||||||
|
|
||||||
except Exception:
|
|
||||||
print("Error importing LDSR:", file=sys.stderr)
|
|
||||||
print(traceback.format_exc(), file=sys.stderr)
|
|
||||||
return None
|
|
||||||
|
|
||||||
def do_upscale(self, img, path):
|
def do_upscale(self, img, path):
|
||||||
ldsr = self.load_model(path)
|
try:
|
||||||
if ldsr is None:
|
ldsr = self.load_model(path)
|
||||||
print("NO LDSR!")
|
except Exception:
|
||||||
|
errors.report(f"Failed loading LDSR model {path}", exc_info=True)
|
||||||
return img
|
return img
|
||||||
ddim_steps = shared.opts.ldsr_steps
|
ddim_steps = shared.opts.ldsr_steps
|
||||||
return ldsr.super_resolution(img, ddim_steps, self.scale)
|
return ldsr.super_resolution(img, ddim_steps, self.scale)
|
||||||
|
@ -1,16 +1,21 @@
|
|||||||
# The content of this file comes from the ldm/models/autoencoder.py file of the compvis/stable-diffusion repo
|
# The content of this file comes from the ldm/models/autoencoder.py file of the compvis/stable-diffusion repo
|
||||||
# The VQModel & VQModelInterface were subsequently removed from ldm/models/autoencoder.py when we moved to the stability-ai/stablediffusion repo
|
# The VQModel & VQModelInterface were subsequently removed from ldm/models/autoencoder.py when we moved to the stability-ai/stablediffusion repo
|
||||||
# As the LDSR upscaler relies on VQModel & VQModelInterface, the hijack aims to put them back into the ldm.models.autoencoder
|
# As the LDSR upscaler relies on VQModel & VQModelInterface, the hijack aims to put them back into the ldm.models.autoencoder
|
||||||
|
import numpy as np
|
||||||
import torch
|
import torch
|
||||||
import pytorch_lightning as pl
|
import pytorch_lightning as pl
|
||||||
import torch.nn.functional as F
|
import torch.nn.functional as F
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from taming.modules.vqvae.quantize import VectorQuantizer2 as VectorQuantizer
|
|
||||||
|
from torch.optim.lr_scheduler import LambdaLR
|
||||||
|
|
||||||
|
from ldm.modules.ema import LitEma
|
||||||
|
from vqvae_quantize import VectorQuantizer2 as VectorQuantizer
|
||||||
from ldm.modules.diffusionmodules.model import Encoder, Decoder
|
from ldm.modules.diffusionmodules.model import Encoder, Decoder
|
||||||
from ldm.util import instantiate_from_config
|
from ldm.util import instantiate_from_config
|
||||||
|
|
||||||
import ldm.models.autoencoder
|
import ldm.models.autoencoder
|
||||||
|
from packaging import version
|
||||||
|
|
||||||
class VQModel(pl.LightningModule):
|
class VQModel(pl.LightningModule):
|
||||||
def __init__(self,
|
def __init__(self,
|
||||||
@ -19,7 +24,7 @@ class VQModel(pl.LightningModule):
|
|||||||
n_embed,
|
n_embed,
|
||||||
embed_dim,
|
embed_dim,
|
||||||
ckpt_path=None,
|
ckpt_path=None,
|
||||||
ignore_keys=[],
|
ignore_keys=None,
|
||||||
image_key="image",
|
image_key="image",
|
||||||
colorize_nlabels=None,
|
colorize_nlabels=None,
|
||||||
monitor=None,
|
monitor=None,
|
||||||
@ -57,7 +62,7 @@ class VQModel(pl.LightningModule):
|
|||||||
print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
|
print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
|
||||||
|
|
||||||
if ckpt_path is not None:
|
if ckpt_path is not None:
|
||||||
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
|
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys or [])
|
||||||
self.scheduler_config = scheduler_config
|
self.scheduler_config = scheduler_config
|
||||||
self.lr_g_factor = lr_g_factor
|
self.lr_g_factor = lr_g_factor
|
||||||
|
|
||||||
@ -76,18 +81,19 @@ class VQModel(pl.LightningModule):
|
|||||||
if context is not None:
|
if context is not None:
|
||||||
print(f"{context}: Restored training weights")
|
print(f"{context}: Restored training weights")
|
||||||
|
|
||||||
def init_from_ckpt(self, path, ignore_keys=list()):
|
def init_from_ckpt(self, path, ignore_keys=None):
|
||||||
sd = torch.load(path, map_location="cpu")["state_dict"]
|
sd = torch.load(path, map_location="cpu")["state_dict"]
|
||||||
keys = list(sd.keys())
|
keys = list(sd.keys())
|
||||||
for k in keys:
|
for k in keys:
|
||||||
for ik in ignore_keys:
|
for ik in ignore_keys or []:
|
||||||
if k.startswith(ik):
|
if k.startswith(ik):
|
||||||
print("Deleting key {} from state_dict.".format(k))
|
print("Deleting key {} from state_dict.".format(k))
|
||||||
del sd[k]
|
del sd[k]
|
||||||
missing, unexpected = self.load_state_dict(sd, strict=False)
|
missing, unexpected = self.load_state_dict(sd, strict=False)
|
||||||
print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
|
print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
|
||||||
if len(missing) > 0:
|
if missing:
|
||||||
print(f"Missing Keys: {missing}")
|
print(f"Missing Keys: {missing}")
|
||||||
|
if unexpected:
|
||||||
print(f"Unexpected Keys: {unexpected}")
|
print(f"Unexpected Keys: {unexpected}")
|
||||||
|
|
||||||
def on_train_batch_end(self, *args, **kwargs):
|
def on_train_batch_end(self, *args, **kwargs):
|
||||||
@ -165,7 +171,7 @@ class VQModel(pl.LightningModule):
|
|||||||
def validation_step(self, batch, batch_idx):
|
def validation_step(self, batch, batch_idx):
|
||||||
log_dict = self._validation_step(batch, batch_idx)
|
log_dict = self._validation_step(batch, batch_idx)
|
||||||
with self.ema_scope():
|
with self.ema_scope():
|
||||||
log_dict_ema = self._validation_step(batch, batch_idx, suffix="_ema")
|
self._validation_step(batch, batch_idx, suffix="_ema")
|
||||||
return log_dict
|
return log_dict
|
||||||
|
|
||||||
def _validation_step(self, batch, batch_idx, suffix=""):
|
def _validation_step(self, batch, batch_idx, suffix=""):
|
||||||
@ -232,7 +238,7 @@ class VQModel(pl.LightningModule):
|
|||||||
return self.decoder.conv_out.weight
|
return self.decoder.conv_out.weight
|
||||||
|
|
||||||
def log_images(self, batch, only_inputs=False, plot_ema=False, **kwargs):
|
def log_images(self, batch, only_inputs=False, plot_ema=False, **kwargs):
|
||||||
log = dict()
|
log = {}
|
||||||
x = self.get_input(batch, self.image_key)
|
x = self.get_input(batch, self.image_key)
|
||||||
x = x.to(self.device)
|
x = x.to(self.device)
|
||||||
if only_inputs:
|
if only_inputs:
|
||||||
@ -249,7 +255,8 @@ class VQModel(pl.LightningModule):
|
|||||||
if plot_ema:
|
if plot_ema:
|
||||||
with self.ema_scope():
|
with self.ema_scope():
|
||||||
xrec_ema, _ = self(x)
|
xrec_ema, _ = self(x)
|
||||||
if x.shape[1] > 3: xrec_ema = self.to_rgb(xrec_ema)
|
if x.shape[1] > 3:
|
||||||
|
xrec_ema = self.to_rgb(xrec_ema)
|
||||||
log["reconstructions_ema"] = xrec_ema
|
log["reconstructions_ema"] = xrec_ema
|
||||||
return log
|
return log
|
||||||
|
|
||||||
@ -264,7 +271,7 @@ class VQModel(pl.LightningModule):
|
|||||||
|
|
||||||
class VQModelInterface(VQModel):
|
class VQModelInterface(VQModel):
|
||||||
def __init__(self, embed_dim, *args, **kwargs):
|
def __init__(self, embed_dim, *args, **kwargs):
|
||||||
super().__init__(embed_dim=embed_dim, *args, **kwargs)
|
super().__init__(*args, embed_dim=embed_dim, **kwargs)
|
||||||
self.embed_dim = embed_dim
|
self.embed_dim = embed_dim
|
||||||
|
|
||||||
def encode(self, x):
|
def encode(self, x):
|
||||||
@ -282,5 +289,5 @@ class VQModelInterface(VQModel):
|
|||||||
dec = self.decoder(quant)
|
dec = self.decoder(quant)
|
||||||
return dec
|
return dec
|
||||||
|
|
||||||
setattr(ldm.models.autoencoder, "VQModel", VQModel)
|
ldm.models.autoencoder.VQModel = VQModel
|
||||||
setattr(ldm.models.autoencoder, "VQModelInterface", VQModelInterface)
|
ldm.models.autoencoder.VQModelInterface = VQModelInterface
|
||||||
|
@ -48,7 +48,7 @@ class DDPMV1(pl.LightningModule):
|
|||||||
beta_schedule="linear",
|
beta_schedule="linear",
|
||||||
loss_type="l2",
|
loss_type="l2",
|
||||||
ckpt_path=None,
|
ckpt_path=None,
|
||||||
ignore_keys=[],
|
ignore_keys=None,
|
||||||
load_only_unet=False,
|
load_only_unet=False,
|
||||||
monitor="val/loss",
|
monitor="val/loss",
|
||||||
use_ema=True,
|
use_ema=True,
|
||||||
@ -100,7 +100,7 @@ class DDPMV1(pl.LightningModule):
|
|||||||
if monitor is not None:
|
if monitor is not None:
|
||||||
self.monitor = monitor
|
self.monitor = monitor
|
||||||
if ckpt_path is not None:
|
if ckpt_path is not None:
|
||||||
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet)
|
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys or [], only_model=load_only_unet)
|
||||||
|
|
||||||
self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps,
|
self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps,
|
||||||
linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s)
|
linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s)
|
||||||
@ -182,22 +182,22 @@ class DDPMV1(pl.LightningModule):
|
|||||||
if context is not None:
|
if context is not None:
|
||||||
print(f"{context}: Restored training weights")
|
print(f"{context}: Restored training weights")
|
||||||
|
|
||||||
def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):
|
def init_from_ckpt(self, path, ignore_keys=None, only_model=False):
|
||||||
sd = torch.load(path, map_location="cpu")
|
sd = torch.load(path, map_location="cpu")
|
||||||
if "state_dict" in list(sd.keys()):
|
if "state_dict" in list(sd.keys()):
|
||||||
sd = sd["state_dict"]
|
sd = sd["state_dict"]
|
||||||
keys = list(sd.keys())
|
keys = list(sd.keys())
|
||||||
for k in keys:
|
for k in keys:
|
||||||
for ik in ignore_keys:
|
for ik in ignore_keys or []:
|
||||||
if k.startswith(ik):
|
if k.startswith(ik):
|
||||||
print("Deleting key {} from state_dict.".format(k))
|
print("Deleting key {} from state_dict.".format(k))
|
||||||
del sd[k]
|
del sd[k]
|
||||||
missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
|
missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
|
||||||
sd, strict=False)
|
sd, strict=False)
|
||||||
print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
|
print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
|
||||||
if len(missing) > 0:
|
if missing:
|
||||||
print(f"Missing Keys: {missing}")
|
print(f"Missing Keys: {missing}")
|
||||||
if len(unexpected) > 0:
|
if unexpected:
|
||||||
print(f"Unexpected Keys: {unexpected}")
|
print(f"Unexpected Keys: {unexpected}")
|
||||||
|
|
||||||
def q_mean_variance(self, x_start, t):
|
def q_mean_variance(self, x_start, t):
|
||||||
@ -301,7 +301,7 @@ class DDPMV1(pl.LightningModule):
|
|||||||
elif self.parameterization == "x0":
|
elif self.parameterization == "x0":
|
||||||
target = x_start
|
target = x_start
|
||||||
else:
|
else:
|
||||||
raise NotImplementedError(f"Paramterization {self.parameterization} not yet supported")
|
raise NotImplementedError(f"Parameterization {self.parameterization} not yet supported")
|
||||||
|
|
||||||
loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3])
|
loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3])
|
||||||
|
|
||||||
@ -375,7 +375,7 @@ class DDPMV1(pl.LightningModule):
|
|||||||
|
|
||||||
@torch.no_grad()
|
@torch.no_grad()
|
||||||
def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs):
|
def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs):
|
||||||
log = dict()
|
log = {}
|
||||||
x = self.get_input(batch, self.first_stage_key)
|
x = self.get_input(batch, self.first_stage_key)
|
||||||
N = min(x.shape[0], N)
|
N = min(x.shape[0], N)
|
||||||
n_row = min(x.shape[0], n_row)
|
n_row = min(x.shape[0], n_row)
|
||||||
@ -383,7 +383,7 @@ class DDPMV1(pl.LightningModule):
|
|||||||
log["inputs"] = x
|
log["inputs"] = x
|
||||||
|
|
||||||
# get diffusion row
|
# get diffusion row
|
||||||
diffusion_row = list()
|
diffusion_row = []
|
||||||
x_start = x[:n_row]
|
x_start = x[:n_row]
|
||||||
|
|
||||||
for t in range(self.num_timesteps):
|
for t in range(self.num_timesteps):
|
||||||
@ -444,13 +444,13 @@ class LatentDiffusionV1(DDPMV1):
|
|||||||
conditioning_key = None
|
conditioning_key = None
|
||||||
ckpt_path = kwargs.pop("ckpt_path", None)
|
ckpt_path = kwargs.pop("ckpt_path", None)
|
||||||
ignore_keys = kwargs.pop("ignore_keys", [])
|
ignore_keys = kwargs.pop("ignore_keys", [])
|
||||||
super().__init__(conditioning_key=conditioning_key, *args, **kwargs)
|
super().__init__(*args, conditioning_key=conditioning_key, **kwargs)
|
||||||
self.concat_mode = concat_mode
|
self.concat_mode = concat_mode
|
||||||
self.cond_stage_trainable = cond_stage_trainable
|
self.cond_stage_trainable = cond_stage_trainable
|
||||||
self.cond_stage_key = cond_stage_key
|
self.cond_stage_key = cond_stage_key
|
||||||
try:
|
try:
|
||||||
self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1
|
self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1
|
||||||
except:
|
except Exception:
|
||||||
self.num_downs = 0
|
self.num_downs = 0
|
||||||
if not scale_by_std:
|
if not scale_by_std:
|
||||||
self.scale_factor = scale_factor
|
self.scale_factor = scale_factor
|
||||||
@ -460,7 +460,7 @@ class LatentDiffusionV1(DDPMV1):
|
|||||||
self.instantiate_cond_stage(cond_stage_config)
|
self.instantiate_cond_stage(cond_stage_config)
|
||||||
self.cond_stage_forward = cond_stage_forward
|
self.cond_stage_forward = cond_stage_forward
|
||||||
self.clip_denoised = False
|
self.clip_denoised = False
|
||||||
self.bbox_tokenizer = None
|
self.bbox_tokenizer = None
|
||||||
|
|
||||||
self.restarted_from_ckpt = False
|
self.restarted_from_ckpt = False
|
||||||
if ckpt_path is not None:
|
if ckpt_path is not None:
|
||||||
@ -572,7 +572,7 @@ class LatentDiffusionV1(DDPMV1):
|
|||||||
:param h: height
|
:param h: height
|
||||||
:param w: width
|
:param w: width
|
||||||
:return: normalized distance to image border,
|
:return: normalized distance to image border,
|
||||||
wtith min distance = 0 at border and max dist = 0.5 at image center
|
with min distance = 0 at border and max dist = 0.5 at image center
|
||||||
"""
|
"""
|
||||||
lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2)
|
lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2)
|
||||||
arr = self.meshgrid(h, w) / lower_right_corner
|
arr = self.meshgrid(h, w) / lower_right_corner
|
||||||
@ -792,7 +792,7 @@ class LatentDiffusionV1(DDPMV1):
|
|||||||
z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
|
z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
|
||||||
|
|
||||||
# 2. apply model loop over last dim
|
# 2. apply model loop over last dim
|
||||||
if isinstance(self.first_stage_model, VQModelInterface):
|
if isinstance(self.first_stage_model, VQModelInterface):
|
||||||
output_list = [self.first_stage_model.decode(z[:, :, :, :, i],
|
output_list = [self.first_stage_model.decode(z[:, :, :, :, i],
|
||||||
force_not_quantize=predict_cids or force_not_quantize)
|
force_not_quantize=predict_cids or force_not_quantize)
|
||||||
for i in range(z.shape[-1])]
|
for i in range(z.shape[-1])]
|
||||||
@ -877,20 +877,10 @@ class LatentDiffusionV1(DDPMV1):
|
|||||||
c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float()))
|
c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float()))
|
||||||
return self.p_losses(x, c, t, *args, **kwargs)
|
return self.p_losses(x, c, t, *args, **kwargs)
|
||||||
|
|
||||||
def _rescale_annotations(self, bboxes, crop_coordinates): # TODO: move to dataset
|
|
||||||
def rescale_bbox(bbox):
|
|
||||||
x0 = clamp((bbox[0] - crop_coordinates[0]) / crop_coordinates[2])
|
|
||||||
y0 = clamp((bbox[1] - crop_coordinates[1]) / crop_coordinates[3])
|
|
||||||
w = min(bbox[2] / crop_coordinates[2], 1 - x0)
|
|
||||||
h = min(bbox[3] / crop_coordinates[3], 1 - y0)
|
|
||||||
return x0, y0, w, h
|
|
||||||
|
|
||||||
return [rescale_bbox(b) for b in bboxes]
|
|
||||||
|
|
||||||
def apply_model(self, x_noisy, t, cond, return_ids=False):
|
def apply_model(self, x_noisy, t, cond, return_ids=False):
|
||||||
|
|
||||||
if isinstance(cond, dict):
|
if isinstance(cond, dict):
|
||||||
# hybrid case, cond is exptected to be a dict
|
# hybrid case, cond is expected to be a dict
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
if not isinstance(cond, list):
|
if not isinstance(cond, list):
|
||||||
@ -900,7 +890,7 @@ class LatentDiffusionV1(DDPMV1):
|
|||||||
|
|
||||||
if hasattr(self, "split_input_params"):
|
if hasattr(self, "split_input_params"):
|
||||||
assert len(cond) == 1 # todo can only deal with one conditioning atm
|
assert len(cond) == 1 # todo can only deal with one conditioning atm
|
||||||
assert not return_ids
|
assert not return_ids
|
||||||
ks = self.split_input_params["ks"] # eg. (128, 128)
|
ks = self.split_input_params["ks"] # eg. (128, 128)
|
||||||
stride = self.split_input_params["stride"] # eg. (64, 64)
|
stride = self.split_input_params["stride"] # eg. (64, 64)
|
||||||
|
|
||||||
@ -926,7 +916,7 @@ class LatentDiffusionV1(DDPMV1):
|
|||||||
cond_list = [{c_key: [c[:, :, :, :, i]]} for i in range(c.shape[-1])]
|
cond_list = [{c_key: [c[:, :, :, :, i]]} for i in range(c.shape[-1])]
|
||||||
|
|
||||||
elif self.cond_stage_key == 'coordinates_bbox':
|
elif self.cond_stage_key == 'coordinates_bbox':
|
||||||
assert 'original_image_size' in self.split_input_params, 'BoudingBoxRescaling is missing original_image_size'
|
assert 'original_image_size' in self.split_input_params, 'BoundingBoxRescaling is missing original_image_size'
|
||||||
|
|
||||||
# assuming padding of unfold is always 0 and its dilation is always 1
|
# assuming padding of unfold is always 0 and its dilation is always 1
|
||||||
n_patches_per_row = int((w - ks[0]) / stride[0] + 1)
|
n_patches_per_row = int((w - ks[0]) / stride[0] + 1)
|
||||||
@ -936,7 +926,7 @@ class LatentDiffusionV1(DDPMV1):
|
|||||||
num_downs = self.first_stage_model.encoder.num_resolutions - 1
|
num_downs = self.first_stage_model.encoder.num_resolutions - 1
|
||||||
rescale_latent = 2 ** (num_downs)
|
rescale_latent = 2 ** (num_downs)
|
||||||
|
|
||||||
# get top left postions of patches as conforming for the bbbox tokenizer, therefore we
|
# get top left positions of patches as conforming for the bbbox tokenizer, therefore we
|
||||||
# need to rescale the tl patch coordinates to be in between (0,1)
|
# need to rescale the tl patch coordinates to be in between (0,1)
|
||||||
tl_patch_coordinates = [(rescale_latent * stride[0] * (patch_nr % n_patches_per_row) / full_img_w,
|
tl_patch_coordinates = [(rescale_latent * stride[0] * (patch_nr % n_patches_per_row) / full_img_w,
|
||||||
rescale_latent * stride[1] * (patch_nr // n_patches_per_row) / full_img_h)
|
rescale_latent * stride[1] * (patch_nr // n_patches_per_row) / full_img_h)
|
||||||
@ -1126,7 +1116,7 @@ class LatentDiffusionV1(DDPMV1):
|
|||||||
if cond is not None:
|
if cond is not None:
|
||||||
if isinstance(cond, dict):
|
if isinstance(cond, dict):
|
||||||
cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
|
cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
|
||||||
list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
|
[x[:batch_size] for x in cond[key]] for key in cond}
|
||||||
else:
|
else:
|
||||||
cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
|
cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
|
||||||
|
|
||||||
@ -1157,8 +1147,10 @@ class LatentDiffusionV1(DDPMV1):
|
|||||||
|
|
||||||
if i % log_every_t == 0 or i == timesteps - 1:
|
if i % log_every_t == 0 or i == timesteps - 1:
|
||||||
intermediates.append(x0_partial)
|
intermediates.append(x0_partial)
|
||||||
if callback: callback(i)
|
if callback:
|
||||||
if img_callback: img_callback(img, i)
|
callback(i)
|
||||||
|
if img_callback:
|
||||||
|
img_callback(img, i)
|
||||||
return img, intermediates
|
return img, intermediates
|
||||||
|
|
||||||
@torch.no_grad()
|
@torch.no_grad()
|
||||||
@ -1205,8 +1197,10 @@ class LatentDiffusionV1(DDPMV1):
|
|||||||
|
|
||||||
if i % log_every_t == 0 or i == timesteps - 1:
|
if i % log_every_t == 0 or i == timesteps - 1:
|
||||||
intermediates.append(img)
|
intermediates.append(img)
|
||||||
if callback: callback(i)
|
if callback:
|
||||||
if img_callback: img_callback(img, i)
|
callback(i)
|
||||||
|
if img_callback:
|
||||||
|
img_callback(img, i)
|
||||||
|
|
||||||
if return_intermediates:
|
if return_intermediates:
|
||||||
return img, intermediates
|
return img, intermediates
|
||||||
@ -1221,7 +1215,7 @@ class LatentDiffusionV1(DDPMV1):
|
|||||||
if cond is not None:
|
if cond is not None:
|
||||||
if isinstance(cond, dict):
|
if isinstance(cond, dict):
|
||||||
cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
|
cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
|
||||||
list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
|
[x[:batch_size] for x in cond[key]] for key in cond}
|
||||||
else:
|
else:
|
||||||
cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
|
cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
|
||||||
return self.p_sample_loop(cond,
|
return self.p_sample_loop(cond,
|
||||||
@ -1253,7 +1247,7 @@ class LatentDiffusionV1(DDPMV1):
|
|||||||
|
|
||||||
use_ddim = ddim_steps is not None
|
use_ddim = ddim_steps is not None
|
||||||
|
|
||||||
log = dict()
|
log = {}
|
||||||
z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key,
|
z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key,
|
||||||
return_first_stage_outputs=True,
|
return_first_stage_outputs=True,
|
||||||
force_c_encode=True,
|
force_c_encode=True,
|
||||||
@ -1280,7 +1274,7 @@ class LatentDiffusionV1(DDPMV1):
|
|||||||
|
|
||||||
if plot_diffusion_rows:
|
if plot_diffusion_rows:
|
||||||
# get diffusion row
|
# get diffusion row
|
||||||
diffusion_row = list()
|
diffusion_row = []
|
||||||
z_start = z[:n_row]
|
z_start = z[:n_row]
|
||||||
for t in range(self.num_timesteps):
|
for t in range(self.num_timesteps):
|
||||||
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
|
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
|
||||||
@ -1322,7 +1316,7 @@ class LatentDiffusionV1(DDPMV1):
|
|||||||
|
|
||||||
if inpaint:
|
if inpaint:
|
||||||
# make a simple center square
|
# make a simple center square
|
||||||
b, h, w = z.shape[0], z.shape[2], z.shape[3]
|
h, w = z.shape[2], z.shape[3]
|
||||||
mask = torch.ones(N, h, w).to(self.device)
|
mask = torch.ones(N, h, w).to(self.device)
|
||||||
# zeros will be filled in
|
# zeros will be filled in
|
||||||
mask[:, h // 4:3 * h // 4, w // 4:3 * w // 4] = 0.
|
mask[:, h // 4:3 * h // 4, w // 4:3 * w // 4] = 0.
|
||||||
@ -1424,10 +1418,10 @@ class Layout2ImgDiffusionV1(LatentDiffusionV1):
|
|||||||
# TODO: move all layout-specific hacks to this class
|
# TODO: move all layout-specific hacks to this class
|
||||||
def __init__(self, cond_stage_key, *args, **kwargs):
|
def __init__(self, cond_stage_key, *args, **kwargs):
|
||||||
assert cond_stage_key == 'coordinates_bbox', 'Layout2ImgDiffusion only for cond_stage_key="coordinates_bbox"'
|
assert cond_stage_key == 'coordinates_bbox', 'Layout2ImgDiffusion only for cond_stage_key="coordinates_bbox"'
|
||||||
super().__init__(cond_stage_key=cond_stage_key, *args, **kwargs)
|
super().__init__(*args, cond_stage_key=cond_stage_key, **kwargs)
|
||||||
|
|
||||||
def log_images(self, batch, N=8, *args, **kwargs):
|
def log_images(self, batch, N=8, *args, **kwargs):
|
||||||
logs = super().log_images(batch=batch, N=N, *args, **kwargs)
|
logs = super().log_images(*args, batch=batch, N=N, **kwargs)
|
||||||
|
|
||||||
key = 'train' if self.training else 'validation'
|
key = 'train' if self.training else 'validation'
|
||||||
dset = self.trainer.datamodule.datasets[key]
|
dset = self.trainer.datamodule.datasets[key]
|
||||||
@ -1443,7 +1437,7 @@ class Layout2ImgDiffusionV1(LatentDiffusionV1):
|
|||||||
logs['bbox_image'] = cond_img
|
logs['bbox_image'] = cond_img
|
||||||
return logs
|
return logs
|
||||||
|
|
||||||
setattr(ldm.models.diffusion.ddpm, "DDPMV1", DDPMV1)
|
ldm.models.diffusion.ddpm.DDPMV1 = DDPMV1
|
||||||
setattr(ldm.models.diffusion.ddpm, "LatentDiffusionV1", LatentDiffusionV1)
|
ldm.models.diffusion.ddpm.LatentDiffusionV1 = LatentDiffusionV1
|
||||||
setattr(ldm.models.diffusion.ddpm, "DiffusionWrapperV1", DiffusionWrapperV1)
|
ldm.models.diffusion.ddpm.DiffusionWrapperV1 = DiffusionWrapperV1
|
||||||
setattr(ldm.models.diffusion.ddpm, "Layout2ImgDiffusionV1", Layout2ImgDiffusionV1)
|
ldm.models.diffusion.ddpm.Layout2ImgDiffusionV1 = Layout2ImgDiffusionV1
|
||||||
|
147
extensions-builtin/LDSR/vqvae_quantize.py
Normal file
147
extensions-builtin/LDSR/vqvae_quantize.py
Normal file
@ -0,0 +1,147 @@
|
|||||||
|
# Vendored from https://raw.githubusercontent.com/CompVis/taming-transformers/24268930bf1dce879235a7fddd0b2355b84d7ea6/taming/modules/vqvae/quantize.py,
|
||||||
|
# where the license is as follows:
|
||||||
|
#
|
||||||
|
# Copyright (c) 2020 Patrick Esser and Robin Rombach and Björn Ommer
|
||||||
|
#
|
||||||
|
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
# of this software and associated documentation files (the "Software"), to deal
|
||||||
|
# in the Software without restriction, including without limitation the rights
|
||||||
|
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
# copies of the Software, and to permit persons to whom the Software is
|
||||||
|
# furnished to do so, subject to the following conditions:
|
||||||
|
#
|
||||||
|
# The above copyright notice and this permission notice shall be included in all
|
||||||
|
# copies or substantial portions of the Software.
|
||||||
|
#
|
||||||
|
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||||
|
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||||
|
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||||
|
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
||||||
|
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
|
||||||
|
# OR OTHER DEALINGS IN THE SOFTWARE./
|
||||||
|
|
||||||
|
import torch
|
||||||
|
import torch.nn as nn
|
||||||
|
import numpy as np
|
||||||
|
from einops import rearrange
|
||||||
|
|
||||||
|
|
||||||
|
class VectorQuantizer2(nn.Module):
|
||||||
|
"""
|
||||||
|
Improved version over VectorQuantizer, can be used as a drop-in replacement. Mostly
|
||||||
|
avoids costly matrix multiplications and allows for post-hoc remapping of indices.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# NOTE: due to a bug the beta term was applied to the wrong term. for
|
||||||
|
# backwards compatibility we use the buggy version by default, but you can
|
||||||
|
# specify legacy=False to fix it.
|
||||||
|
def __init__(self, n_e, e_dim, beta, remap=None, unknown_index="random",
|
||||||
|
sane_index_shape=False, legacy=True):
|
||||||
|
super().__init__()
|
||||||
|
self.n_e = n_e
|
||||||
|
self.e_dim = e_dim
|
||||||
|
self.beta = beta
|
||||||
|
self.legacy = legacy
|
||||||
|
|
||||||
|
self.embedding = nn.Embedding(self.n_e, self.e_dim)
|
||||||
|
self.embedding.weight.data.uniform_(-1.0 / self.n_e, 1.0 / self.n_e)
|
||||||
|
|
||||||
|
self.remap = remap
|
||||||
|
if self.remap is not None:
|
||||||
|
self.register_buffer("used", torch.tensor(np.load(self.remap)))
|
||||||
|
self.re_embed = self.used.shape[0]
|
||||||
|
self.unknown_index = unknown_index # "random" or "extra" or integer
|
||||||
|
if self.unknown_index == "extra":
|
||||||
|
self.unknown_index = self.re_embed
|
||||||
|
self.re_embed = self.re_embed + 1
|
||||||
|
print(f"Remapping {self.n_e} indices to {self.re_embed} indices. "
|
||||||
|
f"Using {self.unknown_index} for unknown indices.")
|
||||||
|
else:
|
||||||
|
self.re_embed = n_e
|
||||||
|
|
||||||
|
self.sane_index_shape = sane_index_shape
|
||||||
|
|
||||||
|
def remap_to_used(self, inds):
|
||||||
|
ishape = inds.shape
|
||||||
|
assert len(ishape) > 1
|
||||||
|
inds = inds.reshape(ishape[0], -1)
|
||||||
|
used = self.used.to(inds)
|
||||||
|
match = (inds[:, :, None] == used[None, None, ...]).long()
|
||||||
|
new = match.argmax(-1)
|
||||||
|
unknown = match.sum(2) < 1
|
||||||
|
if self.unknown_index == "random":
|
||||||
|
new[unknown] = torch.randint(0, self.re_embed, size=new[unknown].shape).to(device=new.device)
|
||||||
|
else:
|
||||||
|
new[unknown] = self.unknown_index
|
||||||
|
return new.reshape(ishape)
|
||||||
|
|
||||||
|
def unmap_to_all(self, inds):
|
||||||
|
ishape = inds.shape
|
||||||
|
assert len(ishape) > 1
|
||||||
|
inds = inds.reshape(ishape[0], -1)
|
||||||
|
used = self.used.to(inds)
|
||||||
|
if self.re_embed > self.used.shape[0]: # extra token
|
||||||
|
inds[inds >= self.used.shape[0]] = 0 # simply set to zero
|
||||||
|
back = torch.gather(used[None, :][inds.shape[0] * [0], :], 1, inds)
|
||||||
|
return back.reshape(ishape)
|
||||||
|
|
||||||
|
def forward(self, z, temp=None, rescale_logits=False, return_logits=False):
|
||||||
|
assert temp is None or temp == 1.0, "Only for interface compatible with Gumbel"
|
||||||
|
assert rescale_logits is False, "Only for interface compatible with Gumbel"
|
||||||
|
assert return_logits is False, "Only for interface compatible with Gumbel"
|
||||||
|
# reshape z -> (batch, height, width, channel) and flatten
|
||||||
|
z = rearrange(z, 'b c h w -> b h w c').contiguous()
|
||||||
|
z_flattened = z.view(-1, self.e_dim)
|
||||||
|
# distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
|
||||||
|
|
||||||
|
d = torch.sum(z_flattened ** 2, dim=1, keepdim=True) + \
|
||||||
|
torch.sum(self.embedding.weight ** 2, dim=1) - 2 * \
|
||||||
|
torch.einsum('bd,dn->bn', z_flattened, rearrange(self.embedding.weight, 'n d -> d n'))
|
||||||
|
|
||||||
|
min_encoding_indices = torch.argmin(d, dim=1)
|
||||||
|
z_q = self.embedding(min_encoding_indices).view(z.shape)
|
||||||
|
perplexity = None
|
||||||
|
min_encodings = None
|
||||||
|
|
||||||
|
# compute loss for embedding
|
||||||
|
if not self.legacy:
|
||||||
|
loss = self.beta * torch.mean((z_q.detach() - z) ** 2) + \
|
||||||
|
torch.mean((z_q - z.detach()) ** 2)
|
||||||
|
else:
|
||||||
|
loss = torch.mean((z_q.detach() - z) ** 2) + self.beta * \
|
||||||
|
torch.mean((z_q - z.detach()) ** 2)
|
||||||
|
|
||||||
|
# preserve gradients
|
||||||
|
z_q = z + (z_q - z).detach()
|
||||||
|
|
||||||
|
# reshape back to match original input shape
|
||||||
|
z_q = rearrange(z_q, 'b h w c -> b c h w').contiguous()
|
||||||
|
|
||||||
|
if self.remap is not None:
|
||||||
|
min_encoding_indices = min_encoding_indices.reshape(z.shape[0], -1) # add batch axis
|
||||||
|
min_encoding_indices = self.remap_to_used(min_encoding_indices)
|
||||||
|
min_encoding_indices = min_encoding_indices.reshape(-1, 1) # flatten
|
||||||
|
|
||||||
|
if self.sane_index_shape:
|
||||||
|
min_encoding_indices = min_encoding_indices.reshape(
|
||||||
|
z_q.shape[0], z_q.shape[2], z_q.shape[3])
|
||||||
|
|
||||||
|
return z_q, loss, (perplexity, min_encodings, min_encoding_indices)
|
||||||
|
|
||||||
|
def get_codebook_entry(self, indices, shape):
|
||||||
|
# shape specifying (batch, height, width, channel)
|
||||||
|
if self.remap is not None:
|
||||||
|
indices = indices.reshape(shape[0], -1) # add batch axis
|
||||||
|
indices = self.unmap_to_all(indices)
|
||||||
|
indices = indices.reshape(-1) # flatten again
|
||||||
|
|
||||||
|
# get quantized latent vectors
|
||||||
|
z_q = self.embedding(indices)
|
||||||
|
|
||||||
|
if shape is not None:
|
||||||
|
z_q = z_q.view(shape)
|
||||||
|
# reshape back to match original input shape
|
||||||
|
z_q = z_q.permute(0, 3, 1, 2).contiguous()
|
||||||
|
|
||||||
|
return z_q
|
@ -1,27 +1,62 @@
|
|||||||
from modules import extra_networks, shared
|
from modules import extra_networks, shared
|
||||||
import lora
|
import networks
|
||||||
|
|
||||||
|
|
||||||
class ExtraNetworkLora(extra_networks.ExtraNetwork):
|
class ExtraNetworkLora(extra_networks.ExtraNetwork):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
super().__init__('lora')
|
super().__init__('lora')
|
||||||
|
|
||||||
|
self.errors = {}
|
||||||
|
"""mapping of network names to the number of errors the network had during operation"""
|
||||||
|
|
||||||
|
remove_symbols = str.maketrans('', '', ":,")
|
||||||
|
|
||||||
def activate(self, p, params_list):
|
def activate(self, p, params_list):
|
||||||
additional = shared.opts.sd_lora
|
additional = shared.opts.sd_lora
|
||||||
|
|
||||||
if additional != "None" and additional in lora.available_loras and len([x for x in params_list if x.items[0] == additional]) == 0:
|
self.errors.clear()
|
||||||
|
|
||||||
|
if additional != "None" and additional in networks.available_networks and not any(x for x in params_list if x.items[0] == additional):
|
||||||
p.all_prompts = [x + f"<lora:{additional}:{shared.opts.extra_networks_default_multiplier}>" for x in p.all_prompts]
|
p.all_prompts = [x + f"<lora:{additional}:{shared.opts.extra_networks_default_multiplier}>" for x in p.all_prompts]
|
||||||
params_list.append(extra_networks.ExtraNetworkParams(items=[additional, shared.opts.extra_networks_default_multiplier]))
|
params_list.append(extra_networks.ExtraNetworkParams(items=[additional, shared.opts.extra_networks_default_multiplier]))
|
||||||
|
|
||||||
names = []
|
names = []
|
||||||
multipliers = []
|
te_multipliers = []
|
||||||
|
unet_multipliers = []
|
||||||
|
dyn_dims = []
|
||||||
for params in params_list:
|
for params in params_list:
|
||||||
assert len(params.items) > 0
|
assert params.items
|
||||||
|
|
||||||
names.append(params.items[0])
|
names.append(params.positional[0])
|
||||||
multipliers.append(float(params.items[1]) if len(params.items) > 1 else 1.0)
|
|
||||||
|
|
||||||
lora.load_loras(names, multipliers)
|
te_multiplier = float(params.positional[1]) if len(params.positional) > 1 else 1.0
|
||||||
|
te_multiplier = float(params.named.get("te", te_multiplier))
|
||||||
|
|
||||||
|
unet_multiplier = float(params.positional[2]) if len(params.positional) > 2 else te_multiplier
|
||||||
|
unet_multiplier = float(params.named.get("unet", unet_multiplier))
|
||||||
|
|
||||||
|
dyn_dim = int(params.positional[3]) if len(params.positional) > 3 else None
|
||||||
|
dyn_dim = int(params.named["dyn"]) if "dyn" in params.named else dyn_dim
|
||||||
|
|
||||||
|
te_multipliers.append(te_multiplier)
|
||||||
|
unet_multipliers.append(unet_multiplier)
|
||||||
|
dyn_dims.append(dyn_dim)
|
||||||
|
|
||||||
|
networks.load_networks(names, te_multipliers, unet_multipliers, dyn_dims)
|
||||||
|
|
||||||
|
if shared.opts.lora_add_hashes_to_infotext:
|
||||||
|
if not getattr(p, "is_hr_pass", False) or not hasattr(p, "lora_hashes"):
|
||||||
|
p.lora_hashes = {}
|
||||||
|
|
||||||
|
for item in networks.loaded_networks:
|
||||||
|
if item.network_on_disk.shorthash and item.mentioned_name:
|
||||||
|
p.lora_hashes[item.mentioned_name.translate(self.remove_symbols)] = item.network_on_disk.shorthash
|
||||||
|
|
||||||
|
if p.lora_hashes:
|
||||||
|
p.extra_generation_params["Lora hashes"] = ', '.join(f'{k}: {v}' for k, v in p.lora_hashes.items())
|
||||||
|
|
||||||
def deactivate(self, p):
|
def deactivate(self, p):
|
||||||
pass
|
if self.errors:
|
||||||
|
p.comment("Networks with errors: " + ", ".join(f"{k} ({v})" for k, v in self.errors.items()))
|
||||||
|
|
||||||
|
self.errors.clear()
|
||||||
|
@ -1,450 +1,9 @@
|
|||||||
import glob
|
import networks
|
||||||
import os
|
|
||||||
import re
|
|
||||||
import torch
|
|
||||||
from typing import Union
|
|
||||||
|
|
||||||
from modules import shared, devices, sd_models, errors, scripts
|
list_available_loras = networks.list_available_networks
|
||||||
|
|
||||||
metadata_tags_order = {"ss_sd_model_name": 1, "ss_resolution": 2, "ss_clip_skip": 3, "ss_num_train_images": 10, "ss_tag_frequency": 20}
|
available_loras = networks.available_networks
|
||||||
|
available_lora_aliases = networks.available_network_aliases
|
||||||
re_digits = re.compile(r"\d+")
|
available_lora_hash_lookup = networks.available_network_hash_lookup
|
||||||
re_x_proj = re.compile(r"(.*)_([qkv]_proj)$")
|
forbidden_lora_aliases = networks.forbidden_network_aliases
|
||||||
re_compiled = {}
|
loaded_loras = networks.loaded_networks
|
||||||
|
|
||||||
suffix_conversion = {
|
|
||||||
"attentions": {},
|
|
||||||
"resnets": {
|
|
||||||
"conv1": "in_layers_2",
|
|
||||||
"conv2": "out_layers_3",
|
|
||||||
"time_emb_proj": "emb_layers_1",
|
|
||||||
"conv_shortcut": "skip_connection",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def convert_diffusers_name_to_compvis(key, is_sd2):
|
|
||||||
def match(match_list, regex_text):
|
|
||||||
regex = re_compiled.get(regex_text)
|
|
||||||
if regex is None:
|
|
||||||
regex = re.compile(regex_text)
|
|
||||||
re_compiled[regex_text] = regex
|
|
||||||
|
|
||||||
r = re.match(regex, key)
|
|
||||||
if not r:
|
|
||||||
return False
|
|
||||||
|
|
||||||
match_list.clear()
|
|
||||||
match_list.extend([int(x) if re.match(re_digits, x) else x for x in r.groups()])
|
|
||||||
return True
|
|
||||||
|
|
||||||
m = []
|
|
||||||
|
|
||||||
if match(m, r"lora_unet_down_blocks_(\d+)_(attentions|resnets)_(\d+)_(.+)"):
|
|
||||||
suffix = suffix_conversion.get(m[1], {}).get(m[3], m[3])
|
|
||||||
return f"diffusion_model_input_blocks_{1 + m[0] * 3 + m[2]}_{1 if m[1] == 'attentions' else 0}_{suffix}"
|
|
||||||
|
|
||||||
if match(m, r"lora_unet_mid_block_(attentions|resnets)_(\d+)_(.+)"):
|
|
||||||
suffix = suffix_conversion.get(m[0], {}).get(m[2], m[2])
|
|
||||||
return f"diffusion_model_middle_block_{1 if m[0] == 'attentions' else m[1] * 2}_{suffix}"
|
|
||||||
|
|
||||||
if match(m, r"lora_unet_up_blocks_(\d+)_(attentions|resnets)_(\d+)_(.+)"):
|
|
||||||
suffix = suffix_conversion.get(m[1], {}).get(m[3], m[3])
|
|
||||||
return f"diffusion_model_output_blocks_{m[0] * 3 + m[2]}_{1 if m[1] == 'attentions' else 0}_{suffix}"
|
|
||||||
|
|
||||||
if match(m, r"lora_unet_down_blocks_(\d+)_downsamplers_0_conv"):
|
|
||||||
return f"diffusion_model_input_blocks_{3 + m[0] * 3}_0_op"
|
|
||||||
|
|
||||||
if match(m, r"lora_unet_up_blocks_(\d+)_upsamplers_0_conv"):
|
|
||||||
return f"diffusion_model_output_blocks_{2 + m[0] * 3}_{2 if m[0]>0 else 1}_conv"
|
|
||||||
|
|
||||||
if match(m, r"lora_te_text_model_encoder_layers_(\d+)_(.+)"):
|
|
||||||
if is_sd2:
|
|
||||||
if 'mlp_fc1' in m[1]:
|
|
||||||
return f"model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc1', 'mlp_c_fc')}"
|
|
||||||
elif 'mlp_fc2' in m[1]:
|
|
||||||
return f"model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc2', 'mlp_c_proj')}"
|
|
||||||
else:
|
|
||||||
return f"model_transformer_resblocks_{m[0]}_{m[1].replace('self_attn', 'attn')}"
|
|
||||||
|
|
||||||
return f"transformer_text_model_encoder_layers_{m[0]}_{m[1]}"
|
|
||||||
|
|
||||||
return key
|
|
||||||
|
|
||||||
|
|
||||||
class LoraOnDisk:
|
|
||||||
def __init__(self, name, filename):
|
|
||||||
self.name = name
|
|
||||||
self.filename = filename
|
|
||||||
self.metadata = {}
|
|
||||||
|
|
||||||
_, ext = os.path.splitext(filename)
|
|
||||||
if ext.lower() == ".safetensors":
|
|
||||||
try:
|
|
||||||
self.metadata = sd_models.read_metadata_from_safetensors(filename)
|
|
||||||
except Exception as e:
|
|
||||||
errors.display(e, f"reading lora {filename}")
|
|
||||||
|
|
||||||
if self.metadata:
|
|
||||||
m = {}
|
|
||||||
for k, v in sorted(self.metadata.items(), key=lambda x: metadata_tags_order.get(x[0], 999)):
|
|
||||||
m[k] = v
|
|
||||||
|
|
||||||
self.metadata = m
|
|
||||||
|
|
||||||
self.ssmd_cover_images = self.metadata.pop('ssmd_cover_images', None) # those are cover images and they are too big to display in UI as text
|
|
||||||
self.alias = self.metadata.get('ss_output_name', self.name)
|
|
||||||
|
|
||||||
|
|
||||||
class LoraModule:
|
|
||||||
def __init__(self, name):
|
|
||||||
self.name = name
|
|
||||||
self.multiplier = 1.0
|
|
||||||
self.modules = {}
|
|
||||||
self.mtime = None
|
|
||||||
|
|
||||||
|
|
||||||
class LoraUpDownModule:
|
|
||||||
def __init__(self):
|
|
||||||
self.up = None
|
|
||||||
self.down = None
|
|
||||||
self.alpha = None
|
|
||||||
|
|
||||||
|
|
||||||
def assign_lora_names_to_compvis_modules(sd_model):
|
|
||||||
lora_layer_mapping = {}
|
|
||||||
|
|
||||||
for name, module in shared.sd_model.cond_stage_model.wrapped.named_modules():
|
|
||||||
lora_name = name.replace(".", "_")
|
|
||||||
lora_layer_mapping[lora_name] = module
|
|
||||||
module.lora_layer_name = lora_name
|
|
||||||
|
|
||||||
for name, module in shared.sd_model.model.named_modules():
|
|
||||||
lora_name = name.replace(".", "_")
|
|
||||||
lora_layer_mapping[lora_name] = module
|
|
||||||
module.lora_layer_name = lora_name
|
|
||||||
|
|
||||||
sd_model.lora_layer_mapping = lora_layer_mapping
|
|
||||||
|
|
||||||
|
|
||||||
def load_lora(name, filename):
|
|
||||||
lora = LoraModule(name)
|
|
||||||
lora.mtime = os.path.getmtime(filename)
|
|
||||||
|
|
||||||
sd = sd_models.read_state_dict(filename)
|
|
||||||
|
|
||||||
keys_failed_to_match = {}
|
|
||||||
is_sd2 = 'model_transformer_resblocks' in shared.sd_model.lora_layer_mapping
|
|
||||||
|
|
||||||
for key_diffusers, weight in sd.items():
|
|
||||||
key_diffusers_without_lora_parts, lora_key = key_diffusers.split(".", 1)
|
|
||||||
key = convert_diffusers_name_to_compvis(key_diffusers_without_lora_parts, is_sd2)
|
|
||||||
|
|
||||||
sd_module = shared.sd_model.lora_layer_mapping.get(key, None)
|
|
||||||
|
|
||||||
if sd_module is None:
|
|
||||||
m = re_x_proj.match(key)
|
|
||||||
if m:
|
|
||||||
sd_module = shared.sd_model.lora_layer_mapping.get(m.group(1), None)
|
|
||||||
|
|
||||||
if sd_module is None:
|
|
||||||
keys_failed_to_match[key_diffusers] = key
|
|
||||||
continue
|
|
||||||
|
|
||||||
lora_module = lora.modules.get(key, None)
|
|
||||||
if lora_module is None:
|
|
||||||
lora_module = LoraUpDownModule()
|
|
||||||
lora.modules[key] = lora_module
|
|
||||||
|
|
||||||
if lora_key == "alpha":
|
|
||||||
lora_module.alpha = weight.item()
|
|
||||||
continue
|
|
||||||
|
|
||||||
if type(sd_module) == torch.nn.Linear:
|
|
||||||
module = torch.nn.Linear(weight.shape[1], weight.shape[0], bias=False)
|
|
||||||
elif type(sd_module) == torch.nn.modules.linear.NonDynamicallyQuantizableLinear:
|
|
||||||
module = torch.nn.Linear(weight.shape[1], weight.shape[0], bias=False)
|
|
||||||
elif type(sd_module) == torch.nn.MultiheadAttention:
|
|
||||||
module = torch.nn.Linear(weight.shape[1], weight.shape[0], bias=False)
|
|
||||||
elif type(sd_module) == torch.nn.Conv2d and weight.shape[2:] == (1, 1):
|
|
||||||
module = torch.nn.Conv2d(weight.shape[1], weight.shape[0], (1, 1), bias=False)
|
|
||||||
elif type(sd_module) == torch.nn.Conv2d and weight.shape[2:] == (3, 3):
|
|
||||||
module = torch.nn.Conv2d(weight.shape[1], weight.shape[0], (3, 3), bias=False)
|
|
||||||
else:
|
|
||||||
print(f'Lora layer {key_diffusers} matched a layer with unsupported type: {type(sd_module).__name__}')
|
|
||||||
continue
|
|
||||||
assert False, f'Lora layer {key_diffusers} matched a layer with unsupported type: {type(sd_module).__name__}'
|
|
||||||
|
|
||||||
with torch.no_grad():
|
|
||||||
module.weight.copy_(weight)
|
|
||||||
|
|
||||||
module.to(device=devices.cpu, dtype=devices.dtype)
|
|
||||||
|
|
||||||
if lora_key == "lora_up.weight":
|
|
||||||
lora_module.up = module
|
|
||||||
elif lora_key == "lora_down.weight":
|
|
||||||
lora_module.down = module
|
|
||||||
else:
|
|
||||||
assert False, f'Bad Lora layer name: {key_diffusers} - must end in lora_up.weight, lora_down.weight or alpha'
|
|
||||||
|
|
||||||
if len(keys_failed_to_match) > 0:
|
|
||||||
print(f"Failed to match keys when loading Lora {filename}: {keys_failed_to_match}")
|
|
||||||
|
|
||||||
return lora
|
|
||||||
|
|
||||||
|
|
||||||
def load_loras(names, multipliers=None):
|
|
||||||
already_loaded = {}
|
|
||||||
|
|
||||||
for lora in loaded_loras:
|
|
||||||
if lora.name in names:
|
|
||||||
already_loaded[lora.name] = lora
|
|
||||||
|
|
||||||
loaded_loras.clear()
|
|
||||||
|
|
||||||
loras_on_disk = [available_lora_aliases.get(name, None) for name in names]
|
|
||||||
if any([x is None for x in loras_on_disk]):
|
|
||||||
list_available_loras()
|
|
||||||
|
|
||||||
loras_on_disk = [available_lora_aliases.get(name, None) for name in names]
|
|
||||||
|
|
||||||
for i, name in enumerate(names):
|
|
||||||
lora = already_loaded.get(name, None)
|
|
||||||
|
|
||||||
lora_on_disk = loras_on_disk[i]
|
|
||||||
if lora_on_disk is not None:
|
|
||||||
if lora is None or os.path.getmtime(lora_on_disk.filename) > lora.mtime:
|
|
||||||
try:
|
|
||||||
lora = load_lora(name, lora_on_disk.filename)
|
|
||||||
except Exception as e:
|
|
||||||
errors.display(e, f"loading Lora {lora_on_disk.filename}")
|
|
||||||
continue
|
|
||||||
|
|
||||||
if lora is None:
|
|
||||||
print(f"Couldn't find Lora with name {name}")
|
|
||||||
continue
|
|
||||||
|
|
||||||
lora.multiplier = multipliers[i] if multipliers else 1.0
|
|
||||||
loaded_loras.append(lora)
|
|
||||||
|
|
||||||
|
|
||||||
def lora_calc_updown(lora, module, target):
|
|
||||||
with torch.no_grad():
|
|
||||||
up = module.up.weight.to(target.device, dtype=target.dtype)
|
|
||||||
down = module.down.weight.to(target.device, dtype=target.dtype)
|
|
||||||
|
|
||||||
if up.shape[2:] == (1, 1) and down.shape[2:] == (1, 1):
|
|
||||||
updown = (up.squeeze(2).squeeze(2) @ down.squeeze(2).squeeze(2)).unsqueeze(2).unsqueeze(3)
|
|
||||||
elif up.shape[2:] == (3, 3) or down.shape[2:] == (3, 3):
|
|
||||||
updown = torch.nn.functional.conv2d(down.permute(1, 0, 2, 3), up).permute(1, 0, 2, 3)
|
|
||||||
else:
|
|
||||||
updown = up @ down
|
|
||||||
|
|
||||||
updown = updown * lora.multiplier * (module.alpha / module.up.weight.shape[1] if module.alpha else 1.0)
|
|
||||||
|
|
||||||
return updown
|
|
||||||
|
|
||||||
|
|
||||||
def lora_restore_weights_from_backup(self: Union[torch.nn.Conv2d, torch.nn.Linear, torch.nn.MultiheadAttention]):
|
|
||||||
weights_backup = getattr(self, "lora_weights_backup", None)
|
|
||||||
|
|
||||||
if weights_backup is None:
|
|
||||||
return
|
|
||||||
|
|
||||||
if isinstance(self, torch.nn.MultiheadAttention):
|
|
||||||
self.in_proj_weight.copy_(weights_backup[0])
|
|
||||||
self.out_proj.weight.copy_(weights_backup[1])
|
|
||||||
else:
|
|
||||||
self.weight.copy_(weights_backup)
|
|
||||||
|
|
||||||
|
|
||||||
def lora_apply_weights(self: Union[torch.nn.Conv2d, torch.nn.Linear, torch.nn.MultiheadAttention]):
|
|
||||||
"""
|
|
||||||
Applies the currently selected set of Loras to the weights of torch layer self.
|
|
||||||
If weights already have this particular set of loras applied, does nothing.
|
|
||||||
If not, restores orginal weights from backup and alters weights according to loras.
|
|
||||||
"""
|
|
||||||
|
|
||||||
lora_layer_name = getattr(self, 'lora_layer_name', None)
|
|
||||||
if lora_layer_name is None:
|
|
||||||
return
|
|
||||||
|
|
||||||
current_names = getattr(self, "lora_current_names", ())
|
|
||||||
wanted_names = tuple((x.name, x.multiplier) for x in loaded_loras)
|
|
||||||
|
|
||||||
weights_backup = getattr(self, "lora_weights_backup", None)
|
|
||||||
if weights_backup is None:
|
|
||||||
if isinstance(self, torch.nn.MultiheadAttention):
|
|
||||||
weights_backup = (self.in_proj_weight.to(devices.cpu, copy=True), self.out_proj.weight.to(devices.cpu, copy=True))
|
|
||||||
else:
|
|
||||||
weights_backup = self.weight.to(devices.cpu, copy=True)
|
|
||||||
|
|
||||||
self.lora_weights_backup = weights_backup
|
|
||||||
|
|
||||||
if current_names != wanted_names:
|
|
||||||
lora_restore_weights_from_backup(self)
|
|
||||||
|
|
||||||
for lora in loaded_loras:
|
|
||||||
module = lora.modules.get(lora_layer_name, None)
|
|
||||||
if module is not None and hasattr(self, 'weight'):
|
|
||||||
self.weight += lora_calc_updown(lora, module, self.weight)
|
|
||||||
continue
|
|
||||||
|
|
||||||
module_q = lora.modules.get(lora_layer_name + "_q_proj", None)
|
|
||||||
module_k = lora.modules.get(lora_layer_name + "_k_proj", None)
|
|
||||||
module_v = lora.modules.get(lora_layer_name + "_v_proj", None)
|
|
||||||
module_out = lora.modules.get(lora_layer_name + "_out_proj", None)
|
|
||||||
|
|
||||||
if isinstance(self, torch.nn.MultiheadAttention) and module_q and module_k and module_v and module_out:
|
|
||||||
updown_q = lora_calc_updown(lora, module_q, self.in_proj_weight)
|
|
||||||
updown_k = lora_calc_updown(lora, module_k, self.in_proj_weight)
|
|
||||||
updown_v = lora_calc_updown(lora, module_v, self.in_proj_weight)
|
|
||||||
updown_qkv = torch.vstack([updown_q, updown_k, updown_v])
|
|
||||||
|
|
||||||
self.in_proj_weight += updown_qkv
|
|
||||||
self.out_proj.weight += lora_calc_updown(lora, module_out, self.out_proj.weight)
|
|
||||||
continue
|
|
||||||
|
|
||||||
if module is None:
|
|
||||||
continue
|
|
||||||
|
|
||||||
print(f'failed to calculate lora weights for layer {lora_layer_name}')
|
|
||||||
|
|
||||||
setattr(self, "lora_current_names", wanted_names)
|
|
||||||
|
|
||||||
|
|
||||||
def lora_forward(module, input, original_forward):
|
|
||||||
"""
|
|
||||||
Old way of applying Lora by executing operations during layer's forward.
|
|
||||||
Stacking many loras this way results in big performance degradation.
|
|
||||||
"""
|
|
||||||
|
|
||||||
if len(loaded_loras) == 0:
|
|
||||||
return original_forward(module, input)
|
|
||||||
|
|
||||||
input = devices.cond_cast_unet(input)
|
|
||||||
|
|
||||||
lora_restore_weights_from_backup(module)
|
|
||||||
lora_reset_cached_weight(module)
|
|
||||||
|
|
||||||
res = original_forward(module, input)
|
|
||||||
|
|
||||||
lora_layer_name = getattr(module, 'lora_layer_name', None)
|
|
||||||
for lora in loaded_loras:
|
|
||||||
module = lora.modules.get(lora_layer_name, None)
|
|
||||||
if module is None:
|
|
||||||
continue
|
|
||||||
|
|
||||||
module.up.to(device=devices.device)
|
|
||||||
module.down.to(device=devices.device)
|
|
||||||
|
|
||||||
res = res + module.up(module.down(input)) * lora.multiplier * (module.alpha / module.up.weight.shape[1] if module.alpha else 1.0)
|
|
||||||
|
|
||||||
return res
|
|
||||||
|
|
||||||
|
|
||||||
def lora_reset_cached_weight(self: Union[torch.nn.Conv2d, torch.nn.Linear]):
|
|
||||||
setattr(self, "lora_current_names", ())
|
|
||||||
setattr(self, "lora_weights_backup", None)
|
|
||||||
|
|
||||||
|
|
||||||
def lora_Linear_forward(self, input):
|
|
||||||
if shared.opts.lora_functional:
|
|
||||||
return lora_forward(self, input, torch.nn.Linear_forward_before_lora)
|
|
||||||
|
|
||||||
lora_apply_weights(self)
|
|
||||||
|
|
||||||
return torch.nn.Linear_forward_before_lora(self, input)
|
|
||||||
|
|
||||||
|
|
||||||
def lora_Linear_load_state_dict(self, *args, **kwargs):
|
|
||||||
lora_reset_cached_weight(self)
|
|
||||||
|
|
||||||
return torch.nn.Linear_load_state_dict_before_lora(self, *args, **kwargs)
|
|
||||||
|
|
||||||
|
|
||||||
def lora_Conv2d_forward(self, input):
|
|
||||||
if shared.opts.lora_functional:
|
|
||||||
return lora_forward(self, input, torch.nn.Conv2d_forward_before_lora)
|
|
||||||
|
|
||||||
lora_apply_weights(self)
|
|
||||||
|
|
||||||
return torch.nn.Conv2d_forward_before_lora(self, input)
|
|
||||||
|
|
||||||
|
|
||||||
def lora_Conv2d_load_state_dict(self, *args, **kwargs):
|
|
||||||
lora_reset_cached_weight(self)
|
|
||||||
|
|
||||||
return torch.nn.Conv2d_load_state_dict_before_lora(self, *args, **kwargs)
|
|
||||||
|
|
||||||
|
|
||||||
def lora_MultiheadAttention_forward(self, *args, **kwargs):
|
|
||||||
lora_apply_weights(self)
|
|
||||||
|
|
||||||
return torch.nn.MultiheadAttention_forward_before_lora(self, *args, **kwargs)
|
|
||||||
|
|
||||||
|
|
||||||
def lora_MultiheadAttention_load_state_dict(self, *args, **kwargs):
|
|
||||||
lora_reset_cached_weight(self)
|
|
||||||
|
|
||||||
return torch.nn.MultiheadAttention_load_state_dict_before_lora(self, *args, **kwargs)
|
|
||||||
|
|
||||||
|
|
||||||
def list_available_loras():
|
|
||||||
available_loras.clear()
|
|
||||||
available_lora_aliases.clear()
|
|
||||||
|
|
||||||
os.makedirs(shared.cmd_opts.lora_dir, exist_ok=True)
|
|
||||||
|
|
||||||
candidates = list(shared.walk_files(shared.cmd_opts.lora_dir, allowed_extensions=[".pt", ".ckpt", ".safetensors"]))
|
|
||||||
for filename in sorted(candidates, key=str.lower):
|
|
||||||
if os.path.isdir(filename):
|
|
||||||
continue
|
|
||||||
|
|
||||||
name = os.path.splitext(os.path.basename(filename))[0]
|
|
||||||
entry = LoraOnDisk(name, filename)
|
|
||||||
|
|
||||||
available_loras[name] = entry
|
|
||||||
|
|
||||||
available_lora_aliases[name] = entry
|
|
||||||
available_lora_aliases[entry.alias] = entry
|
|
||||||
|
|
||||||
|
|
||||||
re_lora_name = re.compile(r"(.*)\s*\([0-9a-fA-F]+\)")
|
|
||||||
|
|
||||||
|
|
||||||
def infotext_pasted(infotext, params):
|
|
||||||
if "AddNet Module 1" in [x[1] for x in scripts.scripts_txt2img.infotext_fields]:
|
|
||||||
return # if the other extension is active, it will handle those fields, no need to do anything
|
|
||||||
|
|
||||||
added = []
|
|
||||||
|
|
||||||
for k, v in params.items():
|
|
||||||
if not k.startswith("AddNet Model "):
|
|
||||||
continue
|
|
||||||
|
|
||||||
num = k[13:]
|
|
||||||
|
|
||||||
if params.get("AddNet Module " + num) != "LoRA":
|
|
||||||
continue
|
|
||||||
|
|
||||||
name = params.get("AddNet Model " + num)
|
|
||||||
if name is None:
|
|
||||||
continue
|
|
||||||
|
|
||||||
m = re_lora_name.match(name)
|
|
||||||
if m:
|
|
||||||
name = m.group(1)
|
|
||||||
|
|
||||||
multiplier = params.get("AddNet Weight A " + num, "1.0")
|
|
||||||
|
|
||||||
added.append(f"<lora:{name}:{multiplier}>")
|
|
||||||
|
|
||||||
if added:
|
|
||||||
params["Prompt"] += "\n" + "".join(added)
|
|
||||||
|
|
||||||
available_loras = {}
|
|
||||||
available_lora_aliases = {}
|
|
||||||
loaded_loras = []
|
|
||||||
|
|
||||||
list_available_loras()
|
|
||||||
|
33
extensions-builtin/Lora/lora_logger.py
Normal file
33
extensions-builtin/Lora/lora_logger.py
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
import sys
|
||||||
|
import copy
|
||||||
|
import logging
|
||||||
|
|
||||||
|
|
||||||
|
class ColoredFormatter(logging.Formatter):
|
||||||
|
COLORS = {
|
||||||
|
"DEBUG": "\033[0;36m", # CYAN
|
||||||
|
"INFO": "\033[0;32m", # GREEN
|
||||||
|
"WARNING": "\033[0;33m", # YELLOW
|
||||||
|
"ERROR": "\033[0;31m", # RED
|
||||||
|
"CRITICAL": "\033[0;37;41m", # WHITE ON RED
|
||||||
|
"RESET": "\033[0m", # RESET COLOR
|
||||||
|
}
|
||||||
|
|
||||||
|
def format(self, record):
|
||||||
|
colored_record = copy.copy(record)
|
||||||
|
levelname = colored_record.levelname
|
||||||
|
seq = self.COLORS.get(levelname, self.COLORS["RESET"])
|
||||||
|
colored_record.levelname = f"{seq}{levelname}{self.COLORS['RESET']}"
|
||||||
|
return super().format(colored_record)
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger("lora")
|
||||||
|
logger.propagate = False
|
||||||
|
|
||||||
|
|
||||||
|
if not logger.handlers:
|
||||||
|
handler = logging.StreamHandler(sys.stdout)
|
||||||
|
handler.setFormatter(
|
||||||
|
ColoredFormatter("[%(name)s]-%(levelname)s: %(message)s")
|
||||||
|
)
|
||||||
|
logger.addHandler(handler)
|
31
extensions-builtin/Lora/lora_patches.py
Normal file
31
extensions-builtin/Lora/lora_patches.py
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
import torch
|
||||||
|
|
||||||
|
import networks
|
||||||
|
from modules import patches
|
||||||
|
|
||||||
|
|
||||||
|
class LoraPatches:
|
||||||
|
def __init__(self):
|
||||||
|
self.Linear_forward = patches.patch(__name__, torch.nn.Linear, 'forward', networks.network_Linear_forward)
|
||||||
|
self.Linear_load_state_dict = patches.patch(__name__, torch.nn.Linear, '_load_from_state_dict', networks.network_Linear_load_state_dict)
|
||||||
|
self.Conv2d_forward = patches.patch(__name__, torch.nn.Conv2d, 'forward', networks.network_Conv2d_forward)
|
||||||
|
self.Conv2d_load_state_dict = patches.patch(__name__, torch.nn.Conv2d, '_load_from_state_dict', networks.network_Conv2d_load_state_dict)
|
||||||
|
self.GroupNorm_forward = patches.patch(__name__, torch.nn.GroupNorm, 'forward', networks.network_GroupNorm_forward)
|
||||||
|
self.GroupNorm_load_state_dict = patches.patch(__name__, torch.nn.GroupNorm, '_load_from_state_dict', networks.network_GroupNorm_load_state_dict)
|
||||||
|
self.LayerNorm_forward = patches.patch(__name__, torch.nn.LayerNorm, 'forward', networks.network_LayerNorm_forward)
|
||||||
|
self.LayerNorm_load_state_dict = patches.patch(__name__, torch.nn.LayerNorm, '_load_from_state_dict', networks.network_LayerNorm_load_state_dict)
|
||||||
|
self.MultiheadAttention_forward = patches.patch(__name__, torch.nn.MultiheadAttention, 'forward', networks.network_MultiheadAttention_forward)
|
||||||
|
self.MultiheadAttention_load_state_dict = patches.patch(__name__, torch.nn.MultiheadAttention, '_load_from_state_dict', networks.network_MultiheadAttention_load_state_dict)
|
||||||
|
|
||||||
|
def undo(self):
|
||||||
|
self.Linear_forward = patches.undo(__name__, torch.nn.Linear, 'forward')
|
||||||
|
self.Linear_load_state_dict = patches.undo(__name__, torch.nn.Linear, '_load_from_state_dict')
|
||||||
|
self.Conv2d_forward = patches.undo(__name__, torch.nn.Conv2d, 'forward')
|
||||||
|
self.Conv2d_load_state_dict = patches.undo(__name__, torch.nn.Conv2d, '_load_from_state_dict')
|
||||||
|
self.GroupNorm_forward = patches.undo(__name__, torch.nn.GroupNorm, 'forward')
|
||||||
|
self.GroupNorm_load_state_dict = patches.undo(__name__, torch.nn.GroupNorm, '_load_from_state_dict')
|
||||||
|
self.LayerNorm_forward = patches.undo(__name__, torch.nn.LayerNorm, 'forward')
|
||||||
|
self.LayerNorm_load_state_dict = patches.undo(__name__, torch.nn.LayerNorm, '_load_from_state_dict')
|
||||||
|
self.MultiheadAttention_forward = patches.undo(__name__, torch.nn.MultiheadAttention, 'forward')
|
||||||
|
self.MultiheadAttention_load_state_dict = patches.undo(__name__, torch.nn.MultiheadAttention, '_load_from_state_dict')
|
||||||
|
|
68
extensions-builtin/Lora/lyco_helpers.py
Normal file
68
extensions-builtin/Lora/lyco_helpers.py
Normal file
@ -0,0 +1,68 @@
|
|||||||
|
import torch
|
||||||
|
|
||||||
|
|
||||||
|
def make_weight_cp(t, wa, wb):
|
||||||
|
temp = torch.einsum('i j k l, j r -> i r k l', t, wb)
|
||||||
|
return torch.einsum('i j k l, i r -> r j k l', temp, wa)
|
||||||
|
|
||||||
|
|
||||||
|
def rebuild_conventional(up, down, shape, dyn_dim=None):
|
||||||
|
up = up.reshape(up.size(0), -1)
|
||||||
|
down = down.reshape(down.size(0), -1)
|
||||||
|
if dyn_dim is not None:
|
||||||
|
up = up[:, :dyn_dim]
|
||||||
|
down = down[:dyn_dim, :]
|
||||||
|
return (up @ down).reshape(shape)
|
||||||
|
|
||||||
|
|
||||||
|
def rebuild_cp_decomposition(up, down, mid):
|
||||||
|
up = up.reshape(up.size(0), -1)
|
||||||
|
down = down.reshape(down.size(0), -1)
|
||||||
|
return torch.einsum('n m k l, i n, m j -> i j k l', mid, up, down)
|
||||||
|
|
||||||
|
|
||||||
|
# copied from https://github.com/KohakuBlueleaf/LyCORIS/blob/dev/lycoris/modules/lokr.py
|
||||||
|
def factorization(dimension: int, factor:int=-1) -> tuple[int, int]:
|
||||||
|
'''
|
||||||
|
return a tuple of two value of input dimension decomposed by the number closest to factor
|
||||||
|
second value is higher or equal than first value.
|
||||||
|
|
||||||
|
In LoRA with Kroneckor Product, first value is a value for weight scale.
|
||||||
|
secon value is a value for weight.
|
||||||
|
|
||||||
|
Because of non-commutative property, A⊗B ≠ B⊗A. Meaning of two matrices is slightly different.
|
||||||
|
|
||||||
|
examples)
|
||||||
|
factor
|
||||||
|
-1 2 4 8 16 ...
|
||||||
|
127 -> 1, 127 127 -> 1, 127 127 -> 1, 127 127 -> 1, 127 127 -> 1, 127
|
||||||
|
128 -> 8, 16 128 -> 2, 64 128 -> 4, 32 128 -> 8, 16 128 -> 8, 16
|
||||||
|
250 -> 10, 25 250 -> 2, 125 250 -> 2, 125 250 -> 5, 50 250 -> 10, 25
|
||||||
|
360 -> 8, 45 360 -> 2, 180 360 -> 4, 90 360 -> 8, 45 360 -> 12, 30
|
||||||
|
512 -> 16, 32 512 -> 2, 256 512 -> 4, 128 512 -> 8, 64 512 -> 16, 32
|
||||||
|
1024 -> 32, 32 1024 -> 2, 512 1024 -> 4, 256 1024 -> 8, 128 1024 -> 16, 64
|
||||||
|
'''
|
||||||
|
|
||||||
|
if factor > 0 and (dimension % factor) == 0:
|
||||||
|
m = factor
|
||||||
|
n = dimension // factor
|
||||||
|
if m > n:
|
||||||
|
n, m = m, n
|
||||||
|
return m, n
|
||||||
|
if factor < 0:
|
||||||
|
factor = dimension
|
||||||
|
m, n = 1, dimension
|
||||||
|
length = m + n
|
||||||
|
while m<n:
|
||||||
|
new_m = m + 1
|
||||||
|
while dimension%new_m != 0:
|
||||||
|
new_m += 1
|
||||||
|
new_n = dimension // new_m
|
||||||
|
if new_m + new_n > length or new_m>factor:
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
m, n = new_m, new_n
|
||||||
|
if m > n:
|
||||||
|
n, m = m, n
|
||||||
|
return m, n
|
||||||
|
|
228
extensions-builtin/Lora/network.py
Normal file
228
extensions-builtin/Lora/network.py
Normal file
@ -0,0 +1,228 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
import os
|
||||||
|
from collections import namedtuple
|
||||||
|
import enum
|
||||||
|
|
||||||
|
import torch.nn as nn
|
||||||
|
import torch.nn.functional as F
|
||||||
|
|
||||||
|
from modules import sd_models, cache, errors, hashes, shared
|
||||||
|
import modules.models.sd3.mmdit
|
||||||
|
|
||||||
|
NetworkWeights = namedtuple('NetworkWeights', ['network_key', 'sd_key', 'w', 'sd_module'])
|
||||||
|
|
||||||
|
metadata_tags_order = {"ss_sd_model_name": 1, "ss_resolution": 2, "ss_clip_skip": 3, "ss_num_train_images": 10, "ss_tag_frequency": 20}
|
||||||
|
|
||||||
|
|
||||||
|
class SdVersion(enum.Enum):
|
||||||
|
Unknown = 1
|
||||||
|
SD1 = 2
|
||||||
|
SD2 = 3
|
||||||
|
SDXL = 4
|
||||||
|
|
||||||
|
|
||||||
|
class NetworkOnDisk:
|
||||||
|
def __init__(self, name, filename):
|
||||||
|
self.name = name
|
||||||
|
self.filename = filename
|
||||||
|
self.metadata = {}
|
||||||
|
self.is_safetensors = os.path.splitext(filename)[1].lower() == ".safetensors"
|
||||||
|
|
||||||
|
def read_metadata():
|
||||||
|
metadata = sd_models.read_metadata_from_safetensors(filename)
|
||||||
|
|
||||||
|
return metadata
|
||||||
|
|
||||||
|
if self.is_safetensors:
|
||||||
|
try:
|
||||||
|
self.metadata = cache.cached_data_for_file('safetensors-metadata', "lora/" + self.name, filename, read_metadata)
|
||||||
|
except Exception as e:
|
||||||
|
errors.display(e, f"reading lora {filename}")
|
||||||
|
|
||||||
|
if self.metadata:
|
||||||
|
m = {}
|
||||||
|
for k, v in sorted(self.metadata.items(), key=lambda x: metadata_tags_order.get(x[0], 999)):
|
||||||
|
m[k] = v
|
||||||
|
|
||||||
|
self.metadata = m
|
||||||
|
|
||||||
|
self.alias = self.metadata.get('ss_output_name', self.name)
|
||||||
|
|
||||||
|
self.hash = None
|
||||||
|
self.shorthash = None
|
||||||
|
self.set_hash(
|
||||||
|
self.metadata.get('sshs_model_hash') or
|
||||||
|
hashes.sha256_from_cache(self.filename, "lora/" + self.name, use_addnet_hash=self.is_safetensors) or
|
||||||
|
''
|
||||||
|
)
|
||||||
|
|
||||||
|
self.sd_version = self.detect_version()
|
||||||
|
|
||||||
|
def detect_version(self):
|
||||||
|
if str(self.metadata.get('ss_base_model_version', "")).startswith("sdxl_"):
|
||||||
|
return SdVersion.SDXL
|
||||||
|
elif str(self.metadata.get('ss_v2', "")) == "True":
|
||||||
|
return SdVersion.SD2
|
||||||
|
elif len(self.metadata):
|
||||||
|
return SdVersion.SD1
|
||||||
|
|
||||||
|
return SdVersion.Unknown
|
||||||
|
|
||||||
|
def set_hash(self, v):
|
||||||
|
self.hash = v
|
||||||
|
self.shorthash = self.hash[0:12]
|
||||||
|
|
||||||
|
if self.shorthash:
|
||||||
|
import networks
|
||||||
|
networks.available_network_hash_lookup[self.shorthash] = self
|
||||||
|
|
||||||
|
def read_hash(self):
|
||||||
|
if not self.hash:
|
||||||
|
self.set_hash(hashes.sha256(self.filename, "lora/" + self.name, use_addnet_hash=self.is_safetensors) or '')
|
||||||
|
|
||||||
|
def get_alias(self):
|
||||||
|
import networks
|
||||||
|
if shared.opts.lora_preferred_name == "Filename" or self.alias.lower() in networks.forbidden_network_aliases:
|
||||||
|
return self.name
|
||||||
|
else:
|
||||||
|
return self.alias
|
||||||
|
|
||||||
|
|
||||||
|
class Network: # LoraModule
|
||||||
|
def __init__(self, name, network_on_disk: NetworkOnDisk):
|
||||||
|
self.name = name
|
||||||
|
self.network_on_disk = network_on_disk
|
||||||
|
self.te_multiplier = 1.0
|
||||||
|
self.unet_multiplier = 1.0
|
||||||
|
self.dyn_dim = None
|
||||||
|
self.modules = {}
|
||||||
|
self.bundle_embeddings = {}
|
||||||
|
self.mtime = None
|
||||||
|
|
||||||
|
self.mentioned_name = None
|
||||||
|
"""the text that was used to add the network to prompt - can be either name or an alias"""
|
||||||
|
|
||||||
|
|
||||||
|
class ModuleType:
|
||||||
|
def create_module(self, net: Network, weights: NetworkWeights) -> Network | None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class NetworkModule:
|
||||||
|
def __init__(self, net: Network, weights: NetworkWeights):
|
||||||
|
self.network = net
|
||||||
|
self.network_key = weights.network_key
|
||||||
|
self.sd_key = weights.sd_key
|
||||||
|
self.sd_module = weights.sd_module
|
||||||
|
|
||||||
|
if isinstance(self.sd_module, modules.models.sd3.mmdit.QkvLinear):
|
||||||
|
s = self.sd_module.weight.shape
|
||||||
|
self.shape = (s[0] // 3, s[1])
|
||||||
|
elif hasattr(self.sd_module, 'weight'):
|
||||||
|
self.shape = self.sd_module.weight.shape
|
||||||
|
elif isinstance(self.sd_module, nn.MultiheadAttention):
|
||||||
|
# For now, only self-attn use Pytorch's MHA
|
||||||
|
# So assume all qkvo proj have same shape
|
||||||
|
self.shape = self.sd_module.out_proj.weight.shape
|
||||||
|
else:
|
||||||
|
self.shape = None
|
||||||
|
|
||||||
|
self.ops = None
|
||||||
|
self.extra_kwargs = {}
|
||||||
|
if isinstance(self.sd_module, nn.Conv2d):
|
||||||
|
self.ops = F.conv2d
|
||||||
|
self.extra_kwargs = {
|
||||||
|
'stride': self.sd_module.stride,
|
||||||
|
'padding': self.sd_module.padding
|
||||||
|
}
|
||||||
|
elif isinstance(self.sd_module, nn.Linear):
|
||||||
|
self.ops = F.linear
|
||||||
|
elif isinstance(self.sd_module, nn.LayerNorm):
|
||||||
|
self.ops = F.layer_norm
|
||||||
|
self.extra_kwargs = {
|
||||||
|
'normalized_shape': self.sd_module.normalized_shape,
|
||||||
|
'eps': self.sd_module.eps
|
||||||
|
}
|
||||||
|
elif isinstance(self.sd_module, nn.GroupNorm):
|
||||||
|
self.ops = F.group_norm
|
||||||
|
self.extra_kwargs = {
|
||||||
|
'num_groups': self.sd_module.num_groups,
|
||||||
|
'eps': self.sd_module.eps
|
||||||
|
}
|
||||||
|
|
||||||
|
self.dim = None
|
||||||
|
self.bias = weights.w.get("bias")
|
||||||
|
self.alpha = weights.w["alpha"].item() if "alpha" in weights.w else None
|
||||||
|
self.scale = weights.w["scale"].item() if "scale" in weights.w else None
|
||||||
|
|
||||||
|
self.dora_scale = weights.w.get("dora_scale", None)
|
||||||
|
self.dora_norm_dims = len(self.shape) - 1
|
||||||
|
|
||||||
|
def multiplier(self):
|
||||||
|
if 'transformer' in self.sd_key[:20]:
|
||||||
|
return self.network.te_multiplier
|
||||||
|
else:
|
||||||
|
return self.network.unet_multiplier
|
||||||
|
|
||||||
|
def calc_scale(self):
|
||||||
|
if self.scale is not None:
|
||||||
|
return self.scale
|
||||||
|
if self.dim is not None and self.alpha is not None:
|
||||||
|
return self.alpha / self.dim
|
||||||
|
|
||||||
|
return 1.0
|
||||||
|
|
||||||
|
def apply_weight_decompose(self, updown, orig_weight):
|
||||||
|
# Match the device/dtype
|
||||||
|
orig_weight = orig_weight.to(updown.dtype)
|
||||||
|
dora_scale = self.dora_scale.to(device=orig_weight.device, dtype=updown.dtype)
|
||||||
|
updown = updown.to(orig_weight.device)
|
||||||
|
|
||||||
|
merged_scale1 = updown + orig_weight
|
||||||
|
merged_scale1_norm = (
|
||||||
|
merged_scale1.transpose(0, 1)
|
||||||
|
.reshape(merged_scale1.shape[1], -1)
|
||||||
|
.norm(dim=1, keepdim=True)
|
||||||
|
.reshape(merged_scale1.shape[1], *[1] * self.dora_norm_dims)
|
||||||
|
.transpose(0, 1)
|
||||||
|
)
|
||||||
|
|
||||||
|
dora_merged = (
|
||||||
|
merged_scale1 * (dora_scale / merged_scale1_norm)
|
||||||
|
)
|
||||||
|
final_updown = dora_merged - orig_weight
|
||||||
|
return final_updown
|
||||||
|
|
||||||
|
def finalize_updown(self, updown, orig_weight, output_shape, ex_bias=None):
|
||||||
|
if self.bias is not None:
|
||||||
|
updown = updown.reshape(self.bias.shape)
|
||||||
|
updown += self.bias.to(orig_weight.device, dtype=updown.dtype)
|
||||||
|
updown = updown.reshape(output_shape)
|
||||||
|
|
||||||
|
if len(output_shape) == 4:
|
||||||
|
updown = updown.reshape(output_shape)
|
||||||
|
|
||||||
|
if orig_weight.size().numel() == updown.size().numel():
|
||||||
|
updown = updown.reshape(orig_weight.shape)
|
||||||
|
|
||||||
|
if ex_bias is not None:
|
||||||
|
ex_bias = ex_bias * self.multiplier()
|
||||||
|
|
||||||
|
updown = updown * self.calc_scale()
|
||||||
|
|
||||||
|
if self.dora_scale is not None:
|
||||||
|
updown = self.apply_weight_decompose(updown, orig_weight)
|
||||||
|
|
||||||
|
return updown * self.multiplier(), ex_bias
|
||||||
|
|
||||||
|
def calc_updown(self, target):
|
||||||
|
raise NotImplementedError()
|
||||||
|
|
||||||
|
def forward(self, x, y):
|
||||||
|
"""A general forward implementation for all modules"""
|
||||||
|
if self.ops is None:
|
||||||
|
raise NotImplementedError()
|
||||||
|
else:
|
||||||
|
updown, ex_bias = self.calc_updown(self.sd_module.weight)
|
||||||
|
return y + self.ops(x, weight=updown, bias=ex_bias, **self.extra_kwargs)
|
||||||
|
|
27
extensions-builtin/Lora/network_full.py
Normal file
27
extensions-builtin/Lora/network_full.py
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
import network
|
||||||
|
|
||||||
|
|
||||||
|
class ModuleTypeFull(network.ModuleType):
|
||||||
|
def create_module(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
if all(x in weights.w for x in ["diff"]):
|
||||||
|
return NetworkModuleFull(net, weights)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class NetworkModuleFull(network.NetworkModule):
|
||||||
|
def __init__(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
super().__init__(net, weights)
|
||||||
|
|
||||||
|
self.weight = weights.w.get("diff")
|
||||||
|
self.ex_bias = weights.w.get("diff_b")
|
||||||
|
|
||||||
|
def calc_updown(self, orig_weight):
|
||||||
|
output_shape = self.weight.shape
|
||||||
|
updown = self.weight.to(orig_weight.device)
|
||||||
|
if self.ex_bias is not None:
|
||||||
|
ex_bias = self.ex_bias.to(orig_weight.device)
|
||||||
|
else:
|
||||||
|
ex_bias = None
|
||||||
|
|
||||||
|
return self.finalize_updown(updown, orig_weight, output_shape, ex_bias)
|
33
extensions-builtin/Lora/network_glora.py
Normal file
33
extensions-builtin/Lora/network_glora.py
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
|
||||||
|
import network
|
||||||
|
|
||||||
|
class ModuleTypeGLora(network.ModuleType):
|
||||||
|
def create_module(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
if all(x in weights.w for x in ["a1.weight", "a2.weight", "alpha", "b1.weight", "b2.weight"]):
|
||||||
|
return NetworkModuleGLora(net, weights)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
# adapted from https://github.com/KohakuBlueleaf/LyCORIS
|
||||||
|
class NetworkModuleGLora(network.NetworkModule):
|
||||||
|
def __init__(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
super().__init__(net, weights)
|
||||||
|
|
||||||
|
if hasattr(self.sd_module, 'weight'):
|
||||||
|
self.shape = self.sd_module.weight.shape
|
||||||
|
|
||||||
|
self.w1a = weights.w["a1.weight"]
|
||||||
|
self.w1b = weights.w["b1.weight"]
|
||||||
|
self.w2a = weights.w["a2.weight"]
|
||||||
|
self.w2b = weights.w["b2.weight"]
|
||||||
|
|
||||||
|
def calc_updown(self, orig_weight):
|
||||||
|
w1a = self.w1a.to(orig_weight.device)
|
||||||
|
w1b = self.w1b.to(orig_weight.device)
|
||||||
|
w2a = self.w2a.to(orig_weight.device)
|
||||||
|
w2b = self.w2b.to(orig_weight.device)
|
||||||
|
|
||||||
|
output_shape = [w1a.size(0), w1b.size(1)]
|
||||||
|
updown = ((w2b @ w1b) + ((orig_weight.to(dtype = w1a.dtype) @ w2a) @ w1a))
|
||||||
|
|
||||||
|
return self.finalize_updown(updown, orig_weight, output_shape)
|
55
extensions-builtin/Lora/network_hada.py
Normal file
55
extensions-builtin/Lora/network_hada.py
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
import lyco_helpers
|
||||||
|
import network
|
||||||
|
|
||||||
|
|
||||||
|
class ModuleTypeHada(network.ModuleType):
|
||||||
|
def create_module(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
if all(x in weights.w for x in ["hada_w1_a", "hada_w1_b", "hada_w2_a", "hada_w2_b"]):
|
||||||
|
return NetworkModuleHada(net, weights)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class NetworkModuleHada(network.NetworkModule):
|
||||||
|
def __init__(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
super().__init__(net, weights)
|
||||||
|
|
||||||
|
if hasattr(self.sd_module, 'weight'):
|
||||||
|
self.shape = self.sd_module.weight.shape
|
||||||
|
|
||||||
|
self.w1a = weights.w["hada_w1_a"]
|
||||||
|
self.w1b = weights.w["hada_w1_b"]
|
||||||
|
self.dim = self.w1b.shape[0]
|
||||||
|
self.w2a = weights.w["hada_w2_a"]
|
||||||
|
self.w2b = weights.w["hada_w2_b"]
|
||||||
|
|
||||||
|
self.t1 = weights.w.get("hada_t1")
|
||||||
|
self.t2 = weights.w.get("hada_t2")
|
||||||
|
|
||||||
|
def calc_updown(self, orig_weight):
|
||||||
|
w1a = self.w1a.to(orig_weight.device)
|
||||||
|
w1b = self.w1b.to(orig_weight.device)
|
||||||
|
w2a = self.w2a.to(orig_weight.device)
|
||||||
|
w2b = self.w2b.to(orig_weight.device)
|
||||||
|
|
||||||
|
output_shape = [w1a.size(0), w1b.size(1)]
|
||||||
|
|
||||||
|
if self.t1 is not None:
|
||||||
|
output_shape = [w1a.size(1), w1b.size(1)]
|
||||||
|
t1 = self.t1.to(orig_weight.device)
|
||||||
|
updown1 = lyco_helpers.make_weight_cp(t1, w1a, w1b)
|
||||||
|
output_shape += t1.shape[2:]
|
||||||
|
else:
|
||||||
|
if len(w1b.shape) == 4:
|
||||||
|
output_shape += w1b.shape[2:]
|
||||||
|
updown1 = lyco_helpers.rebuild_conventional(w1a, w1b, output_shape)
|
||||||
|
|
||||||
|
if self.t2 is not None:
|
||||||
|
t2 = self.t2.to(orig_weight.device)
|
||||||
|
updown2 = lyco_helpers.make_weight_cp(t2, w2a, w2b)
|
||||||
|
else:
|
||||||
|
updown2 = lyco_helpers.rebuild_conventional(w2a, w2b, output_shape)
|
||||||
|
|
||||||
|
updown = updown1 * updown2
|
||||||
|
|
||||||
|
return self.finalize_updown(updown, orig_weight, output_shape)
|
30
extensions-builtin/Lora/network_ia3.py
Normal file
30
extensions-builtin/Lora/network_ia3.py
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
import network
|
||||||
|
|
||||||
|
|
||||||
|
class ModuleTypeIa3(network.ModuleType):
|
||||||
|
def create_module(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
if all(x in weights.w for x in ["weight"]):
|
||||||
|
return NetworkModuleIa3(net, weights)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class NetworkModuleIa3(network.NetworkModule):
|
||||||
|
def __init__(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
super().__init__(net, weights)
|
||||||
|
|
||||||
|
self.w = weights.w["weight"]
|
||||||
|
self.on_input = weights.w["on_input"].item()
|
||||||
|
|
||||||
|
def calc_updown(self, orig_weight):
|
||||||
|
w = self.w.to(orig_weight.device)
|
||||||
|
|
||||||
|
output_shape = [w.size(0), orig_weight.size(1)]
|
||||||
|
if self.on_input:
|
||||||
|
output_shape.reverse()
|
||||||
|
else:
|
||||||
|
w = w.reshape(-1, 1)
|
||||||
|
|
||||||
|
updown = orig_weight * w
|
||||||
|
|
||||||
|
return self.finalize_updown(updown, orig_weight, output_shape)
|
64
extensions-builtin/Lora/network_lokr.py
Normal file
64
extensions-builtin/Lora/network_lokr.py
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
import torch
|
||||||
|
|
||||||
|
import lyco_helpers
|
||||||
|
import network
|
||||||
|
|
||||||
|
|
||||||
|
class ModuleTypeLokr(network.ModuleType):
|
||||||
|
def create_module(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
has_1 = "lokr_w1" in weights.w or ("lokr_w1_a" in weights.w and "lokr_w1_b" in weights.w)
|
||||||
|
has_2 = "lokr_w2" in weights.w or ("lokr_w2_a" in weights.w and "lokr_w2_b" in weights.w)
|
||||||
|
if has_1 and has_2:
|
||||||
|
return NetworkModuleLokr(net, weights)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def make_kron(orig_shape, w1, w2):
|
||||||
|
if len(w2.shape) == 4:
|
||||||
|
w1 = w1.unsqueeze(2).unsqueeze(2)
|
||||||
|
w2 = w2.contiguous()
|
||||||
|
return torch.kron(w1, w2).reshape(orig_shape)
|
||||||
|
|
||||||
|
|
||||||
|
class NetworkModuleLokr(network.NetworkModule):
|
||||||
|
def __init__(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
super().__init__(net, weights)
|
||||||
|
|
||||||
|
self.w1 = weights.w.get("lokr_w1")
|
||||||
|
self.w1a = weights.w.get("lokr_w1_a")
|
||||||
|
self.w1b = weights.w.get("lokr_w1_b")
|
||||||
|
self.dim = self.w1b.shape[0] if self.w1b is not None else self.dim
|
||||||
|
self.w2 = weights.w.get("lokr_w2")
|
||||||
|
self.w2a = weights.w.get("lokr_w2_a")
|
||||||
|
self.w2b = weights.w.get("lokr_w2_b")
|
||||||
|
self.dim = self.w2b.shape[0] if self.w2b is not None else self.dim
|
||||||
|
self.t2 = weights.w.get("lokr_t2")
|
||||||
|
|
||||||
|
def calc_updown(self, orig_weight):
|
||||||
|
if self.w1 is not None:
|
||||||
|
w1 = self.w1.to(orig_weight.device)
|
||||||
|
else:
|
||||||
|
w1a = self.w1a.to(orig_weight.device)
|
||||||
|
w1b = self.w1b.to(orig_weight.device)
|
||||||
|
w1 = w1a @ w1b
|
||||||
|
|
||||||
|
if self.w2 is not None:
|
||||||
|
w2 = self.w2.to(orig_weight.device)
|
||||||
|
elif self.t2 is None:
|
||||||
|
w2a = self.w2a.to(orig_weight.device)
|
||||||
|
w2b = self.w2b.to(orig_weight.device)
|
||||||
|
w2 = w2a @ w2b
|
||||||
|
else:
|
||||||
|
t2 = self.t2.to(orig_weight.device)
|
||||||
|
w2a = self.w2a.to(orig_weight.device)
|
||||||
|
w2b = self.w2b.to(orig_weight.device)
|
||||||
|
w2 = lyco_helpers.make_weight_cp(t2, w2a, w2b)
|
||||||
|
|
||||||
|
output_shape = [w1.size(0) * w2.size(0), w1.size(1) * w2.size(1)]
|
||||||
|
if len(orig_weight.shape) == 4:
|
||||||
|
output_shape = orig_weight.shape
|
||||||
|
|
||||||
|
updown = make_kron(output_shape, w1, w2)
|
||||||
|
|
||||||
|
return self.finalize_updown(updown, orig_weight, output_shape)
|
94
extensions-builtin/Lora/network_lora.py
Normal file
94
extensions-builtin/Lora/network_lora.py
Normal file
@ -0,0 +1,94 @@
|
|||||||
|
import torch
|
||||||
|
|
||||||
|
import lyco_helpers
|
||||||
|
import modules.models.sd3.mmdit
|
||||||
|
import network
|
||||||
|
from modules import devices
|
||||||
|
|
||||||
|
|
||||||
|
class ModuleTypeLora(network.ModuleType):
|
||||||
|
def create_module(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
if all(x in weights.w for x in ["lora_up.weight", "lora_down.weight"]):
|
||||||
|
return NetworkModuleLora(net, weights)
|
||||||
|
|
||||||
|
if all(x in weights.w for x in ["lora_A.weight", "lora_B.weight"]):
|
||||||
|
w = weights.w.copy()
|
||||||
|
weights.w.clear()
|
||||||
|
weights.w.update({"lora_up.weight": w["lora_B.weight"], "lora_down.weight": w["lora_A.weight"]})
|
||||||
|
|
||||||
|
return NetworkModuleLora(net, weights)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class NetworkModuleLora(network.NetworkModule):
|
||||||
|
def __init__(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
super().__init__(net, weights)
|
||||||
|
|
||||||
|
self.up_model = self.create_module(weights.w, "lora_up.weight")
|
||||||
|
self.down_model = self.create_module(weights.w, "lora_down.weight")
|
||||||
|
self.mid_model = self.create_module(weights.w, "lora_mid.weight", none_ok=True)
|
||||||
|
|
||||||
|
self.dim = weights.w["lora_down.weight"].shape[0]
|
||||||
|
|
||||||
|
def create_module(self, weights, key, none_ok=False):
|
||||||
|
weight = weights.get(key)
|
||||||
|
|
||||||
|
if weight is None and none_ok:
|
||||||
|
return None
|
||||||
|
|
||||||
|
is_linear = type(self.sd_module) in [torch.nn.Linear, torch.nn.modules.linear.NonDynamicallyQuantizableLinear, torch.nn.MultiheadAttention, modules.models.sd3.mmdit.QkvLinear]
|
||||||
|
is_conv = type(self.sd_module) in [torch.nn.Conv2d]
|
||||||
|
|
||||||
|
if is_linear:
|
||||||
|
weight = weight.reshape(weight.shape[0], -1)
|
||||||
|
module = torch.nn.Linear(weight.shape[1], weight.shape[0], bias=False)
|
||||||
|
elif is_conv and key == "lora_down.weight" or key == "dyn_up":
|
||||||
|
if len(weight.shape) == 2:
|
||||||
|
weight = weight.reshape(weight.shape[0], -1, 1, 1)
|
||||||
|
|
||||||
|
if weight.shape[2] != 1 or weight.shape[3] != 1:
|
||||||
|
module = torch.nn.Conv2d(weight.shape[1], weight.shape[0], self.sd_module.kernel_size, self.sd_module.stride, self.sd_module.padding, bias=False)
|
||||||
|
else:
|
||||||
|
module = torch.nn.Conv2d(weight.shape[1], weight.shape[0], (1, 1), bias=False)
|
||||||
|
elif is_conv and key == "lora_mid.weight":
|
||||||
|
module = torch.nn.Conv2d(weight.shape[1], weight.shape[0], self.sd_module.kernel_size, self.sd_module.stride, self.sd_module.padding, bias=False)
|
||||||
|
elif is_conv and key == "lora_up.weight" or key == "dyn_down":
|
||||||
|
module = torch.nn.Conv2d(weight.shape[1], weight.shape[0], (1, 1), bias=False)
|
||||||
|
else:
|
||||||
|
raise AssertionError(f'Lora layer {self.network_key} matched a layer with unsupported type: {type(self.sd_module).__name__}')
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
if weight.shape != module.weight.shape:
|
||||||
|
weight = weight.reshape(module.weight.shape)
|
||||||
|
module.weight.copy_(weight)
|
||||||
|
|
||||||
|
module.to(device=devices.cpu, dtype=devices.dtype)
|
||||||
|
module.weight.requires_grad_(False)
|
||||||
|
|
||||||
|
return module
|
||||||
|
|
||||||
|
def calc_updown(self, orig_weight):
|
||||||
|
up = self.up_model.weight.to(orig_weight.device)
|
||||||
|
down = self.down_model.weight.to(orig_weight.device)
|
||||||
|
|
||||||
|
output_shape = [up.size(0), down.size(1)]
|
||||||
|
if self.mid_model is not None:
|
||||||
|
# cp-decomposition
|
||||||
|
mid = self.mid_model.weight.to(orig_weight.device)
|
||||||
|
updown = lyco_helpers.rebuild_cp_decomposition(up, down, mid)
|
||||||
|
output_shape += mid.shape[2:]
|
||||||
|
else:
|
||||||
|
if len(down.shape) == 4:
|
||||||
|
output_shape += down.shape[2:]
|
||||||
|
updown = lyco_helpers.rebuild_conventional(up, down, output_shape, self.network.dyn_dim)
|
||||||
|
|
||||||
|
return self.finalize_updown(updown, orig_weight, output_shape)
|
||||||
|
|
||||||
|
def forward(self, x, y):
|
||||||
|
self.up_model.to(device=devices.device)
|
||||||
|
self.down_model.to(device=devices.device)
|
||||||
|
|
||||||
|
return y + self.up_model(self.down_model(x)) * self.multiplier() * self.calc_scale()
|
||||||
|
|
||||||
|
|
28
extensions-builtin/Lora/network_norm.py
Normal file
28
extensions-builtin/Lora/network_norm.py
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
import network
|
||||||
|
|
||||||
|
|
||||||
|
class ModuleTypeNorm(network.ModuleType):
|
||||||
|
def create_module(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
if all(x in weights.w for x in ["w_norm", "b_norm"]):
|
||||||
|
return NetworkModuleNorm(net, weights)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class NetworkModuleNorm(network.NetworkModule):
|
||||||
|
def __init__(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
super().__init__(net, weights)
|
||||||
|
|
||||||
|
self.w_norm = weights.w.get("w_norm")
|
||||||
|
self.b_norm = weights.w.get("b_norm")
|
||||||
|
|
||||||
|
def calc_updown(self, orig_weight):
|
||||||
|
output_shape = self.w_norm.shape
|
||||||
|
updown = self.w_norm.to(orig_weight.device)
|
||||||
|
|
||||||
|
if self.b_norm is not None:
|
||||||
|
ex_bias = self.b_norm.to(orig_weight.device)
|
||||||
|
else:
|
||||||
|
ex_bias = None
|
||||||
|
|
||||||
|
return self.finalize_updown(updown, orig_weight, output_shape, ex_bias)
|
118
extensions-builtin/Lora/network_oft.py
Normal file
118
extensions-builtin/Lora/network_oft.py
Normal file
@ -0,0 +1,118 @@
|
|||||||
|
import torch
|
||||||
|
import network
|
||||||
|
from einops import rearrange
|
||||||
|
|
||||||
|
|
||||||
|
class ModuleTypeOFT(network.ModuleType):
|
||||||
|
def create_module(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
if all(x in weights.w for x in ["oft_blocks"]) or all(x in weights.w for x in ["oft_diag"]):
|
||||||
|
return NetworkModuleOFT(net, weights)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Supports both kohya-ss' implementation of COFT https://github.com/kohya-ss/sd-scripts/blob/main/networks/oft.py
|
||||||
|
# and KohakuBlueleaf's implementation of OFT/COFT https://github.com/KohakuBlueleaf/LyCORIS/blob/dev/lycoris/modules/diag_oft.py
|
||||||
|
class NetworkModuleOFT(network.NetworkModule):
|
||||||
|
def __init__(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
|
||||||
|
super().__init__(net, weights)
|
||||||
|
|
||||||
|
self.lin_module = None
|
||||||
|
self.org_module: list[torch.Module] = [self.sd_module]
|
||||||
|
|
||||||
|
self.scale = 1.0
|
||||||
|
self.is_R = False
|
||||||
|
self.is_boft = False
|
||||||
|
|
||||||
|
# kohya-ss/New LyCORIS OFT/BOFT
|
||||||
|
if "oft_blocks" in weights.w.keys():
|
||||||
|
self.oft_blocks = weights.w["oft_blocks"] # (num_blocks, block_size, block_size)
|
||||||
|
self.alpha = weights.w.get("alpha", None) # alpha is constraint
|
||||||
|
self.dim = self.oft_blocks.shape[0] # lora dim
|
||||||
|
# Old LyCORIS OFT
|
||||||
|
elif "oft_diag" in weights.w.keys():
|
||||||
|
self.is_R = True
|
||||||
|
self.oft_blocks = weights.w["oft_diag"]
|
||||||
|
# self.alpha is unused
|
||||||
|
self.dim = self.oft_blocks.shape[1] # (num_blocks, block_size, block_size)
|
||||||
|
|
||||||
|
is_linear = type(self.sd_module) in [torch.nn.Linear, torch.nn.modules.linear.NonDynamicallyQuantizableLinear]
|
||||||
|
is_conv = type(self.sd_module) in [torch.nn.Conv2d]
|
||||||
|
is_other_linear = type(self.sd_module) in [torch.nn.MultiheadAttention] # unsupported
|
||||||
|
|
||||||
|
if is_linear:
|
||||||
|
self.out_dim = self.sd_module.out_features
|
||||||
|
elif is_conv:
|
||||||
|
self.out_dim = self.sd_module.out_channels
|
||||||
|
elif is_other_linear:
|
||||||
|
self.out_dim = self.sd_module.embed_dim
|
||||||
|
|
||||||
|
# LyCORIS BOFT
|
||||||
|
if self.oft_blocks.dim() == 4:
|
||||||
|
self.is_boft = True
|
||||||
|
self.rescale = weights.w.get('rescale', None)
|
||||||
|
if self.rescale is not None and not is_other_linear:
|
||||||
|
self.rescale = self.rescale.reshape(-1, *[1]*(self.org_module[0].weight.dim() - 1))
|
||||||
|
|
||||||
|
self.num_blocks = self.dim
|
||||||
|
self.block_size = self.out_dim // self.dim
|
||||||
|
self.constraint = (0 if self.alpha is None else self.alpha) * self.out_dim
|
||||||
|
if self.is_R:
|
||||||
|
self.constraint = None
|
||||||
|
self.block_size = self.dim
|
||||||
|
self.num_blocks = self.out_dim // self.dim
|
||||||
|
elif self.is_boft:
|
||||||
|
self.boft_m = self.oft_blocks.shape[0]
|
||||||
|
self.num_blocks = self.oft_blocks.shape[1]
|
||||||
|
self.block_size = self.oft_blocks.shape[2]
|
||||||
|
self.boft_b = self.block_size
|
||||||
|
|
||||||
|
def calc_updown(self, orig_weight):
|
||||||
|
oft_blocks = self.oft_blocks.to(orig_weight.device)
|
||||||
|
eye = torch.eye(self.block_size, device=oft_blocks.device)
|
||||||
|
|
||||||
|
if not self.is_R:
|
||||||
|
block_Q = oft_blocks - oft_blocks.transpose(-1, -2) # ensure skew-symmetric orthogonal matrix
|
||||||
|
if self.constraint != 0:
|
||||||
|
norm_Q = torch.norm(block_Q.flatten())
|
||||||
|
new_norm_Q = torch.clamp(norm_Q, max=self.constraint.to(oft_blocks.device))
|
||||||
|
block_Q = block_Q * ((new_norm_Q + 1e-8) / (norm_Q + 1e-8))
|
||||||
|
oft_blocks = torch.matmul(eye + block_Q, (eye - block_Q).float().inverse())
|
||||||
|
|
||||||
|
R = oft_blocks.to(orig_weight.device)
|
||||||
|
|
||||||
|
if not self.is_boft:
|
||||||
|
# This errors out for MultiheadAttention, might need to be handled up-stream
|
||||||
|
merged_weight = rearrange(orig_weight, '(k n) ... -> k n ...', k=self.num_blocks, n=self.block_size)
|
||||||
|
merged_weight = torch.einsum(
|
||||||
|
'k n m, k n ... -> k m ...',
|
||||||
|
R,
|
||||||
|
merged_weight
|
||||||
|
)
|
||||||
|
merged_weight = rearrange(merged_weight, 'k m ... -> (k m) ...')
|
||||||
|
else:
|
||||||
|
# TODO: determine correct value for scale
|
||||||
|
scale = 1.0
|
||||||
|
m = self.boft_m
|
||||||
|
b = self.boft_b
|
||||||
|
r_b = b // 2
|
||||||
|
inp = orig_weight
|
||||||
|
for i in range(m):
|
||||||
|
bi = R[i] # b_num, b_size, b_size
|
||||||
|
if i == 0:
|
||||||
|
# Apply multiplier/scale and rescale into first weight
|
||||||
|
bi = bi * scale + (1 - scale) * eye
|
||||||
|
inp = rearrange(inp, "(c g k) ... -> (c k g) ...", g=2, k=2**i * r_b)
|
||||||
|
inp = rearrange(inp, "(d b) ... -> d b ...", b=b)
|
||||||
|
inp = torch.einsum("b i j, b j ... -> b i ...", bi, inp)
|
||||||
|
inp = rearrange(inp, "d b ... -> (d b) ...")
|
||||||
|
inp = rearrange(inp, "(c k g) ... -> (c g k) ...", g=2, k=2**i * r_b)
|
||||||
|
merged_weight = inp
|
||||||
|
|
||||||
|
# Rescale mechanism
|
||||||
|
if self.rescale is not None:
|
||||||
|
merged_weight = self.rescale.to(merged_weight) * merged_weight
|
||||||
|
|
||||||
|
updown = merged_weight.to(orig_weight.device) - orig_weight.to(merged_weight.dtype)
|
||||||
|
output_shape = orig_weight.shape
|
||||||
|
return self.finalize_updown(updown, orig_weight, output_shape)
|
737
extensions-builtin/Lora/networks.py
Normal file
737
extensions-builtin/Lora/networks.py
Normal file
@ -0,0 +1,737 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
import gradio as gr
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
|
||||||
|
import lora_patches
|
||||||
|
import network
|
||||||
|
import network_lora
|
||||||
|
import network_glora
|
||||||
|
import network_hada
|
||||||
|
import network_ia3
|
||||||
|
import network_lokr
|
||||||
|
import network_full
|
||||||
|
import network_norm
|
||||||
|
import network_oft
|
||||||
|
|
||||||
|
import torch
|
||||||
|
from typing import Union
|
||||||
|
|
||||||
|
from modules import shared, devices, sd_models, errors, scripts, sd_hijack
|
||||||
|
import modules.textual_inversion.textual_inversion as textual_inversion
|
||||||
|
import modules.models.sd3.mmdit
|
||||||
|
|
||||||
|
from lora_logger import logger
|
||||||
|
|
||||||
|
module_types = [
|
||||||
|
network_lora.ModuleTypeLora(),
|
||||||
|
network_hada.ModuleTypeHada(),
|
||||||
|
network_ia3.ModuleTypeIa3(),
|
||||||
|
network_lokr.ModuleTypeLokr(),
|
||||||
|
network_full.ModuleTypeFull(),
|
||||||
|
network_norm.ModuleTypeNorm(),
|
||||||
|
network_glora.ModuleTypeGLora(),
|
||||||
|
network_oft.ModuleTypeOFT(),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
re_digits = re.compile(r"\d+")
|
||||||
|
re_x_proj = re.compile(r"(.*)_([qkv]_proj)$")
|
||||||
|
re_compiled = {}
|
||||||
|
|
||||||
|
suffix_conversion = {
|
||||||
|
"attentions": {},
|
||||||
|
"resnets": {
|
||||||
|
"conv1": "in_layers_2",
|
||||||
|
"conv2": "out_layers_3",
|
||||||
|
"norm1": "in_layers_0",
|
||||||
|
"norm2": "out_layers_0",
|
||||||
|
"time_emb_proj": "emb_layers_1",
|
||||||
|
"conv_shortcut": "skip_connection",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def convert_diffusers_name_to_compvis(key, is_sd2):
|
||||||
|
def match(match_list, regex_text):
|
||||||
|
regex = re_compiled.get(regex_text)
|
||||||
|
if regex is None:
|
||||||
|
regex = re.compile(regex_text)
|
||||||
|
re_compiled[regex_text] = regex
|
||||||
|
|
||||||
|
r = re.match(regex, key)
|
||||||
|
if not r:
|
||||||
|
return False
|
||||||
|
|
||||||
|
match_list.clear()
|
||||||
|
match_list.extend([int(x) if re.match(re_digits, x) else x for x in r.groups()])
|
||||||
|
return True
|
||||||
|
|
||||||
|
m = []
|
||||||
|
|
||||||
|
if match(m, r"lora_unet_conv_in(.*)"):
|
||||||
|
return f'diffusion_model_input_blocks_0_0{m[0]}'
|
||||||
|
|
||||||
|
if match(m, r"lora_unet_conv_out(.*)"):
|
||||||
|
return f'diffusion_model_out_2{m[0]}'
|
||||||
|
|
||||||
|
if match(m, r"lora_unet_time_embedding_linear_(\d+)(.*)"):
|
||||||
|
return f"diffusion_model_time_embed_{m[0] * 2 - 2}{m[1]}"
|
||||||
|
|
||||||
|
if match(m, r"lora_unet_down_blocks_(\d+)_(attentions|resnets)_(\d+)_(.+)"):
|
||||||
|
suffix = suffix_conversion.get(m[1], {}).get(m[3], m[3])
|
||||||
|
return f"diffusion_model_input_blocks_{1 + m[0] * 3 + m[2]}_{1 if m[1] == 'attentions' else 0}_{suffix}"
|
||||||
|
|
||||||
|
if match(m, r"lora_unet_mid_block_(attentions|resnets)_(\d+)_(.+)"):
|
||||||
|
suffix = suffix_conversion.get(m[0], {}).get(m[2], m[2])
|
||||||
|
return f"diffusion_model_middle_block_{1 if m[0] == 'attentions' else m[1] * 2}_{suffix}"
|
||||||
|
|
||||||
|
if match(m, r"lora_unet_up_blocks_(\d+)_(attentions|resnets)_(\d+)_(.+)"):
|
||||||
|
suffix = suffix_conversion.get(m[1], {}).get(m[3], m[3])
|
||||||
|
return f"diffusion_model_output_blocks_{m[0] * 3 + m[2]}_{1 if m[1] == 'attentions' else 0}_{suffix}"
|
||||||
|
|
||||||
|
if match(m, r"lora_unet_down_blocks_(\d+)_downsamplers_0_conv"):
|
||||||
|
return f"diffusion_model_input_blocks_{3 + m[0] * 3}_0_op"
|
||||||
|
|
||||||
|
if match(m, r"lora_unet_up_blocks_(\d+)_upsamplers_0_conv"):
|
||||||
|
return f"diffusion_model_output_blocks_{2 + m[0] * 3}_{2 if m[0]>0 else 1}_conv"
|
||||||
|
|
||||||
|
if match(m, r"lora_te_text_model_encoder_layers_(\d+)_(.+)"):
|
||||||
|
if is_sd2:
|
||||||
|
if 'mlp_fc1' in m[1]:
|
||||||
|
return f"model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc1', 'mlp_c_fc')}"
|
||||||
|
elif 'mlp_fc2' in m[1]:
|
||||||
|
return f"model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc2', 'mlp_c_proj')}"
|
||||||
|
else:
|
||||||
|
return f"model_transformer_resblocks_{m[0]}_{m[1].replace('self_attn', 'attn')}"
|
||||||
|
|
||||||
|
return f"transformer_text_model_encoder_layers_{m[0]}_{m[1]}"
|
||||||
|
|
||||||
|
if match(m, r"lora_te2_text_model_encoder_layers_(\d+)_(.+)"):
|
||||||
|
if 'mlp_fc1' in m[1]:
|
||||||
|
return f"1_model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc1', 'mlp_c_fc')}"
|
||||||
|
elif 'mlp_fc2' in m[1]:
|
||||||
|
return f"1_model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc2', 'mlp_c_proj')}"
|
||||||
|
else:
|
||||||
|
return f"1_model_transformer_resblocks_{m[0]}_{m[1].replace('self_attn', 'attn')}"
|
||||||
|
|
||||||
|
return key
|
||||||
|
|
||||||
|
|
||||||
|
def assign_network_names_to_compvis_modules(sd_model):
|
||||||
|
network_layer_mapping = {}
|
||||||
|
|
||||||
|
if shared.sd_model.is_sdxl:
|
||||||
|
for i, embedder in enumerate(shared.sd_model.conditioner.embedders):
|
||||||
|
if not hasattr(embedder, 'wrapped'):
|
||||||
|
continue
|
||||||
|
|
||||||
|
for name, module in embedder.wrapped.named_modules():
|
||||||
|
network_name = f'{i}_{name.replace(".", "_")}'
|
||||||
|
network_layer_mapping[network_name] = module
|
||||||
|
module.network_layer_name = network_name
|
||||||
|
else:
|
||||||
|
cond_stage_model = getattr(shared.sd_model.cond_stage_model, 'wrapped', shared.sd_model.cond_stage_model)
|
||||||
|
|
||||||
|
for name, module in cond_stage_model.named_modules():
|
||||||
|
network_name = name.replace(".", "_")
|
||||||
|
network_layer_mapping[network_name] = module
|
||||||
|
module.network_layer_name = network_name
|
||||||
|
|
||||||
|
for name, module in shared.sd_model.model.named_modules():
|
||||||
|
network_name = name.replace(".", "_")
|
||||||
|
network_layer_mapping[network_name] = module
|
||||||
|
module.network_layer_name = network_name
|
||||||
|
|
||||||
|
sd_model.network_layer_mapping = network_layer_mapping
|
||||||
|
|
||||||
|
|
||||||
|
class BundledTIHash(str):
|
||||||
|
def __init__(self, hash_str):
|
||||||
|
self.hash = hash_str
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return self.hash if shared.opts.lora_bundled_ti_to_infotext else ''
|
||||||
|
|
||||||
|
|
||||||
|
def load_network(name, network_on_disk):
|
||||||
|
net = network.Network(name, network_on_disk)
|
||||||
|
net.mtime = os.path.getmtime(network_on_disk.filename)
|
||||||
|
|
||||||
|
sd = sd_models.read_state_dict(network_on_disk.filename)
|
||||||
|
|
||||||
|
# this should not be needed but is here as an emergency fix for an unknown error people are experiencing in 1.2.0
|
||||||
|
if not hasattr(shared.sd_model, 'network_layer_mapping'):
|
||||||
|
assign_network_names_to_compvis_modules(shared.sd_model)
|
||||||
|
|
||||||
|
keys_failed_to_match = {}
|
||||||
|
is_sd2 = 'model_transformer_resblocks' in shared.sd_model.network_layer_mapping
|
||||||
|
if hasattr(shared.sd_model, 'diffusers_weight_map'):
|
||||||
|
diffusers_weight_map = shared.sd_model.diffusers_weight_map
|
||||||
|
elif hasattr(shared.sd_model, 'diffusers_weight_mapping'):
|
||||||
|
diffusers_weight_map = {}
|
||||||
|
for k, v in shared.sd_model.diffusers_weight_mapping():
|
||||||
|
diffusers_weight_map[k] = v
|
||||||
|
shared.sd_model.diffusers_weight_map = diffusers_weight_map
|
||||||
|
else:
|
||||||
|
diffusers_weight_map = None
|
||||||
|
|
||||||
|
matched_networks = {}
|
||||||
|
bundle_embeddings = {}
|
||||||
|
|
||||||
|
for key_network, weight in sd.items():
|
||||||
|
|
||||||
|
if diffusers_weight_map:
|
||||||
|
key_network_without_network_parts, network_name, network_weight = key_network.rsplit(".", 2)
|
||||||
|
network_part = network_name + '.' + network_weight
|
||||||
|
else:
|
||||||
|
key_network_without_network_parts, _, network_part = key_network.partition(".")
|
||||||
|
|
||||||
|
if key_network_without_network_parts == "bundle_emb":
|
||||||
|
emb_name, vec_name = network_part.split(".", 1)
|
||||||
|
emb_dict = bundle_embeddings.get(emb_name, {})
|
||||||
|
if vec_name.split('.')[0] == 'string_to_param':
|
||||||
|
_, k2 = vec_name.split('.', 1)
|
||||||
|
emb_dict['string_to_param'] = {k2: weight}
|
||||||
|
else:
|
||||||
|
emb_dict[vec_name] = weight
|
||||||
|
bundle_embeddings[emb_name] = emb_dict
|
||||||
|
|
||||||
|
if diffusers_weight_map:
|
||||||
|
key = diffusers_weight_map.get(key_network_without_network_parts, key_network_without_network_parts)
|
||||||
|
else:
|
||||||
|
key = convert_diffusers_name_to_compvis(key_network_without_network_parts, is_sd2)
|
||||||
|
|
||||||
|
sd_module = shared.sd_model.network_layer_mapping.get(key, None)
|
||||||
|
|
||||||
|
if sd_module is None:
|
||||||
|
m = re_x_proj.match(key)
|
||||||
|
if m:
|
||||||
|
sd_module = shared.sd_model.network_layer_mapping.get(m.group(1), None)
|
||||||
|
|
||||||
|
# SDXL loras seem to already have correct compvis keys, so only need to replace "lora_unet" with "diffusion_model"
|
||||||
|
if sd_module is None and "lora_unet" in key_network_without_network_parts:
|
||||||
|
key = key_network_without_network_parts.replace("lora_unet", "diffusion_model")
|
||||||
|
sd_module = shared.sd_model.network_layer_mapping.get(key, None)
|
||||||
|
elif sd_module is None and "lora_te1_text_model" in key_network_without_network_parts:
|
||||||
|
key = key_network_without_network_parts.replace("lora_te1_text_model", "0_transformer_text_model")
|
||||||
|
sd_module = shared.sd_model.network_layer_mapping.get(key, None)
|
||||||
|
|
||||||
|
# some SD1 Loras also have correct compvis keys
|
||||||
|
if sd_module is None:
|
||||||
|
key = key_network_without_network_parts.replace("lora_te1_text_model", "transformer_text_model")
|
||||||
|
sd_module = shared.sd_model.network_layer_mapping.get(key, None)
|
||||||
|
|
||||||
|
# kohya_ss OFT module
|
||||||
|
elif sd_module is None and "oft_unet" in key_network_without_network_parts:
|
||||||
|
key = key_network_without_network_parts.replace("oft_unet", "diffusion_model")
|
||||||
|
sd_module = shared.sd_model.network_layer_mapping.get(key, None)
|
||||||
|
|
||||||
|
# KohakuBlueLeaf OFT module
|
||||||
|
if sd_module is None and "oft_diag" in key:
|
||||||
|
key = key_network_without_network_parts.replace("lora_unet", "diffusion_model")
|
||||||
|
key = key_network_without_network_parts.replace("lora_te1_text_model", "0_transformer_text_model")
|
||||||
|
sd_module = shared.sd_model.network_layer_mapping.get(key, None)
|
||||||
|
|
||||||
|
if sd_module is None:
|
||||||
|
keys_failed_to_match[key_network] = key
|
||||||
|
continue
|
||||||
|
|
||||||
|
if key not in matched_networks:
|
||||||
|
matched_networks[key] = network.NetworkWeights(network_key=key_network, sd_key=key, w={}, sd_module=sd_module)
|
||||||
|
|
||||||
|
matched_networks[key].w[network_part] = weight
|
||||||
|
|
||||||
|
for key, weights in matched_networks.items():
|
||||||
|
net_module = None
|
||||||
|
for nettype in module_types:
|
||||||
|
net_module = nettype.create_module(net, weights)
|
||||||
|
if net_module is not None:
|
||||||
|
break
|
||||||
|
|
||||||
|
if net_module is None:
|
||||||
|
raise AssertionError(f"Could not find a module type (out of {', '.join([x.__class__.__name__ for x in module_types])}) that would accept those keys: {', '.join(weights.w)}")
|
||||||
|
|
||||||
|
net.modules[key] = net_module
|
||||||
|
|
||||||
|
embeddings = {}
|
||||||
|
for emb_name, data in bundle_embeddings.items():
|
||||||
|
embedding = textual_inversion.create_embedding_from_data(data, emb_name, filename=network_on_disk.filename + "/" + emb_name)
|
||||||
|
embedding.loaded = None
|
||||||
|
embedding.shorthash = BundledTIHash(name)
|
||||||
|
embeddings[emb_name] = embedding
|
||||||
|
|
||||||
|
net.bundle_embeddings = embeddings
|
||||||
|
|
||||||
|
if keys_failed_to_match:
|
||||||
|
logging.debug(f"Network {network_on_disk.filename} didn't match keys: {keys_failed_to_match}")
|
||||||
|
|
||||||
|
return net
|
||||||
|
|
||||||
|
|
||||||
|
def purge_networks_from_memory():
|
||||||
|
while len(networks_in_memory) > shared.opts.lora_in_memory_limit and len(networks_in_memory) > 0:
|
||||||
|
name = next(iter(networks_in_memory))
|
||||||
|
networks_in_memory.pop(name, None)
|
||||||
|
|
||||||
|
devices.torch_gc()
|
||||||
|
|
||||||
|
|
||||||
|
def load_networks(names, te_multipliers=None, unet_multipliers=None, dyn_dims=None):
|
||||||
|
emb_db = sd_hijack.model_hijack.embedding_db
|
||||||
|
already_loaded = {}
|
||||||
|
|
||||||
|
for net in loaded_networks:
|
||||||
|
if net.name in names:
|
||||||
|
already_loaded[net.name] = net
|
||||||
|
for emb_name, embedding in net.bundle_embeddings.items():
|
||||||
|
if embedding.loaded:
|
||||||
|
emb_db.register_embedding_by_name(None, shared.sd_model, emb_name)
|
||||||
|
|
||||||
|
loaded_networks.clear()
|
||||||
|
|
||||||
|
unavailable_networks = []
|
||||||
|
for name in names:
|
||||||
|
if name.lower() in forbidden_network_aliases and available_networks.get(name) is None:
|
||||||
|
unavailable_networks.append(name)
|
||||||
|
elif available_network_aliases.get(name) is None:
|
||||||
|
unavailable_networks.append(name)
|
||||||
|
|
||||||
|
if unavailable_networks:
|
||||||
|
update_available_networks_by_names(unavailable_networks)
|
||||||
|
|
||||||
|
networks_on_disk = [available_networks.get(name, None) if name.lower() in forbidden_network_aliases else available_network_aliases.get(name, None) for name in names]
|
||||||
|
if any(x is None for x in networks_on_disk):
|
||||||
|
list_available_networks()
|
||||||
|
|
||||||
|
networks_on_disk = [available_networks.get(name, None) if name.lower() in forbidden_network_aliases else available_network_aliases.get(name, None) for name in names]
|
||||||
|
|
||||||
|
failed_to_load_networks = []
|
||||||
|
|
||||||
|
for i, (network_on_disk, name) in enumerate(zip(networks_on_disk, names)):
|
||||||
|
net = already_loaded.get(name, None)
|
||||||
|
|
||||||
|
if network_on_disk is not None:
|
||||||
|
if net is None:
|
||||||
|
net = networks_in_memory.get(name)
|
||||||
|
|
||||||
|
if net is None or os.path.getmtime(network_on_disk.filename) > net.mtime:
|
||||||
|
try:
|
||||||
|
net = load_network(name, network_on_disk)
|
||||||
|
|
||||||
|
networks_in_memory.pop(name, None)
|
||||||
|
networks_in_memory[name] = net
|
||||||
|
except Exception as e:
|
||||||
|
errors.display(e, f"loading network {network_on_disk.filename}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
net.mentioned_name = name
|
||||||
|
|
||||||
|
network_on_disk.read_hash()
|
||||||
|
|
||||||
|
if net is None:
|
||||||
|
failed_to_load_networks.append(name)
|
||||||
|
logging.info(f"Couldn't find network with name {name}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
net.te_multiplier = te_multipliers[i] if te_multipliers else 1.0
|
||||||
|
net.unet_multiplier = unet_multipliers[i] if unet_multipliers else 1.0
|
||||||
|
net.dyn_dim = dyn_dims[i] if dyn_dims else 1.0
|
||||||
|
loaded_networks.append(net)
|
||||||
|
|
||||||
|
for emb_name, embedding in net.bundle_embeddings.items():
|
||||||
|
if embedding.loaded is None and emb_name in emb_db.word_embeddings:
|
||||||
|
logger.warning(
|
||||||
|
f'Skip bundle embedding: "{emb_name}"'
|
||||||
|
' as it was already loaded from embeddings folder'
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
|
embedding.loaded = False
|
||||||
|
if emb_db.expected_shape == -1 or emb_db.expected_shape == embedding.shape:
|
||||||
|
embedding.loaded = True
|
||||||
|
emb_db.register_embedding(embedding, shared.sd_model)
|
||||||
|
else:
|
||||||
|
emb_db.skipped_embeddings[name] = embedding
|
||||||
|
|
||||||
|
if failed_to_load_networks:
|
||||||
|
lora_not_found_message = f'Lora not found: {", ".join(failed_to_load_networks)}'
|
||||||
|
sd_hijack.model_hijack.comments.append(lora_not_found_message)
|
||||||
|
if shared.opts.lora_not_found_warning_console:
|
||||||
|
print(f'\n{lora_not_found_message}\n')
|
||||||
|
if shared.opts.lora_not_found_gradio_warning:
|
||||||
|
gr.Warning(lora_not_found_message)
|
||||||
|
|
||||||
|
purge_networks_from_memory()
|
||||||
|
|
||||||
|
|
||||||
|
def allowed_layer_without_weight(layer):
|
||||||
|
if isinstance(layer, torch.nn.LayerNorm) and not layer.elementwise_affine:
|
||||||
|
return True
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def store_weights_backup(weight):
|
||||||
|
if weight is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
return weight.to(devices.cpu, copy=True)
|
||||||
|
|
||||||
|
|
||||||
|
def restore_weights_backup(obj, field, weight):
|
||||||
|
if weight is None:
|
||||||
|
setattr(obj, field, None)
|
||||||
|
return
|
||||||
|
|
||||||
|
getattr(obj, field).copy_(weight)
|
||||||
|
|
||||||
|
|
||||||
|
def network_restore_weights_from_backup(self: Union[torch.nn.Conv2d, torch.nn.Linear, torch.nn.GroupNorm, torch.nn.LayerNorm, torch.nn.MultiheadAttention]):
|
||||||
|
weights_backup = getattr(self, "network_weights_backup", None)
|
||||||
|
bias_backup = getattr(self, "network_bias_backup", None)
|
||||||
|
|
||||||
|
if weights_backup is None and bias_backup is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
if weights_backup is not None:
|
||||||
|
if isinstance(self, torch.nn.MultiheadAttention):
|
||||||
|
restore_weights_backup(self, 'in_proj_weight', weights_backup[0])
|
||||||
|
restore_weights_backup(self.out_proj, 'weight', weights_backup[1])
|
||||||
|
else:
|
||||||
|
restore_weights_backup(self, 'weight', weights_backup)
|
||||||
|
|
||||||
|
if isinstance(self, torch.nn.MultiheadAttention):
|
||||||
|
restore_weights_backup(self.out_proj, 'bias', bias_backup)
|
||||||
|
else:
|
||||||
|
restore_weights_backup(self, 'bias', bias_backup)
|
||||||
|
|
||||||
|
|
||||||
|
def network_apply_weights(self: Union[torch.nn.Conv2d, torch.nn.Linear, torch.nn.GroupNorm, torch.nn.LayerNorm, torch.nn.MultiheadAttention]):
|
||||||
|
"""
|
||||||
|
Applies the currently selected set of networks to the weights of torch layer self.
|
||||||
|
If weights already have this particular set of networks applied, does nothing.
|
||||||
|
If not, restores original weights from backup and alters weights according to networks.
|
||||||
|
"""
|
||||||
|
|
||||||
|
network_layer_name = getattr(self, 'network_layer_name', None)
|
||||||
|
if network_layer_name is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
current_names = getattr(self, "network_current_names", ())
|
||||||
|
wanted_names = tuple((x.name, x.te_multiplier, x.unet_multiplier, x.dyn_dim) for x in loaded_networks)
|
||||||
|
|
||||||
|
weights_backup = getattr(self, "network_weights_backup", None)
|
||||||
|
if weights_backup is None and wanted_names != ():
|
||||||
|
if current_names != () and not allowed_layer_without_weight(self):
|
||||||
|
raise RuntimeError(f"{network_layer_name} - no backup weights found and current weights are not unchanged")
|
||||||
|
|
||||||
|
if isinstance(self, torch.nn.MultiheadAttention):
|
||||||
|
weights_backup = (store_weights_backup(self.in_proj_weight), store_weights_backup(self.out_proj.weight))
|
||||||
|
else:
|
||||||
|
weights_backup = store_weights_backup(self.weight)
|
||||||
|
|
||||||
|
self.network_weights_backup = weights_backup
|
||||||
|
|
||||||
|
bias_backup = getattr(self, "network_bias_backup", None)
|
||||||
|
if bias_backup is None and wanted_names != ():
|
||||||
|
if isinstance(self, torch.nn.MultiheadAttention) and self.out_proj.bias is not None:
|
||||||
|
bias_backup = store_weights_backup(self.out_proj.bias)
|
||||||
|
elif getattr(self, 'bias', None) is not None:
|
||||||
|
bias_backup = store_weights_backup(self.bias)
|
||||||
|
else:
|
||||||
|
bias_backup = None
|
||||||
|
|
||||||
|
# Unlike weight which always has value, some modules don't have bias.
|
||||||
|
# Only report if bias is not None and current bias are not unchanged.
|
||||||
|
if bias_backup is not None and current_names != ():
|
||||||
|
raise RuntimeError("no backup bias found and current bias are not unchanged")
|
||||||
|
|
||||||
|
self.network_bias_backup = bias_backup
|
||||||
|
|
||||||
|
if current_names != wanted_names:
|
||||||
|
network_restore_weights_from_backup(self)
|
||||||
|
|
||||||
|
for net in loaded_networks:
|
||||||
|
module = net.modules.get(network_layer_name, None)
|
||||||
|
if module is not None and hasattr(self, 'weight') and not isinstance(module, modules.models.sd3.mmdit.QkvLinear):
|
||||||
|
try:
|
||||||
|
with torch.no_grad():
|
||||||
|
if getattr(self, 'fp16_weight', None) is None:
|
||||||
|
weight = self.weight
|
||||||
|
bias = self.bias
|
||||||
|
else:
|
||||||
|
weight = self.fp16_weight.clone().to(self.weight.device)
|
||||||
|
bias = getattr(self, 'fp16_bias', None)
|
||||||
|
if bias is not None:
|
||||||
|
bias = bias.clone().to(self.bias.device)
|
||||||
|
updown, ex_bias = module.calc_updown(weight)
|
||||||
|
|
||||||
|
if len(weight.shape) == 4 and weight.shape[1] == 9:
|
||||||
|
# inpainting model. zero pad updown to make channel[1] 4 to 9
|
||||||
|
updown = torch.nn.functional.pad(updown, (0, 0, 0, 0, 0, 5))
|
||||||
|
|
||||||
|
self.weight.copy_((weight.to(dtype=updown.dtype) + updown).to(dtype=self.weight.dtype))
|
||||||
|
if ex_bias is not None and hasattr(self, 'bias'):
|
||||||
|
if self.bias is None:
|
||||||
|
self.bias = torch.nn.Parameter(ex_bias).to(self.weight.dtype)
|
||||||
|
else:
|
||||||
|
self.bias.copy_((bias + ex_bias).to(dtype=self.bias.dtype))
|
||||||
|
except RuntimeError as e:
|
||||||
|
logging.debug(f"Network {net.name} layer {network_layer_name}: {e}")
|
||||||
|
extra_network_lora.errors[net.name] = extra_network_lora.errors.get(net.name, 0) + 1
|
||||||
|
|
||||||
|
continue
|
||||||
|
|
||||||
|
module_q = net.modules.get(network_layer_name + "_q_proj", None)
|
||||||
|
module_k = net.modules.get(network_layer_name + "_k_proj", None)
|
||||||
|
module_v = net.modules.get(network_layer_name + "_v_proj", None)
|
||||||
|
module_out = net.modules.get(network_layer_name + "_out_proj", None)
|
||||||
|
|
||||||
|
if isinstance(self, torch.nn.MultiheadAttention) and module_q and module_k and module_v and module_out:
|
||||||
|
try:
|
||||||
|
with torch.no_grad():
|
||||||
|
# Send "real" orig_weight into MHA's lora module
|
||||||
|
qw, kw, vw = self.in_proj_weight.chunk(3, 0)
|
||||||
|
updown_q, _ = module_q.calc_updown(qw)
|
||||||
|
updown_k, _ = module_k.calc_updown(kw)
|
||||||
|
updown_v, _ = module_v.calc_updown(vw)
|
||||||
|
del qw, kw, vw
|
||||||
|
updown_qkv = torch.vstack([updown_q, updown_k, updown_v])
|
||||||
|
updown_out, ex_bias = module_out.calc_updown(self.out_proj.weight)
|
||||||
|
|
||||||
|
self.in_proj_weight += updown_qkv
|
||||||
|
self.out_proj.weight += updown_out
|
||||||
|
if ex_bias is not None:
|
||||||
|
if self.out_proj.bias is None:
|
||||||
|
self.out_proj.bias = torch.nn.Parameter(ex_bias)
|
||||||
|
else:
|
||||||
|
self.out_proj.bias += ex_bias
|
||||||
|
|
||||||
|
except RuntimeError as e:
|
||||||
|
logging.debug(f"Network {net.name} layer {network_layer_name}: {e}")
|
||||||
|
extra_network_lora.errors[net.name] = extra_network_lora.errors.get(net.name, 0) + 1
|
||||||
|
|
||||||
|
continue
|
||||||
|
|
||||||
|
if isinstance(self, modules.models.sd3.mmdit.QkvLinear) and module_q and module_k and module_v:
|
||||||
|
try:
|
||||||
|
with torch.no_grad():
|
||||||
|
# Send "real" orig_weight into MHA's lora module
|
||||||
|
qw, kw, vw = self.weight.chunk(3, 0)
|
||||||
|
updown_q, _ = module_q.calc_updown(qw)
|
||||||
|
updown_k, _ = module_k.calc_updown(kw)
|
||||||
|
updown_v, _ = module_v.calc_updown(vw)
|
||||||
|
del qw, kw, vw
|
||||||
|
updown_qkv = torch.vstack([updown_q, updown_k, updown_v])
|
||||||
|
self.weight += updown_qkv
|
||||||
|
|
||||||
|
except RuntimeError as e:
|
||||||
|
logging.debug(f"Network {net.name} layer {network_layer_name}: {e}")
|
||||||
|
extra_network_lora.errors[net.name] = extra_network_lora.errors.get(net.name, 0) + 1
|
||||||
|
|
||||||
|
continue
|
||||||
|
|
||||||
|
if module is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
logging.debug(f"Network {net.name} layer {network_layer_name}: couldn't find supported operation")
|
||||||
|
extra_network_lora.errors[net.name] = extra_network_lora.errors.get(net.name, 0) + 1
|
||||||
|
|
||||||
|
self.network_current_names = wanted_names
|
||||||
|
|
||||||
|
|
||||||
|
def network_forward(org_module, input, original_forward):
|
||||||
|
"""
|
||||||
|
Old way of applying Lora by executing operations during layer's forward.
|
||||||
|
Stacking many loras this way results in big performance degradation.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if len(loaded_networks) == 0:
|
||||||
|
return original_forward(org_module, input)
|
||||||
|
|
||||||
|
input = devices.cond_cast_unet(input)
|
||||||
|
|
||||||
|
network_restore_weights_from_backup(org_module)
|
||||||
|
network_reset_cached_weight(org_module)
|
||||||
|
|
||||||
|
y = original_forward(org_module, input)
|
||||||
|
|
||||||
|
network_layer_name = getattr(org_module, 'network_layer_name', None)
|
||||||
|
for lora in loaded_networks:
|
||||||
|
module = lora.modules.get(network_layer_name, None)
|
||||||
|
if module is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
y = module.forward(input, y)
|
||||||
|
|
||||||
|
return y
|
||||||
|
|
||||||
|
|
||||||
|
def network_reset_cached_weight(self: Union[torch.nn.Conv2d, torch.nn.Linear]):
|
||||||
|
self.network_current_names = ()
|
||||||
|
self.network_weights_backup = None
|
||||||
|
self.network_bias_backup = None
|
||||||
|
|
||||||
|
|
||||||
|
def network_Linear_forward(self, input):
|
||||||
|
if shared.opts.lora_functional:
|
||||||
|
return network_forward(self, input, originals.Linear_forward)
|
||||||
|
|
||||||
|
network_apply_weights(self)
|
||||||
|
|
||||||
|
return originals.Linear_forward(self, input)
|
||||||
|
|
||||||
|
|
||||||
|
def network_Linear_load_state_dict(self, *args, **kwargs):
|
||||||
|
network_reset_cached_weight(self)
|
||||||
|
|
||||||
|
return originals.Linear_load_state_dict(self, *args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def network_Conv2d_forward(self, input):
|
||||||
|
if shared.opts.lora_functional:
|
||||||
|
return network_forward(self, input, originals.Conv2d_forward)
|
||||||
|
|
||||||
|
network_apply_weights(self)
|
||||||
|
|
||||||
|
return originals.Conv2d_forward(self, input)
|
||||||
|
|
||||||
|
|
||||||
|
def network_Conv2d_load_state_dict(self, *args, **kwargs):
|
||||||
|
network_reset_cached_weight(self)
|
||||||
|
|
||||||
|
return originals.Conv2d_load_state_dict(self, *args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def network_GroupNorm_forward(self, input):
|
||||||
|
if shared.opts.lora_functional:
|
||||||
|
return network_forward(self, input, originals.GroupNorm_forward)
|
||||||
|
|
||||||
|
network_apply_weights(self)
|
||||||
|
|
||||||
|
return originals.GroupNorm_forward(self, input)
|
||||||
|
|
||||||
|
|
||||||
|
def network_GroupNorm_load_state_dict(self, *args, **kwargs):
|
||||||
|
network_reset_cached_weight(self)
|
||||||
|
|
||||||
|
return originals.GroupNorm_load_state_dict(self, *args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def network_LayerNorm_forward(self, input):
|
||||||
|
if shared.opts.lora_functional:
|
||||||
|
return network_forward(self, input, originals.LayerNorm_forward)
|
||||||
|
|
||||||
|
network_apply_weights(self)
|
||||||
|
|
||||||
|
return originals.LayerNorm_forward(self, input)
|
||||||
|
|
||||||
|
|
||||||
|
def network_LayerNorm_load_state_dict(self, *args, **kwargs):
|
||||||
|
network_reset_cached_weight(self)
|
||||||
|
|
||||||
|
return originals.LayerNorm_load_state_dict(self, *args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def network_MultiheadAttention_forward(self, *args, **kwargs):
|
||||||
|
network_apply_weights(self)
|
||||||
|
|
||||||
|
return originals.MultiheadAttention_forward(self, *args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def network_MultiheadAttention_load_state_dict(self, *args, **kwargs):
|
||||||
|
network_reset_cached_weight(self)
|
||||||
|
|
||||||
|
return originals.MultiheadAttention_load_state_dict(self, *args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def process_network_files(names: list[str] | None = None):
|
||||||
|
candidates = list(shared.walk_files(shared.cmd_opts.lora_dir, allowed_extensions=[".pt", ".ckpt", ".safetensors"]))
|
||||||
|
candidates += list(shared.walk_files(shared.cmd_opts.lyco_dir_backcompat, allowed_extensions=[".pt", ".ckpt", ".safetensors"]))
|
||||||
|
for filename in candidates:
|
||||||
|
if os.path.isdir(filename):
|
||||||
|
continue
|
||||||
|
name = os.path.splitext(os.path.basename(filename))[0]
|
||||||
|
# if names is provided, only load networks with names in the list
|
||||||
|
if names and name not in names:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
entry = network.NetworkOnDisk(name, filename)
|
||||||
|
except OSError: # should catch FileNotFoundError and PermissionError etc.
|
||||||
|
errors.report(f"Failed to load network {name} from {filename}", exc_info=True)
|
||||||
|
continue
|
||||||
|
|
||||||
|
available_networks[name] = entry
|
||||||
|
|
||||||
|
if entry.alias in available_network_aliases:
|
||||||
|
forbidden_network_aliases[entry.alias.lower()] = 1
|
||||||
|
|
||||||
|
available_network_aliases[name] = entry
|
||||||
|
available_network_aliases[entry.alias] = entry
|
||||||
|
|
||||||
|
|
||||||
|
def update_available_networks_by_names(names: list[str]):
|
||||||
|
process_network_files(names)
|
||||||
|
|
||||||
|
|
||||||
|
def list_available_networks():
|
||||||
|
available_networks.clear()
|
||||||
|
available_network_aliases.clear()
|
||||||
|
forbidden_network_aliases.clear()
|
||||||
|
available_network_hash_lookup.clear()
|
||||||
|
forbidden_network_aliases.update({"none": 1, "Addams": 1})
|
||||||
|
|
||||||
|
os.makedirs(shared.cmd_opts.lora_dir, exist_ok=True)
|
||||||
|
|
||||||
|
process_network_files()
|
||||||
|
|
||||||
|
|
||||||
|
re_network_name = re.compile(r"(.*)\s*\([0-9a-fA-F]+\)")
|
||||||
|
|
||||||
|
|
||||||
|
def infotext_pasted(infotext, params):
|
||||||
|
if "AddNet Module 1" in [x[1] for x in scripts.scripts_txt2img.infotext_fields]:
|
||||||
|
return # if the other extension is active, it will handle those fields, no need to do anything
|
||||||
|
|
||||||
|
added = []
|
||||||
|
|
||||||
|
for k in params:
|
||||||
|
if not k.startswith("AddNet Model "):
|
||||||
|
continue
|
||||||
|
|
||||||
|
num = k[13:]
|
||||||
|
|
||||||
|
if params.get("AddNet Module " + num) != "LoRA":
|
||||||
|
continue
|
||||||
|
|
||||||
|
name = params.get("AddNet Model " + num)
|
||||||
|
if name is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
m = re_network_name.match(name)
|
||||||
|
if m:
|
||||||
|
name = m.group(1)
|
||||||
|
|
||||||
|
multiplier = params.get("AddNet Weight A " + num, "1.0")
|
||||||
|
|
||||||
|
added.append(f"<lora:{name}:{multiplier}>")
|
||||||
|
|
||||||
|
if added:
|
||||||
|
params["Prompt"] += "\n" + "".join(added)
|
||||||
|
|
||||||
|
|
||||||
|
originals: lora_patches.LoraPatches = None
|
||||||
|
|
||||||
|
extra_network_lora = None
|
||||||
|
|
||||||
|
available_networks = {}
|
||||||
|
available_network_aliases = {}
|
||||||
|
loaded_networks = []
|
||||||
|
loaded_bundle_embeddings = {}
|
||||||
|
networks_in_memory = {}
|
||||||
|
available_network_hash_lookup = {}
|
||||||
|
forbidden_network_aliases = {}
|
||||||
|
|
||||||
|
list_available_networks()
|
@ -1,6 +1,8 @@
|
|||||||
import os
|
import os
|
||||||
from modules import paths
|
from modules import paths
|
||||||
|
from modules.paths_internal import normalized_filepath
|
||||||
|
|
||||||
|
|
||||||
def preload(parser):
|
def preload(parser):
|
||||||
parser.add_argument("--lora-dir", type=str, help="Path to directory with Lora networks.", default=os.path.join(paths.models_path, 'Lora'))
|
parser.add_argument("--lora-dir", type=normalized_filepath, help="Path to directory with Lora networks.", default=os.path.join(paths.models_path, 'Lora'))
|
||||||
|
parser.add_argument("--lyco-dir-backcompat", type=normalized_filepath, help="Path to directory with LyCORIS networks (for backawards compatibility; can also use --lyco-dir).", default=os.path.join(paths.models_path, 'LyCORIS'))
|
||||||
|
@ -1,68 +1,56 @@
|
|||||||
import torch
|
import re
|
||||||
|
|
||||||
import gradio as gr
|
import gradio as gr
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
|
|
||||||
import lora
|
import network
|
||||||
|
import networks
|
||||||
|
import lora # noqa:F401
|
||||||
|
import lora_patches
|
||||||
import extra_networks_lora
|
import extra_networks_lora
|
||||||
import ui_extra_networks_lora
|
import ui_extra_networks_lora
|
||||||
from modules import script_callbacks, ui_extra_networks, extra_networks, shared
|
from modules import script_callbacks, ui_extra_networks, extra_networks, shared
|
||||||
|
|
||||||
|
|
||||||
def unload():
|
def unload():
|
||||||
torch.nn.Linear.forward = torch.nn.Linear_forward_before_lora
|
networks.originals.undo()
|
||||||
torch.nn.Linear._load_from_state_dict = torch.nn.Linear_load_state_dict_before_lora
|
|
||||||
torch.nn.Conv2d.forward = torch.nn.Conv2d_forward_before_lora
|
|
||||||
torch.nn.Conv2d._load_from_state_dict = torch.nn.Conv2d_load_state_dict_before_lora
|
|
||||||
torch.nn.MultiheadAttention.forward = torch.nn.MultiheadAttention_forward_before_lora
|
|
||||||
torch.nn.MultiheadAttention._load_from_state_dict = torch.nn.MultiheadAttention_load_state_dict_before_lora
|
|
||||||
|
|
||||||
|
|
||||||
def before_ui():
|
def before_ui():
|
||||||
ui_extra_networks.register_page(ui_extra_networks_lora.ExtraNetworksPageLora())
|
ui_extra_networks.register_page(ui_extra_networks_lora.ExtraNetworksPageLora())
|
||||||
extra_networks.register_extra_network(extra_networks_lora.ExtraNetworkLora())
|
|
||||||
|
networks.extra_network_lora = extra_networks_lora.ExtraNetworkLora()
|
||||||
|
extra_networks.register_extra_network(networks.extra_network_lora)
|
||||||
|
extra_networks.register_extra_network_alias(networks.extra_network_lora, "lyco")
|
||||||
|
|
||||||
|
|
||||||
if not hasattr(torch.nn, 'Linear_forward_before_lora'):
|
networks.originals = lora_patches.LoraPatches()
|
||||||
torch.nn.Linear_forward_before_lora = torch.nn.Linear.forward
|
|
||||||
|
|
||||||
if not hasattr(torch.nn, 'Linear_load_state_dict_before_lora'):
|
script_callbacks.on_model_loaded(networks.assign_network_names_to_compvis_modules)
|
||||||
torch.nn.Linear_load_state_dict_before_lora = torch.nn.Linear._load_from_state_dict
|
|
||||||
|
|
||||||
if not hasattr(torch.nn, 'Conv2d_forward_before_lora'):
|
|
||||||
torch.nn.Conv2d_forward_before_lora = torch.nn.Conv2d.forward
|
|
||||||
|
|
||||||
if not hasattr(torch.nn, 'Conv2d_load_state_dict_before_lora'):
|
|
||||||
torch.nn.Conv2d_load_state_dict_before_lora = torch.nn.Conv2d._load_from_state_dict
|
|
||||||
|
|
||||||
if not hasattr(torch.nn, 'MultiheadAttention_forward_before_lora'):
|
|
||||||
torch.nn.MultiheadAttention_forward_before_lora = torch.nn.MultiheadAttention.forward
|
|
||||||
|
|
||||||
if not hasattr(torch.nn, 'MultiheadAttention_load_state_dict_before_lora'):
|
|
||||||
torch.nn.MultiheadAttention_load_state_dict_before_lora = torch.nn.MultiheadAttention._load_from_state_dict
|
|
||||||
|
|
||||||
torch.nn.Linear.forward = lora.lora_Linear_forward
|
|
||||||
torch.nn.Linear._load_from_state_dict = lora.lora_Linear_load_state_dict
|
|
||||||
torch.nn.Conv2d.forward = lora.lora_Conv2d_forward
|
|
||||||
torch.nn.Conv2d._load_from_state_dict = lora.lora_Conv2d_load_state_dict
|
|
||||||
torch.nn.MultiheadAttention.forward = lora.lora_MultiheadAttention_forward
|
|
||||||
torch.nn.MultiheadAttention._load_from_state_dict = lora.lora_MultiheadAttention_load_state_dict
|
|
||||||
|
|
||||||
script_callbacks.on_model_loaded(lora.assign_lora_names_to_compvis_modules)
|
|
||||||
script_callbacks.on_script_unloaded(unload)
|
script_callbacks.on_script_unloaded(unload)
|
||||||
script_callbacks.on_before_ui(before_ui)
|
script_callbacks.on_before_ui(before_ui)
|
||||||
script_callbacks.on_infotext_pasted(lora.infotext_pasted)
|
script_callbacks.on_infotext_pasted(networks.infotext_pasted)
|
||||||
|
|
||||||
|
|
||||||
shared.options_templates.update(shared.options_section(('extra_networks', "Extra Networks"), {
|
shared.options_templates.update(shared.options_section(('extra_networks', "Extra Networks"), {
|
||||||
"sd_lora": shared.OptionInfo("None", "Add Lora to prompt", gr.Dropdown, lambda: {"choices": ["None"] + [x for x in lora.available_loras]}, refresh=lora.list_available_loras),
|
"sd_lora": shared.OptionInfo("None", "Add network to prompt", gr.Dropdown, lambda: {"choices": ["None", *networks.available_networks]}, refresh=networks.list_available_networks),
|
||||||
|
"lora_preferred_name": shared.OptionInfo("Alias from file", "When adding to prompt, refer to Lora by", gr.Radio, {"choices": ["Alias from file", "Filename"]}),
|
||||||
|
"lora_add_hashes_to_infotext": shared.OptionInfo(True, "Add Lora hashes to infotext"),
|
||||||
|
"lora_bundled_ti_to_infotext": shared.OptionInfo(True, "Add Lora name as TI hashes for bundled Textual Inversion").info('"Add Textual Inversion hashes to infotext" needs to be enabled'),
|
||||||
|
"lora_show_all": shared.OptionInfo(False, "Always show all networks on the Lora page").info("otherwise, those detected as for incompatible version of Stable Diffusion will be hidden"),
|
||||||
|
"lora_hide_unknown_for_versions": shared.OptionInfo([], "Hide networks of unknown versions for model versions", gr.CheckboxGroup, {"choices": ["SD1", "SD2", "SDXL"]}),
|
||||||
|
"lora_in_memory_limit": shared.OptionInfo(0, "Number of Lora networks to keep cached in memory", gr.Number, {"precision": 0}),
|
||||||
|
"lora_not_found_warning_console": shared.OptionInfo(False, "Lora not found warning in console"),
|
||||||
|
"lora_not_found_gradio_warning": shared.OptionInfo(False, "Lora not found warning popup in webui"),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
|
|
||||||
shared.options_templates.update(shared.options_section(('compatibility', "Compatibility"), {
|
shared.options_templates.update(shared.options_section(('compatibility', "Compatibility"), {
|
||||||
"lora_functional": shared.OptionInfo(False, "Lora: use old method that takes longer when you have multiple Loras active and produces same results as kohya-ss/sd-webui-additional-networks extension"),
|
"lora_functional": shared.OptionInfo(False, "Lora/Networks: use old method that takes longer when you have multiple Loras active and produces same results as kohya-ss/sd-webui-additional-networks extension"),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
|
|
||||||
def create_lora_json(obj: lora.LoraOnDisk):
|
def create_lora_json(obj: network.NetworkOnDisk):
|
||||||
return {
|
return {
|
||||||
"name": obj.name,
|
"name": obj.name,
|
||||||
"alias": obj.alias,
|
"alias": obj.alias,
|
||||||
@ -71,11 +59,44 @@ def create_lora_json(obj: lora.LoraOnDisk):
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def api_loras(_: gr.Blocks, app: FastAPI):
|
def api_networks(_: gr.Blocks, app: FastAPI):
|
||||||
@app.get("/sdapi/v1/loras")
|
@app.get("/sdapi/v1/loras")
|
||||||
async def get_loras():
|
async def get_loras():
|
||||||
return [create_lora_json(obj) for obj in lora.available_loras.values()]
|
return [create_lora_json(obj) for obj in networks.available_networks.values()]
|
||||||
|
|
||||||
|
@app.post("/sdapi/v1/refresh-loras")
|
||||||
|
async def refresh_loras():
|
||||||
|
return networks.list_available_networks()
|
||||||
|
|
||||||
|
|
||||||
script_callbacks.on_app_started(api_loras)
|
script_callbacks.on_app_started(api_networks)
|
||||||
|
|
||||||
|
re_lora = re.compile("<lora:([^:]+):")
|
||||||
|
|
||||||
|
|
||||||
|
def infotext_pasted(infotext, d):
|
||||||
|
hashes = d.get("Lora hashes")
|
||||||
|
if not hashes:
|
||||||
|
return
|
||||||
|
|
||||||
|
hashes = [x.strip().split(':', 1) for x in hashes.split(",")]
|
||||||
|
hashes = {x[0].strip().replace(",", ""): x[1].strip() for x in hashes}
|
||||||
|
|
||||||
|
def network_replacement(m):
|
||||||
|
alias = m.group(1)
|
||||||
|
shorthash = hashes.get(alias)
|
||||||
|
if shorthash is None:
|
||||||
|
return m.group(0)
|
||||||
|
|
||||||
|
network_on_disk = networks.available_network_hash_lookup.get(shorthash)
|
||||||
|
if network_on_disk is None:
|
||||||
|
return m.group(0)
|
||||||
|
|
||||||
|
return f'<lora:{network_on_disk.get_alias()}:'
|
||||||
|
|
||||||
|
d["Prompt"] = re.sub(re_lora, network_replacement, d["Prompt"])
|
||||||
|
|
||||||
|
|
||||||
|
script_callbacks.on_infotext_pasted(infotext_pasted)
|
||||||
|
|
||||||
|
shared.opts.onchange("lora_in_memory_limit", networks.purge_networks_from_memory)
|
||||||
|
226
extensions-builtin/Lora/ui_edit_user_metadata.py
Normal file
226
extensions-builtin/Lora/ui_edit_user_metadata.py
Normal file
@ -0,0 +1,226 @@
|
|||||||
|
import datetime
|
||||||
|
import html
|
||||||
|
import random
|
||||||
|
|
||||||
|
import gradio as gr
|
||||||
|
import re
|
||||||
|
|
||||||
|
from modules import ui_extra_networks_user_metadata
|
||||||
|
|
||||||
|
|
||||||
|
def is_non_comma_tagset(tags):
|
||||||
|
average_tag_length = sum(len(x) for x in tags.keys()) / len(tags)
|
||||||
|
|
||||||
|
return average_tag_length >= 16
|
||||||
|
|
||||||
|
|
||||||
|
re_word = re.compile(r"[-_\w']+")
|
||||||
|
re_comma = re.compile(r" *, *")
|
||||||
|
|
||||||
|
|
||||||
|
def build_tags(metadata):
|
||||||
|
tags = {}
|
||||||
|
|
||||||
|
ss_tag_frequency = metadata.get("ss_tag_frequency", {})
|
||||||
|
if ss_tag_frequency is not None and hasattr(ss_tag_frequency, 'items'):
|
||||||
|
for _, tags_dict in ss_tag_frequency.items():
|
||||||
|
for tag, tag_count in tags_dict.items():
|
||||||
|
tag = tag.strip()
|
||||||
|
tags[tag] = tags.get(tag, 0) + int(tag_count)
|
||||||
|
|
||||||
|
if tags and is_non_comma_tagset(tags):
|
||||||
|
new_tags = {}
|
||||||
|
|
||||||
|
for text, text_count in tags.items():
|
||||||
|
for word in re.findall(re_word, text):
|
||||||
|
if len(word) < 3:
|
||||||
|
continue
|
||||||
|
|
||||||
|
new_tags[word] = new_tags.get(word, 0) + text_count
|
||||||
|
|
||||||
|
tags = new_tags
|
||||||
|
|
||||||
|
ordered_tags = sorted(tags.keys(), key=tags.get, reverse=True)
|
||||||
|
|
||||||
|
return [(tag, tags[tag]) for tag in ordered_tags]
|
||||||
|
|
||||||
|
|
||||||
|
class LoraUserMetadataEditor(ui_extra_networks_user_metadata.UserMetadataEditor):
|
||||||
|
def __init__(self, ui, tabname, page):
|
||||||
|
super().__init__(ui, tabname, page)
|
||||||
|
|
||||||
|
self.select_sd_version = None
|
||||||
|
|
||||||
|
self.taginfo = None
|
||||||
|
self.edit_activation_text = None
|
||||||
|
self.slider_preferred_weight = None
|
||||||
|
self.edit_notes = None
|
||||||
|
|
||||||
|
def save_lora_user_metadata(self, name, desc, sd_version, activation_text, preferred_weight, negative_text, notes):
|
||||||
|
user_metadata = self.get_user_metadata(name)
|
||||||
|
user_metadata["description"] = desc
|
||||||
|
user_metadata["sd version"] = sd_version
|
||||||
|
user_metadata["activation text"] = activation_text
|
||||||
|
user_metadata["preferred weight"] = preferred_weight
|
||||||
|
user_metadata["negative text"] = negative_text
|
||||||
|
user_metadata["notes"] = notes
|
||||||
|
|
||||||
|
self.write_user_metadata(name, user_metadata)
|
||||||
|
|
||||||
|
def get_metadata_table(self, name):
|
||||||
|
table = super().get_metadata_table(name)
|
||||||
|
item = self.page.items.get(name, {})
|
||||||
|
metadata = item.get("metadata") or {}
|
||||||
|
|
||||||
|
keys = {
|
||||||
|
'ss_output_name': "Output name:",
|
||||||
|
'ss_sd_model_name': "Model:",
|
||||||
|
'ss_clip_skip': "Clip skip:",
|
||||||
|
'ss_network_module': "Kohya module:",
|
||||||
|
}
|
||||||
|
|
||||||
|
for key, label in keys.items():
|
||||||
|
value = metadata.get(key, None)
|
||||||
|
if value is not None and str(value) != "None":
|
||||||
|
table.append((label, html.escape(value)))
|
||||||
|
|
||||||
|
ss_training_started_at = metadata.get('ss_training_started_at')
|
||||||
|
if ss_training_started_at:
|
||||||
|
table.append(("Date trained:", datetime.datetime.utcfromtimestamp(float(ss_training_started_at)).strftime('%Y-%m-%d %H:%M')))
|
||||||
|
|
||||||
|
ss_bucket_info = metadata.get("ss_bucket_info")
|
||||||
|
if ss_bucket_info and "buckets" in ss_bucket_info:
|
||||||
|
resolutions = {}
|
||||||
|
for _, bucket in ss_bucket_info["buckets"].items():
|
||||||
|
resolution = bucket["resolution"]
|
||||||
|
resolution = f'{resolution[1]}x{resolution[0]}'
|
||||||
|
|
||||||
|
resolutions[resolution] = resolutions.get(resolution, 0) + int(bucket["count"])
|
||||||
|
|
||||||
|
resolutions_list = sorted(resolutions.keys(), key=resolutions.get, reverse=True)
|
||||||
|
resolutions_text = html.escape(", ".join(resolutions_list[0:4]))
|
||||||
|
if len(resolutions) > 4:
|
||||||
|
resolutions_text += ", ..."
|
||||||
|
resolutions_text = f"<span title='{html.escape(', '.join(resolutions_list))}'>{resolutions_text}</span>"
|
||||||
|
|
||||||
|
table.append(('Resolutions:' if len(resolutions_list) > 1 else 'Resolution:', resolutions_text))
|
||||||
|
|
||||||
|
image_count = 0
|
||||||
|
for _, params in metadata.get("ss_dataset_dirs", {}).items():
|
||||||
|
image_count += int(params.get("img_count", 0))
|
||||||
|
|
||||||
|
if image_count:
|
||||||
|
table.append(("Dataset size:", image_count))
|
||||||
|
|
||||||
|
return table
|
||||||
|
|
||||||
|
def put_values_into_components(self, name):
|
||||||
|
user_metadata = self.get_user_metadata(name)
|
||||||
|
values = super().put_values_into_components(name)
|
||||||
|
|
||||||
|
item = self.page.items.get(name, {})
|
||||||
|
metadata = item.get("metadata") or {}
|
||||||
|
|
||||||
|
tags = build_tags(metadata)
|
||||||
|
gradio_tags = [(tag, str(count)) for tag, count in tags[0:24]]
|
||||||
|
|
||||||
|
return [
|
||||||
|
*values[0:5],
|
||||||
|
item.get("sd_version", "Unknown"),
|
||||||
|
gr.HighlightedText.update(value=gradio_tags, visible=True if tags else False),
|
||||||
|
user_metadata.get('activation text', ''),
|
||||||
|
float(user_metadata.get('preferred weight', 0.0)),
|
||||||
|
user_metadata.get('negative text', ''),
|
||||||
|
gr.update(visible=True if tags else False),
|
||||||
|
gr.update(value=self.generate_random_prompt_from_tags(tags), visible=True if tags else False),
|
||||||
|
]
|
||||||
|
|
||||||
|
def generate_random_prompt(self, name):
|
||||||
|
item = self.page.items.get(name, {})
|
||||||
|
metadata = item.get("metadata") or {}
|
||||||
|
tags = build_tags(metadata)
|
||||||
|
|
||||||
|
return self.generate_random_prompt_from_tags(tags)
|
||||||
|
|
||||||
|
def generate_random_prompt_from_tags(self, tags):
|
||||||
|
max_count = None
|
||||||
|
res = []
|
||||||
|
for tag, count in tags:
|
||||||
|
if not max_count:
|
||||||
|
max_count = count
|
||||||
|
|
||||||
|
v = random.random() * max_count
|
||||||
|
if count > v:
|
||||||
|
for x in "({[]})":
|
||||||
|
tag = tag.replace(x, '\\' + x)
|
||||||
|
res.append(tag)
|
||||||
|
|
||||||
|
return ", ".join(sorted(res))
|
||||||
|
|
||||||
|
def create_extra_default_items_in_left_column(self):
|
||||||
|
|
||||||
|
# this would be a lot better as gr.Radio but I can't make it work
|
||||||
|
self.select_sd_version = gr.Dropdown(['SD1', 'SD2', 'SDXL', 'Unknown'], value='Unknown', label='Stable Diffusion version', interactive=True)
|
||||||
|
|
||||||
|
def create_editor(self):
|
||||||
|
self.create_default_editor_elems()
|
||||||
|
|
||||||
|
self.taginfo = gr.HighlightedText(label="Training dataset tags")
|
||||||
|
self.edit_activation_text = gr.Text(label='Activation text', info="Will be added to prompt along with Lora")
|
||||||
|
self.slider_preferred_weight = gr.Slider(label='Preferred weight', info="Set to 0 to disable", minimum=0.0, maximum=2.0, step=0.01)
|
||||||
|
self.edit_negative_text = gr.Text(label='Negative prompt', info="Will be added to negative prompts")
|
||||||
|
with gr.Row() as row_random_prompt:
|
||||||
|
with gr.Column(scale=8):
|
||||||
|
random_prompt = gr.Textbox(label='Random prompt', lines=4, max_lines=4, interactive=False)
|
||||||
|
|
||||||
|
with gr.Column(scale=1, min_width=120):
|
||||||
|
generate_random_prompt = gr.Button('Generate', size="lg", scale=1)
|
||||||
|
|
||||||
|
self.edit_notes = gr.TextArea(label='Notes', lines=4)
|
||||||
|
|
||||||
|
generate_random_prompt.click(fn=self.generate_random_prompt, inputs=[self.edit_name_input], outputs=[random_prompt], show_progress=False)
|
||||||
|
|
||||||
|
def select_tag(activation_text, evt: gr.SelectData):
|
||||||
|
tag = evt.value[0]
|
||||||
|
|
||||||
|
words = re.split(re_comma, activation_text)
|
||||||
|
if tag in words:
|
||||||
|
words = [x for x in words if x != tag and x.strip()]
|
||||||
|
return ", ".join(words)
|
||||||
|
|
||||||
|
return activation_text + ", " + tag if activation_text else tag
|
||||||
|
|
||||||
|
self.taginfo.select(fn=select_tag, inputs=[self.edit_activation_text], outputs=[self.edit_activation_text], show_progress=False)
|
||||||
|
|
||||||
|
self.create_default_buttons()
|
||||||
|
|
||||||
|
viewed_components = [
|
||||||
|
self.edit_name,
|
||||||
|
self.edit_description,
|
||||||
|
self.html_filedata,
|
||||||
|
self.html_preview,
|
||||||
|
self.edit_notes,
|
||||||
|
self.select_sd_version,
|
||||||
|
self.taginfo,
|
||||||
|
self.edit_activation_text,
|
||||||
|
self.slider_preferred_weight,
|
||||||
|
self.edit_negative_text,
|
||||||
|
row_random_prompt,
|
||||||
|
random_prompt,
|
||||||
|
]
|
||||||
|
|
||||||
|
self.button_edit\
|
||||||
|
.click(fn=self.put_values_into_components, inputs=[self.edit_name_input], outputs=viewed_components)\
|
||||||
|
.then(fn=lambda: gr.update(visible=True), inputs=[], outputs=[self.box])
|
||||||
|
|
||||||
|
edited_components = [
|
||||||
|
self.edit_description,
|
||||||
|
self.select_sd_version,
|
||||||
|
self.edit_activation_text,
|
||||||
|
self.slider_preferred_weight,
|
||||||
|
self.edit_negative_text,
|
||||||
|
self.edit_notes,
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
self.setup_save_handler(self.button_save, self.save_lora_user_metadata, edited_components)
|
@ -1,8 +1,11 @@
|
|||||||
import json
|
|
||||||
import os
|
import os
|
||||||
import lora
|
|
||||||
|
import network
|
||||||
|
import networks
|
||||||
|
|
||||||
from modules import shared, ui_extra_networks
|
from modules import shared, ui_extra_networks
|
||||||
|
from modules.ui_extra_networks import quote_js
|
||||||
|
from ui_edit_user_metadata import LoraUserMetadataEditor
|
||||||
|
|
||||||
|
|
||||||
class ExtraNetworksPageLora(ui_extra_networks.ExtraNetworksPage):
|
class ExtraNetworksPageLora(ui_extra_networks.ExtraNetworksPage):
|
||||||
@ -10,22 +13,78 @@ class ExtraNetworksPageLora(ui_extra_networks.ExtraNetworksPage):
|
|||||||
super().__init__('Lora')
|
super().__init__('Lora')
|
||||||
|
|
||||||
def refresh(self):
|
def refresh(self):
|
||||||
lora.list_available_loras()
|
networks.list_available_networks()
|
||||||
|
|
||||||
|
def create_item(self, name, index=None, enable_filter=True):
|
||||||
|
lora_on_disk = networks.available_networks.get(name)
|
||||||
|
if lora_on_disk is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
path, ext = os.path.splitext(lora_on_disk.filename)
|
||||||
|
|
||||||
|
alias = lora_on_disk.get_alias()
|
||||||
|
|
||||||
|
search_terms = [self.search_terms_from_path(lora_on_disk.filename)]
|
||||||
|
if lora_on_disk.hash:
|
||||||
|
search_terms.append(lora_on_disk.hash)
|
||||||
|
item = {
|
||||||
|
"name": name,
|
||||||
|
"filename": lora_on_disk.filename,
|
||||||
|
"shorthash": lora_on_disk.shorthash,
|
||||||
|
"preview": self.find_preview(path) or self.find_embedded_preview(path, name, lora_on_disk.metadata),
|
||||||
|
"description": self.find_description(path),
|
||||||
|
"search_terms": search_terms,
|
||||||
|
"local_preview": f"{path}.{shared.opts.samples_format}",
|
||||||
|
"metadata": lora_on_disk.metadata,
|
||||||
|
"sort_keys": {'default': index, **self.get_sort_keys(lora_on_disk.filename)},
|
||||||
|
"sd_version": lora_on_disk.sd_version.name,
|
||||||
|
}
|
||||||
|
|
||||||
|
self.read_user_metadata(item)
|
||||||
|
activation_text = item["user_metadata"].get("activation text")
|
||||||
|
preferred_weight = item["user_metadata"].get("preferred weight", 0.0)
|
||||||
|
item["prompt"] = quote_js(f"<lora:{alias}:") + " + " + (str(preferred_weight) if preferred_weight else "opts.extra_networks_default_multiplier") + " + " + quote_js(">")
|
||||||
|
|
||||||
|
if activation_text:
|
||||||
|
item["prompt"] += " + " + quote_js(" " + activation_text)
|
||||||
|
|
||||||
|
negative_prompt = item["user_metadata"].get("negative text")
|
||||||
|
item["negative_prompt"] = quote_js("")
|
||||||
|
if negative_prompt:
|
||||||
|
item["negative_prompt"] = quote_js('(' + negative_prompt + ':1)')
|
||||||
|
|
||||||
|
sd_version = item["user_metadata"].get("sd version")
|
||||||
|
if sd_version in network.SdVersion.__members__:
|
||||||
|
item["sd_version"] = sd_version
|
||||||
|
sd_version = network.SdVersion[sd_version]
|
||||||
|
else:
|
||||||
|
sd_version = lora_on_disk.sd_version
|
||||||
|
|
||||||
|
if shared.opts.lora_show_all or not enable_filter or not shared.sd_model:
|
||||||
|
pass
|
||||||
|
elif sd_version == network.SdVersion.Unknown:
|
||||||
|
model_version = network.SdVersion.SDXL if shared.sd_model.is_sdxl else network.SdVersion.SD2 if shared.sd_model.is_sd2 else network.SdVersion.SD1
|
||||||
|
if model_version.name in shared.opts.lora_hide_unknown_for_versions:
|
||||||
|
return None
|
||||||
|
elif shared.sd_model.is_sdxl and sd_version != network.SdVersion.SDXL:
|
||||||
|
return None
|
||||||
|
elif shared.sd_model.is_sd2 and sd_version != network.SdVersion.SD2:
|
||||||
|
return None
|
||||||
|
elif shared.sd_model.is_sd1 and sd_version != network.SdVersion.SD1:
|
||||||
|
return None
|
||||||
|
|
||||||
|
return item
|
||||||
|
|
||||||
def list_items(self):
|
def list_items(self):
|
||||||
for name, lora_on_disk in lora.available_loras.items():
|
# instantiate a list to protect against concurrent modification
|
||||||
path, ext = os.path.splitext(lora_on_disk.filename)
|
names = list(networks.available_networks)
|
||||||
yield {
|
for index, name in enumerate(names):
|
||||||
"name": name,
|
item = self.create_item(name, index)
|
||||||
"filename": path,
|
if item is not None:
|
||||||
"preview": self.find_preview(path),
|
yield item
|
||||||
"description": self.find_description(path),
|
|
||||||
"search_term": self.search_terms_from_path(lora_on_disk.filename),
|
|
||||||
"prompt": json.dumps(f"<lora:{lora_on_disk.alias}:") + " + opts.extra_networks_default_multiplier + " + json.dumps(">"),
|
|
||||||
"local_preview": f"{path}.{shared.opts.samples_format}",
|
|
||||||
"metadata": json.dumps(lora_on_disk.metadata, indent=4) if lora_on_disk.metadata else None,
|
|
||||||
}
|
|
||||||
|
|
||||||
def allowed_directories_for_previews(self):
|
def allowed_directories_for_previews(self):
|
||||||
return [shared.cmd_opts.lora_dir]
|
return [shared.cmd_opts.lora_dir, shared.cmd_opts.lyco_dir_backcompat]
|
||||||
|
|
||||||
|
def create_user_metadata_editor(self, ui, tabname):
|
||||||
|
return LoraUserMetadataEditor(ui, tabname, self)
|
||||||
|
@ -1,19 +1,9 @@
|
|||||||
import os.path
|
|
||||||
import sys
|
import sys
|
||||||
import traceback
|
|
||||||
|
|
||||||
import PIL.Image
|
import PIL.Image
|
||||||
import numpy as np
|
|
||||||
import torch
|
|
||||||
from tqdm import tqdm
|
|
||||||
|
|
||||||
from basicsr.utils.download_util import load_file_from_url
|
|
||||||
|
|
||||||
import modules.upscaler
|
import modules.upscaler
|
||||||
from modules import devices, modelloader
|
from modules import devices, errors, modelloader, script_callbacks, shared, upscaler_utils
|
||||||
from scunet_model_arch import SCUNet as net
|
|
||||||
from modules.shared import opts
|
|
||||||
from modules import images
|
|
||||||
|
|
||||||
|
|
||||||
class UpscalerScuNET(modules.upscaler.Upscaler):
|
class UpscalerScuNET(modules.upscaler.Upscaler):
|
||||||
@ -29,7 +19,7 @@ class UpscalerScuNET(modules.upscaler.Upscaler):
|
|||||||
scalers = []
|
scalers = []
|
||||||
add_model2 = True
|
add_model2 = True
|
||||||
for file in model_paths:
|
for file in model_paths:
|
||||||
if "http" in file:
|
if file.startswith("http"):
|
||||||
name = self.model_name
|
name = self.model_name
|
||||||
else:
|
else:
|
||||||
name = modelloader.friendly_name(file)
|
name = modelloader.friendly_name(file)
|
||||||
@ -39,102 +29,46 @@ class UpscalerScuNET(modules.upscaler.Upscaler):
|
|||||||
scaler_data = modules.upscaler.UpscalerData(name, file, self, 4)
|
scaler_data = modules.upscaler.UpscalerData(name, file, self, 4)
|
||||||
scalers.append(scaler_data)
|
scalers.append(scaler_data)
|
||||||
except Exception:
|
except Exception:
|
||||||
print(f"Error loading ScuNET model: {file}", file=sys.stderr)
|
errors.report(f"Error loading ScuNET model: {file}", exc_info=True)
|
||||||
print(traceback.format_exc(), file=sys.stderr)
|
|
||||||
if add_model2:
|
if add_model2:
|
||||||
scaler_data2 = modules.upscaler.UpscalerData(self.model_name2, self.model_url2, self)
|
scaler_data2 = modules.upscaler.UpscalerData(self.model_name2, self.model_url2, self)
|
||||||
scalers.append(scaler_data2)
|
scalers.append(scaler_data2)
|
||||||
self.scalers = scalers
|
self.scalers = scalers
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
@torch.no_grad()
|
|
||||||
def tiled_inference(img, model):
|
|
||||||
# test the image tile by tile
|
|
||||||
h, w = img.shape[2:]
|
|
||||||
tile = opts.SCUNET_tile
|
|
||||||
tile_overlap = opts.SCUNET_tile_overlap
|
|
||||||
if tile == 0:
|
|
||||||
return model(img)
|
|
||||||
|
|
||||||
device = devices.get_device_for('scunet')
|
|
||||||
assert tile % 8 == 0, "tile size should be a multiple of window_size"
|
|
||||||
sf = 1
|
|
||||||
|
|
||||||
stride = tile - tile_overlap
|
|
||||||
h_idx_list = list(range(0, h - tile, stride)) + [h - tile]
|
|
||||||
w_idx_list = list(range(0, w - tile, stride)) + [w - tile]
|
|
||||||
E = torch.zeros(1, 3, h * sf, w * sf, dtype=img.dtype, device=device)
|
|
||||||
W = torch.zeros_like(E, dtype=devices.dtype, device=device)
|
|
||||||
|
|
||||||
with tqdm(total=len(h_idx_list) * len(w_idx_list), desc="ScuNET tiles") as pbar:
|
|
||||||
for h_idx in h_idx_list:
|
|
||||||
|
|
||||||
for w_idx in w_idx_list:
|
|
||||||
|
|
||||||
in_patch = img[..., h_idx: h_idx + tile, w_idx: w_idx + tile]
|
|
||||||
|
|
||||||
out_patch = model(in_patch)
|
|
||||||
out_patch_mask = torch.ones_like(out_patch)
|
|
||||||
|
|
||||||
E[
|
|
||||||
..., h_idx * sf: (h_idx + tile) * sf, w_idx * sf: (w_idx + tile) * sf
|
|
||||||
].add_(out_patch)
|
|
||||||
W[
|
|
||||||
..., h_idx * sf: (h_idx + tile) * sf, w_idx * sf: (w_idx + tile) * sf
|
|
||||||
].add_(out_patch_mask)
|
|
||||||
pbar.update(1)
|
|
||||||
output = E.div_(W)
|
|
||||||
|
|
||||||
return output
|
|
||||||
|
|
||||||
def do_upscale(self, img: PIL.Image.Image, selected_file):
|
def do_upscale(self, img: PIL.Image.Image, selected_file):
|
||||||
|
devices.torch_gc()
|
||||||
torch.cuda.empty_cache()
|
try:
|
||||||
|
model = self.load_model(selected_file)
|
||||||
model = self.load_model(selected_file)
|
except Exception as e:
|
||||||
if model is None:
|
print(f"ScuNET: Unable to load model from {selected_file}: {e}", file=sys.stderr)
|
||||||
print(f"ScuNET: Unable to load model from {selected_file}", file=sys.stderr)
|
|
||||||
return img
|
return img
|
||||||
|
|
||||||
device = devices.get_device_for('scunet')
|
img = upscaler_utils.upscale_2(
|
||||||
tile = opts.SCUNET_tile
|
img,
|
||||||
h, w = img.height, img.width
|
model,
|
||||||
np_img = np.array(img)
|
tile_size=shared.opts.SCUNET_tile,
|
||||||
np_img = np_img[:, :, ::-1] # RGB to BGR
|
tile_overlap=shared.opts.SCUNET_tile_overlap,
|
||||||
np_img = np_img.transpose((2, 0, 1)) / 255 # HWC to CHW
|
scale=1, # ScuNET is a denoising model, not an upscaler
|
||||||
torch_img = torch.from_numpy(np_img).float().unsqueeze(0).to(device) # type: ignore
|
desc='ScuNET',
|
||||||
|
)
|
||||||
if tile > h or tile > w:
|
devices.torch_gc()
|
||||||
_img = torch.zeros(1, 3, max(h, tile), max(w, tile), dtype=torch_img.dtype, device=torch_img.device)
|
return img
|
||||||
_img[:, :, :h, :w] = torch_img # pad image
|
|
||||||
torch_img = _img
|
|
||||||
|
|
||||||
torch_output = self.tiled_inference(torch_img, model).squeeze(0)
|
|
||||||
torch_output = torch_output[:, :h * 1, :w * 1] # remove padding, if any
|
|
||||||
np_output: np.ndarray = torch_output.float().cpu().clamp_(0, 1).numpy()
|
|
||||||
del torch_img, torch_output
|
|
||||||
torch.cuda.empty_cache()
|
|
||||||
|
|
||||||
output = np_output.transpose((1, 2, 0)) # CHW to HWC
|
|
||||||
output = output[:, :, ::-1] # BGR to RGB
|
|
||||||
return PIL.Image.fromarray((output * 255).astype(np.uint8))
|
|
||||||
|
|
||||||
def load_model(self, path: str):
|
def load_model(self, path: str):
|
||||||
device = devices.get_device_for('scunet')
|
device = devices.get_device_for('scunet')
|
||||||
if "http" in path:
|
if path.startswith("http"):
|
||||||
filename = load_file_from_url(url=self.model_url, model_dir=self.model_path, file_name="%s.pth" % self.name,
|
# TODO: this doesn't use `path` at all?
|
||||||
progress=True)
|
filename = modelloader.load_file_from_url(self.model_url, model_dir=self.model_download_path, file_name=f"{self.name}.pth")
|
||||||
else:
|
else:
|
||||||
filename = path
|
filename = path
|
||||||
if not os.path.exists(os.path.join(self.model_path, filename)) or filename is None:
|
return modelloader.load_spandrel_model(filename, device=device, expected_architecture='SCUNet')
|
||||||
print(f"ScuNET: Unable to load model from {filename}", file=sys.stderr)
|
|
||||||
return None
|
|
||||||
|
|
||||||
model = net(in_nc=3, config=[4, 4, 4, 4, 4, 4, 4], dim=64)
|
|
||||||
model.load_state_dict(torch.load(filename), strict=True)
|
|
||||||
model.eval()
|
|
||||||
for k, v in model.named_parameters():
|
|
||||||
v.requires_grad = False
|
|
||||||
model = model.to(device)
|
|
||||||
|
|
||||||
return model
|
def on_ui_settings():
|
||||||
|
import gradio as gr
|
||||||
|
|
||||||
|
shared.opts.add_option("SCUNET_tile", shared.OptionInfo(256, "Tile size for SCUNET upscalers.", gr.Slider, {"minimum": 0, "maximum": 512, "step": 16}, section=('upscaling', "Upscaling")).info("0 = no tiling"))
|
||||||
|
shared.opts.add_option("SCUNET_tile_overlap", shared.OptionInfo(8, "Tile overlap for SCUNET upscalers.", gr.Slider, {"minimum": 0, "maximum": 64, "step": 1}, section=('upscaling', "Upscaling")).info("Low values = visible seam"))
|
||||||
|
|
||||||
|
|
||||||
|
script_callbacks.on_ui_settings(on_ui_settings)
|
||||||
|
@ -1,265 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
import numpy as np
|
|
||||||
import torch
|
|
||||||
import torch.nn as nn
|
|
||||||
from einops import rearrange
|
|
||||||
from einops.layers.torch import Rearrange
|
|
||||||
from timm.models.layers import trunc_normal_, DropPath
|
|
||||||
|
|
||||||
|
|
||||||
class WMSA(nn.Module):
|
|
||||||
""" Self-attention module in Swin Transformer
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, input_dim, output_dim, head_dim, window_size, type):
|
|
||||||
super(WMSA, self).__init__()
|
|
||||||
self.input_dim = input_dim
|
|
||||||
self.output_dim = output_dim
|
|
||||||
self.head_dim = head_dim
|
|
||||||
self.scale = self.head_dim ** -0.5
|
|
||||||
self.n_heads = input_dim // head_dim
|
|
||||||
self.window_size = window_size
|
|
||||||
self.type = type
|
|
||||||
self.embedding_layer = nn.Linear(self.input_dim, 3 * self.input_dim, bias=True)
|
|
||||||
|
|
||||||
self.relative_position_params = nn.Parameter(
|
|
||||||
torch.zeros((2 * window_size - 1) * (2 * window_size - 1), self.n_heads))
|
|
||||||
|
|
||||||
self.linear = nn.Linear(self.input_dim, self.output_dim)
|
|
||||||
|
|
||||||
trunc_normal_(self.relative_position_params, std=.02)
|
|
||||||
self.relative_position_params = torch.nn.Parameter(
|
|
||||||
self.relative_position_params.view(2 * window_size - 1, 2 * window_size - 1, self.n_heads).transpose(1,
|
|
||||||
2).transpose(
|
|
||||||
0, 1))
|
|
||||||
|
|
||||||
def generate_mask(self, h, w, p, shift):
|
|
||||||
""" generating the mask of SW-MSA
|
|
||||||
Args:
|
|
||||||
shift: shift parameters in CyclicShift.
|
|
||||||
Returns:
|
|
||||||
attn_mask: should be (1 1 w p p),
|
|
||||||
"""
|
|
||||||
# supporting square.
|
|
||||||
attn_mask = torch.zeros(h, w, p, p, p, p, dtype=torch.bool, device=self.relative_position_params.device)
|
|
||||||
if self.type == 'W':
|
|
||||||
return attn_mask
|
|
||||||
|
|
||||||
s = p - shift
|
|
||||||
attn_mask[-1, :, :s, :, s:, :] = True
|
|
||||||
attn_mask[-1, :, s:, :, :s, :] = True
|
|
||||||
attn_mask[:, -1, :, :s, :, s:] = True
|
|
||||||
attn_mask[:, -1, :, s:, :, :s] = True
|
|
||||||
attn_mask = rearrange(attn_mask, 'w1 w2 p1 p2 p3 p4 -> 1 1 (w1 w2) (p1 p2) (p3 p4)')
|
|
||||||
return attn_mask
|
|
||||||
|
|
||||||
def forward(self, x):
|
|
||||||
""" Forward pass of Window Multi-head Self-attention module.
|
|
||||||
Args:
|
|
||||||
x: input tensor with shape of [b h w c];
|
|
||||||
attn_mask: attention mask, fill -inf where the value is True;
|
|
||||||
Returns:
|
|
||||||
output: tensor shape [b h w c]
|
|
||||||
"""
|
|
||||||
if self.type != 'W': x = torch.roll(x, shifts=(-(self.window_size // 2), -(self.window_size // 2)), dims=(1, 2))
|
|
||||||
x = rearrange(x, 'b (w1 p1) (w2 p2) c -> b w1 w2 p1 p2 c', p1=self.window_size, p2=self.window_size)
|
|
||||||
h_windows = x.size(1)
|
|
||||||
w_windows = x.size(2)
|
|
||||||
# square validation
|
|
||||||
# assert h_windows == w_windows
|
|
||||||
|
|
||||||
x = rearrange(x, 'b w1 w2 p1 p2 c -> b (w1 w2) (p1 p2) c', p1=self.window_size, p2=self.window_size)
|
|
||||||
qkv = self.embedding_layer(x)
|
|
||||||
q, k, v = rearrange(qkv, 'b nw np (threeh c) -> threeh b nw np c', c=self.head_dim).chunk(3, dim=0)
|
|
||||||
sim = torch.einsum('hbwpc,hbwqc->hbwpq', q, k) * self.scale
|
|
||||||
# Adding learnable relative embedding
|
|
||||||
sim = sim + rearrange(self.relative_embedding(), 'h p q -> h 1 1 p q')
|
|
||||||
# Using Attn Mask to distinguish different subwindows.
|
|
||||||
if self.type != 'W':
|
|
||||||
attn_mask = self.generate_mask(h_windows, w_windows, self.window_size, shift=self.window_size // 2)
|
|
||||||
sim = sim.masked_fill_(attn_mask, float("-inf"))
|
|
||||||
|
|
||||||
probs = nn.functional.softmax(sim, dim=-1)
|
|
||||||
output = torch.einsum('hbwij,hbwjc->hbwic', probs, v)
|
|
||||||
output = rearrange(output, 'h b w p c -> b w p (h c)')
|
|
||||||
output = self.linear(output)
|
|
||||||
output = rearrange(output, 'b (w1 w2) (p1 p2) c -> b (w1 p1) (w2 p2) c', w1=h_windows, p1=self.window_size)
|
|
||||||
|
|
||||||
if self.type != 'W': output = torch.roll(output, shifts=(self.window_size // 2, self.window_size // 2),
|
|
||||||
dims=(1, 2))
|
|
||||||
return output
|
|
||||||
|
|
||||||
def relative_embedding(self):
|
|
||||||
cord = torch.tensor(np.array([[i, j] for i in range(self.window_size) for j in range(self.window_size)]))
|
|
||||||
relation = cord[:, None, :] - cord[None, :, :] + self.window_size - 1
|
|
||||||
# negative is allowed
|
|
||||||
return self.relative_position_params[:, relation[:, :, 0].long(), relation[:, :, 1].long()]
|
|
||||||
|
|
||||||
|
|
||||||
class Block(nn.Module):
|
|
||||||
def __init__(self, input_dim, output_dim, head_dim, window_size, drop_path, type='W', input_resolution=None):
|
|
||||||
""" SwinTransformer Block
|
|
||||||
"""
|
|
||||||
super(Block, self).__init__()
|
|
||||||
self.input_dim = input_dim
|
|
||||||
self.output_dim = output_dim
|
|
||||||
assert type in ['W', 'SW']
|
|
||||||
self.type = type
|
|
||||||
if input_resolution <= window_size:
|
|
||||||
self.type = 'W'
|
|
||||||
|
|
||||||
self.ln1 = nn.LayerNorm(input_dim)
|
|
||||||
self.msa = WMSA(input_dim, input_dim, head_dim, window_size, self.type)
|
|
||||||
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
|
||||||
self.ln2 = nn.LayerNorm(input_dim)
|
|
||||||
self.mlp = nn.Sequential(
|
|
||||||
nn.Linear(input_dim, 4 * input_dim),
|
|
||||||
nn.GELU(),
|
|
||||||
nn.Linear(4 * input_dim, output_dim),
|
|
||||||
)
|
|
||||||
|
|
||||||
def forward(self, x):
|
|
||||||
x = x + self.drop_path(self.msa(self.ln1(x)))
|
|
||||||
x = x + self.drop_path(self.mlp(self.ln2(x)))
|
|
||||||
return x
|
|
||||||
|
|
||||||
|
|
||||||
class ConvTransBlock(nn.Module):
|
|
||||||
def __init__(self, conv_dim, trans_dim, head_dim, window_size, drop_path, type='W', input_resolution=None):
|
|
||||||
""" SwinTransformer and Conv Block
|
|
||||||
"""
|
|
||||||
super(ConvTransBlock, self).__init__()
|
|
||||||
self.conv_dim = conv_dim
|
|
||||||
self.trans_dim = trans_dim
|
|
||||||
self.head_dim = head_dim
|
|
||||||
self.window_size = window_size
|
|
||||||
self.drop_path = drop_path
|
|
||||||
self.type = type
|
|
||||||
self.input_resolution = input_resolution
|
|
||||||
|
|
||||||
assert self.type in ['W', 'SW']
|
|
||||||
if self.input_resolution <= self.window_size:
|
|
||||||
self.type = 'W'
|
|
||||||
|
|
||||||
self.trans_block = Block(self.trans_dim, self.trans_dim, self.head_dim, self.window_size, self.drop_path,
|
|
||||||
self.type, self.input_resolution)
|
|
||||||
self.conv1_1 = nn.Conv2d(self.conv_dim + self.trans_dim, self.conv_dim + self.trans_dim, 1, 1, 0, bias=True)
|
|
||||||
self.conv1_2 = nn.Conv2d(self.conv_dim + self.trans_dim, self.conv_dim + self.trans_dim, 1, 1, 0, bias=True)
|
|
||||||
|
|
||||||
self.conv_block = nn.Sequential(
|
|
||||||
nn.Conv2d(self.conv_dim, self.conv_dim, 3, 1, 1, bias=False),
|
|
||||||
nn.ReLU(True),
|
|
||||||
nn.Conv2d(self.conv_dim, self.conv_dim, 3, 1, 1, bias=False)
|
|
||||||
)
|
|
||||||
|
|
||||||
def forward(self, x):
|
|
||||||
conv_x, trans_x = torch.split(self.conv1_1(x), (self.conv_dim, self.trans_dim), dim=1)
|
|
||||||
conv_x = self.conv_block(conv_x) + conv_x
|
|
||||||
trans_x = Rearrange('b c h w -> b h w c')(trans_x)
|
|
||||||
trans_x = self.trans_block(trans_x)
|
|
||||||
trans_x = Rearrange('b h w c -> b c h w')(trans_x)
|
|
||||||
res = self.conv1_2(torch.cat((conv_x, trans_x), dim=1))
|
|
||||||
x = x + res
|
|
||||||
|
|
||||||
return x
|
|
||||||
|
|
||||||
|
|
||||||
class SCUNet(nn.Module):
|
|
||||||
# def __init__(self, in_nc=3, config=[2, 2, 2, 2, 2, 2, 2], dim=64, drop_path_rate=0.0, input_resolution=256):
|
|
||||||
def __init__(self, in_nc=3, config=None, dim=64, drop_path_rate=0.0, input_resolution=256):
|
|
||||||
super(SCUNet, self).__init__()
|
|
||||||
if config is None:
|
|
||||||
config = [2, 2, 2, 2, 2, 2, 2]
|
|
||||||
self.config = config
|
|
||||||
self.dim = dim
|
|
||||||
self.head_dim = 32
|
|
||||||
self.window_size = 8
|
|
||||||
|
|
||||||
# drop path rate for each layer
|
|
||||||
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(config))]
|
|
||||||
|
|
||||||
self.m_head = [nn.Conv2d(in_nc, dim, 3, 1, 1, bias=False)]
|
|
||||||
|
|
||||||
begin = 0
|
|
||||||
self.m_down1 = [ConvTransBlock(dim // 2, dim // 2, self.head_dim, self.window_size, dpr[i + begin],
|
|
||||||
'W' if not i % 2 else 'SW', input_resolution)
|
|
||||||
for i in range(config[0])] + \
|
|
||||||
[nn.Conv2d(dim, 2 * dim, 2, 2, 0, bias=False)]
|
|
||||||
|
|
||||||
begin += config[0]
|
|
||||||
self.m_down2 = [ConvTransBlock(dim, dim, self.head_dim, self.window_size, dpr[i + begin],
|
|
||||||
'W' if not i % 2 else 'SW', input_resolution // 2)
|
|
||||||
for i in range(config[1])] + \
|
|
||||||
[nn.Conv2d(2 * dim, 4 * dim, 2, 2, 0, bias=False)]
|
|
||||||
|
|
||||||
begin += config[1]
|
|
||||||
self.m_down3 = [ConvTransBlock(2 * dim, 2 * dim, self.head_dim, self.window_size, dpr[i + begin],
|
|
||||||
'W' if not i % 2 else 'SW', input_resolution // 4)
|
|
||||||
for i in range(config[2])] + \
|
|
||||||
[nn.Conv2d(4 * dim, 8 * dim, 2, 2, 0, bias=False)]
|
|
||||||
|
|
||||||
begin += config[2]
|
|
||||||
self.m_body = [ConvTransBlock(4 * dim, 4 * dim, self.head_dim, self.window_size, dpr[i + begin],
|
|
||||||
'W' if not i % 2 else 'SW', input_resolution // 8)
|
|
||||||
for i in range(config[3])]
|
|
||||||
|
|
||||||
begin += config[3]
|
|
||||||
self.m_up3 = [nn.ConvTranspose2d(8 * dim, 4 * dim, 2, 2, 0, bias=False), ] + \
|
|
||||||
[ConvTransBlock(2 * dim, 2 * dim, self.head_dim, self.window_size, dpr[i + begin],
|
|
||||||
'W' if not i % 2 else 'SW', input_resolution // 4)
|
|
||||||
for i in range(config[4])]
|
|
||||||
|
|
||||||
begin += config[4]
|
|
||||||
self.m_up2 = [nn.ConvTranspose2d(4 * dim, 2 * dim, 2, 2, 0, bias=False), ] + \
|
|
||||||
[ConvTransBlock(dim, dim, self.head_dim, self.window_size, dpr[i + begin],
|
|
||||||
'W' if not i % 2 else 'SW', input_resolution // 2)
|
|
||||||
for i in range(config[5])]
|
|
||||||
|
|
||||||
begin += config[5]
|
|
||||||
self.m_up1 = [nn.ConvTranspose2d(2 * dim, dim, 2, 2, 0, bias=False), ] + \
|
|
||||||
[ConvTransBlock(dim // 2, dim // 2, self.head_dim, self.window_size, dpr[i + begin],
|
|
||||||
'W' if not i % 2 else 'SW', input_resolution)
|
|
||||||
for i in range(config[6])]
|
|
||||||
|
|
||||||
self.m_tail = [nn.Conv2d(dim, in_nc, 3, 1, 1, bias=False)]
|
|
||||||
|
|
||||||
self.m_head = nn.Sequential(*self.m_head)
|
|
||||||
self.m_down1 = nn.Sequential(*self.m_down1)
|
|
||||||
self.m_down2 = nn.Sequential(*self.m_down2)
|
|
||||||
self.m_down3 = nn.Sequential(*self.m_down3)
|
|
||||||
self.m_body = nn.Sequential(*self.m_body)
|
|
||||||
self.m_up3 = nn.Sequential(*self.m_up3)
|
|
||||||
self.m_up2 = nn.Sequential(*self.m_up2)
|
|
||||||
self.m_up1 = nn.Sequential(*self.m_up1)
|
|
||||||
self.m_tail = nn.Sequential(*self.m_tail)
|
|
||||||
# self.apply(self._init_weights)
|
|
||||||
|
|
||||||
def forward(self, x0):
|
|
||||||
|
|
||||||
h, w = x0.size()[-2:]
|
|
||||||
paddingBottom = int(np.ceil(h / 64) * 64 - h)
|
|
||||||
paddingRight = int(np.ceil(w / 64) * 64 - w)
|
|
||||||
x0 = nn.ReplicationPad2d((0, paddingRight, 0, paddingBottom))(x0)
|
|
||||||
|
|
||||||
x1 = self.m_head(x0)
|
|
||||||
x2 = self.m_down1(x1)
|
|
||||||
x3 = self.m_down2(x2)
|
|
||||||
x4 = self.m_down3(x3)
|
|
||||||
x = self.m_body(x4)
|
|
||||||
x = self.m_up3(x + x4)
|
|
||||||
x = self.m_up2(x + x3)
|
|
||||||
x = self.m_up1(x + x2)
|
|
||||||
x = self.m_tail(x + x1)
|
|
||||||
|
|
||||||
x = x[..., :h, :w]
|
|
||||||
|
|
||||||
return x
|
|
||||||
|
|
||||||
def _init_weights(self, m):
|
|
||||||
if isinstance(m, nn.Linear):
|
|
||||||
trunc_normal_(m.weight, std=.02)
|
|
||||||
if m.bias is not None:
|
|
||||||
nn.init.constant_(m.bias, 0)
|
|
||||||
elif isinstance(m, nn.LayerNorm):
|
|
||||||
nn.init.constant_(m.bias, 0)
|
|
||||||
nn.init.constant_(m.weight, 1.0)
|
|
@ -1,35 +1,30 @@
|
|||||||
import contextlib
|
import logging
|
||||||
import os
|
import sys
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import torch
|
import torch
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
from basicsr.utils.download_util import load_file_from_url
|
|
||||||
from tqdm import tqdm
|
|
||||||
|
|
||||||
from modules import modelloader, devices, script_callbacks, shared
|
from modules import devices, modelloader, script_callbacks, shared, upscaler_utils
|
||||||
from modules.shared import cmd_opts, opts, state
|
|
||||||
from swinir_model_arch import SwinIR as net
|
|
||||||
from swinir_model_arch_v2 import Swin2SR as net2
|
|
||||||
from modules.upscaler import Upscaler, UpscalerData
|
from modules.upscaler import Upscaler, UpscalerData
|
||||||
|
|
||||||
|
SWINIR_MODEL_URL = "https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR-L_x4_GAN.pth"
|
||||||
|
|
||||||
device_swinir = devices.get_device_for('swinir')
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class UpscalerSwinIR(Upscaler):
|
class UpscalerSwinIR(Upscaler):
|
||||||
def __init__(self, dirname):
|
def __init__(self, dirname):
|
||||||
|
self._cached_model = None # keep the model when SWIN_torch_compile is on to prevent re-compile every runs
|
||||||
|
self._cached_model_config = None # to clear '_cached_model' when changing model (v1/v2) or settings
|
||||||
self.name = "SwinIR"
|
self.name = "SwinIR"
|
||||||
self.model_url = "https://github.com/JingyunLiang/SwinIR/releases/download/v0.0" \
|
self.model_url = SWINIR_MODEL_URL
|
||||||
"/003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR" \
|
|
||||||
"-L_x4_GAN.pth "
|
|
||||||
self.model_name = "SwinIR 4x"
|
self.model_name = "SwinIR 4x"
|
||||||
self.user_path = dirname
|
self.user_path = dirname
|
||||||
super().__init__()
|
super().__init__()
|
||||||
scalers = []
|
scalers = []
|
||||||
model_files = self.find_models(ext_filter=[".pt", ".pth"])
|
model_files = self.find_models(ext_filter=[".pt", ".pth"])
|
||||||
for model in model_files:
|
for model in model_files:
|
||||||
if "http" in model:
|
if model.startswith("http"):
|
||||||
name = self.model_name
|
name = self.model_name
|
||||||
else:
|
else:
|
||||||
name = modelloader.friendly_name(model)
|
name = modelloader.friendly_name(model)
|
||||||
@ -37,135 +32,56 @@ class UpscalerSwinIR(Upscaler):
|
|||||||
scalers.append(model_data)
|
scalers.append(model_data)
|
||||||
self.scalers = scalers
|
self.scalers = scalers
|
||||||
|
|
||||||
def do_upscale(self, img, model_file):
|
def do_upscale(self, img: Image.Image, model_file: str) -> Image.Image:
|
||||||
model = self.load_model(model_file)
|
current_config = (model_file, shared.opts.SWIN_tile)
|
||||||
if model is None:
|
|
||||||
return img
|
if self._cached_model_config == current_config:
|
||||||
model = model.to(device_swinir, dtype=devices.dtype)
|
model = self._cached_model
|
||||||
img = upscale(img, model)
|
else:
|
||||||
try:
|
try:
|
||||||
torch.cuda.empty_cache()
|
model = self.load_model(model_file)
|
||||||
except:
|
except Exception as e:
|
||||||
pass
|
print(f"Failed loading SwinIR model {model_file}: {e}", file=sys.stderr)
|
||||||
|
return img
|
||||||
|
self._cached_model = model
|
||||||
|
self._cached_model_config = current_config
|
||||||
|
|
||||||
|
img = upscaler_utils.upscale_2(
|
||||||
|
img,
|
||||||
|
model,
|
||||||
|
tile_size=shared.opts.SWIN_tile,
|
||||||
|
tile_overlap=shared.opts.SWIN_tile_overlap,
|
||||||
|
scale=model.scale,
|
||||||
|
desc="SwinIR",
|
||||||
|
)
|
||||||
|
devices.torch_gc()
|
||||||
return img
|
return img
|
||||||
|
|
||||||
def load_model(self, path, scale=4):
|
def load_model(self, path, scale=4):
|
||||||
if "http" in path:
|
if path.startswith("http"):
|
||||||
dl_name = "%s%s" % (self.model_name.replace(" ", "_"), ".pth")
|
filename = modelloader.load_file_from_url(
|
||||||
filename = load_file_from_url(url=path, model_dir=self.model_path, file_name=dl_name, progress=True)
|
url=path,
|
||||||
|
model_dir=self.model_download_path,
|
||||||
|
file_name=f"{self.model_name.replace(' ', '_')}.pth",
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
filename = path
|
filename = path
|
||||||
if filename is None or not os.path.exists(filename):
|
|
||||||
return None
|
|
||||||
if filename.endswith(".v2.pth"):
|
|
||||||
model = net2(
|
|
||||||
upscale=scale,
|
|
||||||
in_chans=3,
|
|
||||||
img_size=64,
|
|
||||||
window_size=8,
|
|
||||||
img_range=1.0,
|
|
||||||
depths=[6, 6, 6, 6, 6, 6],
|
|
||||||
embed_dim=180,
|
|
||||||
num_heads=[6, 6, 6, 6, 6, 6],
|
|
||||||
mlp_ratio=2,
|
|
||||||
upsampler="nearest+conv",
|
|
||||||
resi_connection="1conv",
|
|
||||||
)
|
|
||||||
params = None
|
|
||||||
else:
|
|
||||||
model = net(
|
|
||||||
upscale=scale,
|
|
||||||
in_chans=3,
|
|
||||||
img_size=64,
|
|
||||||
window_size=8,
|
|
||||||
img_range=1.0,
|
|
||||||
depths=[6, 6, 6, 6, 6, 6, 6, 6, 6],
|
|
||||||
embed_dim=240,
|
|
||||||
num_heads=[8, 8, 8, 8, 8, 8, 8, 8, 8],
|
|
||||||
mlp_ratio=2,
|
|
||||||
upsampler="nearest+conv",
|
|
||||||
resi_connection="3conv",
|
|
||||||
)
|
|
||||||
params = "params_ema"
|
|
||||||
|
|
||||||
pretrained_model = torch.load(filename)
|
model_descriptor = modelloader.load_spandrel_model(
|
||||||
if params is not None:
|
filename,
|
||||||
model.load_state_dict(pretrained_model[params], strict=True)
|
device=self._get_device(),
|
||||||
else:
|
prefer_half=(devices.dtype == torch.float16),
|
||||||
model.load_state_dict(pretrained_model, strict=True)
|
expected_architecture="SwinIR",
|
||||||
return model
|
)
|
||||||
|
if getattr(shared.opts, 'SWIN_torch_compile', False):
|
||||||
|
try:
|
||||||
|
model_descriptor.model.compile()
|
||||||
|
except Exception:
|
||||||
|
logger.warning("Failed to compile SwinIR model, fallback to JIT", exc_info=True)
|
||||||
|
return model_descriptor
|
||||||
|
|
||||||
|
def _get_device(self):
|
||||||
def upscale(
|
return devices.get_device_for('swinir')
|
||||||
img,
|
|
||||||
model,
|
|
||||||
tile=None,
|
|
||||||
tile_overlap=None,
|
|
||||||
window_size=8,
|
|
||||||
scale=4,
|
|
||||||
):
|
|
||||||
tile = tile or opts.SWIN_tile
|
|
||||||
tile_overlap = tile_overlap or opts.SWIN_tile_overlap
|
|
||||||
|
|
||||||
|
|
||||||
img = np.array(img)
|
|
||||||
img = img[:, :, ::-1]
|
|
||||||
img = np.moveaxis(img, 2, 0) / 255
|
|
||||||
img = torch.from_numpy(img).float()
|
|
||||||
img = img.unsqueeze(0).to(device_swinir, dtype=devices.dtype)
|
|
||||||
with torch.no_grad(), devices.autocast():
|
|
||||||
_, _, h_old, w_old = img.size()
|
|
||||||
h_pad = (h_old // window_size + 1) * window_size - h_old
|
|
||||||
w_pad = (w_old // window_size + 1) * window_size - w_old
|
|
||||||
img = torch.cat([img, torch.flip(img, [2])], 2)[:, :, : h_old + h_pad, :]
|
|
||||||
img = torch.cat([img, torch.flip(img, [3])], 3)[:, :, :, : w_old + w_pad]
|
|
||||||
output = inference(img, model, tile, tile_overlap, window_size, scale)
|
|
||||||
output = output[..., : h_old * scale, : w_old * scale]
|
|
||||||
output = output.data.squeeze().float().cpu().clamp_(0, 1).numpy()
|
|
||||||
if output.ndim == 3:
|
|
||||||
output = np.transpose(
|
|
||||||
output[[2, 1, 0], :, :], (1, 2, 0)
|
|
||||||
) # CHW-RGB to HCW-BGR
|
|
||||||
output = (output * 255.0).round().astype(np.uint8) # float32 to uint8
|
|
||||||
return Image.fromarray(output, "RGB")
|
|
||||||
|
|
||||||
|
|
||||||
def inference(img, model, tile, tile_overlap, window_size, scale):
|
|
||||||
# test the image tile by tile
|
|
||||||
b, c, h, w = img.size()
|
|
||||||
tile = min(tile, h, w)
|
|
||||||
assert tile % window_size == 0, "tile size should be a multiple of window_size"
|
|
||||||
sf = scale
|
|
||||||
|
|
||||||
stride = tile - tile_overlap
|
|
||||||
h_idx_list = list(range(0, h - tile, stride)) + [h - tile]
|
|
||||||
w_idx_list = list(range(0, w - tile, stride)) + [w - tile]
|
|
||||||
E = torch.zeros(b, c, h * sf, w * sf, dtype=devices.dtype, device=device_swinir).type_as(img)
|
|
||||||
W = torch.zeros_like(E, dtype=devices.dtype, device=device_swinir)
|
|
||||||
|
|
||||||
with tqdm(total=len(h_idx_list) * len(w_idx_list), desc="SwinIR tiles") as pbar:
|
|
||||||
for h_idx in h_idx_list:
|
|
||||||
if state.interrupted or state.skipped:
|
|
||||||
break
|
|
||||||
|
|
||||||
for w_idx in w_idx_list:
|
|
||||||
if state.interrupted or state.skipped:
|
|
||||||
break
|
|
||||||
|
|
||||||
in_patch = img[..., h_idx: h_idx + tile, w_idx: w_idx + tile]
|
|
||||||
out_patch = model(in_patch)
|
|
||||||
out_patch_mask = torch.ones_like(out_patch)
|
|
||||||
|
|
||||||
E[
|
|
||||||
..., h_idx * sf: (h_idx + tile) * sf, w_idx * sf: (w_idx + tile) * sf
|
|
||||||
].add_(out_patch)
|
|
||||||
W[
|
|
||||||
..., h_idx * sf: (h_idx + tile) * sf, w_idx * sf: (w_idx + tile) * sf
|
|
||||||
].add_(out_patch_mask)
|
|
||||||
pbar.update(1)
|
|
||||||
output = E.div_(W)
|
|
||||||
|
|
||||||
return output
|
|
||||||
|
|
||||||
|
|
||||||
def on_ui_settings():
|
def on_ui_settings():
|
||||||
@ -173,6 +89,7 @@ def on_ui_settings():
|
|||||||
|
|
||||||
shared.opts.add_option("SWIN_tile", shared.OptionInfo(192, "Tile size for all SwinIR.", gr.Slider, {"minimum": 16, "maximum": 512, "step": 16}, section=('upscaling', "Upscaling")))
|
shared.opts.add_option("SWIN_tile", shared.OptionInfo(192, "Tile size for all SwinIR.", gr.Slider, {"minimum": 16, "maximum": 512, "step": 16}, section=('upscaling', "Upscaling")))
|
||||||
shared.opts.add_option("SWIN_tile_overlap", shared.OptionInfo(8, "Tile overlap, in pixels for SwinIR. Low values = visible seam.", gr.Slider, {"minimum": 0, "maximum": 48, "step": 1}, section=('upscaling', "Upscaling")))
|
shared.opts.add_option("SWIN_tile_overlap", shared.OptionInfo(8, "Tile overlap, in pixels for SwinIR. Low values = visible seam.", gr.Slider, {"minimum": 0, "maximum": 48, "step": 1}, section=('upscaling', "Upscaling")))
|
||||||
|
shared.opts.add_option("SWIN_torch_compile", shared.OptionInfo(False, "Use torch.compile to accelerate SwinIR.", gr.Checkbox, {"interactive": True}, section=('upscaling', "Upscaling")).info("Takes longer on first run"))
|
||||||
|
|
||||||
|
|
||||||
script_callbacks.on_ui_settings(on_ui_settings)
|
script_callbacks.on_ui_settings(on_ui_settings)
|
||||||
|
@ -1,867 +0,0 @@
|
|||||||
# -----------------------------------------------------------------------------------
|
|
||||||
# SwinIR: Image Restoration Using Swin Transformer, https://arxiv.org/abs/2108.10257
|
|
||||||
# Originally Written by Ze Liu, Modified by Jingyun Liang.
|
|
||||||
# -----------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
import math
|
|
||||||
import torch
|
|
||||||
import torch.nn as nn
|
|
||||||
import torch.nn.functional as F
|
|
||||||
import torch.utils.checkpoint as checkpoint
|
|
||||||
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
|
|
||||||
|
|
||||||
|
|
||||||
class Mlp(nn.Module):
|
|
||||||
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
|
|
||||||
super().__init__()
|
|
||||||
out_features = out_features or in_features
|
|
||||||
hidden_features = hidden_features or in_features
|
|
||||||
self.fc1 = nn.Linear(in_features, hidden_features)
|
|
||||||
self.act = act_layer()
|
|
||||||
self.fc2 = nn.Linear(hidden_features, out_features)
|
|
||||||
self.drop = nn.Dropout(drop)
|
|
||||||
|
|
||||||
def forward(self, x):
|
|
||||||
x = self.fc1(x)
|
|
||||||
x = self.act(x)
|
|
||||||
x = self.drop(x)
|
|
||||||
x = self.fc2(x)
|
|
||||||
x = self.drop(x)
|
|
||||||
return x
|
|
||||||
|
|
||||||
|
|
||||||
def window_partition(x, window_size):
|
|
||||||
"""
|
|
||||||
Args:
|
|
||||||
x: (B, H, W, C)
|
|
||||||
window_size (int): window size
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
windows: (num_windows*B, window_size, window_size, C)
|
|
||||||
"""
|
|
||||||
B, H, W, C = x.shape
|
|
||||||
x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
|
|
||||||
windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
|
|
||||||
return windows
|
|
||||||
|
|
||||||
|
|
||||||
def window_reverse(windows, window_size, H, W):
|
|
||||||
"""
|
|
||||||
Args:
|
|
||||||
windows: (num_windows*B, window_size, window_size, C)
|
|
||||||
window_size (int): Window size
|
|
||||||
H (int): Height of image
|
|
||||||
W (int): Width of image
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
x: (B, H, W, C)
|
|
||||||
"""
|
|
||||||
B = int(windows.shape[0] / (H * W / window_size / window_size))
|
|
||||||
x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
|
|
||||||
x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
|
|
||||||
return x
|
|
||||||
|
|
||||||
|
|
||||||
class WindowAttention(nn.Module):
|
|
||||||
r""" Window based multi-head self attention (W-MSA) module with relative position bias.
|
|
||||||
It supports both of shifted and non-shifted window.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
dim (int): Number of input channels.
|
|
||||||
window_size (tuple[int]): The height and width of the window.
|
|
||||||
num_heads (int): Number of attention heads.
|
|
||||||
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
|
||||||
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
|
|
||||||
attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
|
|
||||||
proj_drop (float, optional): Dropout ratio of output. Default: 0.0
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):
|
|
||||||
|
|
||||||
super().__init__()
|
|
||||||
self.dim = dim
|
|
||||||
self.window_size = window_size # Wh, Ww
|
|
||||||
self.num_heads = num_heads
|
|
||||||
head_dim = dim // num_heads
|
|
||||||
self.scale = qk_scale or head_dim ** -0.5
|
|
||||||
|
|
||||||
# define a parameter table of relative position bias
|
|
||||||
self.relative_position_bias_table = nn.Parameter(
|
|
||||||
torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
|
|
||||||
|
|
||||||
# get pair-wise relative position index for each token inside the window
|
|
||||||
coords_h = torch.arange(self.window_size[0])
|
|
||||||
coords_w = torch.arange(self.window_size[1])
|
|
||||||
coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
|
|
||||||
coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
|
|
||||||
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
|
|
||||||
relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
|
|
||||||
relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
|
|
||||||
relative_coords[:, :, 1] += self.window_size[1] - 1
|
|
||||||
relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
|
|
||||||
relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
|
|
||||||
self.register_buffer("relative_position_index", relative_position_index)
|
|
||||||
|
|
||||||
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
|
||||||
self.attn_drop = nn.Dropout(attn_drop)
|
|
||||||
self.proj = nn.Linear(dim, dim)
|
|
||||||
|
|
||||||
self.proj_drop = nn.Dropout(proj_drop)
|
|
||||||
|
|
||||||
trunc_normal_(self.relative_position_bias_table, std=.02)
|
|
||||||
self.softmax = nn.Softmax(dim=-1)
|
|
||||||
|
|
||||||
def forward(self, x, mask=None):
|
|
||||||
"""
|
|
||||||
Args:
|
|
||||||
x: input features with shape of (num_windows*B, N, C)
|
|
||||||
mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
|
|
||||||
"""
|
|
||||||
B_, N, C = x.shape
|
|
||||||
qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
|
|
||||||
q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
|
|
||||||
|
|
||||||
q = q * self.scale
|
|
||||||
attn = (q @ k.transpose(-2, -1))
|
|
||||||
|
|
||||||
relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
|
|
||||||
self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH
|
|
||||||
relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
|
|
||||||
attn = attn + relative_position_bias.unsqueeze(0)
|
|
||||||
|
|
||||||
if mask is not None:
|
|
||||||
nW = mask.shape[0]
|
|
||||||
attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
|
|
||||||
attn = attn.view(-1, self.num_heads, N, N)
|
|
||||||
attn = self.softmax(attn)
|
|
||||||
else:
|
|
||||||
attn = self.softmax(attn)
|
|
||||||
|
|
||||||
attn = self.attn_drop(attn)
|
|
||||||
|
|
||||||
x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
|
|
||||||
x = self.proj(x)
|
|
||||||
x = self.proj_drop(x)
|
|
||||||
return x
|
|
||||||
|
|
||||||
def extra_repr(self) -> str:
|
|
||||||
return f'dim={self.dim}, window_size={self.window_size}, num_heads={self.num_heads}'
|
|
||||||
|
|
||||||
def flops(self, N):
|
|
||||||
# calculate flops for 1 window with token length of N
|
|
||||||
flops = 0
|
|
||||||
# qkv = self.qkv(x)
|
|
||||||
flops += N * self.dim * 3 * self.dim
|
|
||||||
# attn = (q @ k.transpose(-2, -1))
|
|
||||||
flops += self.num_heads * N * (self.dim // self.num_heads) * N
|
|
||||||
# x = (attn @ v)
|
|
||||||
flops += self.num_heads * N * N * (self.dim // self.num_heads)
|
|
||||||
# x = self.proj(x)
|
|
||||||
flops += N * self.dim * self.dim
|
|
||||||
return flops
|
|
||||||
|
|
||||||
|
|
||||||
class SwinTransformerBlock(nn.Module):
|
|
||||||
r""" Swin Transformer Block.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
dim (int): Number of input channels.
|
|
||||||
input_resolution (tuple[int]): Input resolution.
|
|
||||||
num_heads (int): Number of attention heads.
|
|
||||||
window_size (int): Window size.
|
|
||||||
shift_size (int): Shift size for SW-MSA.
|
|
||||||
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
|
|
||||||
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
|
||||||
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
|
|
||||||
drop (float, optional): Dropout rate. Default: 0.0
|
|
||||||
attn_drop (float, optional): Attention dropout rate. Default: 0.0
|
|
||||||
drop_path (float, optional): Stochastic depth rate. Default: 0.0
|
|
||||||
act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
|
|
||||||
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, dim, input_resolution, num_heads, window_size=7, shift_size=0,
|
|
||||||
mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,
|
|
||||||
act_layer=nn.GELU, norm_layer=nn.LayerNorm):
|
|
||||||
super().__init__()
|
|
||||||
self.dim = dim
|
|
||||||
self.input_resolution = input_resolution
|
|
||||||
self.num_heads = num_heads
|
|
||||||
self.window_size = window_size
|
|
||||||
self.shift_size = shift_size
|
|
||||||
self.mlp_ratio = mlp_ratio
|
|
||||||
if min(self.input_resolution) <= self.window_size:
|
|
||||||
# if window size is larger than input resolution, we don't partition windows
|
|
||||||
self.shift_size = 0
|
|
||||||
self.window_size = min(self.input_resolution)
|
|
||||||
assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
|
|
||||||
|
|
||||||
self.norm1 = norm_layer(dim)
|
|
||||||
self.attn = WindowAttention(
|
|
||||||
dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,
|
|
||||||
qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
|
|
||||||
|
|
||||||
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
|
||||||
self.norm2 = norm_layer(dim)
|
|
||||||
mlp_hidden_dim = int(dim * mlp_ratio)
|
|
||||||
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
|
|
||||||
|
|
||||||
if self.shift_size > 0:
|
|
||||||
attn_mask = self.calculate_mask(self.input_resolution)
|
|
||||||
else:
|
|
||||||
attn_mask = None
|
|
||||||
|
|
||||||
self.register_buffer("attn_mask", attn_mask)
|
|
||||||
|
|
||||||
def calculate_mask(self, x_size):
|
|
||||||
# calculate attention mask for SW-MSA
|
|
||||||
H, W = x_size
|
|
||||||
img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1
|
|
||||||
h_slices = (slice(0, -self.window_size),
|
|
||||||
slice(-self.window_size, -self.shift_size),
|
|
||||||
slice(-self.shift_size, None))
|
|
||||||
w_slices = (slice(0, -self.window_size),
|
|
||||||
slice(-self.window_size, -self.shift_size),
|
|
||||||
slice(-self.shift_size, None))
|
|
||||||
cnt = 0
|
|
||||||
for h in h_slices:
|
|
||||||
for w in w_slices:
|
|
||||||
img_mask[:, h, w, :] = cnt
|
|
||||||
cnt += 1
|
|
||||||
|
|
||||||
mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
|
|
||||||
mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
|
|
||||||
attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
|
|
||||||
attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
|
|
||||||
|
|
||||||
return attn_mask
|
|
||||||
|
|
||||||
def forward(self, x, x_size):
|
|
||||||
H, W = x_size
|
|
||||||
B, L, C = x.shape
|
|
||||||
# assert L == H * W, "input feature has wrong size"
|
|
||||||
|
|
||||||
shortcut = x
|
|
||||||
x = self.norm1(x)
|
|
||||||
x = x.view(B, H, W, C)
|
|
||||||
|
|
||||||
# cyclic shift
|
|
||||||
if self.shift_size > 0:
|
|
||||||
shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
|
|
||||||
else:
|
|
||||||
shifted_x = x
|
|
||||||
|
|
||||||
# partition windows
|
|
||||||
x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
|
|
||||||
x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
|
|
||||||
|
|
||||||
# W-MSA/SW-MSA (to be compatible for testing on images whose shapes are the multiple of window size
|
|
||||||
if self.input_resolution == x_size:
|
|
||||||
attn_windows = self.attn(x_windows, mask=self.attn_mask) # nW*B, window_size*window_size, C
|
|
||||||
else:
|
|
||||||
attn_windows = self.attn(x_windows, mask=self.calculate_mask(x_size).to(x.device))
|
|
||||||
|
|
||||||
# merge windows
|
|
||||||
attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
|
|
||||||
shifted_x = window_reverse(attn_windows, self.window_size, H, W) # B H' W' C
|
|
||||||
|
|
||||||
# reverse cyclic shift
|
|
||||||
if self.shift_size > 0:
|
|
||||||
x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
|
|
||||||
else:
|
|
||||||
x = shifted_x
|
|
||||||
x = x.view(B, H * W, C)
|
|
||||||
|
|
||||||
# FFN
|
|
||||||
x = shortcut + self.drop_path(x)
|
|
||||||
x = x + self.drop_path(self.mlp(self.norm2(x)))
|
|
||||||
|
|
||||||
return x
|
|
||||||
|
|
||||||
def extra_repr(self) -> str:
|
|
||||||
return f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " \
|
|
||||||
f"window_size={self.window_size}, shift_size={self.shift_size}, mlp_ratio={self.mlp_ratio}"
|
|
||||||
|
|
||||||
def flops(self):
|
|
||||||
flops = 0
|
|
||||||
H, W = self.input_resolution
|
|
||||||
# norm1
|
|
||||||
flops += self.dim * H * W
|
|
||||||
# W-MSA/SW-MSA
|
|
||||||
nW = H * W / self.window_size / self.window_size
|
|
||||||
flops += nW * self.attn.flops(self.window_size * self.window_size)
|
|
||||||
# mlp
|
|
||||||
flops += 2 * H * W * self.dim * self.dim * self.mlp_ratio
|
|
||||||
# norm2
|
|
||||||
flops += self.dim * H * W
|
|
||||||
return flops
|
|
||||||
|
|
||||||
|
|
||||||
class PatchMerging(nn.Module):
|
|
||||||
r""" Patch Merging Layer.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
input_resolution (tuple[int]): Resolution of input feature.
|
|
||||||
dim (int): Number of input channels.
|
|
||||||
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm):
|
|
||||||
super().__init__()
|
|
||||||
self.input_resolution = input_resolution
|
|
||||||
self.dim = dim
|
|
||||||
self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
|
|
||||||
self.norm = norm_layer(4 * dim)
|
|
||||||
|
|
||||||
def forward(self, x):
|
|
||||||
"""
|
|
||||||
x: B, H*W, C
|
|
||||||
"""
|
|
||||||
H, W = self.input_resolution
|
|
||||||
B, L, C = x.shape
|
|
||||||
assert L == H * W, "input feature has wrong size"
|
|
||||||
assert H % 2 == 0 and W % 2 == 0, f"x size ({H}*{W}) are not even."
|
|
||||||
|
|
||||||
x = x.view(B, H, W, C)
|
|
||||||
|
|
||||||
x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
|
|
||||||
x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
|
|
||||||
x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
|
|
||||||
x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
|
|
||||||
x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
|
|
||||||
x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
|
|
||||||
|
|
||||||
x = self.norm(x)
|
|
||||||
x = self.reduction(x)
|
|
||||||
|
|
||||||
return x
|
|
||||||
|
|
||||||
def extra_repr(self) -> str:
|
|
||||||
return f"input_resolution={self.input_resolution}, dim={self.dim}"
|
|
||||||
|
|
||||||
def flops(self):
|
|
||||||
H, W = self.input_resolution
|
|
||||||
flops = H * W * self.dim
|
|
||||||
flops += (H // 2) * (W // 2) * 4 * self.dim * 2 * self.dim
|
|
||||||
return flops
|
|
||||||
|
|
||||||
|
|
||||||
class BasicLayer(nn.Module):
|
|
||||||
""" A basic Swin Transformer layer for one stage.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
dim (int): Number of input channels.
|
|
||||||
input_resolution (tuple[int]): Input resolution.
|
|
||||||
depth (int): Number of blocks.
|
|
||||||
num_heads (int): Number of attention heads.
|
|
||||||
window_size (int): Local window size.
|
|
||||||
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
|
|
||||||
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
|
||||||
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
|
|
||||||
drop (float, optional): Dropout rate. Default: 0.0
|
|
||||||
attn_drop (float, optional): Attention dropout rate. Default: 0.0
|
|
||||||
drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
|
|
||||||
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
|
|
||||||
downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
|
|
||||||
use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, dim, input_resolution, depth, num_heads, window_size,
|
|
||||||
mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0.,
|
|
||||||
drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False):
|
|
||||||
|
|
||||||
super().__init__()
|
|
||||||
self.dim = dim
|
|
||||||
self.input_resolution = input_resolution
|
|
||||||
self.depth = depth
|
|
||||||
self.use_checkpoint = use_checkpoint
|
|
||||||
|
|
||||||
# build blocks
|
|
||||||
self.blocks = nn.ModuleList([
|
|
||||||
SwinTransformerBlock(dim=dim, input_resolution=input_resolution,
|
|
||||||
num_heads=num_heads, window_size=window_size,
|
|
||||||
shift_size=0 if (i % 2 == 0) else window_size // 2,
|
|
||||||
mlp_ratio=mlp_ratio,
|
|
||||||
qkv_bias=qkv_bias, qk_scale=qk_scale,
|
|
||||||
drop=drop, attn_drop=attn_drop,
|
|
||||||
drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
|
|
||||||
norm_layer=norm_layer)
|
|
||||||
for i in range(depth)])
|
|
||||||
|
|
||||||
# patch merging layer
|
|
||||||
if downsample is not None:
|
|
||||||
self.downsample = downsample(input_resolution, dim=dim, norm_layer=norm_layer)
|
|
||||||
else:
|
|
||||||
self.downsample = None
|
|
||||||
|
|
||||||
def forward(self, x, x_size):
|
|
||||||
for blk in self.blocks:
|
|
||||||
if self.use_checkpoint:
|
|
||||||
x = checkpoint.checkpoint(blk, x, x_size)
|
|
||||||
else:
|
|
||||||
x = blk(x, x_size)
|
|
||||||
if self.downsample is not None:
|
|
||||||
x = self.downsample(x)
|
|
||||||
return x
|
|
||||||
|
|
||||||
def extra_repr(self) -> str:
|
|
||||||
return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}"
|
|
||||||
|
|
||||||
def flops(self):
|
|
||||||
flops = 0
|
|
||||||
for blk in self.blocks:
|
|
||||||
flops += blk.flops()
|
|
||||||
if self.downsample is not None:
|
|
||||||
flops += self.downsample.flops()
|
|
||||||
return flops
|
|
||||||
|
|
||||||
|
|
||||||
class RSTB(nn.Module):
|
|
||||||
"""Residual Swin Transformer Block (RSTB).
|
|
||||||
|
|
||||||
Args:
|
|
||||||
dim (int): Number of input channels.
|
|
||||||
input_resolution (tuple[int]): Input resolution.
|
|
||||||
depth (int): Number of blocks.
|
|
||||||
num_heads (int): Number of attention heads.
|
|
||||||
window_size (int): Local window size.
|
|
||||||
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
|
|
||||||
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
|
||||||
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
|
|
||||||
drop (float, optional): Dropout rate. Default: 0.0
|
|
||||||
attn_drop (float, optional): Attention dropout rate. Default: 0.0
|
|
||||||
drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
|
|
||||||
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
|
|
||||||
downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
|
|
||||||
use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
|
|
||||||
img_size: Input image size.
|
|
||||||
patch_size: Patch size.
|
|
||||||
resi_connection: The convolutional block before residual connection.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, dim, input_resolution, depth, num_heads, window_size,
|
|
||||||
mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0.,
|
|
||||||
drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False,
|
|
||||||
img_size=224, patch_size=4, resi_connection='1conv'):
|
|
||||||
super(RSTB, self).__init__()
|
|
||||||
|
|
||||||
self.dim = dim
|
|
||||||
self.input_resolution = input_resolution
|
|
||||||
|
|
||||||
self.residual_group = BasicLayer(dim=dim,
|
|
||||||
input_resolution=input_resolution,
|
|
||||||
depth=depth,
|
|
||||||
num_heads=num_heads,
|
|
||||||
window_size=window_size,
|
|
||||||
mlp_ratio=mlp_ratio,
|
|
||||||
qkv_bias=qkv_bias, qk_scale=qk_scale,
|
|
||||||
drop=drop, attn_drop=attn_drop,
|
|
||||||
drop_path=drop_path,
|
|
||||||
norm_layer=norm_layer,
|
|
||||||
downsample=downsample,
|
|
||||||
use_checkpoint=use_checkpoint)
|
|
||||||
|
|
||||||
if resi_connection == '1conv':
|
|
||||||
self.conv = nn.Conv2d(dim, dim, 3, 1, 1)
|
|
||||||
elif resi_connection == '3conv':
|
|
||||||
# to save parameters and memory
|
|
||||||
self.conv = nn.Sequential(nn.Conv2d(dim, dim // 4, 3, 1, 1), nn.LeakyReLU(negative_slope=0.2, inplace=True),
|
|
||||||
nn.Conv2d(dim // 4, dim // 4, 1, 1, 0),
|
|
||||||
nn.LeakyReLU(negative_slope=0.2, inplace=True),
|
|
||||||
nn.Conv2d(dim // 4, dim, 3, 1, 1))
|
|
||||||
|
|
||||||
self.patch_embed = PatchEmbed(
|
|
||||||
img_size=img_size, patch_size=patch_size, in_chans=0, embed_dim=dim,
|
|
||||||
norm_layer=None)
|
|
||||||
|
|
||||||
self.patch_unembed = PatchUnEmbed(
|
|
||||||
img_size=img_size, patch_size=patch_size, in_chans=0, embed_dim=dim,
|
|
||||||
norm_layer=None)
|
|
||||||
|
|
||||||
def forward(self, x, x_size):
|
|
||||||
return self.patch_embed(self.conv(self.patch_unembed(self.residual_group(x, x_size), x_size))) + x
|
|
||||||
|
|
||||||
def flops(self):
|
|
||||||
flops = 0
|
|
||||||
flops += self.residual_group.flops()
|
|
||||||
H, W = self.input_resolution
|
|
||||||
flops += H * W * self.dim * self.dim * 9
|
|
||||||
flops += self.patch_embed.flops()
|
|
||||||
flops += self.patch_unembed.flops()
|
|
||||||
|
|
||||||
return flops
|
|
||||||
|
|
||||||
|
|
||||||
class PatchEmbed(nn.Module):
|
|
||||||
r""" Image to Patch Embedding
|
|
||||||
|
|
||||||
Args:
|
|
||||||
img_size (int): Image size. Default: 224.
|
|
||||||
patch_size (int): Patch token size. Default: 4.
|
|
||||||
in_chans (int): Number of input image channels. Default: 3.
|
|
||||||
embed_dim (int): Number of linear projection output channels. Default: 96.
|
|
||||||
norm_layer (nn.Module, optional): Normalization layer. Default: None
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
|
|
||||||
super().__init__()
|
|
||||||
img_size = to_2tuple(img_size)
|
|
||||||
patch_size = to_2tuple(patch_size)
|
|
||||||
patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]]
|
|
||||||
self.img_size = img_size
|
|
||||||
self.patch_size = patch_size
|
|
||||||
self.patches_resolution = patches_resolution
|
|
||||||
self.num_patches = patches_resolution[0] * patches_resolution[1]
|
|
||||||
|
|
||||||
self.in_chans = in_chans
|
|
||||||
self.embed_dim = embed_dim
|
|
||||||
|
|
||||||
if norm_layer is not None:
|
|
||||||
self.norm = norm_layer(embed_dim)
|
|
||||||
else:
|
|
||||||
self.norm = None
|
|
||||||
|
|
||||||
def forward(self, x):
|
|
||||||
x = x.flatten(2).transpose(1, 2) # B Ph*Pw C
|
|
||||||
if self.norm is not None:
|
|
||||||
x = self.norm(x)
|
|
||||||
return x
|
|
||||||
|
|
||||||
def flops(self):
|
|
||||||
flops = 0
|
|
||||||
H, W = self.img_size
|
|
||||||
if self.norm is not None:
|
|
||||||
flops += H * W * self.embed_dim
|
|
||||||
return flops
|
|
||||||
|
|
||||||
|
|
||||||
class PatchUnEmbed(nn.Module):
|
|
||||||
r""" Image to Patch Unembedding
|
|
||||||
|
|
||||||
Args:
|
|
||||||
img_size (int): Image size. Default: 224.
|
|
||||||
patch_size (int): Patch token size. Default: 4.
|
|
||||||
in_chans (int): Number of input image channels. Default: 3.
|
|
||||||
embed_dim (int): Number of linear projection output channels. Default: 96.
|
|
||||||
norm_layer (nn.Module, optional): Normalization layer. Default: None
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
|
|
||||||
super().__init__()
|
|
||||||
img_size = to_2tuple(img_size)
|
|
||||||
patch_size = to_2tuple(patch_size)
|
|
||||||
patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]]
|
|
||||||
self.img_size = img_size
|
|
||||||
self.patch_size = patch_size
|
|
||||||
self.patches_resolution = patches_resolution
|
|
||||||
self.num_patches = patches_resolution[0] * patches_resolution[1]
|
|
||||||
|
|
||||||
self.in_chans = in_chans
|
|
||||||
self.embed_dim = embed_dim
|
|
||||||
|
|
||||||
def forward(self, x, x_size):
|
|
||||||
B, HW, C = x.shape
|
|
||||||
x = x.transpose(1, 2).view(B, self.embed_dim, x_size[0], x_size[1]) # B Ph*Pw C
|
|
||||||
return x
|
|
||||||
|
|
||||||
def flops(self):
|
|
||||||
flops = 0
|
|
||||||
return flops
|
|
||||||
|
|
||||||
|
|
||||||
class Upsample(nn.Sequential):
|
|
||||||
"""Upsample module.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
scale (int): Scale factor. Supported scales: 2^n and 3.
|
|
||||||
num_feat (int): Channel number of intermediate features.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, scale, num_feat):
|
|
||||||
m = []
|
|
||||||
if (scale & (scale - 1)) == 0: # scale = 2^n
|
|
||||||
for _ in range(int(math.log(scale, 2))):
|
|
||||||
m.append(nn.Conv2d(num_feat, 4 * num_feat, 3, 1, 1))
|
|
||||||
m.append(nn.PixelShuffle(2))
|
|
||||||
elif scale == 3:
|
|
||||||
m.append(nn.Conv2d(num_feat, 9 * num_feat, 3, 1, 1))
|
|
||||||
m.append(nn.PixelShuffle(3))
|
|
||||||
else:
|
|
||||||
raise ValueError(f'scale {scale} is not supported. ' 'Supported scales: 2^n and 3.')
|
|
||||||
super(Upsample, self).__init__(*m)
|
|
||||||
|
|
||||||
|
|
||||||
class UpsampleOneStep(nn.Sequential):
|
|
||||||
"""UpsampleOneStep module (the difference with Upsample is that it always only has 1conv + 1pixelshuffle)
|
|
||||||
Used in lightweight SR to save parameters.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
scale (int): Scale factor. Supported scales: 2^n and 3.
|
|
||||||
num_feat (int): Channel number of intermediate features.
|
|
||||||
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, scale, num_feat, num_out_ch, input_resolution=None):
|
|
||||||
self.num_feat = num_feat
|
|
||||||
self.input_resolution = input_resolution
|
|
||||||
m = []
|
|
||||||
m.append(nn.Conv2d(num_feat, (scale ** 2) * num_out_ch, 3, 1, 1))
|
|
||||||
m.append(nn.PixelShuffle(scale))
|
|
||||||
super(UpsampleOneStep, self).__init__(*m)
|
|
||||||
|
|
||||||
def flops(self):
|
|
||||||
H, W = self.input_resolution
|
|
||||||
flops = H * W * self.num_feat * 3 * 9
|
|
||||||
return flops
|
|
||||||
|
|
||||||
|
|
||||||
class SwinIR(nn.Module):
|
|
||||||
r""" SwinIR
|
|
||||||
A PyTorch impl of : `SwinIR: Image Restoration Using Swin Transformer`, based on Swin Transformer.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
img_size (int | tuple(int)): Input image size. Default 64
|
|
||||||
patch_size (int | tuple(int)): Patch size. Default: 1
|
|
||||||
in_chans (int): Number of input image channels. Default: 3
|
|
||||||
embed_dim (int): Patch embedding dimension. Default: 96
|
|
||||||
depths (tuple(int)): Depth of each Swin Transformer layer.
|
|
||||||
num_heads (tuple(int)): Number of attention heads in different layers.
|
|
||||||
window_size (int): Window size. Default: 7
|
|
||||||
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4
|
|
||||||
qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
|
|
||||||
qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. Default: None
|
|
||||||
drop_rate (float): Dropout rate. Default: 0
|
|
||||||
attn_drop_rate (float): Attention dropout rate. Default: 0
|
|
||||||
drop_path_rate (float): Stochastic depth rate. Default: 0.1
|
|
||||||
norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
|
|
||||||
ape (bool): If True, add absolute position embedding to the patch embedding. Default: False
|
|
||||||
patch_norm (bool): If True, add normalization after patch embedding. Default: True
|
|
||||||
use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False
|
|
||||||
upscale: Upscale factor. 2/3/4/8 for image SR, 1 for denoising and compress artifact reduction
|
|
||||||
img_range: Image range. 1. or 255.
|
|
||||||
upsampler: The reconstruction reconstruction module. 'pixelshuffle'/'pixelshuffledirect'/'nearest+conv'/None
|
|
||||||
resi_connection: The convolutional block before residual connection. '1conv'/'3conv'
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, img_size=64, patch_size=1, in_chans=3,
|
|
||||||
embed_dim=96, depths=[6, 6, 6, 6], num_heads=[6, 6, 6, 6],
|
|
||||||
window_size=7, mlp_ratio=4., qkv_bias=True, qk_scale=None,
|
|
||||||
drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1,
|
|
||||||
norm_layer=nn.LayerNorm, ape=False, patch_norm=True,
|
|
||||||
use_checkpoint=False, upscale=2, img_range=1., upsampler='', resi_connection='1conv',
|
|
||||||
**kwargs):
|
|
||||||
super(SwinIR, self).__init__()
|
|
||||||
num_in_ch = in_chans
|
|
||||||
num_out_ch = in_chans
|
|
||||||
num_feat = 64
|
|
||||||
self.img_range = img_range
|
|
||||||
if in_chans == 3:
|
|
||||||
rgb_mean = (0.4488, 0.4371, 0.4040)
|
|
||||||
self.mean = torch.Tensor(rgb_mean).view(1, 3, 1, 1)
|
|
||||||
else:
|
|
||||||
self.mean = torch.zeros(1, 1, 1, 1)
|
|
||||||
self.upscale = upscale
|
|
||||||
self.upsampler = upsampler
|
|
||||||
self.window_size = window_size
|
|
||||||
|
|
||||||
#####################################################################################################
|
|
||||||
################################### 1, shallow feature extraction ###################################
|
|
||||||
self.conv_first = nn.Conv2d(num_in_ch, embed_dim, 3, 1, 1)
|
|
||||||
|
|
||||||
#####################################################################################################
|
|
||||||
################################### 2, deep feature extraction ######################################
|
|
||||||
self.num_layers = len(depths)
|
|
||||||
self.embed_dim = embed_dim
|
|
||||||
self.ape = ape
|
|
||||||
self.patch_norm = patch_norm
|
|
||||||
self.num_features = embed_dim
|
|
||||||
self.mlp_ratio = mlp_ratio
|
|
||||||
|
|
||||||
# split image into non-overlapping patches
|
|
||||||
self.patch_embed = PatchEmbed(
|
|
||||||
img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim,
|
|
||||||
norm_layer=norm_layer if self.patch_norm else None)
|
|
||||||
num_patches = self.patch_embed.num_patches
|
|
||||||
patches_resolution = self.patch_embed.patches_resolution
|
|
||||||
self.patches_resolution = patches_resolution
|
|
||||||
|
|
||||||
# merge non-overlapping patches into image
|
|
||||||
self.patch_unembed = PatchUnEmbed(
|
|
||||||
img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim,
|
|
||||||
norm_layer=norm_layer if self.patch_norm else None)
|
|
||||||
|
|
||||||
# absolute position embedding
|
|
||||||
if self.ape:
|
|
||||||
self.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim))
|
|
||||||
trunc_normal_(self.absolute_pos_embed, std=.02)
|
|
||||||
|
|
||||||
self.pos_drop = nn.Dropout(p=drop_rate)
|
|
||||||
|
|
||||||
# stochastic depth
|
|
||||||
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
|
|
||||||
|
|
||||||
# build Residual Swin Transformer blocks (RSTB)
|
|
||||||
self.layers = nn.ModuleList()
|
|
||||||
for i_layer in range(self.num_layers):
|
|
||||||
layer = RSTB(dim=embed_dim,
|
|
||||||
input_resolution=(patches_resolution[0],
|
|
||||||
patches_resolution[1]),
|
|
||||||
depth=depths[i_layer],
|
|
||||||
num_heads=num_heads[i_layer],
|
|
||||||
window_size=window_size,
|
|
||||||
mlp_ratio=self.mlp_ratio,
|
|
||||||
qkv_bias=qkv_bias, qk_scale=qk_scale,
|
|
||||||
drop=drop_rate, attn_drop=attn_drop_rate,
|
|
||||||
drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])], # no impact on SR results
|
|
||||||
norm_layer=norm_layer,
|
|
||||||
downsample=None,
|
|
||||||
use_checkpoint=use_checkpoint,
|
|
||||||
img_size=img_size,
|
|
||||||
patch_size=patch_size,
|
|
||||||
resi_connection=resi_connection
|
|
||||||
|
|
||||||
)
|
|
||||||
self.layers.append(layer)
|
|
||||||
self.norm = norm_layer(self.num_features)
|
|
||||||
|
|
||||||
# build the last conv layer in deep feature extraction
|
|
||||||
if resi_connection == '1conv':
|
|
||||||
self.conv_after_body = nn.Conv2d(embed_dim, embed_dim, 3, 1, 1)
|
|
||||||
elif resi_connection == '3conv':
|
|
||||||
# to save parameters and memory
|
|
||||||
self.conv_after_body = nn.Sequential(nn.Conv2d(embed_dim, embed_dim // 4, 3, 1, 1),
|
|
||||||
nn.LeakyReLU(negative_slope=0.2, inplace=True),
|
|
||||||
nn.Conv2d(embed_dim // 4, embed_dim // 4, 1, 1, 0),
|
|
||||||
nn.LeakyReLU(negative_slope=0.2, inplace=True),
|
|
||||||
nn.Conv2d(embed_dim // 4, embed_dim, 3, 1, 1))
|
|
||||||
|
|
||||||
#####################################################################################################
|
|
||||||
################################ 3, high quality image reconstruction ################################
|
|
||||||
if self.upsampler == 'pixelshuffle':
|
|
||||||
# for classical SR
|
|
||||||
self.conv_before_upsample = nn.Sequential(nn.Conv2d(embed_dim, num_feat, 3, 1, 1),
|
|
||||||
nn.LeakyReLU(inplace=True))
|
|
||||||
self.upsample = Upsample(upscale, num_feat)
|
|
||||||
self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
|
|
||||||
elif self.upsampler == 'pixelshuffledirect':
|
|
||||||
# for lightweight SR (to save parameters)
|
|
||||||
self.upsample = UpsampleOneStep(upscale, embed_dim, num_out_ch,
|
|
||||||
(patches_resolution[0], patches_resolution[1]))
|
|
||||||
elif self.upsampler == 'nearest+conv':
|
|
||||||
# for real-world SR (less artifacts)
|
|
||||||
self.conv_before_upsample = nn.Sequential(nn.Conv2d(embed_dim, num_feat, 3, 1, 1),
|
|
||||||
nn.LeakyReLU(inplace=True))
|
|
||||||
self.conv_up1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
|
|
||||||
if self.upscale == 4:
|
|
||||||
self.conv_up2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
|
|
||||||
self.conv_hr = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
|
|
||||||
self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
|
|
||||||
self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
|
|
||||||
else:
|
|
||||||
# for image denoising and JPEG compression artifact reduction
|
|
||||||
self.conv_last = nn.Conv2d(embed_dim, num_out_ch, 3, 1, 1)
|
|
||||||
|
|
||||||
self.apply(self._init_weights)
|
|
||||||
|
|
||||||
def _init_weights(self, m):
|
|
||||||
if isinstance(m, nn.Linear):
|
|
||||||
trunc_normal_(m.weight, std=.02)
|
|
||||||
if isinstance(m, nn.Linear) and m.bias is not None:
|
|
||||||
nn.init.constant_(m.bias, 0)
|
|
||||||
elif isinstance(m, nn.LayerNorm):
|
|
||||||
nn.init.constant_(m.bias, 0)
|
|
||||||
nn.init.constant_(m.weight, 1.0)
|
|
||||||
|
|
||||||
@torch.jit.ignore
|
|
||||||
def no_weight_decay(self):
|
|
||||||
return {'absolute_pos_embed'}
|
|
||||||
|
|
||||||
@torch.jit.ignore
|
|
||||||
def no_weight_decay_keywords(self):
|
|
||||||
return {'relative_position_bias_table'}
|
|
||||||
|
|
||||||
def check_image_size(self, x):
|
|
||||||
_, _, h, w = x.size()
|
|
||||||
mod_pad_h = (self.window_size - h % self.window_size) % self.window_size
|
|
||||||
mod_pad_w = (self.window_size - w % self.window_size) % self.window_size
|
|
||||||
x = F.pad(x, (0, mod_pad_w, 0, mod_pad_h), 'reflect')
|
|
||||||
return x
|
|
||||||
|
|
||||||
def forward_features(self, x):
|
|
||||||
x_size = (x.shape[2], x.shape[3])
|
|
||||||
x = self.patch_embed(x)
|
|
||||||
if self.ape:
|
|
||||||
x = x + self.absolute_pos_embed
|
|
||||||
x = self.pos_drop(x)
|
|
||||||
|
|
||||||
for layer in self.layers:
|
|
||||||
x = layer(x, x_size)
|
|
||||||
|
|
||||||
x = self.norm(x) # B L C
|
|
||||||
x = self.patch_unembed(x, x_size)
|
|
||||||
|
|
||||||
return x
|
|
||||||
|
|
||||||
def forward(self, x):
|
|
||||||
H, W = x.shape[2:]
|
|
||||||
x = self.check_image_size(x)
|
|
||||||
|
|
||||||
self.mean = self.mean.type_as(x)
|
|
||||||
x = (x - self.mean) * self.img_range
|
|
||||||
|
|
||||||
if self.upsampler == 'pixelshuffle':
|
|
||||||
# for classical SR
|
|
||||||
x = self.conv_first(x)
|
|
||||||
x = self.conv_after_body(self.forward_features(x)) + x
|
|
||||||
x = self.conv_before_upsample(x)
|
|
||||||
x = self.conv_last(self.upsample(x))
|
|
||||||
elif self.upsampler == 'pixelshuffledirect':
|
|
||||||
# for lightweight SR
|
|
||||||
x = self.conv_first(x)
|
|
||||||
x = self.conv_after_body(self.forward_features(x)) + x
|
|
||||||
x = self.upsample(x)
|
|
||||||
elif self.upsampler == 'nearest+conv':
|
|
||||||
# for real-world SR
|
|
||||||
x = self.conv_first(x)
|
|
||||||
x = self.conv_after_body(self.forward_features(x)) + x
|
|
||||||
x = self.conv_before_upsample(x)
|
|
||||||
x = self.lrelu(self.conv_up1(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest')))
|
|
||||||
if self.upscale == 4:
|
|
||||||
x = self.lrelu(self.conv_up2(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest')))
|
|
||||||
x = self.conv_last(self.lrelu(self.conv_hr(x)))
|
|
||||||
else:
|
|
||||||
# for image denoising and JPEG compression artifact reduction
|
|
||||||
x_first = self.conv_first(x)
|
|
||||||
res = self.conv_after_body(self.forward_features(x_first)) + x_first
|
|
||||||
x = x + self.conv_last(res)
|
|
||||||
|
|
||||||
x = x / self.img_range + self.mean
|
|
||||||
|
|
||||||
return x[:, :, :H*self.upscale, :W*self.upscale]
|
|
||||||
|
|
||||||
def flops(self):
|
|
||||||
flops = 0
|
|
||||||
H, W = self.patches_resolution
|
|
||||||
flops += H * W * 3 * self.embed_dim * 9
|
|
||||||
flops += self.patch_embed.flops()
|
|
||||||
for i, layer in enumerate(self.layers):
|
|
||||||
flops += layer.flops()
|
|
||||||
flops += H * W * 3 * self.embed_dim * self.embed_dim
|
|
||||||
flops += self.upsample.flops()
|
|
||||||
return flops
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
upscale = 4
|
|
||||||
window_size = 8
|
|
||||||
height = (1024 // upscale // window_size + 1) * window_size
|
|
||||||
width = (720 // upscale // window_size + 1) * window_size
|
|
||||||
model = SwinIR(upscale=2, img_size=(height, width),
|
|
||||||
window_size=window_size, img_range=1., depths=[6, 6, 6, 6],
|
|
||||||
embed_dim=60, num_heads=[6, 6, 6, 6], mlp_ratio=2, upsampler='pixelshuffledirect')
|
|
||||||
print(model)
|
|
||||||
print(height, width, model.flops() / 1e9)
|
|
||||||
|
|
||||||
x = torch.randn((1, 3, height, width))
|
|
||||||
x = model(x)
|
|
||||||
print(x.shape)
|
|
File diff suppressed because it is too large
Load Diff
995
extensions-builtin/canvas-zoom-and-pan/javascript/zoom.js
Normal file
995
extensions-builtin/canvas-zoom-and-pan/javascript/zoom.js
Normal file
@ -0,0 +1,995 @@
|
|||||||
|
onUiLoaded(async() => {
|
||||||
|
const elementIDs = {
|
||||||
|
img2imgTabs: "#mode_img2img .tab-nav",
|
||||||
|
inpaint: "#img2maskimg",
|
||||||
|
inpaintSketch: "#inpaint_sketch",
|
||||||
|
rangeGroup: "#img2img_column_size",
|
||||||
|
sketch: "#img2img_sketch"
|
||||||
|
};
|
||||||
|
const tabNameToElementId = {
|
||||||
|
"Inpaint sketch": elementIDs.inpaintSketch,
|
||||||
|
"Inpaint": elementIDs.inpaint,
|
||||||
|
"Sketch": elementIDs.sketch
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
// Helper functions
|
||||||
|
// Get active tab
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Waits for an element to be present in the DOM.
|
||||||
|
*/
|
||||||
|
const waitForElement = (id) => new Promise(resolve => {
|
||||||
|
const checkForElement = () => {
|
||||||
|
const element = document.querySelector(id);
|
||||||
|
if (element) return resolve(element);
|
||||||
|
setTimeout(checkForElement, 100);
|
||||||
|
};
|
||||||
|
checkForElement();
|
||||||
|
});
|
||||||
|
|
||||||
|
function getActiveTab(elements, all = false) {
|
||||||
|
if (!elements.img2imgTabs) return null;
|
||||||
|
const tabs = elements.img2imgTabs.querySelectorAll("button");
|
||||||
|
|
||||||
|
if (all) return tabs;
|
||||||
|
|
||||||
|
for (let tab of tabs) {
|
||||||
|
if (tab.classList.contains("selected")) {
|
||||||
|
return tab;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get tab ID
|
||||||
|
function getTabId(elements) {
|
||||||
|
const activeTab = getActiveTab(elements);
|
||||||
|
if (!activeTab) return null;
|
||||||
|
return tabNameToElementId[activeTab.innerText];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait until opts loaded
|
||||||
|
async function waitForOpts() {
|
||||||
|
for (; ;) {
|
||||||
|
if (window.opts && Object.keys(window.opts).length) {
|
||||||
|
return window.opts;
|
||||||
|
}
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 100));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Detect whether the element has a horizontal scroll bar
|
||||||
|
function hasHorizontalScrollbar(element) {
|
||||||
|
return element.scrollWidth > element.clientWidth;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Function for defining the "Ctrl", "Shift" and "Alt" keys
|
||||||
|
function isModifierKey(event, key) {
|
||||||
|
switch (key) {
|
||||||
|
case "Ctrl":
|
||||||
|
return event.ctrlKey;
|
||||||
|
case "Shift":
|
||||||
|
return event.shiftKey;
|
||||||
|
case "Alt":
|
||||||
|
return event.altKey;
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if hotkey is valid
|
||||||
|
function isValidHotkey(value) {
|
||||||
|
const specialKeys = ["Ctrl", "Alt", "Shift", "Disable"];
|
||||||
|
return (
|
||||||
|
(typeof value === "string" &&
|
||||||
|
value.length === 1 &&
|
||||||
|
/[a-z]/i.test(value)) ||
|
||||||
|
specialKeys.includes(value)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normalize hotkey
|
||||||
|
function normalizeHotkey(hotkey) {
|
||||||
|
return hotkey.length === 1 ? "Key" + hotkey.toUpperCase() : hotkey;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Format hotkey for display
|
||||||
|
function formatHotkeyForDisplay(hotkey) {
|
||||||
|
return hotkey.startsWith("Key") ? hotkey.slice(3) : hotkey;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create hotkey configuration with the provided options
|
||||||
|
function createHotkeyConfig(defaultHotkeysConfig, hotkeysConfigOpts) {
|
||||||
|
const result = {}; // Resulting hotkey configuration
|
||||||
|
const usedKeys = new Set(); // Set of used hotkeys
|
||||||
|
|
||||||
|
// Iterate through defaultHotkeysConfig keys
|
||||||
|
for (const key in defaultHotkeysConfig) {
|
||||||
|
const userValue = hotkeysConfigOpts[key]; // User-provided hotkey value
|
||||||
|
const defaultValue = defaultHotkeysConfig[key]; // Default hotkey value
|
||||||
|
|
||||||
|
// Apply appropriate value for undefined, boolean, or object userValue
|
||||||
|
if (
|
||||||
|
userValue === undefined ||
|
||||||
|
typeof userValue === "boolean" ||
|
||||||
|
typeof userValue === "object" ||
|
||||||
|
userValue === "disable"
|
||||||
|
) {
|
||||||
|
result[key] =
|
||||||
|
userValue === undefined ? defaultValue : userValue;
|
||||||
|
} else if (isValidHotkey(userValue)) {
|
||||||
|
const normalizedUserValue = normalizeHotkey(userValue);
|
||||||
|
|
||||||
|
// Check for conflicting hotkeys
|
||||||
|
if (!usedKeys.has(normalizedUserValue)) {
|
||||||
|
usedKeys.add(normalizedUserValue);
|
||||||
|
result[key] = normalizedUserValue;
|
||||||
|
} else {
|
||||||
|
console.error(
|
||||||
|
`Hotkey: ${formatHotkeyForDisplay(
|
||||||
|
userValue
|
||||||
|
)} for ${key} is repeated and conflicts with another hotkey. The default hotkey is used: ${formatHotkeyForDisplay(
|
||||||
|
defaultValue
|
||||||
|
)}`
|
||||||
|
);
|
||||||
|
result[key] = defaultValue;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.error(
|
||||||
|
`Hotkey: ${formatHotkeyForDisplay(
|
||||||
|
userValue
|
||||||
|
)} for ${key} is not valid. The default hotkey is used: ${formatHotkeyForDisplay(
|
||||||
|
defaultValue
|
||||||
|
)}`
|
||||||
|
);
|
||||||
|
result[key] = defaultValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Disables functions in the config object based on the provided list of function names
|
||||||
|
function disableFunctions(config, disabledFunctions) {
|
||||||
|
// Bind the hasOwnProperty method to the functionMap object to avoid errors
|
||||||
|
const hasOwnProperty =
|
||||||
|
Object.prototype.hasOwnProperty.bind(functionMap);
|
||||||
|
|
||||||
|
// Loop through the disabledFunctions array and disable the corresponding functions in the config object
|
||||||
|
disabledFunctions.forEach(funcName => {
|
||||||
|
if (hasOwnProperty(funcName)) {
|
||||||
|
const key = functionMap[funcName];
|
||||||
|
config[key] = "disable";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Return the updated config object
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The restoreImgRedMask function displays a red mask around an image to indicate the aspect ratio.
|
||||||
|
* If the image display property is set to 'none', the mask breaks. To fix this, the function
|
||||||
|
* temporarily sets the display property to 'block' and then hides the mask again after 300 milliseconds
|
||||||
|
* to avoid breaking the canvas. Additionally, the function adjusts the mask to work correctly on
|
||||||
|
* very long images.
|
||||||
|
*/
|
||||||
|
function restoreImgRedMask(elements) {
|
||||||
|
const mainTabId = getTabId(elements);
|
||||||
|
|
||||||
|
if (!mainTabId) return;
|
||||||
|
|
||||||
|
const mainTab = gradioApp().querySelector(mainTabId);
|
||||||
|
const img = mainTab.querySelector("img");
|
||||||
|
const imageARPreview = gradioApp().querySelector("#imageARPreview");
|
||||||
|
|
||||||
|
if (!img || !imageARPreview) return;
|
||||||
|
|
||||||
|
imageARPreview.style.transform = "";
|
||||||
|
if (parseFloat(mainTab.style.width) > 865) {
|
||||||
|
const transformString = mainTab.style.transform;
|
||||||
|
const scaleMatch = transformString.match(
|
||||||
|
/scale\(([-+]?[0-9]*\.?[0-9]+)\)/
|
||||||
|
);
|
||||||
|
let zoom = 1; // default zoom
|
||||||
|
|
||||||
|
if (scaleMatch && scaleMatch[1]) {
|
||||||
|
zoom = Number(scaleMatch[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
imageARPreview.style.transformOrigin = "0 0";
|
||||||
|
imageARPreview.style.transform = `scale(${zoom})`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (img.style.display !== "none") return;
|
||||||
|
|
||||||
|
img.style.display = "block";
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
img.style.display = "none";
|
||||||
|
}, 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
const hotkeysConfigOpts = await waitForOpts();
|
||||||
|
|
||||||
|
// Default config
|
||||||
|
const defaultHotkeysConfig = {
|
||||||
|
canvas_hotkey_zoom: "Alt",
|
||||||
|
canvas_hotkey_adjust: "Ctrl",
|
||||||
|
canvas_hotkey_reset: "KeyR",
|
||||||
|
canvas_hotkey_fullscreen: "KeyS",
|
||||||
|
canvas_hotkey_move: "KeyF",
|
||||||
|
canvas_hotkey_overlap: "KeyO",
|
||||||
|
canvas_hotkey_shrink_brush: "KeyQ",
|
||||||
|
canvas_hotkey_grow_brush: "KeyW",
|
||||||
|
canvas_disabled_functions: [],
|
||||||
|
canvas_show_tooltip: true,
|
||||||
|
canvas_auto_expand: true,
|
||||||
|
canvas_blur_prompt: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
const functionMap = {
|
||||||
|
"Zoom": "canvas_hotkey_zoom",
|
||||||
|
"Adjust brush size": "canvas_hotkey_adjust",
|
||||||
|
"Hotkey shrink brush": "canvas_hotkey_shrink_brush",
|
||||||
|
"Hotkey enlarge brush": "canvas_hotkey_grow_brush",
|
||||||
|
"Moving canvas": "canvas_hotkey_move",
|
||||||
|
"Fullscreen": "canvas_hotkey_fullscreen",
|
||||||
|
"Reset Zoom": "canvas_hotkey_reset",
|
||||||
|
"Overlap": "canvas_hotkey_overlap"
|
||||||
|
};
|
||||||
|
|
||||||
|
// Loading the configuration from opts
|
||||||
|
const preHotkeysConfig = createHotkeyConfig(
|
||||||
|
defaultHotkeysConfig,
|
||||||
|
hotkeysConfigOpts
|
||||||
|
);
|
||||||
|
|
||||||
|
// Disable functions that are not needed by the user
|
||||||
|
const hotkeysConfig = disableFunctions(
|
||||||
|
preHotkeysConfig,
|
||||||
|
preHotkeysConfig.canvas_disabled_functions
|
||||||
|
);
|
||||||
|
|
||||||
|
let isMoving = false;
|
||||||
|
let mouseX, mouseY;
|
||||||
|
let activeElement;
|
||||||
|
let interactedWithAltKey = false;
|
||||||
|
|
||||||
|
const elements = Object.fromEntries(
|
||||||
|
Object.keys(elementIDs).map(id => [
|
||||||
|
id,
|
||||||
|
gradioApp().querySelector(elementIDs[id])
|
||||||
|
])
|
||||||
|
);
|
||||||
|
const elemData = {};
|
||||||
|
|
||||||
|
// Apply functionality to the range inputs. Restore redmask and correct for long images.
|
||||||
|
const rangeInputs = elements.rangeGroup ?
|
||||||
|
Array.from(elements.rangeGroup.querySelectorAll("input")) :
|
||||||
|
[
|
||||||
|
gradioApp().querySelector("#img2img_width input[type='range']"),
|
||||||
|
gradioApp().querySelector("#img2img_height input[type='range']")
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const input of rangeInputs) {
|
||||||
|
input?.addEventListener("input", () => restoreImgRedMask(elements));
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyZoomAndPan(elemId, isExtension = true) {
|
||||||
|
const targetElement = gradioApp().querySelector(elemId);
|
||||||
|
|
||||||
|
if (!targetElement) {
|
||||||
|
console.log("Element not found", elemId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
targetElement.style.transformOrigin = "0 0";
|
||||||
|
|
||||||
|
elemData[elemId] = {
|
||||||
|
zoom: 1,
|
||||||
|
panX: 0,
|
||||||
|
panY: 0
|
||||||
|
};
|
||||||
|
let fullScreenMode = false;
|
||||||
|
|
||||||
|
// Create tooltip
|
||||||
|
function createTooltip() {
|
||||||
|
const toolTipElement =
|
||||||
|
targetElement.querySelector(".image-container");
|
||||||
|
const tooltip = document.createElement("div");
|
||||||
|
tooltip.className = "canvas-tooltip";
|
||||||
|
|
||||||
|
// Creating an item of information
|
||||||
|
const info = document.createElement("i");
|
||||||
|
info.className = "canvas-tooltip-info";
|
||||||
|
info.textContent = "";
|
||||||
|
|
||||||
|
// Create a container for the contents of the tooltip
|
||||||
|
const tooltipContent = document.createElement("div");
|
||||||
|
tooltipContent.className = "canvas-tooltip-content";
|
||||||
|
|
||||||
|
// Define an array with hotkey information and their actions
|
||||||
|
const hotkeysInfo = [
|
||||||
|
{
|
||||||
|
configKey: "canvas_hotkey_zoom",
|
||||||
|
action: "Zoom canvas",
|
||||||
|
keySuffix: " + wheel"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
configKey: "canvas_hotkey_adjust",
|
||||||
|
action: "Adjust brush size",
|
||||||
|
keySuffix: " + wheel"
|
||||||
|
},
|
||||||
|
{configKey: "canvas_hotkey_reset", action: "Reset zoom"},
|
||||||
|
{
|
||||||
|
configKey: "canvas_hotkey_fullscreen",
|
||||||
|
action: "Fullscreen mode"
|
||||||
|
},
|
||||||
|
{configKey: "canvas_hotkey_move", action: "Move canvas"},
|
||||||
|
{configKey: "canvas_hotkey_overlap", action: "Overlap"}
|
||||||
|
];
|
||||||
|
|
||||||
|
// Create hotkeys array with disabled property based on the config values
|
||||||
|
const hotkeys = hotkeysInfo.map(info => {
|
||||||
|
const configValue = hotkeysConfig[info.configKey];
|
||||||
|
const key = info.keySuffix ?
|
||||||
|
`${configValue}${info.keySuffix}` :
|
||||||
|
configValue.charAt(configValue.length - 1);
|
||||||
|
return {
|
||||||
|
key,
|
||||||
|
action: info.action,
|
||||||
|
disabled: configValue === "disable"
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const hotkey of hotkeys) {
|
||||||
|
if (hotkey.disabled) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const p = document.createElement("p");
|
||||||
|
p.innerHTML = `<b>${hotkey.key}</b> - ${hotkey.action}`;
|
||||||
|
tooltipContent.appendChild(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add information and content elements to the tooltip element
|
||||||
|
tooltip.appendChild(info);
|
||||||
|
tooltip.appendChild(tooltipContent);
|
||||||
|
|
||||||
|
// Add a hint element to the target element
|
||||||
|
toolTipElement.appendChild(tooltip);
|
||||||
|
}
|
||||||
|
|
||||||
|
//Show tool tip if setting enable
|
||||||
|
if (hotkeysConfig.canvas_show_tooltip) {
|
||||||
|
createTooltip();
|
||||||
|
}
|
||||||
|
|
||||||
|
// In the course of research, it was found that the tag img is very harmful when zooming and creates white canvases. This hack allows you to almost never think about this problem, it has no effect on webui.
|
||||||
|
function fixCanvas() {
|
||||||
|
const activeTab = getActiveTab(elements)?.textContent.trim();
|
||||||
|
|
||||||
|
if (activeTab && activeTab !== "img2img") {
|
||||||
|
const img = targetElement.querySelector(`${elemId} img`);
|
||||||
|
|
||||||
|
if (img && img.style.display !== "none") {
|
||||||
|
img.style.display = "none";
|
||||||
|
img.style.visibility = "hidden";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset the zoom level and pan position of the target element to their initial values
|
||||||
|
function resetZoom() {
|
||||||
|
elemData[elemId] = {
|
||||||
|
zoomLevel: 1,
|
||||||
|
panX: 0,
|
||||||
|
panY: 0
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isExtension) {
|
||||||
|
targetElement.style.overflow = "hidden";
|
||||||
|
}
|
||||||
|
|
||||||
|
targetElement.isZoomed = false;
|
||||||
|
|
||||||
|
fixCanvas();
|
||||||
|
targetElement.style.transform = `scale(${elemData[elemId].zoomLevel}) translate(${elemData[elemId].panX}px, ${elemData[elemId].panY}px)`;
|
||||||
|
|
||||||
|
const canvas = gradioApp().querySelector(
|
||||||
|
`${elemId} canvas[key="interface"]`
|
||||||
|
);
|
||||||
|
|
||||||
|
toggleOverlap("off");
|
||||||
|
fullScreenMode = false;
|
||||||
|
|
||||||
|
const closeBtn = targetElement.querySelector("button[aria-label='Remove Image']");
|
||||||
|
if (closeBtn) {
|
||||||
|
closeBtn.addEventListener("click", resetZoom);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (canvas && isExtension) {
|
||||||
|
const parentElement = targetElement.closest('[id^="component-"]');
|
||||||
|
if (
|
||||||
|
canvas &&
|
||||||
|
parseFloat(canvas.style.width) > parentElement.offsetWidth &&
|
||||||
|
parseFloat(targetElement.style.width) > parentElement.offsetWidth
|
||||||
|
) {
|
||||||
|
fitToElement();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
canvas &&
|
||||||
|
!isExtension &&
|
||||||
|
parseFloat(canvas.style.width) > 865 &&
|
||||||
|
parseFloat(targetElement.style.width) > 865
|
||||||
|
) {
|
||||||
|
fitToElement();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
targetElement.style.width = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Toggle the zIndex of the target element between two values, allowing it to overlap or be overlapped by other elements
|
||||||
|
function toggleOverlap(forced = "") {
|
||||||
|
const zIndex1 = "0";
|
||||||
|
const zIndex2 = "998";
|
||||||
|
|
||||||
|
targetElement.style.zIndex =
|
||||||
|
targetElement.style.zIndex !== zIndex2 ? zIndex2 : zIndex1;
|
||||||
|
|
||||||
|
if (forced === "off") {
|
||||||
|
targetElement.style.zIndex = zIndex1;
|
||||||
|
} else if (forced === "on") {
|
||||||
|
targetElement.style.zIndex = zIndex2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Adjust the brush size based on the deltaY value from a mouse wheel event
|
||||||
|
function adjustBrushSize(
|
||||||
|
elemId,
|
||||||
|
deltaY,
|
||||||
|
withoutValue = false,
|
||||||
|
percentage = 5
|
||||||
|
) {
|
||||||
|
const input =
|
||||||
|
gradioApp().querySelector(
|
||||||
|
`${elemId} input[aria-label='Brush radius']`
|
||||||
|
) ||
|
||||||
|
gradioApp().querySelector(
|
||||||
|
`${elemId} button[aria-label="Use brush"]`
|
||||||
|
);
|
||||||
|
|
||||||
|
if (input) {
|
||||||
|
input.click();
|
||||||
|
if (!withoutValue) {
|
||||||
|
const maxValue =
|
||||||
|
parseFloat(input.getAttribute("max")) || 100;
|
||||||
|
const changeAmount = maxValue * (percentage / 100);
|
||||||
|
const newValue =
|
||||||
|
parseFloat(input.value) +
|
||||||
|
(deltaY > 0 ? -changeAmount : changeAmount);
|
||||||
|
input.value = Math.min(Math.max(newValue, 0), maxValue);
|
||||||
|
input.dispatchEvent(new Event("change"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset zoom when uploading a new image
|
||||||
|
const fileInput = gradioApp().querySelector(
|
||||||
|
`${elemId} input[type="file"][accept="image/*"].svelte-116rqfv`
|
||||||
|
);
|
||||||
|
fileInput.addEventListener("click", resetZoom);
|
||||||
|
|
||||||
|
// Update the zoom level and pan position of the target element based on the values of the zoomLevel, panX and panY variables
|
||||||
|
function updateZoom(newZoomLevel, mouseX, mouseY) {
|
||||||
|
newZoomLevel = Math.max(0.1, Math.min(newZoomLevel, 15));
|
||||||
|
|
||||||
|
elemData[elemId].panX +=
|
||||||
|
mouseX - (mouseX * newZoomLevel) / elemData[elemId].zoomLevel;
|
||||||
|
elemData[elemId].panY +=
|
||||||
|
mouseY - (mouseY * newZoomLevel) / elemData[elemId].zoomLevel;
|
||||||
|
|
||||||
|
targetElement.style.transformOrigin = "0 0";
|
||||||
|
targetElement.style.transform = `translate(${elemData[elemId].panX}px, ${elemData[elemId].panY}px) scale(${newZoomLevel})`;
|
||||||
|
|
||||||
|
toggleOverlap("on");
|
||||||
|
if (isExtension) {
|
||||||
|
targetElement.style.overflow = "visible";
|
||||||
|
}
|
||||||
|
|
||||||
|
return newZoomLevel;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Change the zoom level based on user interaction
|
||||||
|
function changeZoomLevel(operation, e) {
|
||||||
|
if (isModifierKey(e, hotkeysConfig.canvas_hotkey_zoom)) {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
if (hotkeysConfig.canvas_hotkey_zoom === "Alt") {
|
||||||
|
interactedWithAltKey = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
let zoomPosX, zoomPosY;
|
||||||
|
let delta = 0.2;
|
||||||
|
if (elemData[elemId].zoomLevel > 7) {
|
||||||
|
delta = 0.9;
|
||||||
|
} else if (elemData[elemId].zoomLevel > 2) {
|
||||||
|
delta = 0.6;
|
||||||
|
}
|
||||||
|
|
||||||
|
zoomPosX = e.clientX;
|
||||||
|
zoomPosY = e.clientY;
|
||||||
|
|
||||||
|
fullScreenMode = false;
|
||||||
|
elemData[elemId].zoomLevel = updateZoom(
|
||||||
|
elemData[elemId].zoomLevel +
|
||||||
|
(operation === "+" ? delta : -delta),
|
||||||
|
zoomPosX - targetElement.getBoundingClientRect().left,
|
||||||
|
zoomPosY - targetElement.getBoundingClientRect().top
|
||||||
|
);
|
||||||
|
|
||||||
|
targetElement.isZoomed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function fits the target element to the screen by calculating
|
||||||
|
* the required scale and offsets. It also updates the global variables
|
||||||
|
* zoomLevel, panX, and panY to reflect the new state.
|
||||||
|
*/
|
||||||
|
|
||||||
|
function fitToElement() {
|
||||||
|
//Reset Zoom
|
||||||
|
targetElement.style.transform = `translate(${0}px, ${0}px) scale(${1})`;
|
||||||
|
|
||||||
|
let parentElement;
|
||||||
|
|
||||||
|
if (isExtension) {
|
||||||
|
parentElement = targetElement.closest('[id^="component-"]');
|
||||||
|
} else {
|
||||||
|
parentElement = targetElement.parentElement;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Get element and screen dimensions
|
||||||
|
const elementWidth = targetElement.offsetWidth;
|
||||||
|
const elementHeight = targetElement.offsetHeight;
|
||||||
|
|
||||||
|
const screenWidth = parentElement.clientWidth;
|
||||||
|
const screenHeight = parentElement.clientHeight;
|
||||||
|
|
||||||
|
// Get element's coordinates relative to the parent element
|
||||||
|
const elementRect = targetElement.getBoundingClientRect();
|
||||||
|
const parentRect = parentElement.getBoundingClientRect();
|
||||||
|
const elementX = elementRect.x - parentRect.x;
|
||||||
|
|
||||||
|
// Calculate scale and offsets
|
||||||
|
const scaleX = screenWidth / elementWidth;
|
||||||
|
const scaleY = screenHeight / elementHeight;
|
||||||
|
const scale = Math.min(scaleX, scaleY);
|
||||||
|
|
||||||
|
const transformOrigin =
|
||||||
|
window.getComputedStyle(targetElement).transformOrigin;
|
||||||
|
const [originX, originY] = transformOrigin.split(" ");
|
||||||
|
const originXValue = parseFloat(originX);
|
||||||
|
const originYValue = parseFloat(originY);
|
||||||
|
|
||||||
|
const offsetX =
|
||||||
|
(screenWidth - elementWidth * scale) / 2 -
|
||||||
|
originXValue * (1 - scale);
|
||||||
|
const offsetY =
|
||||||
|
(screenHeight - elementHeight * scale) / 2.5 -
|
||||||
|
originYValue * (1 - scale);
|
||||||
|
|
||||||
|
// Apply scale and offsets to the element
|
||||||
|
targetElement.style.transform = `translate(${offsetX}px, ${offsetY}px) scale(${scale})`;
|
||||||
|
|
||||||
|
// Update global variables
|
||||||
|
elemData[elemId].zoomLevel = scale;
|
||||||
|
elemData[elemId].panX = offsetX;
|
||||||
|
elemData[elemId].panY = offsetY;
|
||||||
|
|
||||||
|
fullScreenMode = false;
|
||||||
|
toggleOverlap("off");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function fits the target element to the screen by calculating
|
||||||
|
* the required scale and offsets. It also updates the global variables
|
||||||
|
* zoomLevel, panX, and panY to reflect the new state.
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Fullscreen mode
|
||||||
|
function fitToScreen() {
|
||||||
|
const canvas = gradioApp().querySelector(
|
||||||
|
`${elemId} canvas[key="interface"]`
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!canvas) return;
|
||||||
|
|
||||||
|
if (canvas.offsetWidth > 862 || isExtension) {
|
||||||
|
targetElement.style.width = (canvas.offsetWidth + 2) + "px";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isExtension) {
|
||||||
|
targetElement.style.overflow = "visible";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fullScreenMode) {
|
||||||
|
resetZoom();
|
||||||
|
fullScreenMode = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
//Reset Zoom
|
||||||
|
targetElement.style.transform = `translate(${0}px, ${0}px) scale(${1})`;
|
||||||
|
|
||||||
|
// Get scrollbar width to right-align the image
|
||||||
|
const scrollbarWidth =
|
||||||
|
window.innerWidth - document.documentElement.clientWidth;
|
||||||
|
|
||||||
|
// Get element and screen dimensions
|
||||||
|
const elementWidth = targetElement.offsetWidth;
|
||||||
|
const elementHeight = targetElement.offsetHeight;
|
||||||
|
const screenWidth = window.innerWidth - scrollbarWidth;
|
||||||
|
const screenHeight = window.innerHeight;
|
||||||
|
|
||||||
|
// Get element's coordinates relative to the page
|
||||||
|
const elementRect = targetElement.getBoundingClientRect();
|
||||||
|
const elementY = elementRect.y;
|
||||||
|
const elementX = elementRect.x;
|
||||||
|
|
||||||
|
// Calculate scale and offsets
|
||||||
|
const scaleX = screenWidth / elementWidth;
|
||||||
|
const scaleY = screenHeight / elementHeight;
|
||||||
|
const scale = Math.min(scaleX, scaleY);
|
||||||
|
|
||||||
|
// Get the current transformOrigin
|
||||||
|
const computedStyle = window.getComputedStyle(targetElement);
|
||||||
|
const transformOrigin = computedStyle.transformOrigin;
|
||||||
|
const [originX, originY] = transformOrigin.split(" ");
|
||||||
|
const originXValue = parseFloat(originX);
|
||||||
|
const originYValue = parseFloat(originY);
|
||||||
|
|
||||||
|
// Calculate offsets with respect to the transformOrigin
|
||||||
|
const offsetX =
|
||||||
|
(screenWidth - elementWidth * scale) / 2 -
|
||||||
|
elementX -
|
||||||
|
originXValue * (1 - scale);
|
||||||
|
const offsetY =
|
||||||
|
(screenHeight - elementHeight * scale) / 2 -
|
||||||
|
elementY -
|
||||||
|
originYValue * (1 - scale);
|
||||||
|
|
||||||
|
// Apply scale and offsets to the element
|
||||||
|
targetElement.style.transform = `translate(${offsetX}px, ${offsetY}px) scale(${scale})`;
|
||||||
|
|
||||||
|
// Update global variables
|
||||||
|
elemData[elemId].zoomLevel = scale;
|
||||||
|
elemData[elemId].panX = offsetX;
|
||||||
|
elemData[elemId].panY = offsetY;
|
||||||
|
|
||||||
|
fullScreenMode = true;
|
||||||
|
toggleOverlap("on");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle keydown events
|
||||||
|
function handleKeyDown(event) {
|
||||||
|
// Disable key locks to make pasting from the buffer work correctly
|
||||||
|
if ((event.ctrlKey && event.code === 'KeyV') || (event.ctrlKey && event.code === 'KeyC') || event.code === "F5") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// before activating shortcut, ensure user is not actively typing in an input field
|
||||||
|
if (!hotkeysConfig.canvas_blur_prompt) {
|
||||||
|
if (event.target.nodeName === 'TEXTAREA' || event.target.nodeName === 'INPUT') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const hotkeyActions = {
|
||||||
|
[hotkeysConfig.canvas_hotkey_reset]: resetZoom,
|
||||||
|
[hotkeysConfig.canvas_hotkey_overlap]: toggleOverlap,
|
||||||
|
[hotkeysConfig.canvas_hotkey_fullscreen]: fitToScreen,
|
||||||
|
[hotkeysConfig.canvas_hotkey_shrink_brush]: () => adjustBrushSize(elemId, 10),
|
||||||
|
[hotkeysConfig.canvas_hotkey_grow_brush]: () => adjustBrushSize(elemId, -10)
|
||||||
|
};
|
||||||
|
|
||||||
|
const action = hotkeyActions[event.code];
|
||||||
|
if (action) {
|
||||||
|
event.preventDefault();
|
||||||
|
action(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
isModifierKey(event, hotkeysConfig.canvas_hotkey_zoom) ||
|
||||||
|
isModifierKey(event, hotkeysConfig.canvas_hotkey_adjust)
|
||||||
|
) {
|
||||||
|
event.preventDefault();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get Mouse position
|
||||||
|
function getMousePosition(e) {
|
||||||
|
mouseX = e.offsetX;
|
||||||
|
mouseY = e.offsetY;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Simulation of the function to put a long image into the screen.
|
||||||
|
// We detect if an image has a scroll bar or not, make a fullscreen to reveal the image, then reduce it to fit into the element.
|
||||||
|
// We hide the image and show it to the user when it is ready.
|
||||||
|
|
||||||
|
targetElement.isExpanded = false;
|
||||||
|
function autoExpand() {
|
||||||
|
const canvas = document.querySelector(`${elemId} canvas[key="interface"]`);
|
||||||
|
if (canvas) {
|
||||||
|
if (hasHorizontalScrollbar(targetElement) && targetElement.isExpanded === false) {
|
||||||
|
targetElement.style.visibility = "hidden";
|
||||||
|
setTimeout(() => {
|
||||||
|
fitToScreen();
|
||||||
|
resetZoom();
|
||||||
|
targetElement.style.visibility = "visible";
|
||||||
|
targetElement.isExpanded = true;
|
||||||
|
}, 10);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
targetElement.addEventListener("mousemove", getMousePosition);
|
||||||
|
|
||||||
|
//observers
|
||||||
|
// Creating an observer with a callback function to handle DOM changes
|
||||||
|
const observer = new MutationObserver((mutationsList, observer) => {
|
||||||
|
for (let mutation of mutationsList) {
|
||||||
|
// If the style attribute of the canvas has changed, by observation it happens only when the picture changes
|
||||||
|
if (mutation.type === 'attributes' && mutation.attributeName === 'style' &&
|
||||||
|
mutation.target.tagName.toLowerCase() === 'canvas') {
|
||||||
|
targetElement.isExpanded = false;
|
||||||
|
setTimeout(resetZoom, 10);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Apply auto expand if enabled
|
||||||
|
if (hotkeysConfig.canvas_auto_expand) {
|
||||||
|
targetElement.addEventListener("mousemove", autoExpand);
|
||||||
|
// Set up an observer to track attribute changes
|
||||||
|
observer.observe(targetElement, {attributes: true, childList: true, subtree: true});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle events only inside the targetElement
|
||||||
|
let isKeyDownHandlerAttached = false;
|
||||||
|
|
||||||
|
function handleMouseMove() {
|
||||||
|
if (!isKeyDownHandlerAttached) {
|
||||||
|
document.addEventListener("keydown", handleKeyDown);
|
||||||
|
isKeyDownHandlerAttached = true;
|
||||||
|
|
||||||
|
activeElement = elemId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleMouseLeave() {
|
||||||
|
if (isKeyDownHandlerAttached) {
|
||||||
|
document.removeEventListener("keydown", handleKeyDown);
|
||||||
|
isKeyDownHandlerAttached = false;
|
||||||
|
|
||||||
|
activeElement = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add mouse event handlers
|
||||||
|
targetElement.addEventListener("mousemove", handleMouseMove);
|
||||||
|
targetElement.addEventListener("mouseleave", handleMouseLeave);
|
||||||
|
|
||||||
|
// Reset zoom when click on another tab
|
||||||
|
if (elements.img2imgTabs) {
|
||||||
|
elements.img2imgTabs.addEventListener("click", resetZoom);
|
||||||
|
elements.img2imgTabs.addEventListener("click", () => {
|
||||||
|
// targetElement.style.width = "";
|
||||||
|
if (parseInt(targetElement.style.width) > 865) {
|
||||||
|
setTimeout(fitToElement, 0);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
targetElement.addEventListener("wheel", e => {
|
||||||
|
// change zoom level
|
||||||
|
const operation = (e.deltaY || -e.wheelDelta) > 0 ? "-" : "+";
|
||||||
|
changeZoomLevel(operation, e);
|
||||||
|
|
||||||
|
// Handle brush size adjustment with ctrl key pressed
|
||||||
|
if (isModifierKey(e, hotkeysConfig.canvas_hotkey_adjust)) {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
if (hotkeysConfig.canvas_hotkey_adjust === "Alt") {
|
||||||
|
interactedWithAltKey = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Increase or decrease brush size based on scroll direction
|
||||||
|
adjustBrushSize(elemId, e.deltaY);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Handle the move event for pan functionality. Updates the panX and panY variables and applies the new transform to the target element.
|
||||||
|
function handleMoveKeyDown(e) {
|
||||||
|
|
||||||
|
// Disable key locks to make pasting from the buffer work correctly
|
||||||
|
if ((e.ctrlKey && e.code === 'KeyV') || (e.ctrlKey && event.code === 'KeyC') || e.code === "F5") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// before activating shortcut, ensure user is not actively typing in an input field
|
||||||
|
if (!hotkeysConfig.canvas_blur_prompt) {
|
||||||
|
if (e.target.nodeName === 'TEXTAREA' || e.target.nodeName === 'INPUT') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if (e.code === hotkeysConfig.canvas_hotkey_move) {
|
||||||
|
if (!e.ctrlKey && !e.metaKey && isKeyDownHandlerAttached) {
|
||||||
|
e.preventDefault();
|
||||||
|
document.activeElement.blur();
|
||||||
|
isMoving = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleMoveKeyUp(e) {
|
||||||
|
if (e.code === hotkeysConfig.canvas_hotkey_move) {
|
||||||
|
isMoving = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener("keydown", handleMoveKeyDown);
|
||||||
|
document.addEventListener("keyup", handleMoveKeyUp);
|
||||||
|
|
||||||
|
|
||||||
|
// Prevent firefox from opening main menu when alt is used as a hotkey for zoom or brush size
|
||||||
|
function handleAltKeyUp(e) {
|
||||||
|
if (e.key !== "Alt" || !interactedWithAltKey) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
e.preventDefault();
|
||||||
|
interactedWithAltKey = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener("keyup", handleAltKeyUp);
|
||||||
|
|
||||||
|
|
||||||
|
// Detect zoom level and update the pan speed.
|
||||||
|
function updatePanPosition(movementX, movementY) {
|
||||||
|
let panSpeed = 2;
|
||||||
|
|
||||||
|
if (elemData[elemId].zoomLevel > 8) {
|
||||||
|
panSpeed = 3.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
elemData[elemId].panX += movementX * panSpeed;
|
||||||
|
elemData[elemId].panY += movementY * panSpeed;
|
||||||
|
|
||||||
|
// Delayed redraw of an element
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
targetElement.style.transform = `translate(${elemData[elemId].panX}px, ${elemData[elemId].panY}px) scale(${elemData[elemId].zoomLevel})`;
|
||||||
|
toggleOverlap("on");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleMoveByKey(e) {
|
||||||
|
if (isMoving && elemId === activeElement) {
|
||||||
|
updatePanPosition(e.movementX, e.movementY);
|
||||||
|
targetElement.style.pointerEvents = "none";
|
||||||
|
|
||||||
|
if (isExtension) {
|
||||||
|
targetElement.style.overflow = "visible";
|
||||||
|
}
|
||||||
|
|
||||||
|
} else {
|
||||||
|
targetElement.style.pointerEvents = "auto";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prevents sticking to the mouse
|
||||||
|
window.onblur = function() {
|
||||||
|
isMoving = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Checks for extension
|
||||||
|
function checkForOutBox() {
|
||||||
|
const parentElement = targetElement.closest('[id^="component-"]');
|
||||||
|
if (parentElement.offsetWidth < targetElement.offsetWidth && !targetElement.isExpanded) {
|
||||||
|
resetZoom();
|
||||||
|
targetElement.isExpanded = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (parentElement.offsetWidth < targetElement.offsetWidth && elemData[elemId].zoomLevel == 1) {
|
||||||
|
resetZoom();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (parentElement.offsetWidth < targetElement.offsetWidth && targetElement.offsetWidth * elemData[elemId].zoomLevel > parentElement.offsetWidth && elemData[elemId].zoomLevel < 1 && !targetElement.isZoomed) {
|
||||||
|
resetZoom();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isExtension) {
|
||||||
|
targetElement.addEventListener("mousemove", checkForOutBox);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
window.addEventListener('resize', (e) => {
|
||||||
|
resetZoom();
|
||||||
|
|
||||||
|
if (isExtension) {
|
||||||
|
targetElement.isExpanded = false;
|
||||||
|
targetElement.isZoomed = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
gradioApp().addEventListener("mousemove", handleMoveByKey);
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
applyZoomAndPan(elementIDs.sketch, false);
|
||||||
|
applyZoomAndPan(elementIDs.inpaint, false);
|
||||||
|
applyZoomAndPan(elementIDs.inpaintSketch, false);
|
||||||
|
|
||||||
|
// Make the function global so that other extensions can take advantage of this solution
|
||||||
|
const applyZoomAndPanIntegration = async(id, elementIDs) => {
|
||||||
|
const mainEl = document.querySelector(id);
|
||||||
|
if (id.toLocaleLowerCase() === "none") {
|
||||||
|
for (const elementID of elementIDs) {
|
||||||
|
const el = await waitForElement(elementID);
|
||||||
|
if (!el) break;
|
||||||
|
applyZoomAndPan(elementID);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!mainEl) return;
|
||||||
|
mainEl.addEventListener("click", async() => {
|
||||||
|
for (const elementID of elementIDs) {
|
||||||
|
const el = await waitForElement(elementID);
|
||||||
|
if (!el) break;
|
||||||
|
applyZoomAndPan(elementID);
|
||||||
|
}
|
||||||
|
}, {once: true});
|
||||||
|
};
|
||||||
|
|
||||||
|
window.applyZoomAndPan = applyZoomAndPan; // Only 1 elements, argument elementID, for example applyZoomAndPan("#txt2img_controlnet_ControlNet_input_image")
|
||||||
|
|
||||||
|
window.applyZoomAndPanIntegration = applyZoomAndPanIntegration; // for any extension
|
||||||
|
|
||||||
|
/*
|
||||||
|
The function `applyZoomAndPanIntegration` takes two arguments:
|
||||||
|
|
||||||
|
1. `id`: A string identifier for the element to which zoom and pan functionality will be applied on click.
|
||||||
|
If the `id` value is "none", the functionality will be applied to all elements specified in the second argument without a click event.
|
||||||
|
|
||||||
|
2. `elementIDs`: An array of string identifiers for elements. Zoom and pan functionality will be applied to each of these elements on click of the element specified by the first argument.
|
||||||
|
If "none" is specified in the first argument, the functionality will be applied to each of these elements without a click event.
|
||||||
|
|
||||||
|
Example usage:
|
||||||
|
applyZoomAndPanIntegration("#txt2img_controlnet", ["#txt2img_controlnet_ControlNet_input_image"]);
|
||||||
|
In this example, zoom and pan functionality will be applied to the element with the identifier "txt2img_controlnet_ControlNet_input_image" upon clicking the element with the identifier "txt2img_controlnet".
|
||||||
|
*/
|
||||||
|
|
||||||
|
// More examples
|
||||||
|
// Add integration with ControlNet txt2img One TAB
|
||||||
|
// applyZoomAndPanIntegration("#txt2img_controlnet", ["#txt2img_controlnet_ControlNet_input_image"]);
|
||||||
|
|
||||||
|
// Add integration with ControlNet txt2img Tabs
|
||||||
|
// applyZoomAndPanIntegration("#txt2img_controlnet",Array.from({ length: 10 }, (_, i) => `#txt2img_controlnet_ControlNet-${i}_input_image`));
|
||||||
|
|
||||||
|
// Add integration with Inpaint Anything
|
||||||
|
// applyZoomAndPanIntegration("None", ["#ia_sam_image", "#ia_sel_mask"]);
|
||||||
|
});
|
@ -0,0 +1,17 @@
|
|||||||
|
import gradio as gr
|
||||||
|
from modules import shared
|
||||||
|
|
||||||
|
shared.options_templates.update(shared.options_section(('canvas_hotkey', "Canvas Hotkeys"), {
|
||||||
|
"canvas_hotkey_zoom": shared.OptionInfo("Alt", "Zoom canvas", gr.Radio, {"choices": ["Shift","Ctrl", "Alt"]}).info("If you choose 'Shift' you cannot scroll horizontally, 'Alt' can cause a little trouble in firefox"),
|
||||||
|
"canvas_hotkey_adjust": shared.OptionInfo("Ctrl", "Adjust brush size", gr.Radio, {"choices": ["Shift","Ctrl", "Alt"]}).info("If you choose 'Shift' you cannot scroll horizontally, 'Alt' can cause a little trouble in firefox"),
|
||||||
|
"canvas_hotkey_shrink_brush": shared.OptionInfo("Q", "Shrink the brush size"),
|
||||||
|
"canvas_hotkey_grow_brush": shared.OptionInfo("W", "Enlarge the brush size"),
|
||||||
|
"canvas_hotkey_move": shared.OptionInfo("F", "Moving the canvas").info("To work correctly in firefox, turn off 'Automatically search the page text when typing' in the browser settings"),
|
||||||
|
"canvas_hotkey_fullscreen": shared.OptionInfo("S", "Fullscreen Mode, maximizes the picture so that it fits into the screen and stretches it to its full width "),
|
||||||
|
"canvas_hotkey_reset": shared.OptionInfo("R", "Reset zoom and canvas position"),
|
||||||
|
"canvas_hotkey_overlap": shared.OptionInfo("O", "Toggle overlap").info("Technical button, needed for testing"),
|
||||||
|
"canvas_show_tooltip": shared.OptionInfo(True, "Enable tooltip on the canvas"),
|
||||||
|
"canvas_auto_expand": shared.OptionInfo(True, "Automatically expands an image that does not fit completely in the canvas area, similar to manually pressing the S and R buttons"),
|
||||||
|
"canvas_blur_prompt": shared.OptionInfo(False, "Take the focus off the prompt when working with a canvas"),
|
||||||
|
"canvas_disabled_functions": shared.OptionInfo(["Overlap"], "Disable function that you don't use", gr.CheckboxGroup, {"choices": ["Zoom","Adjust brush size","Hotkey enlarge brush","Hotkey shrink brush","Moving canvas","Fullscreen","Reset Zoom","Overlap"]}),
|
||||||
|
}))
|
66
extensions-builtin/canvas-zoom-and-pan/style.css
Normal file
66
extensions-builtin/canvas-zoom-and-pan/style.css
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
.canvas-tooltip-info {
|
||||||
|
position: absolute;
|
||||||
|
top: 10px;
|
||||||
|
left: 10px;
|
||||||
|
cursor: help;
|
||||||
|
background-color: rgba(0, 0, 0, 0.3);
|
||||||
|
width: 20px;
|
||||||
|
height: 20px;
|
||||||
|
border-radius: 50%;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
flex-direction: column;
|
||||||
|
|
||||||
|
z-index: 100;
|
||||||
|
}
|
||||||
|
|
||||||
|
.canvas-tooltip-info::after {
|
||||||
|
content: '';
|
||||||
|
display: block;
|
||||||
|
width: 2px;
|
||||||
|
height: 7px;
|
||||||
|
background-color: white;
|
||||||
|
margin-top: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.canvas-tooltip-info::before {
|
||||||
|
content: '';
|
||||||
|
display: block;
|
||||||
|
width: 2px;
|
||||||
|
height: 2px;
|
||||||
|
background-color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.canvas-tooltip-content {
|
||||||
|
display: none;
|
||||||
|
background-color: #f9f9f9;
|
||||||
|
color: #333;
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
padding: 15px;
|
||||||
|
position: absolute;
|
||||||
|
top: 40px;
|
||||||
|
left: 10px;
|
||||||
|
width: 250px;
|
||||||
|
font-size: 16px;
|
||||||
|
opacity: 0;
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
|
||||||
|
|
||||||
|
z-index: 100;
|
||||||
|
}
|
||||||
|
|
||||||
|
.canvas-tooltip:hover .canvas-tooltip-content {
|
||||||
|
display: block;
|
||||||
|
animation: fadeIn 0.5s;
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes fadeIn {
|
||||||
|
from {opacity: 0;}
|
||||||
|
to {opacity: 1;}
|
||||||
|
}
|
||||||
|
|
||||||
|
.styler {
|
||||||
|
overflow:inherit !important;
|
||||||
|
}
|
@ -0,0 +1,82 @@
|
|||||||
|
import math
|
||||||
|
|
||||||
|
import gradio as gr
|
||||||
|
from modules import scripts, shared, ui_components, ui_settings, infotext_utils, errors
|
||||||
|
from modules.ui_components import FormColumn
|
||||||
|
|
||||||
|
|
||||||
|
class ExtraOptionsSection(scripts.Script):
|
||||||
|
section = "extra_options"
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.comps = None
|
||||||
|
self.setting_names = None
|
||||||
|
|
||||||
|
def title(self):
|
||||||
|
return "Extra options"
|
||||||
|
|
||||||
|
def show(self, is_img2img):
|
||||||
|
return scripts.AlwaysVisible
|
||||||
|
|
||||||
|
def ui(self, is_img2img):
|
||||||
|
self.comps = []
|
||||||
|
self.setting_names = []
|
||||||
|
self.infotext_fields = []
|
||||||
|
extra_options = shared.opts.extra_options_img2img if is_img2img else shared.opts.extra_options_txt2img
|
||||||
|
elem_id_tabname = "extra_options_" + ("img2img" if is_img2img else "txt2img")
|
||||||
|
|
||||||
|
mapping = {k: v for v, k in infotext_utils.infotext_to_setting_name_mapping}
|
||||||
|
|
||||||
|
with gr.Blocks() as interface:
|
||||||
|
with gr.Accordion("Options", open=False, elem_id=elem_id_tabname) if shared.opts.extra_options_accordion and extra_options else gr.Group(elem_id=elem_id_tabname):
|
||||||
|
|
||||||
|
row_count = math.ceil(len(extra_options) / shared.opts.extra_options_cols)
|
||||||
|
|
||||||
|
for row in range(row_count):
|
||||||
|
with gr.Row():
|
||||||
|
for col in range(shared.opts.extra_options_cols):
|
||||||
|
index = row * shared.opts.extra_options_cols + col
|
||||||
|
if index >= len(extra_options):
|
||||||
|
break
|
||||||
|
|
||||||
|
setting_name = extra_options[index]
|
||||||
|
|
||||||
|
with FormColumn():
|
||||||
|
try:
|
||||||
|
comp = ui_settings.create_setting_component(setting_name)
|
||||||
|
except KeyError:
|
||||||
|
errors.report(f"Can't add extra options for {setting_name} in ui")
|
||||||
|
continue
|
||||||
|
|
||||||
|
self.comps.append(comp)
|
||||||
|
self.setting_names.append(setting_name)
|
||||||
|
|
||||||
|
setting_infotext_name = mapping.get(setting_name)
|
||||||
|
if setting_infotext_name is not None:
|
||||||
|
self.infotext_fields.append((comp, setting_infotext_name))
|
||||||
|
|
||||||
|
def get_settings_values():
|
||||||
|
res = [ui_settings.get_value_for_setting(key) for key in self.setting_names]
|
||||||
|
return res[0] if len(res) == 1 else res
|
||||||
|
|
||||||
|
interface.load(fn=get_settings_values, inputs=[], outputs=self.comps, queue=False, show_progress=False)
|
||||||
|
|
||||||
|
return self.comps
|
||||||
|
|
||||||
|
def before_process(self, p, *args):
|
||||||
|
for name, value in zip(self.setting_names, args):
|
||||||
|
if name not in p.override_settings:
|
||||||
|
p.override_settings[name] = value
|
||||||
|
|
||||||
|
|
||||||
|
shared.options_templates.update(shared.options_section(('settings_in_ui', "Settings in UI", "ui"), {
|
||||||
|
"settings_in_ui": shared.OptionHTML("""
|
||||||
|
This page allows you to add some settings to the main interface of txt2img and img2img tabs.
|
||||||
|
"""),
|
||||||
|
"extra_options_txt2img": shared.OptionInfo([], "Settings for txt2img", ui_components.DropdownMulti, lambda: {"choices": list(shared.opts.data_labels.keys())}).js("info", "settingsHintsShowQuicksettings").info("setting entries that also appear in txt2img interfaces").needs_reload_ui(),
|
||||||
|
"extra_options_img2img": shared.OptionInfo([], "Settings for img2img", ui_components.DropdownMulti, lambda: {"choices": list(shared.opts.data_labels.keys())}).js("info", "settingsHintsShowQuicksettings").info("setting entries that also appear in img2img interfaces").needs_reload_ui(),
|
||||||
|
"extra_options_cols": shared.OptionInfo(1, "Number of columns for added settings", gr.Slider, {"step": 1, "minimum": 1, "maximum": 20}).info("displayed amount will depend on the actual browser window width").needs_reload_ui(),
|
||||||
|
"extra_options_accordion": shared.OptionInfo(False, "Place added settings into an accordion").needs_reload_ui()
|
||||||
|
}))
|
||||||
|
|
||||||
|
|
351
extensions-builtin/hypertile/hypertile.py
Normal file
351
extensions-builtin/hypertile/hypertile.py
Normal file
@ -0,0 +1,351 @@
|
|||||||
|
"""
|
||||||
|
Hypertile module for splitting attention layers in SD-1.5 U-Net and SD-1.5 VAE
|
||||||
|
Warn: The patch works well only if the input image has a width and height that are multiples of 128
|
||||||
|
Original author: @tfernd Github: https://github.com/tfernd/HyperTile
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
from functools import wraps, cache
|
||||||
|
|
||||||
|
import math
|
||||||
|
import torch.nn as nn
|
||||||
|
import random
|
||||||
|
|
||||||
|
from einops import rearrange
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class HypertileParams:
|
||||||
|
depth = 0
|
||||||
|
layer_name = ""
|
||||||
|
tile_size: int = 0
|
||||||
|
swap_size: int = 0
|
||||||
|
aspect_ratio: float = 1.0
|
||||||
|
forward = None
|
||||||
|
enabled = False
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# TODO add SD-XL layers
|
||||||
|
DEPTH_LAYERS = {
|
||||||
|
0: [
|
||||||
|
# SD 1.5 U-Net (diffusers)
|
||||||
|
"down_blocks.0.attentions.0.transformer_blocks.0.attn1",
|
||||||
|
"down_blocks.0.attentions.1.transformer_blocks.0.attn1",
|
||||||
|
"up_blocks.3.attentions.0.transformer_blocks.0.attn1",
|
||||||
|
"up_blocks.3.attentions.1.transformer_blocks.0.attn1",
|
||||||
|
"up_blocks.3.attentions.2.transformer_blocks.0.attn1",
|
||||||
|
# SD 1.5 U-Net (ldm)
|
||||||
|
"input_blocks.1.1.transformer_blocks.0.attn1",
|
||||||
|
"input_blocks.2.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.9.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.10.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.11.1.transformer_blocks.0.attn1",
|
||||||
|
# SD 1.5 VAE
|
||||||
|
"decoder.mid_block.attentions.0",
|
||||||
|
"decoder.mid.attn_1",
|
||||||
|
],
|
||||||
|
1: [
|
||||||
|
# SD 1.5 U-Net (diffusers)
|
||||||
|
"down_blocks.1.attentions.0.transformer_blocks.0.attn1",
|
||||||
|
"down_blocks.1.attentions.1.transformer_blocks.0.attn1",
|
||||||
|
"up_blocks.2.attentions.0.transformer_blocks.0.attn1",
|
||||||
|
"up_blocks.2.attentions.1.transformer_blocks.0.attn1",
|
||||||
|
"up_blocks.2.attentions.2.transformer_blocks.0.attn1",
|
||||||
|
# SD 1.5 U-Net (ldm)
|
||||||
|
"input_blocks.4.1.transformer_blocks.0.attn1",
|
||||||
|
"input_blocks.5.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.6.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.7.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.8.1.transformer_blocks.0.attn1",
|
||||||
|
],
|
||||||
|
2: [
|
||||||
|
# SD 1.5 U-Net (diffusers)
|
||||||
|
"down_blocks.2.attentions.0.transformer_blocks.0.attn1",
|
||||||
|
"down_blocks.2.attentions.1.transformer_blocks.0.attn1",
|
||||||
|
"up_blocks.1.attentions.0.transformer_blocks.0.attn1",
|
||||||
|
"up_blocks.1.attentions.1.transformer_blocks.0.attn1",
|
||||||
|
"up_blocks.1.attentions.2.transformer_blocks.0.attn1",
|
||||||
|
# SD 1.5 U-Net (ldm)
|
||||||
|
"input_blocks.7.1.transformer_blocks.0.attn1",
|
||||||
|
"input_blocks.8.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.3.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.4.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.5.1.transformer_blocks.0.attn1",
|
||||||
|
],
|
||||||
|
3: [
|
||||||
|
# SD 1.5 U-Net (diffusers)
|
||||||
|
"mid_block.attentions.0.transformer_blocks.0.attn1",
|
||||||
|
# SD 1.5 U-Net (ldm)
|
||||||
|
"middle_block.1.transformer_blocks.0.attn1",
|
||||||
|
],
|
||||||
|
}
|
||||||
|
# XL layers, thanks for GitHub@gel-crabs for the help
|
||||||
|
DEPTH_LAYERS_XL = {
|
||||||
|
0: [
|
||||||
|
# SD 1.5 U-Net (diffusers)
|
||||||
|
"down_blocks.0.attentions.0.transformer_blocks.0.attn1",
|
||||||
|
"down_blocks.0.attentions.1.transformer_blocks.0.attn1",
|
||||||
|
"up_blocks.3.attentions.0.transformer_blocks.0.attn1",
|
||||||
|
"up_blocks.3.attentions.1.transformer_blocks.0.attn1",
|
||||||
|
"up_blocks.3.attentions.2.transformer_blocks.0.attn1",
|
||||||
|
# SD 1.5 U-Net (ldm)
|
||||||
|
"input_blocks.4.1.transformer_blocks.0.attn1",
|
||||||
|
"input_blocks.5.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.3.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.4.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.5.1.transformer_blocks.0.attn1",
|
||||||
|
# SD 1.5 VAE
|
||||||
|
"decoder.mid_block.attentions.0",
|
||||||
|
"decoder.mid.attn_1",
|
||||||
|
],
|
||||||
|
1: [
|
||||||
|
# SD 1.5 U-Net (diffusers)
|
||||||
|
#"down_blocks.1.attentions.0.transformer_blocks.0.attn1",
|
||||||
|
#"down_blocks.1.attentions.1.transformer_blocks.0.attn1",
|
||||||
|
#"up_blocks.2.attentions.0.transformer_blocks.0.attn1",
|
||||||
|
#"up_blocks.2.attentions.1.transformer_blocks.0.attn1",
|
||||||
|
#"up_blocks.2.attentions.2.transformer_blocks.0.attn1",
|
||||||
|
# SD 1.5 U-Net (ldm)
|
||||||
|
"input_blocks.4.1.transformer_blocks.1.attn1",
|
||||||
|
"input_blocks.5.1.transformer_blocks.1.attn1",
|
||||||
|
"output_blocks.3.1.transformer_blocks.1.attn1",
|
||||||
|
"output_blocks.4.1.transformer_blocks.1.attn1",
|
||||||
|
"output_blocks.5.1.transformer_blocks.1.attn1",
|
||||||
|
"input_blocks.7.1.transformer_blocks.0.attn1",
|
||||||
|
"input_blocks.8.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.0.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.1.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.2.1.transformer_blocks.0.attn1",
|
||||||
|
"input_blocks.7.1.transformer_blocks.1.attn1",
|
||||||
|
"input_blocks.8.1.transformer_blocks.1.attn1",
|
||||||
|
"output_blocks.0.1.transformer_blocks.1.attn1",
|
||||||
|
"output_blocks.1.1.transformer_blocks.1.attn1",
|
||||||
|
"output_blocks.2.1.transformer_blocks.1.attn1",
|
||||||
|
"input_blocks.7.1.transformer_blocks.2.attn1",
|
||||||
|
"input_blocks.8.1.transformer_blocks.2.attn1",
|
||||||
|
"output_blocks.0.1.transformer_blocks.2.attn1",
|
||||||
|
"output_blocks.1.1.transformer_blocks.2.attn1",
|
||||||
|
"output_blocks.2.1.transformer_blocks.2.attn1",
|
||||||
|
"input_blocks.7.1.transformer_blocks.3.attn1",
|
||||||
|
"input_blocks.8.1.transformer_blocks.3.attn1",
|
||||||
|
"output_blocks.0.1.transformer_blocks.3.attn1",
|
||||||
|
"output_blocks.1.1.transformer_blocks.3.attn1",
|
||||||
|
"output_blocks.2.1.transformer_blocks.3.attn1",
|
||||||
|
"input_blocks.7.1.transformer_blocks.4.attn1",
|
||||||
|
"input_blocks.8.1.transformer_blocks.4.attn1",
|
||||||
|
"output_blocks.0.1.transformer_blocks.4.attn1",
|
||||||
|
"output_blocks.1.1.transformer_blocks.4.attn1",
|
||||||
|
"output_blocks.2.1.transformer_blocks.4.attn1",
|
||||||
|
"input_blocks.7.1.transformer_blocks.5.attn1",
|
||||||
|
"input_blocks.8.1.transformer_blocks.5.attn1",
|
||||||
|
"output_blocks.0.1.transformer_blocks.5.attn1",
|
||||||
|
"output_blocks.1.1.transformer_blocks.5.attn1",
|
||||||
|
"output_blocks.2.1.transformer_blocks.5.attn1",
|
||||||
|
"input_blocks.7.1.transformer_blocks.6.attn1",
|
||||||
|
"input_blocks.8.1.transformer_blocks.6.attn1",
|
||||||
|
"output_blocks.0.1.transformer_blocks.6.attn1",
|
||||||
|
"output_blocks.1.1.transformer_blocks.6.attn1",
|
||||||
|
"output_blocks.2.1.transformer_blocks.6.attn1",
|
||||||
|
"input_blocks.7.1.transformer_blocks.7.attn1",
|
||||||
|
"input_blocks.8.1.transformer_blocks.7.attn1",
|
||||||
|
"output_blocks.0.1.transformer_blocks.7.attn1",
|
||||||
|
"output_blocks.1.1.transformer_blocks.7.attn1",
|
||||||
|
"output_blocks.2.1.transformer_blocks.7.attn1",
|
||||||
|
"input_blocks.7.1.transformer_blocks.8.attn1",
|
||||||
|
"input_blocks.8.1.transformer_blocks.8.attn1",
|
||||||
|
"output_blocks.0.1.transformer_blocks.8.attn1",
|
||||||
|
"output_blocks.1.1.transformer_blocks.8.attn1",
|
||||||
|
"output_blocks.2.1.transformer_blocks.8.attn1",
|
||||||
|
"input_blocks.7.1.transformer_blocks.9.attn1",
|
||||||
|
"input_blocks.8.1.transformer_blocks.9.attn1",
|
||||||
|
"output_blocks.0.1.transformer_blocks.9.attn1",
|
||||||
|
"output_blocks.1.1.transformer_blocks.9.attn1",
|
||||||
|
"output_blocks.2.1.transformer_blocks.9.attn1",
|
||||||
|
],
|
||||||
|
2: [
|
||||||
|
# SD 1.5 U-Net (diffusers)
|
||||||
|
"mid_block.attentions.0.transformer_blocks.0.attn1",
|
||||||
|
# SD 1.5 U-Net (ldm)
|
||||||
|
"middle_block.1.transformer_blocks.0.attn1",
|
||||||
|
"middle_block.1.transformer_blocks.1.attn1",
|
||||||
|
"middle_block.1.transformer_blocks.2.attn1",
|
||||||
|
"middle_block.1.transformer_blocks.3.attn1",
|
||||||
|
"middle_block.1.transformer_blocks.4.attn1",
|
||||||
|
"middle_block.1.transformer_blocks.5.attn1",
|
||||||
|
"middle_block.1.transformer_blocks.6.attn1",
|
||||||
|
"middle_block.1.transformer_blocks.7.attn1",
|
||||||
|
"middle_block.1.transformer_blocks.8.attn1",
|
||||||
|
"middle_block.1.transformer_blocks.9.attn1",
|
||||||
|
],
|
||||||
|
3 : [] # TODO - separate layers for SD-XL
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
RNG_INSTANCE = random.Random()
|
||||||
|
|
||||||
|
@cache
|
||||||
|
def get_divisors(value: int, min_value: int, /, max_options: int = 1) -> list[int]:
|
||||||
|
"""
|
||||||
|
Returns divisors of value that
|
||||||
|
x * min_value <= value
|
||||||
|
in big -> small order, amount of divisors is limited by max_options
|
||||||
|
"""
|
||||||
|
max_options = max(1, max_options) # at least 1 option should be returned
|
||||||
|
min_value = min(min_value, value)
|
||||||
|
divisors = [i for i in range(min_value, value + 1) if value % i == 0] # divisors in small -> big order
|
||||||
|
ns = [value // i for i in divisors[:max_options]] # has at least 1 element # big -> small order
|
||||||
|
return ns
|
||||||
|
|
||||||
|
|
||||||
|
def random_divisor(value: int, min_value: int, /, max_options: int = 1) -> int:
|
||||||
|
"""
|
||||||
|
Returns a random divisor of value that
|
||||||
|
x * min_value <= value
|
||||||
|
if max_options is 1, the behavior is deterministic
|
||||||
|
"""
|
||||||
|
ns = get_divisors(value, min_value, max_options=max_options) # get cached divisors
|
||||||
|
idx = RNG_INSTANCE.randint(0, len(ns) - 1)
|
||||||
|
|
||||||
|
return ns[idx]
|
||||||
|
|
||||||
|
|
||||||
|
def set_hypertile_seed(seed: int) -> None:
|
||||||
|
RNG_INSTANCE.seed(seed)
|
||||||
|
|
||||||
|
|
||||||
|
@cache
|
||||||
|
def largest_tile_size_available(width: int, height: int) -> int:
|
||||||
|
"""
|
||||||
|
Calculates the largest tile size available for a given width and height
|
||||||
|
Tile size is always a power of 2
|
||||||
|
"""
|
||||||
|
gcd = math.gcd(width, height)
|
||||||
|
largest_tile_size_available = 1
|
||||||
|
while gcd % (largest_tile_size_available * 2) == 0:
|
||||||
|
largest_tile_size_available *= 2
|
||||||
|
return largest_tile_size_available
|
||||||
|
|
||||||
|
|
||||||
|
def iterative_closest_divisors(hw:int, aspect_ratio:float) -> tuple[int, int]:
|
||||||
|
"""
|
||||||
|
Finds h and w such that h*w = hw and h/w = aspect_ratio
|
||||||
|
We check all possible divisors of hw and return the closest to the aspect ratio
|
||||||
|
"""
|
||||||
|
divisors = [i for i in range(2, hw + 1) if hw % i == 0] # all divisors of hw
|
||||||
|
pairs = [(i, hw // i) for i in divisors] # all pairs of divisors of hw
|
||||||
|
ratios = [w/h for h, w in pairs] # all ratios of pairs of divisors of hw
|
||||||
|
closest_ratio = min(ratios, key=lambda x: abs(x - aspect_ratio)) # closest ratio to aspect_ratio
|
||||||
|
closest_pair = pairs[ratios.index(closest_ratio)] # closest pair of divisors to aspect_ratio
|
||||||
|
return closest_pair
|
||||||
|
|
||||||
|
|
||||||
|
@cache
|
||||||
|
def find_hw_candidates(hw:int, aspect_ratio:float) -> tuple[int, int]:
|
||||||
|
"""
|
||||||
|
Finds h and w such that h*w = hw and h/w = aspect_ratio
|
||||||
|
"""
|
||||||
|
h, w = round(math.sqrt(hw * aspect_ratio)), round(math.sqrt(hw / aspect_ratio))
|
||||||
|
# find h and w such that h*w = hw and h/w = aspect_ratio
|
||||||
|
if h * w != hw:
|
||||||
|
w_candidate = hw / h
|
||||||
|
# check if w is an integer
|
||||||
|
if not w_candidate.is_integer():
|
||||||
|
h_candidate = hw / w
|
||||||
|
# check if h is an integer
|
||||||
|
if not h_candidate.is_integer():
|
||||||
|
return iterative_closest_divisors(hw, aspect_ratio)
|
||||||
|
else:
|
||||||
|
h = int(h_candidate)
|
||||||
|
else:
|
||||||
|
w = int(w_candidate)
|
||||||
|
return h, w
|
||||||
|
|
||||||
|
|
||||||
|
def self_attn_forward(params: HypertileParams, scale_depth=True) -> Callable:
|
||||||
|
|
||||||
|
@wraps(params.forward)
|
||||||
|
def wrapper(*args, **kwargs):
|
||||||
|
if not params.enabled:
|
||||||
|
return params.forward(*args, **kwargs)
|
||||||
|
|
||||||
|
latent_tile_size = max(128, params.tile_size) // 8
|
||||||
|
x = args[0]
|
||||||
|
|
||||||
|
# VAE
|
||||||
|
if x.ndim == 4:
|
||||||
|
b, c, h, w = x.shape
|
||||||
|
|
||||||
|
nh = random_divisor(h, latent_tile_size, params.swap_size)
|
||||||
|
nw = random_divisor(w, latent_tile_size, params.swap_size)
|
||||||
|
|
||||||
|
if nh * nw > 1:
|
||||||
|
x = rearrange(x, "b c (nh h) (nw w) -> (b nh nw) c h w", nh=nh, nw=nw) # split into nh * nw tiles
|
||||||
|
|
||||||
|
out = params.forward(x, *args[1:], **kwargs)
|
||||||
|
|
||||||
|
if nh * nw > 1:
|
||||||
|
out = rearrange(out, "(b nh nw) c h w -> b c (nh h) (nw w)", nh=nh, nw=nw)
|
||||||
|
|
||||||
|
# U-Net
|
||||||
|
else:
|
||||||
|
hw: int = x.size(1)
|
||||||
|
h, w = find_hw_candidates(hw, params.aspect_ratio)
|
||||||
|
assert h * w == hw, f"Invalid aspect ratio {params.aspect_ratio} for input of shape {x.shape}, hw={hw}, h={h}, w={w}"
|
||||||
|
|
||||||
|
factor = 2 ** params.depth if scale_depth else 1
|
||||||
|
nh = random_divisor(h, latent_tile_size * factor, params.swap_size)
|
||||||
|
nw = random_divisor(w, latent_tile_size * factor, params.swap_size)
|
||||||
|
|
||||||
|
if nh * nw > 1:
|
||||||
|
x = rearrange(x, "b (nh h nw w) c -> (b nh nw) (h w) c", h=h // nh, w=w // nw, nh=nh, nw=nw)
|
||||||
|
|
||||||
|
out = params.forward(x, *args[1:], **kwargs)
|
||||||
|
|
||||||
|
if nh * nw > 1:
|
||||||
|
out = rearrange(out, "(b nh nw) hw c -> b nh nw hw c", nh=nh, nw=nw)
|
||||||
|
out = rearrange(out, "b nh nw (h w) c -> b (nh h nw w) c", h=h // nh, w=w // nw)
|
||||||
|
|
||||||
|
return out
|
||||||
|
|
||||||
|
return wrapper
|
||||||
|
|
||||||
|
|
||||||
|
def hypertile_hook_model(model: nn.Module, width, height, *, enable=False, tile_size_max=128, swap_size=1, max_depth=3, is_sdxl=False):
|
||||||
|
hypertile_layers = getattr(model, "__webui_hypertile_layers", None)
|
||||||
|
if hypertile_layers is None:
|
||||||
|
if not enable:
|
||||||
|
return
|
||||||
|
|
||||||
|
hypertile_layers = {}
|
||||||
|
layers = DEPTH_LAYERS_XL if is_sdxl else DEPTH_LAYERS
|
||||||
|
|
||||||
|
for depth in range(4):
|
||||||
|
for layer_name, module in model.named_modules():
|
||||||
|
if any(layer_name.endswith(try_name) for try_name in layers[depth]):
|
||||||
|
params = HypertileParams()
|
||||||
|
module.__webui_hypertile_params = params
|
||||||
|
params.forward = module.forward
|
||||||
|
params.depth = depth
|
||||||
|
params.layer_name = layer_name
|
||||||
|
module.forward = self_attn_forward(params)
|
||||||
|
|
||||||
|
hypertile_layers[layer_name] = 1
|
||||||
|
|
||||||
|
model.__webui_hypertile_layers = hypertile_layers
|
||||||
|
|
||||||
|
aspect_ratio = width / height
|
||||||
|
tile_size = min(largest_tile_size_available(width, height), tile_size_max)
|
||||||
|
|
||||||
|
for layer_name, module in model.named_modules():
|
||||||
|
if layer_name in hypertile_layers:
|
||||||
|
params = module.__webui_hypertile_params
|
||||||
|
|
||||||
|
params.tile_size = tile_size
|
||||||
|
params.swap_size = swap_size
|
||||||
|
params.aspect_ratio = aspect_ratio
|
||||||
|
params.enabled = enable and params.depth <= max_depth
|
122
extensions-builtin/hypertile/scripts/hypertile_script.py
Normal file
122
extensions-builtin/hypertile/scripts/hypertile_script.py
Normal file
@ -0,0 +1,122 @@
|
|||||||
|
import hypertile
|
||||||
|
from modules import scripts, script_callbacks, shared
|
||||||
|
|
||||||
|
|
||||||
|
class ScriptHypertile(scripts.Script):
|
||||||
|
name = "Hypertile"
|
||||||
|
|
||||||
|
def title(self):
|
||||||
|
return self.name
|
||||||
|
|
||||||
|
def show(self, is_img2img):
|
||||||
|
return scripts.AlwaysVisible
|
||||||
|
|
||||||
|
def process(self, p, *args):
|
||||||
|
hypertile.set_hypertile_seed(p.all_seeds[0])
|
||||||
|
|
||||||
|
configure_hypertile(p.width, p.height, enable_unet=shared.opts.hypertile_enable_unet)
|
||||||
|
|
||||||
|
self.add_infotext(p)
|
||||||
|
|
||||||
|
def before_hr(self, p, *args):
|
||||||
|
|
||||||
|
enable = shared.opts.hypertile_enable_unet_secondpass or shared.opts.hypertile_enable_unet
|
||||||
|
|
||||||
|
# exclusive hypertile seed for the second pass
|
||||||
|
if enable:
|
||||||
|
hypertile.set_hypertile_seed(p.all_seeds[0])
|
||||||
|
|
||||||
|
configure_hypertile(p.hr_upscale_to_x, p.hr_upscale_to_y, enable_unet=enable)
|
||||||
|
|
||||||
|
if enable and not shared.opts.hypertile_enable_unet:
|
||||||
|
p.extra_generation_params["Hypertile U-Net second pass"] = True
|
||||||
|
|
||||||
|
self.add_infotext(p, add_unet_params=True)
|
||||||
|
|
||||||
|
def add_infotext(self, p, add_unet_params=False):
|
||||||
|
def option(name):
|
||||||
|
value = getattr(shared.opts, name)
|
||||||
|
default_value = shared.opts.get_default(name)
|
||||||
|
return None if value == default_value else value
|
||||||
|
|
||||||
|
if shared.opts.hypertile_enable_unet:
|
||||||
|
p.extra_generation_params["Hypertile U-Net"] = True
|
||||||
|
|
||||||
|
if shared.opts.hypertile_enable_unet or add_unet_params:
|
||||||
|
p.extra_generation_params["Hypertile U-Net max depth"] = option('hypertile_max_depth_unet')
|
||||||
|
p.extra_generation_params["Hypertile U-Net max tile size"] = option('hypertile_max_tile_unet')
|
||||||
|
p.extra_generation_params["Hypertile U-Net swap size"] = option('hypertile_swap_size_unet')
|
||||||
|
|
||||||
|
if shared.opts.hypertile_enable_vae:
|
||||||
|
p.extra_generation_params["Hypertile VAE"] = True
|
||||||
|
p.extra_generation_params["Hypertile VAE max depth"] = option('hypertile_max_depth_vae')
|
||||||
|
p.extra_generation_params["Hypertile VAE max tile size"] = option('hypertile_max_tile_vae')
|
||||||
|
p.extra_generation_params["Hypertile VAE swap size"] = option('hypertile_swap_size_vae')
|
||||||
|
|
||||||
|
|
||||||
|
def configure_hypertile(width, height, enable_unet=True):
|
||||||
|
hypertile.hypertile_hook_model(
|
||||||
|
shared.sd_model.first_stage_model,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
swap_size=shared.opts.hypertile_swap_size_vae,
|
||||||
|
max_depth=shared.opts.hypertile_max_depth_vae,
|
||||||
|
tile_size_max=shared.opts.hypertile_max_tile_vae,
|
||||||
|
enable=shared.opts.hypertile_enable_vae,
|
||||||
|
)
|
||||||
|
|
||||||
|
hypertile.hypertile_hook_model(
|
||||||
|
shared.sd_model.model,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
swap_size=shared.opts.hypertile_swap_size_unet,
|
||||||
|
max_depth=shared.opts.hypertile_max_depth_unet,
|
||||||
|
tile_size_max=shared.opts.hypertile_max_tile_unet,
|
||||||
|
enable=enable_unet,
|
||||||
|
is_sdxl=shared.sd_model.is_sdxl
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def on_ui_settings():
|
||||||
|
import gradio as gr
|
||||||
|
|
||||||
|
options = {
|
||||||
|
"hypertile_explanation": shared.OptionHTML("""
|
||||||
|
<a href='https://github.com/tfernd/HyperTile'>Hypertile</a> optimizes the self-attention layer within U-Net and VAE models,
|
||||||
|
resulting in a reduction in computation time ranging from 1 to 4 times. The larger the generated image is, the greater the
|
||||||
|
benefit.
|
||||||
|
"""),
|
||||||
|
|
||||||
|
"hypertile_enable_unet": shared.OptionInfo(False, "Enable Hypertile U-Net", infotext="Hypertile U-Net").info("enables hypertile for all modes, including hires fix second pass; noticeable change in details of the generated picture"),
|
||||||
|
"hypertile_enable_unet_secondpass": shared.OptionInfo(False, "Enable Hypertile U-Net for hires fix second pass", infotext="Hypertile U-Net second pass").info("enables hypertile just for hires fix second pass - regardless of whether the above setting is enabled"),
|
||||||
|
"hypertile_max_depth_unet": shared.OptionInfo(3, "Hypertile U-Net max depth", gr.Slider, {"minimum": 0, "maximum": 3, "step": 1}, infotext="Hypertile U-Net max depth").info("larger = more neural network layers affected; minor effect on performance"),
|
||||||
|
"hypertile_max_tile_unet": shared.OptionInfo(256, "Hypertile U-Net max tile size", gr.Slider, {"minimum": 0, "maximum": 512, "step": 16}, infotext="Hypertile U-Net max tile size").info("larger = worse performance"),
|
||||||
|
"hypertile_swap_size_unet": shared.OptionInfo(3, "Hypertile U-Net swap size", gr.Slider, {"minimum": 0, "maximum": 64, "step": 1}, infotext="Hypertile U-Net swap size"),
|
||||||
|
"hypertile_enable_vae": shared.OptionInfo(False, "Enable Hypertile VAE", infotext="Hypertile VAE").info("minimal change in the generated picture"),
|
||||||
|
"hypertile_max_depth_vae": shared.OptionInfo(3, "Hypertile VAE max depth", gr.Slider, {"minimum": 0, "maximum": 3, "step": 1}, infotext="Hypertile VAE max depth"),
|
||||||
|
"hypertile_max_tile_vae": shared.OptionInfo(128, "Hypertile VAE max tile size", gr.Slider, {"minimum": 0, "maximum": 512, "step": 16}, infotext="Hypertile VAE max tile size"),
|
||||||
|
"hypertile_swap_size_vae": shared.OptionInfo(3, "Hypertile VAE swap size ", gr.Slider, {"minimum": 0, "maximum": 64, "step": 1}, infotext="Hypertile VAE swap size"),
|
||||||
|
}
|
||||||
|
|
||||||
|
for name, opt in options.items():
|
||||||
|
opt.section = ('hypertile', "Hypertile")
|
||||||
|
shared.opts.add_option(name, opt)
|
||||||
|
|
||||||
|
|
||||||
|
def add_axis_options():
|
||||||
|
xyz_grid = [x for x in scripts.scripts_data if x.script_class.__module__ == "xyz_grid.py"][0].module
|
||||||
|
xyz_grid.axis_options.extend([
|
||||||
|
xyz_grid.AxisOption("[Hypertile] Unet First pass Enabled", str, xyz_grid.apply_override('hypertile_enable_unet', boolean=True), choices=xyz_grid.boolean_choice(reverse=True)),
|
||||||
|
xyz_grid.AxisOption("[Hypertile] Unet Second pass Enabled", str, xyz_grid.apply_override('hypertile_enable_unet_secondpass', boolean=True), choices=xyz_grid.boolean_choice(reverse=True)),
|
||||||
|
xyz_grid.AxisOption("[Hypertile] Unet Max Depth", int, xyz_grid.apply_override("hypertile_max_depth_unet"), confirm=xyz_grid.confirm_range(0, 3, '[Hypertile] Unet Max Depth'), choices=lambda: [str(x) for x in range(4)]),
|
||||||
|
xyz_grid.AxisOption("[Hypertile] Unet Max Tile Size", int, xyz_grid.apply_override("hypertile_max_tile_unet"), confirm=xyz_grid.confirm_range(0, 512, '[Hypertile] Unet Max Tile Size')),
|
||||||
|
xyz_grid.AxisOption("[Hypertile] Unet Swap Size", int, xyz_grid.apply_override("hypertile_swap_size_unet"), confirm=xyz_grid.confirm_range(0, 64, '[Hypertile] Unet Swap Size')),
|
||||||
|
xyz_grid.AxisOption("[Hypertile] VAE Enabled", str, xyz_grid.apply_override('hypertile_enable_vae', boolean=True), choices=xyz_grid.boolean_choice(reverse=True)),
|
||||||
|
xyz_grid.AxisOption("[Hypertile] VAE Max Depth", int, xyz_grid.apply_override("hypertile_max_depth_vae"), confirm=xyz_grid.confirm_range(0, 3, '[Hypertile] VAE Max Depth'), choices=lambda: [str(x) for x in range(4)]),
|
||||||
|
xyz_grid.AxisOption("[Hypertile] VAE Max Tile Size", int, xyz_grid.apply_override("hypertile_max_tile_vae"), confirm=xyz_grid.confirm_range(0, 512, '[Hypertile] VAE Max Tile Size')),
|
||||||
|
xyz_grid.AxisOption("[Hypertile] VAE Swap Size", int, xyz_grid.apply_override("hypertile_swap_size_vae"), confirm=xyz_grid.confirm_range(0, 64, '[Hypertile] VAE Swap Size')),
|
||||||
|
])
|
||||||
|
|
||||||
|
|
||||||
|
script_callbacks.on_ui_settings(on_ui_settings)
|
||||||
|
script_callbacks.on_before_ui(add_axis_options)
|
34
extensions-builtin/mobile/javascript/mobile.js
Normal file
34
extensions-builtin/mobile/javascript/mobile.js
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
var isSetupForMobile = false;
|
||||||
|
|
||||||
|
function isMobile() {
|
||||||
|
for (var tab of ["txt2img", "img2img"]) {
|
||||||
|
var imageTab = gradioApp().getElementById(tab + '_results');
|
||||||
|
if (imageTab && imageTab.offsetParent && imageTab.offsetLeft == 0) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function reportWindowSize() {
|
||||||
|
if (gradioApp().querySelector('.toprow-compact-tools')) return; // not applicable for compact prompt layout
|
||||||
|
|
||||||
|
var currentlyMobile = isMobile();
|
||||||
|
if (currentlyMobile == isSetupForMobile) return;
|
||||||
|
isSetupForMobile = currentlyMobile;
|
||||||
|
|
||||||
|
for (var tab of ["txt2img", "img2img"]) {
|
||||||
|
var button = gradioApp().getElementById(tab + '_generate_box');
|
||||||
|
var target = gradioApp().getElementById(currentlyMobile ? tab + '_results' : tab + '_actions_column');
|
||||||
|
target.insertBefore(button, target.firstElementChild);
|
||||||
|
|
||||||
|
gradioApp().getElementById(tab + '_results').classList.toggle('mobile', currentlyMobile);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener("resize", reportWindowSize);
|
||||||
|
|
||||||
|
onUiLoaded(function() {
|
||||||
|
reportWindowSize();
|
||||||
|
});
|
@ -0,0 +1,64 @@
|
|||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from modules import scripts_postprocessing, ui_components
|
||||||
|
import gradio as gr
|
||||||
|
|
||||||
|
|
||||||
|
def center_crop(image: Image, w: int, h: int):
|
||||||
|
iw, ih = image.size
|
||||||
|
if ih / h < iw / w:
|
||||||
|
sw = w * ih / h
|
||||||
|
box = (iw - sw) / 2, 0, iw - (iw - sw) / 2, ih
|
||||||
|
else:
|
||||||
|
sh = h * iw / w
|
||||||
|
box = 0, (ih - sh) / 2, iw, ih - (ih - sh) / 2
|
||||||
|
return image.resize((w, h), Image.Resampling.LANCZOS, box)
|
||||||
|
|
||||||
|
|
||||||
|
def multicrop_pic(image: Image, mindim, maxdim, minarea, maxarea, objective, threshold):
|
||||||
|
iw, ih = image.size
|
||||||
|
err = lambda w, h: 1 - (lambda x: x if x < 1 else 1 / x)(iw / ih / (w / h))
|
||||||
|
wh = max(((w, h) for w in range(mindim, maxdim + 1, 64) for h in range(mindim, maxdim + 1, 64)
|
||||||
|
if minarea <= w * h <= maxarea and err(w, h) <= threshold),
|
||||||
|
key=lambda wh: (wh[0] * wh[1], -err(*wh))[::1 if objective == 'Maximize area' else -1],
|
||||||
|
default=None
|
||||||
|
)
|
||||||
|
return wh and center_crop(image, *wh)
|
||||||
|
|
||||||
|
|
||||||
|
class ScriptPostprocessingAutosizedCrop(scripts_postprocessing.ScriptPostprocessing):
|
||||||
|
name = "Auto-sized crop"
|
||||||
|
order = 4020
|
||||||
|
|
||||||
|
def ui(self):
|
||||||
|
with ui_components.InputAccordion(False, label="Auto-sized crop") as enable:
|
||||||
|
gr.Markdown('Each image is center-cropped with an automatically chosen width and height.')
|
||||||
|
with gr.Row():
|
||||||
|
mindim = gr.Slider(minimum=64, maximum=2048, step=8, label="Dimension lower bound", value=384, elem_id="postprocess_multicrop_mindim")
|
||||||
|
maxdim = gr.Slider(minimum=64, maximum=2048, step=8, label="Dimension upper bound", value=768, elem_id="postprocess_multicrop_maxdim")
|
||||||
|
with gr.Row():
|
||||||
|
minarea = gr.Slider(minimum=64 * 64, maximum=2048 * 2048, step=1, label="Area lower bound", value=64 * 64, elem_id="postprocess_multicrop_minarea")
|
||||||
|
maxarea = gr.Slider(minimum=64 * 64, maximum=2048 * 2048, step=1, label="Area upper bound", value=640 * 640, elem_id="postprocess_multicrop_maxarea")
|
||||||
|
with gr.Row():
|
||||||
|
objective = gr.Radio(["Maximize area", "Minimize error"], value="Maximize area", label="Resizing objective", elem_id="postprocess_multicrop_objective")
|
||||||
|
threshold = gr.Slider(minimum=0, maximum=1, step=0.01, label="Error threshold", value=0.1, elem_id="postprocess_multicrop_threshold")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"enable": enable,
|
||||||
|
"mindim": mindim,
|
||||||
|
"maxdim": maxdim,
|
||||||
|
"minarea": minarea,
|
||||||
|
"maxarea": maxarea,
|
||||||
|
"objective": objective,
|
||||||
|
"threshold": threshold,
|
||||||
|
}
|
||||||
|
|
||||||
|
def process(self, pp: scripts_postprocessing.PostprocessedImage, enable, mindim, maxdim, minarea, maxarea, objective, threshold):
|
||||||
|
if not enable:
|
||||||
|
return
|
||||||
|
|
||||||
|
cropped = multicrop_pic(pp.image, mindim, maxdim, minarea, maxarea, objective, threshold)
|
||||||
|
if cropped is not None:
|
||||||
|
pp.image = cropped
|
||||||
|
else:
|
||||||
|
print(f"skipped {pp.image.width}x{pp.image.height} image (can't find suitable size within error threshold)")
|
@ -0,0 +1,30 @@
|
|||||||
|
from modules import scripts_postprocessing, ui_components, deepbooru, shared
|
||||||
|
import gradio as gr
|
||||||
|
|
||||||
|
|
||||||
|
class ScriptPostprocessingCeption(scripts_postprocessing.ScriptPostprocessing):
|
||||||
|
name = "Caption"
|
||||||
|
order = 4040
|
||||||
|
|
||||||
|
def ui(self):
|
||||||
|
with ui_components.InputAccordion(False, label="Caption") as enable:
|
||||||
|
option = gr.CheckboxGroup(value=["Deepbooru"], choices=["Deepbooru", "BLIP"], show_label=False)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"enable": enable,
|
||||||
|
"option": option,
|
||||||
|
}
|
||||||
|
|
||||||
|
def process(self, pp: scripts_postprocessing.PostprocessedImage, enable, option):
|
||||||
|
if not enable:
|
||||||
|
return
|
||||||
|
|
||||||
|
captions = [pp.caption]
|
||||||
|
|
||||||
|
if "Deepbooru" in option:
|
||||||
|
captions.append(deepbooru.model.tag(pp.image))
|
||||||
|
|
||||||
|
if "BLIP" in option:
|
||||||
|
captions.append(shared.interrogator.interrogate(pp.image.convert("RGB")))
|
||||||
|
|
||||||
|
pp.caption = ", ".join([x for x in captions if x])
|
@ -0,0 +1,32 @@
|
|||||||
|
from PIL import ImageOps, Image
|
||||||
|
|
||||||
|
from modules import scripts_postprocessing, ui_components
|
||||||
|
import gradio as gr
|
||||||
|
|
||||||
|
|
||||||
|
class ScriptPostprocessingCreateFlippedCopies(scripts_postprocessing.ScriptPostprocessing):
|
||||||
|
name = "Create flipped copies"
|
||||||
|
order = 4030
|
||||||
|
|
||||||
|
def ui(self):
|
||||||
|
with ui_components.InputAccordion(False, label="Create flipped copies") as enable:
|
||||||
|
with gr.Row():
|
||||||
|
option = gr.CheckboxGroup(value=["Horizontal"], choices=["Horizontal", "Vertical", "Both"], show_label=False)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"enable": enable,
|
||||||
|
"option": option,
|
||||||
|
}
|
||||||
|
|
||||||
|
def process(self, pp: scripts_postprocessing.PostprocessedImage, enable, option):
|
||||||
|
if not enable:
|
||||||
|
return
|
||||||
|
|
||||||
|
if "Horizontal" in option:
|
||||||
|
pp.extra_images.append(ImageOps.mirror(pp.image))
|
||||||
|
|
||||||
|
if "Vertical" in option:
|
||||||
|
pp.extra_images.append(pp.image.transpose(Image.Transpose.FLIP_TOP_BOTTOM))
|
||||||
|
|
||||||
|
if "Both" in option:
|
||||||
|
pp.extra_images.append(pp.image.transpose(Image.Transpose.FLIP_TOP_BOTTOM).transpose(Image.Transpose.FLIP_LEFT_RIGHT))
|
@ -0,0 +1,54 @@
|
|||||||
|
|
||||||
|
from modules import scripts_postprocessing, ui_components, errors
|
||||||
|
import gradio as gr
|
||||||
|
|
||||||
|
from modules.textual_inversion import autocrop
|
||||||
|
|
||||||
|
|
||||||
|
class ScriptPostprocessingFocalCrop(scripts_postprocessing.ScriptPostprocessing):
|
||||||
|
name = "Auto focal point crop"
|
||||||
|
order = 4010
|
||||||
|
|
||||||
|
def ui(self):
|
||||||
|
with ui_components.InputAccordion(False, label="Auto focal point crop") as enable:
|
||||||
|
face_weight = gr.Slider(label='Focal point face weight', value=0.9, minimum=0.0, maximum=1.0, step=0.05, elem_id="postprocess_focal_crop_face_weight")
|
||||||
|
entropy_weight = gr.Slider(label='Focal point entropy weight', value=0.15, minimum=0.0, maximum=1.0, step=0.05, elem_id="postprocess_focal_crop_entropy_weight")
|
||||||
|
edges_weight = gr.Slider(label='Focal point edges weight', value=0.5, minimum=0.0, maximum=1.0, step=0.05, elem_id="postprocess_focal_crop_edges_weight")
|
||||||
|
debug = gr.Checkbox(label='Create debug image', elem_id="train_process_focal_crop_debug")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"enable": enable,
|
||||||
|
"face_weight": face_weight,
|
||||||
|
"entropy_weight": entropy_weight,
|
||||||
|
"edges_weight": edges_weight,
|
||||||
|
"debug": debug,
|
||||||
|
}
|
||||||
|
|
||||||
|
def process(self, pp: scripts_postprocessing.PostprocessedImage, enable, face_weight, entropy_weight, edges_weight, debug):
|
||||||
|
if not enable:
|
||||||
|
return
|
||||||
|
|
||||||
|
if not pp.shared.target_width or not pp.shared.target_height:
|
||||||
|
return
|
||||||
|
|
||||||
|
dnn_model_path = None
|
||||||
|
try:
|
||||||
|
dnn_model_path = autocrop.download_and_cache_models()
|
||||||
|
except Exception:
|
||||||
|
errors.report("Unable to load face detection model for auto crop selection. Falling back to lower quality haar method.", exc_info=True)
|
||||||
|
|
||||||
|
autocrop_settings = autocrop.Settings(
|
||||||
|
crop_width=pp.shared.target_width,
|
||||||
|
crop_height=pp.shared.target_height,
|
||||||
|
face_points_weight=face_weight,
|
||||||
|
entropy_points_weight=entropy_weight,
|
||||||
|
corner_points_weight=edges_weight,
|
||||||
|
annotate_image=debug,
|
||||||
|
dnn_model_path=dnn_model_path,
|
||||||
|
)
|
||||||
|
|
||||||
|
result, *others = autocrop.crop_image(pp.image, autocrop_settings)
|
||||||
|
|
||||||
|
pp.image = result
|
||||||
|
pp.extra_images = [pp.create_copy(x, nametags=["focal-crop-debug"], disable_processing=True) for x in others]
|
||||||
|
|
@ -0,0 +1,71 @@
|
|||||||
|
import math
|
||||||
|
|
||||||
|
from modules import scripts_postprocessing, ui_components
|
||||||
|
import gradio as gr
|
||||||
|
|
||||||
|
|
||||||
|
def split_pic(image, inverse_xy, width, height, overlap_ratio):
|
||||||
|
if inverse_xy:
|
||||||
|
from_w, from_h = image.height, image.width
|
||||||
|
to_w, to_h = height, width
|
||||||
|
else:
|
||||||
|
from_w, from_h = image.width, image.height
|
||||||
|
to_w, to_h = width, height
|
||||||
|
h = from_h * to_w // from_w
|
||||||
|
if inverse_xy:
|
||||||
|
image = image.resize((h, to_w))
|
||||||
|
else:
|
||||||
|
image = image.resize((to_w, h))
|
||||||
|
|
||||||
|
split_count = math.ceil((h - to_h * overlap_ratio) / (to_h * (1.0 - overlap_ratio)))
|
||||||
|
y_step = (h - to_h) / (split_count - 1)
|
||||||
|
for i in range(split_count):
|
||||||
|
y = int(y_step * i)
|
||||||
|
if inverse_xy:
|
||||||
|
splitted = image.crop((y, 0, y + to_h, to_w))
|
||||||
|
else:
|
||||||
|
splitted = image.crop((0, y, to_w, y + to_h))
|
||||||
|
yield splitted
|
||||||
|
|
||||||
|
|
||||||
|
class ScriptPostprocessingSplitOversized(scripts_postprocessing.ScriptPostprocessing):
|
||||||
|
name = "Split oversized images"
|
||||||
|
order = 4000
|
||||||
|
|
||||||
|
def ui(self):
|
||||||
|
with ui_components.InputAccordion(False, label="Split oversized images") as enable:
|
||||||
|
with gr.Row():
|
||||||
|
split_threshold = gr.Slider(label='Threshold', value=0.5, minimum=0.0, maximum=1.0, step=0.05, elem_id="postprocess_split_threshold")
|
||||||
|
overlap_ratio = gr.Slider(label='Overlap ratio', value=0.2, minimum=0.0, maximum=0.9, step=0.05, elem_id="postprocess_overlap_ratio")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"enable": enable,
|
||||||
|
"split_threshold": split_threshold,
|
||||||
|
"overlap_ratio": overlap_ratio,
|
||||||
|
}
|
||||||
|
|
||||||
|
def process(self, pp: scripts_postprocessing.PostprocessedImage, enable, split_threshold, overlap_ratio):
|
||||||
|
if not enable:
|
||||||
|
return
|
||||||
|
|
||||||
|
width = pp.shared.target_width
|
||||||
|
height = pp.shared.target_height
|
||||||
|
|
||||||
|
if not width or not height:
|
||||||
|
return
|
||||||
|
|
||||||
|
if pp.image.height > pp.image.width:
|
||||||
|
ratio = (pp.image.width * height) / (pp.image.height * width)
|
||||||
|
inverse_xy = False
|
||||||
|
else:
|
||||||
|
ratio = (pp.image.height * width) / (pp.image.width * height)
|
||||||
|
inverse_xy = True
|
||||||
|
|
||||||
|
if ratio >= 1.0 or ratio > split_threshold:
|
||||||
|
return
|
||||||
|
|
||||||
|
result, *others = split_pic(pp.image, inverse_xy, width, height, overlap_ratio)
|
||||||
|
|
||||||
|
pp.image = result
|
||||||
|
pp.extra_images = [pp.create_copy(x) for x in others]
|
||||||
|
|
@ -4,39 +4,39 @@
|
|||||||
// If there's a mismatch, the keyword counter turns red and if you hover on it, a tooltip tells you what's wrong.
|
// If there's a mismatch, the keyword counter turns red and if you hover on it, a tooltip tells you what's wrong.
|
||||||
|
|
||||||
function checkBrackets(textArea, counterElt) {
|
function checkBrackets(textArea, counterElt) {
|
||||||
var counts = {};
|
var counts = {};
|
||||||
(textArea.value.match(/[(){}\[\]]/g) || []).forEach(bracket => {
|
(textArea.value.match(/[(){}[\]]/g) || []).forEach(bracket => {
|
||||||
counts[bracket] = (counts[bracket] || 0) + 1;
|
counts[bracket] = (counts[bracket] || 0) + 1;
|
||||||
});
|
});
|
||||||
var errors = [];
|
var errors = [];
|
||||||
|
|
||||||
function checkPair(open, close, kind) {
|
function checkPair(open, close, kind) {
|
||||||
if (counts[open] !== counts[close]) {
|
if (counts[open] !== counts[close]) {
|
||||||
errors.push(
|
errors.push(
|
||||||
`${open}...${close} - Detected ${counts[open] || 0} opening and ${counts[close] || 0} closing ${kind}.`
|
`${open}...${close} - Detected ${counts[open] || 0} opening and ${counts[close] || 0} closing ${kind}.`
|
||||||
);
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
checkPair('(', ')', 'round brackets');
|
checkPair('(', ')', 'round brackets');
|
||||||
checkPair('[', ']', 'square brackets');
|
checkPair('[', ']', 'square brackets');
|
||||||
checkPair('{', '}', 'curly brackets');
|
checkPair('{', '}', 'curly brackets');
|
||||||
counterElt.title = errors.join('\n');
|
counterElt.title = errors.join('\n');
|
||||||
counterElt.classList.toggle('error', errors.length !== 0);
|
counterElt.classList.toggle('error', errors.length !== 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
function setupBracketChecking(id_prompt, id_counter) {
|
function setupBracketChecking(id_prompt, id_counter) {
|
||||||
var textarea = gradioApp().querySelector("#" + id_prompt + " > label > textarea");
|
var textarea = gradioApp().querySelector("#" + id_prompt + " > label > textarea");
|
||||||
var counter = gradioApp().getElementById(id_counter)
|
var counter = gradioApp().getElementById(id_counter);
|
||||||
|
|
||||||
if (textarea && counter) {
|
if (textarea && counter) {
|
||||||
textarea.addEventListener("input", () => checkBrackets(textarea, counter));
|
textarea.addEventListener("input", () => checkBrackets(textarea, counter));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
onUiLoaded(function () {
|
onUiLoaded(function() {
|
||||||
setupBracketChecking('txt2img_prompt', 'txt2img_token_counter');
|
setupBracketChecking('txt2img_prompt', 'txt2img_token_counter');
|
||||||
setupBracketChecking('txt2img_neg_prompt', 'txt2img_negative_token_counter');
|
setupBracketChecking('txt2img_neg_prompt', 'txt2img_negative_token_counter');
|
||||||
setupBracketChecking('img2img_prompt', 'img2img_token_counter');
|
setupBracketChecking('img2img_prompt', 'img2img_token_counter');
|
||||||
setupBracketChecking('img2img_neg_prompt', 'img2img_negative_token_counter');
|
setupBracketChecking('img2img_neg_prompt', 'img2img_negative_token_counter');
|
||||||
});
|
});
|
||||||
|
760
extensions-builtin/soft-inpainting/scripts/soft_inpainting.py
Normal file
760
extensions-builtin/soft-inpainting/scripts/soft_inpainting.py
Normal file
@ -0,0 +1,760 @@
|
|||||||
|
import numpy as np
|
||||||
|
import gradio as gr
|
||||||
|
import math
|
||||||
|
from modules.ui_components import InputAccordion
|
||||||
|
import modules.scripts as scripts
|
||||||
|
from modules.torch_utils import float64
|
||||||
|
|
||||||
|
|
||||||
|
class SoftInpaintingSettings:
|
||||||
|
def __init__(self,
|
||||||
|
mask_blend_power,
|
||||||
|
mask_blend_scale,
|
||||||
|
inpaint_detail_preservation,
|
||||||
|
composite_mask_influence,
|
||||||
|
composite_difference_threshold,
|
||||||
|
composite_difference_contrast):
|
||||||
|
self.mask_blend_power = mask_blend_power
|
||||||
|
self.mask_blend_scale = mask_blend_scale
|
||||||
|
self.inpaint_detail_preservation = inpaint_detail_preservation
|
||||||
|
self.composite_mask_influence = composite_mask_influence
|
||||||
|
self.composite_difference_threshold = composite_difference_threshold
|
||||||
|
self.composite_difference_contrast = composite_difference_contrast
|
||||||
|
|
||||||
|
def add_generation_params(self, dest):
|
||||||
|
dest[enabled_gen_param_label] = True
|
||||||
|
dest[gen_param_labels.mask_blend_power] = self.mask_blend_power
|
||||||
|
dest[gen_param_labels.mask_blend_scale] = self.mask_blend_scale
|
||||||
|
dest[gen_param_labels.inpaint_detail_preservation] = self.inpaint_detail_preservation
|
||||||
|
dest[gen_param_labels.composite_mask_influence] = self.composite_mask_influence
|
||||||
|
dest[gen_param_labels.composite_difference_threshold] = self.composite_difference_threshold
|
||||||
|
dest[gen_param_labels.composite_difference_contrast] = self.composite_difference_contrast
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------- Methods -------------------
|
||||||
|
|
||||||
|
def processing_uses_inpainting(p):
|
||||||
|
# TODO: Figure out a better way to determine if inpainting is being used by p
|
||||||
|
if getattr(p, "image_mask", None) is not None:
|
||||||
|
return True
|
||||||
|
|
||||||
|
if getattr(p, "mask", None) is not None:
|
||||||
|
return True
|
||||||
|
|
||||||
|
if getattr(p, "nmask", None) is not None:
|
||||||
|
return True
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def latent_blend(settings, a, b, t):
|
||||||
|
"""
|
||||||
|
Interpolates two latent image representations according to the parameter t,
|
||||||
|
where the interpolated vectors' magnitudes are also interpolated separately.
|
||||||
|
The "detail_preservation" factor biases the magnitude interpolation towards
|
||||||
|
the larger of the two magnitudes.
|
||||||
|
"""
|
||||||
|
import torch
|
||||||
|
|
||||||
|
# NOTE: We use inplace operations wherever possible.
|
||||||
|
|
||||||
|
if len(t.shape) == 3:
|
||||||
|
# [4][w][h] to [1][4][w][h]
|
||||||
|
t2 = t.unsqueeze(0)
|
||||||
|
# [4][w][h] to [1][1][w][h] - the [4] seem redundant.
|
||||||
|
t3 = t[0].unsqueeze(0).unsqueeze(0)
|
||||||
|
else:
|
||||||
|
t2 = t
|
||||||
|
t3 = t[:, 0][:, None]
|
||||||
|
|
||||||
|
one_minus_t2 = 1 - t2
|
||||||
|
one_minus_t3 = 1 - t3
|
||||||
|
|
||||||
|
# Linearly interpolate the image vectors.
|
||||||
|
a_scaled = a * one_minus_t2
|
||||||
|
b_scaled = b * t2
|
||||||
|
image_interp = a_scaled
|
||||||
|
image_interp.add_(b_scaled)
|
||||||
|
result_type = image_interp.dtype
|
||||||
|
del a_scaled, b_scaled, t2, one_minus_t2
|
||||||
|
|
||||||
|
# Calculate the magnitude of the interpolated vectors. (We will remove this magnitude.)
|
||||||
|
# 64-bit operations are used here to allow large exponents.
|
||||||
|
current_magnitude = torch.norm(image_interp, p=2, dim=1, keepdim=True).to(float64(image_interp)).add_(0.00001)
|
||||||
|
|
||||||
|
# Interpolate the powered magnitudes, then un-power them (bring them back to a power of 1).
|
||||||
|
a_magnitude = torch.norm(a, p=2, dim=1, keepdim=True).to(float64(a)).pow_(settings.inpaint_detail_preservation) * one_minus_t3
|
||||||
|
b_magnitude = torch.norm(b, p=2, dim=1, keepdim=True).to(float64(b)).pow_(settings.inpaint_detail_preservation) * t3
|
||||||
|
desired_magnitude = a_magnitude
|
||||||
|
desired_magnitude.add_(b_magnitude).pow_(1 / settings.inpaint_detail_preservation)
|
||||||
|
del a_magnitude, b_magnitude, t3, one_minus_t3
|
||||||
|
|
||||||
|
# Change the linearly interpolated image vectors' magnitudes to the value we want.
|
||||||
|
# This is the last 64-bit operation.
|
||||||
|
image_interp_scaling_factor = desired_magnitude
|
||||||
|
image_interp_scaling_factor.div_(current_magnitude)
|
||||||
|
image_interp_scaling_factor = image_interp_scaling_factor.to(result_type)
|
||||||
|
image_interp_scaled = image_interp
|
||||||
|
image_interp_scaled.mul_(image_interp_scaling_factor)
|
||||||
|
del current_magnitude
|
||||||
|
del desired_magnitude
|
||||||
|
del image_interp
|
||||||
|
del image_interp_scaling_factor
|
||||||
|
del result_type
|
||||||
|
|
||||||
|
return image_interp_scaled
|
||||||
|
|
||||||
|
|
||||||
|
def get_modified_nmask(settings, nmask, sigma):
|
||||||
|
"""
|
||||||
|
Converts a negative mask representing the transparency of the original latent vectors being overlaid
|
||||||
|
to a mask that is scaled according to the denoising strength for this step.
|
||||||
|
|
||||||
|
Where:
|
||||||
|
0 = fully opaque, infinite density, fully masked
|
||||||
|
1 = fully transparent, zero density, fully unmasked
|
||||||
|
|
||||||
|
We bring this transparency to a power, as this allows one to simulate N number of blending operations
|
||||||
|
where N can be any positive real value. Using this one can control the balance of influence between
|
||||||
|
the denoiser and the original latents according to the sigma value.
|
||||||
|
|
||||||
|
NOTE: "mask" is not used
|
||||||
|
"""
|
||||||
|
import torch
|
||||||
|
return torch.pow(nmask, (sigma ** settings.mask_blend_power) * settings.mask_blend_scale)
|
||||||
|
|
||||||
|
|
||||||
|
def apply_adaptive_masks(
|
||||||
|
settings: SoftInpaintingSettings,
|
||||||
|
nmask,
|
||||||
|
latent_orig,
|
||||||
|
latent_processed,
|
||||||
|
overlay_images,
|
||||||
|
width, height,
|
||||||
|
paste_to):
|
||||||
|
import torch
|
||||||
|
import modules.processing as proc
|
||||||
|
import modules.images as images
|
||||||
|
from PIL import Image, ImageOps, ImageFilter
|
||||||
|
|
||||||
|
# TODO: Bias the blending according to the latent mask, add adjustable parameter for bias control.
|
||||||
|
if len(nmask.shape) == 3:
|
||||||
|
latent_mask = nmask[0].float()
|
||||||
|
else:
|
||||||
|
latent_mask = nmask[:, 0].float()
|
||||||
|
# convert the original mask into a form we use to scale distances for thresholding
|
||||||
|
mask_scalar = 1 - (torch.clamp(latent_mask, min=0, max=1) ** (settings.mask_blend_scale / 2))
|
||||||
|
mask_scalar = (0.5 * (1 - settings.composite_mask_influence)
|
||||||
|
+ mask_scalar * settings.composite_mask_influence)
|
||||||
|
mask_scalar = mask_scalar / (1.00001 - mask_scalar)
|
||||||
|
mask_scalar = mask_scalar.cpu().numpy()
|
||||||
|
|
||||||
|
latent_distance = torch.norm(latent_processed - latent_orig, p=2, dim=1)
|
||||||
|
|
||||||
|
kernel, kernel_center = get_gaussian_kernel(stddev_radius=1.5, max_radius=2)
|
||||||
|
|
||||||
|
masks_for_overlay = []
|
||||||
|
|
||||||
|
for i, (distance_map, overlay_image) in enumerate(zip(latent_distance, overlay_images)):
|
||||||
|
converted_mask = distance_map.float().cpu().numpy()
|
||||||
|
converted_mask = weighted_histogram_filter(converted_mask, kernel, kernel_center,
|
||||||
|
percentile_min=0.9, percentile_max=1, min_width=1)
|
||||||
|
converted_mask = weighted_histogram_filter(converted_mask, kernel, kernel_center,
|
||||||
|
percentile_min=0.25, percentile_max=0.75, min_width=1)
|
||||||
|
|
||||||
|
# The distance at which opacity of original decreases to 50%
|
||||||
|
if len(mask_scalar.shape) == 3:
|
||||||
|
if mask_scalar.shape[0] > i:
|
||||||
|
half_weighted_distance = settings.composite_difference_threshold * mask_scalar[i]
|
||||||
|
else:
|
||||||
|
half_weighted_distance = settings.composite_difference_threshold * mask_scalar[0]
|
||||||
|
else:
|
||||||
|
half_weighted_distance = settings.composite_difference_threshold * mask_scalar
|
||||||
|
|
||||||
|
converted_mask = converted_mask / half_weighted_distance
|
||||||
|
|
||||||
|
converted_mask = 1 / (1 + converted_mask ** settings.composite_difference_contrast)
|
||||||
|
converted_mask = smootherstep(converted_mask)
|
||||||
|
converted_mask = 1 - converted_mask
|
||||||
|
converted_mask = 255. * converted_mask
|
||||||
|
converted_mask = converted_mask.astype(np.uint8)
|
||||||
|
converted_mask = Image.fromarray(converted_mask)
|
||||||
|
converted_mask = images.resize_image(2, converted_mask, width, height)
|
||||||
|
converted_mask = proc.create_binary_mask(converted_mask, round=False)
|
||||||
|
|
||||||
|
# Remove aliasing artifacts using a gaussian blur.
|
||||||
|
converted_mask = converted_mask.filter(ImageFilter.GaussianBlur(radius=4))
|
||||||
|
|
||||||
|
# Expand the mask to fit the whole image if needed.
|
||||||
|
if paste_to is not None:
|
||||||
|
converted_mask = proc.uncrop(converted_mask,
|
||||||
|
(overlay_image.width, overlay_image.height),
|
||||||
|
paste_to)
|
||||||
|
|
||||||
|
masks_for_overlay.append(converted_mask)
|
||||||
|
|
||||||
|
image_masked = Image.new('RGBa', (overlay_image.width, overlay_image.height))
|
||||||
|
image_masked.paste(overlay_image.convert("RGBA").convert("RGBa"),
|
||||||
|
mask=ImageOps.invert(converted_mask.convert('L')))
|
||||||
|
|
||||||
|
overlay_images[i] = image_masked.convert('RGBA')
|
||||||
|
|
||||||
|
return masks_for_overlay
|
||||||
|
|
||||||
|
|
||||||
|
def apply_masks(
|
||||||
|
settings,
|
||||||
|
nmask,
|
||||||
|
overlay_images,
|
||||||
|
width, height,
|
||||||
|
paste_to):
|
||||||
|
import torch
|
||||||
|
import modules.processing as proc
|
||||||
|
import modules.images as images
|
||||||
|
from PIL import Image, ImageOps, ImageFilter
|
||||||
|
|
||||||
|
converted_mask = nmask[0].float()
|
||||||
|
converted_mask = torch.clamp(converted_mask, min=0, max=1).pow_(settings.mask_blend_scale / 2)
|
||||||
|
converted_mask = 255. * converted_mask
|
||||||
|
converted_mask = converted_mask.cpu().numpy().astype(np.uint8)
|
||||||
|
converted_mask = Image.fromarray(converted_mask)
|
||||||
|
converted_mask = images.resize_image(2, converted_mask, width, height)
|
||||||
|
converted_mask = proc.create_binary_mask(converted_mask, round=False)
|
||||||
|
|
||||||
|
# Remove aliasing artifacts using a gaussian blur.
|
||||||
|
converted_mask = converted_mask.filter(ImageFilter.GaussianBlur(radius=4))
|
||||||
|
|
||||||
|
# Expand the mask to fit the whole image if needed.
|
||||||
|
if paste_to is not None:
|
||||||
|
converted_mask = proc.uncrop(converted_mask,
|
||||||
|
(width, height),
|
||||||
|
paste_to)
|
||||||
|
|
||||||
|
masks_for_overlay = []
|
||||||
|
|
||||||
|
for i, overlay_image in enumerate(overlay_images):
|
||||||
|
masks_for_overlay[i] = converted_mask
|
||||||
|
|
||||||
|
image_masked = Image.new('RGBa', (overlay_image.width, overlay_image.height))
|
||||||
|
image_masked.paste(overlay_image.convert("RGBA").convert("RGBa"),
|
||||||
|
mask=ImageOps.invert(converted_mask.convert('L')))
|
||||||
|
|
||||||
|
overlay_images[i] = image_masked.convert('RGBA')
|
||||||
|
|
||||||
|
return masks_for_overlay
|
||||||
|
|
||||||
|
|
||||||
|
def weighted_histogram_filter(img, kernel, kernel_center, percentile_min=0.0, percentile_max=1.0, min_width=1.0):
|
||||||
|
"""
|
||||||
|
Generalization convolution filter capable of applying
|
||||||
|
weighted mean, median, maximum, and minimum filters
|
||||||
|
parametrically using an arbitrary kernel.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
img (nparray):
|
||||||
|
The image, a 2-D array of floats, to which the filter is being applied.
|
||||||
|
kernel (nparray):
|
||||||
|
The kernel, a 2-D array of floats.
|
||||||
|
kernel_center (nparray):
|
||||||
|
The kernel center coordinate, a 1-D array with two elements.
|
||||||
|
percentile_min (float):
|
||||||
|
The lower bound of the histogram window used by the filter,
|
||||||
|
from 0 to 1.
|
||||||
|
percentile_max (float):
|
||||||
|
The upper bound of the histogram window used by the filter,
|
||||||
|
from 0 to 1.
|
||||||
|
min_width (float):
|
||||||
|
The minimum size of the histogram window bounds, in weight units.
|
||||||
|
Must be greater than 0.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(nparray): A filtered copy of the input image "img", a 2-D array of floats.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Converts an index tuple into a vector.
|
||||||
|
def vec(x):
|
||||||
|
return np.array(x)
|
||||||
|
|
||||||
|
kernel_min = -kernel_center
|
||||||
|
kernel_max = vec(kernel.shape) - kernel_center
|
||||||
|
|
||||||
|
def weighted_histogram_filter_single(idx):
|
||||||
|
idx = vec(idx)
|
||||||
|
min_index = np.maximum(0, idx + kernel_min)
|
||||||
|
max_index = np.minimum(vec(img.shape), idx + kernel_max)
|
||||||
|
window_shape = max_index - min_index
|
||||||
|
|
||||||
|
class WeightedElement:
|
||||||
|
"""
|
||||||
|
An element of the histogram, its weight
|
||||||
|
and bounds.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, value, weight):
|
||||||
|
self.value: float = value
|
||||||
|
self.weight: float = weight
|
||||||
|
self.window_min: float = 0.0
|
||||||
|
self.window_max: float = 1.0
|
||||||
|
|
||||||
|
# Collect the values in the image as WeightedElements,
|
||||||
|
# weighted by their corresponding kernel values.
|
||||||
|
values = []
|
||||||
|
for window_tup in np.ndindex(tuple(window_shape)):
|
||||||
|
window_index = vec(window_tup)
|
||||||
|
image_index = window_index + min_index
|
||||||
|
centered_kernel_index = image_index - idx
|
||||||
|
kernel_index = centered_kernel_index + kernel_center
|
||||||
|
element = WeightedElement(img[tuple(image_index)], kernel[tuple(kernel_index)])
|
||||||
|
values.append(element)
|
||||||
|
|
||||||
|
def sort_key(x: WeightedElement):
|
||||||
|
return x.value
|
||||||
|
|
||||||
|
values.sort(key=sort_key)
|
||||||
|
|
||||||
|
# Calculate the height of the stack (sum)
|
||||||
|
# and each sample's range they occupy in the stack
|
||||||
|
sum = 0
|
||||||
|
for i in range(len(values)):
|
||||||
|
values[i].window_min = sum
|
||||||
|
sum += values[i].weight
|
||||||
|
values[i].window_max = sum
|
||||||
|
|
||||||
|
# Calculate what range of this stack ("window")
|
||||||
|
# we want to get the weighted average across.
|
||||||
|
window_min = sum * percentile_min
|
||||||
|
window_max = sum * percentile_max
|
||||||
|
window_width = window_max - window_min
|
||||||
|
|
||||||
|
# Ensure the window is within the stack and at least a certain size.
|
||||||
|
if window_width < min_width:
|
||||||
|
window_center = (window_min + window_max) / 2
|
||||||
|
window_min = window_center - min_width / 2
|
||||||
|
window_max = window_center + min_width / 2
|
||||||
|
|
||||||
|
if window_max > sum:
|
||||||
|
window_max = sum
|
||||||
|
window_min = sum - min_width
|
||||||
|
|
||||||
|
if window_min < 0:
|
||||||
|
window_min = 0
|
||||||
|
window_max = min_width
|
||||||
|
|
||||||
|
value = 0
|
||||||
|
value_weight = 0
|
||||||
|
|
||||||
|
# Get the weighted average of all the samples
|
||||||
|
# that overlap with the window, weighted
|
||||||
|
# by the size of their overlap.
|
||||||
|
for i in range(len(values)):
|
||||||
|
if window_min >= values[i].window_max:
|
||||||
|
continue
|
||||||
|
if window_max <= values[i].window_min:
|
||||||
|
break
|
||||||
|
|
||||||
|
s = max(window_min, values[i].window_min)
|
||||||
|
e = min(window_max, values[i].window_max)
|
||||||
|
w = e - s
|
||||||
|
|
||||||
|
value += values[i].value * w
|
||||||
|
value_weight += w
|
||||||
|
|
||||||
|
return value / value_weight if value_weight != 0 else 0
|
||||||
|
|
||||||
|
img_out = img.copy()
|
||||||
|
|
||||||
|
# Apply the kernel operation over each pixel.
|
||||||
|
for index in np.ndindex(img.shape):
|
||||||
|
img_out[index] = weighted_histogram_filter_single(index)
|
||||||
|
|
||||||
|
return img_out
|
||||||
|
|
||||||
|
|
||||||
|
def smoothstep(x):
|
||||||
|
"""
|
||||||
|
The smoothstep function, input should be clamped to 0-1 range.
|
||||||
|
Turns a diagonal line (f(x) = x) into a sigmoid-like curve.
|
||||||
|
"""
|
||||||
|
return x * x * (3 - 2 * x)
|
||||||
|
|
||||||
|
|
||||||
|
def smootherstep(x):
|
||||||
|
"""
|
||||||
|
The smootherstep function, input should be clamped to 0-1 range.
|
||||||
|
Turns a diagonal line (f(x) = x) into a sigmoid-like curve.
|
||||||
|
"""
|
||||||
|
return x * x * x * (x * (6 * x - 15) + 10)
|
||||||
|
|
||||||
|
|
||||||
|
def get_gaussian_kernel(stddev_radius=1.0, max_radius=2):
|
||||||
|
"""
|
||||||
|
Creates a Gaussian kernel with thresholded edges.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
stddev_radius (float):
|
||||||
|
Standard deviation of the gaussian kernel, in pixels.
|
||||||
|
max_radius (int):
|
||||||
|
The size of the filter kernel. The number of pixels is (max_radius*2+1) ** 2.
|
||||||
|
The kernel is thresholded so that any values one pixel beyond this radius
|
||||||
|
is weighted at 0.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(nparray, nparray): A kernel array (shape: (N, N)), its center coordinate (shape: (2))
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Evaluates a 0-1 normalized gaussian function for a given square distance from the mean.
|
||||||
|
def gaussian(sqr_mag):
|
||||||
|
return math.exp(-sqr_mag / (stddev_radius * stddev_radius))
|
||||||
|
|
||||||
|
# Helper function for converting a tuple to an array.
|
||||||
|
def vec(x):
|
||||||
|
return np.array(x)
|
||||||
|
|
||||||
|
"""
|
||||||
|
Since a gaussian is unbounded, we need to limit ourselves
|
||||||
|
to a finite range.
|
||||||
|
We taper the ends off at the end of that range so they equal zero
|
||||||
|
while preserving the maximum value of 1 at the mean.
|
||||||
|
"""
|
||||||
|
zero_radius = max_radius + 1.0
|
||||||
|
gauss_zero = gaussian(zero_radius * zero_radius)
|
||||||
|
gauss_kernel_scale = 1 / (1 - gauss_zero)
|
||||||
|
|
||||||
|
def gaussian_kernel_func(coordinate):
|
||||||
|
x = coordinate[0] ** 2.0 + coordinate[1] ** 2.0
|
||||||
|
x = gaussian(x)
|
||||||
|
x -= gauss_zero
|
||||||
|
x *= gauss_kernel_scale
|
||||||
|
x = max(0.0, x)
|
||||||
|
return x
|
||||||
|
|
||||||
|
size = max_radius * 2 + 1
|
||||||
|
kernel_center = max_radius
|
||||||
|
kernel = np.zeros((size, size))
|
||||||
|
|
||||||
|
for index in np.ndindex(kernel.shape):
|
||||||
|
kernel[index] = gaussian_kernel_func(vec(index) - kernel_center)
|
||||||
|
|
||||||
|
return kernel, kernel_center
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------- Constants -------------------
|
||||||
|
|
||||||
|
|
||||||
|
default = SoftInpaintingSettings(1, 0.5, 4, 0, 0.5, 2)
|
||||||
|
|
||||||
|
enabled_ui_label = "Soft inpainting"
|
||||||
|
enabled_gen_param_label = "Soft inpainting enabled"
|
||||||
|
enabled_el_id = "soft_inpainting_enabled"
|
||||||
|
|
||||||
|
ui_labels = SoftInpaintingSettings(
|
||||||
|
"Schedule bias",
|
||||||
|
"Preservation strength",
|
||||||
|
"Transition contrast boost",
|
||||||
|
"Mask influence",
|
||||||
|
"Difference threshold",
|
||||||
|
"Difference contrast")
|
||||||
|
|
||||||
|
ui_info = SoftInpaintingSettings(
|
||||||
|
"Shifts when preservation of original content occurs during denoising.",
|
||||||
|
"How strongly partially masked content should be preserved.",
|
||||||
|
"Amplifies the contrast that may be lost in partially masked regions.",
|
||||||
|
"How strongly the original mask should bias the difference threshold.",
|
||||||
|
"How much an image region can change before the original pixels are not blended in anymore.",
|
||||||
|
"How sharp the transition should be between blended and not blended.")
|
||||||
|
|
||||||
|
gen_param_labels = SoftInpaintingSettings(
|
||||||
|
"Soft inpainting schedule bias",
|
||||||
|
"Soft inpainting preservation strength",
|
||||||
|
"Soft inpainting transition contrast boost",
|
||||||
|
"Soft inpainting mask influence",
|
||||||
|
"Soft inpainting difference threshold",
|
||||||
|
"Soft inpainting difference contrast")
|
||||||
|
|
||||||
|
el_ids = SoftInpaintingSettings(
|
||||||
|
"mask_blend_power",
|
||||||
|
"mask_blend_scale",
|
||||||
|
"inpaint_detail_preservation",
|
||||||
|
"composite_mask_influence",
|
||||||
|
"composite_difference_threshold",
|
||||||
|
"composite_difference_contrast")
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------- Script -------------------
|
||||||
|
|
||||||
|
|
||||||
|
class Script(scripts.Script):
|
||||||
|
def __init__(self):
|
||||||
|
self.section = "inpaint"
|
||||||
|
self.masks_for_overlay = None
|
||||||
|
self.overlay_images = None
|
||||||
|
|
||||||
|
def title(self):
|
||||||
|
return "Soft Inpainting"
|
||||||
|
|
||||||
|
def show(self, is_img2img):
|
||||||
|
return scripts.AlwaysVisible if is_img2img else False
|
||||||
|
|
||||||
|
def ui(self, is_img2img):
|
||||||
|
if not is_img2img:
|
||||||
|
return
|
||||||
|
|
||||||
|
with InputAccordion(False, label=enabled_ui_label, elem_id=enabled_el_id) as soft_inpainting_enabled:
|
||||||
|
with gr.Group():
|
||||||
|
gr.Markdown(
|
||||||
|
"""
|
||||||
|
Soft inpainting allows you to **seamlessly blend original content with inpainted content** according to the mask opacity.
|
||||||
|
**High _Mask blur_** values are recommended!
|
||||||
|
""")
|
||||||
|
|
||||||
|
power = \
|
||||||
|
gr.Slider(label=ui_labels.mask_blend_power,
|
||||||
|
info=ui_info.mask_blend_power,
|
||||||
|
minimum=0,
|
||||||
|
maximum=8,
|
||||||
|
step=0.1,
|
||||||
|
value=default.mask_blend_power,
|
||||||
|
elem_id=el_ids.mask_blend_power)
|
||||||
|
scale = \
|
||||||
|
gr.Slider(label=ui_labels.mask_blend_scale,
|
||||||
|
info=ui_info.mask_blend_scale,
|
||||||
|
minimum=0,
|
||||||
|
maximum=8,
|
||||||
|
step=0.05,
|
||||||
|
value=default.mask_blend_scale,
|
||||||
|
elem_id=el_ids.mask_blend_scale)
|
||||||
|
detail = \
|
||||||
|
gr.Slider(label=ui_labels.inpaint_detail_preservation,
|
||||||
|
info=ui_info.inpaint_detail_preservation,
|
||||||
|
minimum=1,
|
||||||
|
maximum=32,
|
||||||
|
step=0.5,
|
||||||
|
value=default.inpaint_detail_preservation,
|
||||||
|
elem_id=el_ids.inpaint_detail_preservation)
|
||||||
|
|
||||||
|
gr.Markdown(
|
||||||
|
"""
|
||||||
|
### Pixel Composite Settings
|
||||||
|
""")
|
||||||
|
|
||||||
|
mask_inf = \
|
||||||
|
gr.Slider(label=ui_labels.composite_mask_influence,
|
||||||
|
info=ui_info.composite_mask_influence,
|
||||||
|
minimum=0,
|
||||||
|
maximum=1,
|
||||||
|
step=0.05,
|
||||||
|
value=default.composite_mask_influence,
|
||||||
|
elem_id=el_ids.composite_mask_influence)
|
||||||
|
|
||||||
|
dif_thresh = \
|
||||||
|
gr.Slider(label=ui_labels.composite_difference_threshold,
|
||||||
|
info=ui_info.composite_difference_threshold,
|
||||||
|
minimum=0,
|
||||||
|
maximum=8,
|
||||||
|
step=0.25,
|
||||||
|
value=default.composite_difference_threshold,
|
||||||
|
elem_id=el_ids.composite_difference_threshold)
|
||||||
|
|
||||||
|
dif_contr = \
|
||||||
|
gr.Slider(label=ui_labels.composite_difference_contrast,
|
||||||
|
info=ui_info.composite_difference_contrast,
|
||||||
|
minimum=0,
|
||||||
|
maximum=8,
|
||||||
|
step=0.25,
|
||||||
|
value=default.composite_difference_contrast,
|
||||||
|
elem_id=el_ids.composite_difference_contrast)
|
||||||
|
|
||||||
|
with gr.Accordion("Help", open=False):
|
||||||
|
gr.Markdown(
|
||||||
|
f"""
|
||||||
|
### {ui_labels.mask_blend_power}
|
||||||
|
|
||||||
|
The blending strength of original content is scaled proportionally with the decreasing noise level values at each step (sigmas).
|
||||||
|
This ensures that the influence of the denoiser and original content preservation is roughly balanced at each step.
|
||||||
|
This balance can be shifted using this parameter, controlling whether earlier or later steps have stronger preservation.
|
||||||
|
|
||||||
|
- **Below 1**: Stronger preservation near the end (with low sigma)
|
||||||
|
- **1**: Balanced (proportional to sigma)
|
||||||
|
- **Above 1**: Stronger preservation in the beginning (with high sigma)
|
||||||
|
""")
|
||||||
|
gr.Markdown(
|
||||||
|
f"""
|
||||||
|
### {ui_labels.mask_blend_scale}
|
||||||
|
|
||||||
|
Skews whether partially masked image regions should be more likely to preserve the original content or favor inpainted content.
|
||||||
|
This may need to be adjusted depending on the {ui_labels.mask_blend_power}, CFG Scale, prompt and Denoising strength.
|
||||||
|
|
||||||
|
- **Low values**: Favors generated content.
|
||||||
|
- **High values**: Favors original content.
|
||||||
|
""")
|
||||||
|
gr.Markdown(
|
||||||
|
f"""
|
||||||
|
### {ui_labels.inpaint_detail_preservation}
|
||||||
|
|
||||||
|
This parameter controls how the original latent vectors and denoised latent vectors are interpolated.
|
||||||
|
With higher values, the magnitude of the resulting blended vector will be closer to the maximum of the two interpolated vectors.
|
||||||
|
This can prevent the loss of contrast that occurs with linear interpolation.
|
||||||
|
|
||||||
|
- **Low values**: Softer blending, details may fade.
|
||||||
|
- **High values**: Stronger contrast, may over-saturate colors.
|
||||||
|
""")
|
||||||
|
|
||||||
|
gr.Markdown(
|
||||||
|
"""
|
||||||
|
## Pixel Composite Settings
|
||||||
|
|
||||||
|
Masks are generated based on how much a part of the image changed after denoising.
|
||||||
|
These masks are used to blend the original and final images together.
|
||||||
|
If the difference is low, the original pixels are used instead of the pixels returned by the inpainting process.
|
||||||
|
""")
|
||||||
|
|
||||||
|
gr.Markdown(
|
||||||
|
f"""
|
||||||
|
### {ui_labels.composite_mask_influence}
|
||||||
|
|
||||||
|
This parameter controls how much the mask should bias this sensitivity to difference.
|
||||||
|
|
||||||
|
- **0**: Ignore the mask, only consider differences in image content.
|
||||||
|
- **1**: Follow the mask closely despite image content changes.
|
||||||
|
""")
|
||||||
|
|
||||||
|
gr.Markdown(
|
||||||
|
f"""
|
||||||
|
### {ui_labels.composite_difference_threshold}
|
||||||
|
|
||||||
|
This value represents the difference at which the original pixels will have less than 50% opacity.
|
||||||
|
|
||||||
|
- **Low values**: Two images patches must be almost the same in order to retain original pixels.
|
||||||
|
- **High values**: Two images patches can be very different and still retain original pixels.
|
||||||
|
""")
|
||||||
|
|
||||||
|
gr.Markdown(
|
||||||
|
f"""
|
||||||
|
### {ui_labels.composite_difference_contrast}
|
||||||
|
|
||||||
|
This value represents the contrast between the opacity of the original and inpainted content.
|
||||||
|
|
||||||
|
- **Low values**: The blend will be more gradual and have longer transitions, but may cause ghosting.
|
||||||
|
- **High values**: Ghosting will be less common, but transitions may be very sudden.
|
||||||
|
""")
|
||||||
|
|
||||||
|
self.infotext_fields = [(soft_inpainting_enabled, enabled_gen_param_label),
|
||||||
|
(power, gen_param_labels.mask_blend_power),
|
||||||
|
(scale, gen_param_labels.mask_blend_scale),
|
||||||
|
(detail, gen_param_labels.inpaint_detail_preservation),
|
||||||
|
(mask_inf, gen_param_labels.composite_mask_influence),
|
||||||
|
(dif_thresh, gen_param_labels.composite_difference_threshold),
|
||||||
|
(dif_contr, gen_param_labels.composite_difference_contrast)]
|
||||||
|
|
||||||
|
self.paste_field_names = []
|
||||||
|
for _, field_name in self.infotext_fields:
|
||||||
|
self.paste_field_names.append(field_name)
|
||||||
|
|
||||||
|
return [soft_inpainting_enabled,
|
||||||
|
power,
|
||||||
|
scale,
|
||||||
|
detail,
|
||||||
|
mask_inf,
|
||||||
|
dif_thresh,
|
||||||
|
dif_contr]
|
||||||
|
|
||||||
|
def process(self, p, enabled, power, scale, detail_preservation, mask_inf, dif_thresh, dif_contr):
|
||||||
|
if not enabled:
|
||||||
|
return
|
||||||
|
|
||||||
|
if not processing_uses_inpainting(p):
|
||||||
|
return
|
||||||
|
|
||||||
|
# Shut off the rounding it normally does.
|
||||||
|
p.mask_round = False
|
||||||
|
|
||||||
|
settings = SoftInpaintingSettings(power, scale, detail_preservation, mask_inf, dif_thresh, dif_contr)
|
||||||
|
|
||||||
|
# p.extra_generation_params["Mask rounding"] = False
|
||||||
|
settings.add_generation_params(p.extra_generation_params)
|
||||||
|
|
||||||
|
def on_mask_blend(self, p, mba: scripts.MaskBlendArgs, enabled, power, scale, detail_preservation, mask_inf,
|
||||||
|
dif_thresh, dif_contr):
|
||||||
|
if not enabled:
|
||||||
|
return
|
||||||
|
|
||||||
|
if not processing_uses_inpainting(p):
|
||||||
|
return
|
||||||
|
|
||||||
|
if mba.is_final_blend:
|
||||||
|
mba.blended_latent = mba.current_latent
|
||||||
|
return
|
||||||
|
|
||||||
|
settings = SoftInpaintingSettings(power, scale, detail_preservation, mask_inf, dif_thresh, dif_contr)
|
||||||
|
|
||||||
|
# todo: Why is sigma 2D? Both values are the same.
|
||||||
|
mba.blended_latent = latent_blend(settings,
|
||||||
|
mba.init_latent,
|
||||||
|
mba.current_latent,
|
||||||
|
get_modified_nmask(settings, mba.nmask, mba.sigma[0]))
|
||||||
|
|
||||||
|
def post_sample(self, p, ps: scripts.PostSampleArgs, enabled, power, scale, detail_preservation, mask_inf,
|
||||||
|
dif_thresh, dif_contr):
|
||||||
|
if not enabled:
|
||||||
|
return
|
||||||
|
|
||||||
|
if not processing_uses_inpainting(p):
|
||||||
|
return
|
||||||
|
|
||||||
|
nmask = getattr(p, "nmask", None)
|
||||||
|
if nmask is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
from modules import images
|
||||||
|
from modules.shared import opts
|
||||||
|
|
||||||
|
settings = SoftInpaintingSettings(power, scale, detail_preservation, mask_inf, dif_thresh, dif_contr)
|
||||||
|
|
||||||
|
# since the original code puts holes in the existing overlay images,
|
||||||
|
# we have to rebuild them.
|
||||||
|
self.overlay_images = []
|
||||||
|
for img in p.init_images:
|
||||||
|
|
||||||
|
image = images.flatten(img, opts.img2img_background_color)
|
||||||
|
|
||||||
|
if p.paste_to is None and p.resize_mode != 3:
|
||||||
|
image = images.resize_image(p.resize_mode, image, p.width, p.height)
|
||||||
|
|
||||||
|
self.overlay_images.append(image.convert('RGBA'))
|
||||||
|
|
||||||
|
if len(p.init_images) == 1:
|
||||||
|
self.overlay_images = self.overlay_images * p.batch_size
|
||||||
|
|
||||||
|
if getattr(ps.samples, 'already_decoded', False):
|
||||||
|
self.masks_for_overlay = apply_masks(settings=settings,
|
||||||
|
nmask=nmask,
|
||||||
|
overlay_images=self.overlay_images,
|
||||||
|
width=p.width,
|
||||||
|
height=p.height,
|
||||||
|
paste_to=p.paste_to)
|
||||||
|
else:
|
||||||
|
self.masks_for_overlay = apply_adaptive_masks(settings=settings,
|
||||||
|
nmask=nmask,
|
||||||
|
latent_orig=p.init_latent,
|
||||||
|
latent_processed=ps.samples,
|
||||||
|
overlay_images=self.overlay_images,
|
||||||
|
width=p.width,
|
||||||
|
height=p.height,
|
||||||
|
paste_to=p.paste_to)
|
||||||
|
|
||||||
|
def postprocess_maskoverlay(self, p, ppmo: scripts.PostProcessMaskOverlayArgs, enabled, power, scale,
|
||||||
|
detail_preservation, mask_inf, dif_thresh, dif_contr):
|
||||||
|
if not enabled:
|
||||||
|
return
|
||||||
|
|
||||||
|
if not processing_uses_inpainting(p):
|
||||||
|
return
|
||||||
|
|
||||||
|
if self.masks_for_overlay is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
if self.overlay_images is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
ppmo.mask_for_overlay = self.masks_for_overlay[ppmo.index]
|
||||||
|
ppmo.overlay_image = self.overlay_images[ppmo.index]
|
@ -1,15 +1,9 @@
|
|||||||
<div class='card' style={style} onclick={card_clicked}>
|
<div class="card" style="{style}" onclick="{card_clicked}" data-name="{name}" {sort_keys}>
|
||||||
{metadata_button}
|
{background_image}
|
||||||
|
<div class="button-row">{copy_path_button}{metadata_button}{edit_button}</div>
|
||||||
<div class='actions'>
|
<div class="actions">
|
||||||
<div class='additional'>
|
<div class="additional">{search_terms}</div>
|
||||||
<ul>
|
<span class="name">{name}</span>
|
||||||
<a href="#" title="replace preview image with currently selected in gallery" onclick={save_card_preview}>replace preview</a>
|
<span class="description">{description}</span>
|
||||||
</ul>
|
|
||||||
<span style="display:none" class='search_term{serach_only}'>{search_term}</span>
|
|
||||||
</div>
|
|
||||||
<span class='name'>{name}</span>
|
|
||||||
<span class='description'>{description}</span>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
5
html/extra-networks-copy-path-button.html
Normal file
5
html/extra-networks-copy-path-button.html
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
<div class="copy-path-button card-button"
|
||||||
|
title="Copy path to clipboard"
|
||||||
|
onclick="extraNetworksCopyCardPath(event)"
|
||||||
|
data-clipboard-text="{filename}">
|
||||||
|
</div>
|
4
html/extra-networks-edit-item-button.html
Normal file
4
html/extra-networks-edit-item-button.html
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
<div class="edit-button card-button"
|
||||||
|
title="Edit metadata"
|
||||||
|
onclick="extraNetworksEditUserMetadata(event, '{tabname}', '{extra_networks_tabname}')">
|
||||||
|
</div>
|
4
html/extra-networks-metadata-button.html
Normal file
4
html/extra-networks-metadata-button.html
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
<div class="metadata-button card-button"
|
||||||
|
title="Show internal metadata"
|
||||||
|
onclick="extraNetworksRequestMetadata(event, '{extra_networks_tabname}')">
|
||||||
|
</div>
|
8
html/extra-networks-pane-dirs.html
Normal file
8
html/extra-networks-pane-dirs.html
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
<div class="extra-network-pane-content-dirs">
|
||||||
|
<div id='{tabname}_{extra_networks_tabname}_dirs' class='extra-network-dirs'>
|
||||||
|
{dirs_html}
|
||||||
|
</div>
|
||||||
|
<div id='{tabname}_{extra_networks_tabname}_cards' class='extra-network-cards'>
|
||||||
|
{items_html}
|
||||||
|
</div>
|
||||||
|
</div>
|
8
html/extra-networks-pane-tree.html
Normal file
8
html/extra-networks-pane-tree.html
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
<div class="extra-network-pane-content-tree resize-handle-row">
|
||||||
|
<div id='{tabname}_{extra_networks_tabname}_tree' class='extra-network-tree' style='flex-basis: {extra_networks_tree_view_default_width}px'>
|
||||||
|
{tree_html}
|
||||||
|
</div>
|
||||||
|
<div id='{tabname}_{extra_networks_tabname}_cards' class='extra-network-cards' style='flex-grow: 1;'>
|
||||||
|
{items_html}
|
||||||
|
</div>
|
||||||
|
</div>
|
81
html/extra-networks-pane.html
Normal file
81
html/extra-networks-pane.html
Normal file
@ -0,0 +1,81 @@
|
|||||||
|
<div id='{tabname}_{extra_networks_tabname}_pane' class='extra-network-pane {tree_view_div_default_display_class}'>
|
||||||
|
<div class="extra-network-control" id="{tabname}_{extra_networks_tabname}_controls" style="display:none" >
|
||||||
|
<div class="extra-network-control--search">
|
||||||
|
<input
|
||||||
|
id="{tabname}_{extra_networks_tabname}_extra_search"
|
||||||
|
class="extra-network-control--search-text"
|
||||||
|
type="search"
|
||||||
|
placeholder="Search"
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<small>Sort: </small>
|
||||||
|
<div
|
||||||
|
id="{tabname}_{extra_networks_tabname}_extra_sort_path"
|
||||||
|
class="extra-network-control--sort{sort_path_active}"
|
||||||
|
data-sortkey="default"
|
||||||
|
title="Sort by path"
|
||||||
|
onclick="extraNetworksControlSortOnClick(event, '{tabname}', '{extra_networks_tabname}');"
|
||||||
|
>
|
||||||
|
<i class="extra-network-control--icon extra-network-control--sort-icon"></i>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
id="{tabname}_{extra_networks_tabname}_extra_sort_name"
|
||||||
|
class="extra-network-control--sort{sort_name_active}"
|
||||||
|
data-sortkey="name"
|
||||||
|
title="Sort by name"
|
||||||
|
onclick="extraNetworksControlSortOnClick(event, '{tabname}', '{extra_networks_tabname}');"
|
||||||
|
>
|
||||||
|
<i class="extra-network-control--icon extra-network-control--sort-icon"></i>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
id="{tabname}_{extra_networks_tabname}_extra_sort_date_created"
|
||||||
|
class="extra-network-control--sort{sort_date_created_active}"
|
||||||
|
data-sortkey="date_created"
|
||||||
|
title="Sort by date created"
|
||||||
|
onclick="extraNetworksControlSortOnClick(event, '{tabname}', '{extra_networks_tabname}');"
|
||||||
|
>
|
||||||
|
<i class="extra-network-control--icon extra-network-control--sort-icon"></i>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
id="{tabname}_{extra_networks_tabname}_extra_sort_date_modified"
|
||||||
|
class="extra-network-control--sort{sort_date_modified_active}"
|
||||||
|
data-sortkey="date_modified"
|
||||||
|
title="Sort by date modified"
|
||||||
|
onclick="extraNetworksControlSortOnClick(event, '{tabname}', '{extra_networks_tabname}');"
|
||||||
|
>
|
||||||
|
<i class="extra-network-control--icon extra-network-control--sort-icon"></i>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<small> </small>
|
||||||
|
<div
|
||||||
|
id="{tabname}_{extra_networks_tabname}_extra_sort_dir"
|
||||||
|
class="extra-network-control--sort-dir"
|
||||||
|
data-sortdir="{data_sortdir}"
|
||||||
|
title="Sort ascending"
|
||||||
|
onclick="extraNetworksControlSortDirOnClick(event, '{tabname}', '{extra_networks_tabname}');"
|
||||||
|
>
|
||||||
|
<i class="extra-network-control--icon extra-network-control--sort-dir-icon"></i>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
<small> </small>
|
||||||
|
<div
|
||||||
|
id="{tabname}_{extra_networks_tabname}_extra_tree_view"
|
||||||
|
class="extra-network-control--tree-view {tree_view_btn_extra_class}"
|
||||||
|
title="Enable Tree View"
|
||||||
|
onclick="extraNetworksControlTreeViewOnClick(event, '{tabname}', '{extra_networks_tabname}');"
|
||||||
|
>
|
||||||
|
<i class="extra-network-control--icon extra-network-control--tree-view-icon"></i>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
id="{tabname}_{extra_networks_tabname}_extra_refresh"
|
||||||
|
class="extra-network-control--refresh"
|
||||||
|
title="Refresh page"
|
||||||
|
onclick="extraNetworksControlRefreshOnClick(event, '{tabname}', '{extra_networks_tabname}');"
|
||||||
|
>
|
||||||
|
<i class="extra-network-control--icon extra-network-control--refresh-icon"></i>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{pane_content}
|
||||||
|
</div>
|
23
html/extra-networks-tree-button.html
Normal file
23
html/extra-networks-tree-button.html
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
<span data-filterable-item-text hidden>{search_terms}</span>
|
||||||
|
<div class="tree-list-content {subclass}"
|
||||||
|
type="button"
|
||||||
|
onclick="extraNetworksTreeOnClick(event, '{tabname}', '{extra_networks_tabname}');{onclick_extra}"
|
||||||
|
data-path="{data_path}"
|
||||||
|
data-hash="{data_hash}"
|
||||||
|
>
|
||||||
|
<span class='tree-list-item-action tree-list-item-action--leading'>
|
||||||
|
{action_list_item_action_leading}
|
||||||
|
</span>
|
||||||
|
<span class="tree-list-item-visual tree-list-item-visual--leading">
|
||||||
|
{action_list_item_visual_leading}
|
||||||
|
</span>
|
||||||
|
<span class="tree-list-item-label tree-list-item-label--truncate">
|
||||||
|
{action_list_item_label}
|
||||||
|
</span>
|
||||||
|
<span class="tree-list-item-visual tree-list-item-visual--trailing">
|
||||||
|
{action_list_item_visual_trailing}
|
||||||
|
</span>
|
||||||
|
<span class="tree-list-item-action tree-list-item-action--trailing">
|
||||||
|
{action_list_item_action_trailing}
|
||||||
|
</span>
|
||||||
|
</div>
|
@ -1,10 +1,12 @@
|
|||||||
<div>
|
<div>
|
||||||
<a href="/docs">API</a>
|
<a href="{api_docs}">API</a>
|
||||||
•
|
•
|
||||||
<a href="https://github.com/AUTOMATIC1111/stable-diffusion-webui">Github</a>
|
<a href="https://github.com/AUTOMATIC1111/stable-diffusion-webui">Github</a>
|
||||||
•
|
•
|
||||||
<a href="https://gradio.app">Gradio</a>
|
<a href="https://gradio.app">Gradio</a>
|
||||||
•
|
•
|
||||||
|
<a href="#" onclick="showProfile('./internal/profile-startup'); return false;">Startup profile</a>
|
||||||
|
•
|
||||||
<a href="/" onclick="javascript:gradioApp().getElementById('settings_restart_gradio').click(); return false">Reload UI</a>
|
<a href="/" onclick="javascript:gradioApp().getElementById('settings_restart_gradio').click(); return false">Reload UI</a>
|
||||||
</div>
|
</div>
|
||||||
<br />
|
<br />
|
||||||
|
@ -1,7 +0,0 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
|
||||||
<filter id='shadow' color-interpolation-filters="sRGB">
|
|
||||||
<feDropShadow flood-color="black" dx="0" dy="0" flood-opacity="0.9" stdDeviation="0.5"/>
|
|
||||||
<feDropShadow flood-color="black" dx="0" dy="0" flood-opacity="0.9" stdDeviation="0.5"/>
|
|
||||||
</filter>
|
|
||||||
<path style="filter:url(#shadow);" fill="#FFFFFF" d="M13.18 19C13.35 19.72 13.64 20.39 14.03 21H5C3.9 21 3 20.11 3 19V5C3 3.9 3.9 3 5 3H19C20.11 3 21 3.9 21 5V11.18C20.5 11.07 20 11 19.5 11C19.33 11 19.17 11 19 11.03V5H5V19H13.18M11.21 15.83L9.25 13.47L6.5 17H13.03C13.14 15.54 13.73 14.22 14.64 13.19L13.96 12.29L11.21 15.83M19 13.5V12L16.75 14.25L19 16.5V15C20.38 15 21.5 16.12 21.5 17.5C21.5 17.9 21.41 18.28 21.24 18.62L22.33 19.71C22.75 19.08 23 18.32 23 17.5C23 15.29 21.21 13.5 19 13.5M19 20C17.62 20 16.5 18.88 16.5 17.5C16.5 17.1 16.59 16.72 16.76 16.38L15.67 15.29C15.25 15.92 15 16.68 15 17.5C15 19.71 16.79 21.5 19 21.5V23L21.25 20.75L19 18.5V20Z" />
|
|
||||||
</svg>
|
|
Before Width: | Height: | Size: 989 B |
@ -4,107 +4,6 @@
|
|||||||
#licenses pre { margin: 1em 0 2em 0;}
|
#licenses pre { margin: 1em 0 2em 0;}
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
<h2><a href="https://github.com/sczhou/CodeFormer/blob/master/LICENSE">CodeFormer</a></h2>
|
|
||||||
<small>Parts of CodeFormer code had to be copied to be compatible with GFPGAN.</small>
|
|
||||||
<pre>
|
|
||||||
S-Lab License 1.0
|
|
||||||
|
|
||||||
Copyright 2022 S-Lab
|
|
||||||
|
|
||||||
Redistribution and use for non-commercial purpose in source and
|
|
||||||
binary forms, with or without modification, are permitted provided
|
|
||||||
that the following conditions are met:
|
|
||||||
|
|
||||||
1. Redistributions of source code must retain the above copyright
|
|
||||||
notice, this list of conditions and the following disclaimer.
|
|
||||||
|
|
||||||
2. Redistributions in binary form must reproduce the above copyright
|
|
||||||
notice, this list of conditions and the following disclaimer in
|
|
||||||
the documentation and/or other materials provided with the
|
|
||||||
distribution.
|
|
||||||
|
|
||||||
3. Neither the name of the copyright holder nor the names of its
|
|
||||||
contributors may be used to endorse or promote products derived
|
|
||||||
from this software without specific prior written permission.
|
|
||||||
|
|
||||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
|
||||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
||||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
|
||||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
|
||||||
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
||||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
|
||||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
||||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
||||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
||||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
||||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
|
|
||||||
In the event that redistribution and/or use for commercial purpose in
|
|
||||||
source or binary forms, with or without modification is required,
|
|
||||||
please contact the contributor(s) of the work.
|
|
||||||
</pre>
|
|
||||||
|
|
||||||
|
|
||||||
<h2><a href="https://github.com/victorca25/iNNfer/blob/main/LICENSE">ESRGAN</a></h2>
|
|
||||||
<small>Code for architecture and reading models copied.</small>
|
|
||||||
<pre>
|
|
||||||
MIT License
|
|
||||||
|
|
||||||
Copyright (c) 2021 victorca25
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
|
||||||
copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
||||||
SOFTWARE.
|
|
||||||
</pre>
|
|
||||||
|
|
||||||
<h2><a href="https://github.com/xinntao/Real-ESRGAN/blob/master/LICENSE">Real-ESRGAN</a></h2>
|
|
||||||
<small>Some code is copied to support ESRGAN models.</small>
|
|
||||||
<pre>
|
|
||||||
BSD 3-Clause License
|
|
||||||
|
|
||||||
Copyright (c) 2021, Xintao Wang
|
|
||||||
All rights reserved.
|
|
||||||
|
|
||||||
Redistribution and use in source and binary forms, with or without
|
|
||||||
modification, are permitted provided that the following conditions are met:
|
|
||||||
|
|
||||||
1. Redistributions of source code must retain the above copyright notice, this
|
|
||||||
list of conditions and the following disclaimer.
|
|
||||||
|
|
||||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
||||||
this list of conditions and the following disclaimer in the documentation
|
|
||||||
and/or other materials provided with the distribution.
|
|
||||||
|
|
||||||
3. Neither the name of the copyright holder nor the names of its
|
|
||||||
contributors may be used to endorse or promote products derived from
|
|
||||||
this software without specific prior written permission.
|
|
||||||
|
|
||||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
||||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
||||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
||||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
||||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
||||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
||||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
||||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
||||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
||||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
</pre>
|
|
||||||
|
|
||||||
<h2><a href="https://github.com/invoke-ai/InvokeAI/blob/main/LICENSE">InvokeAI</a></h2>
|
<h2><a href="https://github.com/invoke-ai/InvokeAI/blob/main/LICENSE">InvokeAI</a></h2>
|
||||||
<small>Some code for compatibility with OSX is taken from lstein's repository.</small>
|
<small>Some code for compatibility with OSX is taken from lstein's repository.</small>
|
||||||
<pre>
|
<pre>
|
||||||
@ -183,213 +82,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|||||||
SOFTWARE.
|
SOFTWARE.
|
||||||
</pre>
|
</pre>
|
||||||
|
|
||||||
<h2><a href="https://github.com/JingyunLiang/SwinIR/blob/main/LICENSE">SwinIR</a></h2>
|
|
||||||
<small>Code added by contributors, most likely copied from this repository.</small>
|
|
||||||
|
|
||||||
<pre>
|
|
||||||
Apache License
|
|
||||||
Version 2.0, January 2004
|
|
||||||
http://www.apache.org/licenses/
|
|
||||||
|
|
||||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
||||||
|
|
||||||
1. Definitions.
|
|
||||||
|
|
||||||
"License" shall mean the terms and conditions for use, reproduction,
|
|
||||||
and distribution as defined by Sections 1 through 9 of this document.
|
|
||||||
|
|
||||||
"Licensor" shall mean the copyright owner or entity authorized by
|
|
||||||
the copyright owner that is granting the License.
|
|
||||||
|
|
||||||
"Legal Entity" shall mean the union of the acting entity and all
|
|
||||||
other entities that control, are controlled by, or are under common
|
|
||||||
control with that entity. For the purposes of this definition,
|
|
||||||
"control" means (i) the power, direct or indirect, to cause the
|
|
||||||
direction or management of such entity, whether by contract or
|
|
||||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
||||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
||||||
|
|
||||||
"You" (or "Your") shall mean an individual or Legal Entity
|
|
||||||
exercising permissions granted by this License.
|
|
||||||
|
|
||||||
"Source" form shall mean the preferred form for making modifications,
|
|
||||||
including but not limited to software source code, documentation
|
|
||||||
source, and configuration files.
|
|
||||||
|
|
||||||
"Object" form shall mean any form resulting from mechanical
|
|
||||||
transformation or translation of a Source form, including but
|
|
||||||
not limited to compiled object code, generated documentation,
|
|
||||||
and conversions to other media types.
|
|
||||||
|
|
||||||
"Work" shall mean the work of authorship, whether in Source or
|
|
||||||
Object form, made available under the License, as indicated by a
|
|
||||||
copyright notice that is included in or attached to the work
|
|
||||||
(an example is provided in the Appendix below).
|
|
||||||
|
|
||||||
"Derivative Works" shall mean any work, whether in Source or Object
|
|
||||||
form, that is based on (or derived from) the Work and for which the
|
|
||||||
editorial revisions, annotations, elaborations, or other modifications
|
|
||||||
represent, as a whole, an original work of authorship. For the purposes
|
|
||||||
of this License, Derivative Works shall not include works that remain
|
|
||||||
separable from, or merely link (or bind by name) to the interfaces of,
|
|
||||||
the Work and Derivative Works thereof.
|
|
||||||
|
|
||||||
"Contribution" shall mean any work of authorship, including
|
|
||||||
the original version of the Work and any modifications or additions
|
|
||||||
to that Work or Derivative Works thereof, that is intentionally
|
|
||||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
||||||
or by an individual or Legal Entity authorized to submit on behalf of
|
|
||||||
the copyright owner. For the purposes of this definition, "submitted"
|
|
||||||
means any form of electronic, verbal, or written communication sent
|
|
||||||
to the Licensor or its representatives, including but not limited to
|
|
||||||
communication on electronic mailing lists, source code control systems,
|
|
||||||
and issue tracking systems that are managed by, or on behalf of, the
|
|
||||||
Licensor for the purpose of discussing and improving the Work, but
|
|
||||||
excluding communication that is conspicuously marked or otherwise
|
|
||||||
designated in writing by the copyright owner as "Not a Contribution."
|
|
||||||
|
|
||||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
||||||
on behalf of whom a Contribution has been received by Licensor and
|
|
||||||
subsequently incorporated within the Work.
|
|
||||||
|
|
||||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
||||||
this License, each Contributor hereby grants to You a perpetual,
|
|
||||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
||||||
copyright license to reproduce, prepare Derivative Works of,
|
|
||||||
publicly display, publicly perform, sublicense, and distribute the
|
|
||||||
Work and such Derivative Works in Source or Object form.
|
|
||||||
|
|
||||||
3. Grant of Patent License. Subject to the terms and conditions of
|
|
||||||
this License, each Contributor hereby grants to You a perpetual,
|
|
||||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
||||||
(except as stated in this section) patent license to make, have made,
|
|
||||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
||||||
where such license applies only to those patent claims licensable
|
|
||||||
by such Contributor that are necessarily infringed by their
|
|
||||||
Contribution(s) alone or by combination of their Contribution(s)
|
|
||||||
with the Work to which such Contribution(s) was submitted. If You
|
|
||||||
institute patent litigation against any entity (including a
|
|
||||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
||||||
or a Contribution incorporated within the Work constitutes direct
|
|
||||||
or contributory patent infringement, then any patent licenses
|
|
||||||
granted to You under this License for that Work shall terminate
|
|
||||||
as of the date such litigation is filed.
|
|
||||||
|
|
||||||
4. Redistribution. You may reproduce and distribute copies of the
|
|
||||||
Work or Derivative Works thereof in any medium, with or without
|
|
||||||
modifications, and in Source or Object form, provided that You
|
|
||||||
meet the following conditions:
|
|
||||||
|
|
||||||
(a) You must give any other recipients of the Work or
|
|
||||||
Derivative Works a copy of this License; and
|
|
||||||
|
|
||||||
(b) You must cause any modified files to carry prominent notices
|
|
||||||
stating that You changed the files; and
|
|
||||||
|
|
||||||
(c) You must retain, in the Source form of any Derivative Works
|
|
||||||
that You distribute, all copyright, patent, trademark, and
|
|
||||||
attribution notices from the Source form of the Work,
|
|
||||||
excluding those notices that do not pertain to any part of
|
|
||||||
the Derivative Works; and
|
|
||||||
|
|
||||||
(d) If the Work includes a "NOTICE" text file as part of its
|
|
||||||
distribution, then any Derivative Works that You distribute must
|
|
||||||
include a readable copy of the attribution notices contained
|
|
||||||
within such NOTICE file, excluding those notices that do not
|
|
||||||
pertain to any part of the Derivative Works, in at least one
|
|
||||||
of the following places: within a NOTICE text file distributed
|
|
||||||
as part of the Derivative Works; within the Source form or
|
|
||||||
documentation, if provided along with the Derivative Works; or,
|
|
||||||
within a display generated by the Derivative Works, if and
|
|
||||||
wherever such third-party notices normally appear. The contents
|
|
||||||
of the NOTICE file are for informational purposes only and
|
|
||||||
do not modify the License. You may add Your own attribution
|
|
||||||
notices within Derivative Works that You distribute, alongside
|
|
||||||
or as an addendum to the NOTICE text from the Work, provided
|
|
||||||
that such additional attribution notices cannot be construed
|
|
||||||
as modifying the License.
|
|
||||||
|
|
||||||
You may add Your own copyright statement to Your modifications and
|
|
||||||
may provide additional or different license terms and conditions
|
|
||||||
for use, reproduction, or distribution of Your modifications, or
|
|
||||||
for any such Derivative Works as a whole, provided Your use,
|
|
||||||
reproduction, and distribution of the Work otherwise complies with
|
|
||||||
the conditions stated in this License.
|
|
||||||
|
|
||||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
||||||
any Contribution intentionally submitted for inclusion in the Work
|
|
||||||
by You to the Licensor shall be under the terms and conditions of
|
|
||||||
this License, without any additional terms or conditions.
|
|
||||||
Notwithstanding the above, nothing herein shall supersede or modify
|
|
||||||
the terms of any separate license agreement you may have executed
|
|
||||||
with Licensor regarding such Contributions.
|
|
||||||
|
|
||||||
6. Trademarks. This License does not grant permission to use the trade
|
|
||||||
names, trademarks, service marks, or product names of the Licensor,
|
|
||||||
except as required for reasonable and customary use in describing the
|
|
||||||
origin of the Work and reproducing the content of the NOTICE file.
|
|
||||||
|
|
||||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
||||||
agreed to in writing, Licensor provides the Work (and each
|
|
||||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
||||||
implied, including, without limitation, any warranties or conditions
|
|
||||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
||||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
||||||
appropriateness of using or redistributing the Work and assume any
|
|
||||||
risks associated with Your exercise of permissions under this License.
|
|
||||||
|
|
||||||
8. Limitation of Liability. In no event and under no legal theory,
|
|
||||||
whether in tort (including negligence), contract, or otherwise,
|
|
||||||
unless required by applicable law (such as deliberate and grossly
|
|
||||||
negligent acts) or agreed to in writing, shall any Contributor be
|
|
||||||
liable to You for damages, including any direct, indirect, special,
|
|
||||||
incidental, or consequential damages of any character arising as a
|
|
||||||
result of this License or out of the use or inability to use the
|
|
||||||
Work (including but not limited to damages for loss of goodwill,
|
|
||||||
work stoppage, computer failure or malfunction, or any and all
|
|
||||||
other commercial damages or losses), even if such Contributor
|
|
||||||
has been advised of the possibility of such damages.
|
|
||||||
|
|
||||||
9. Accepting Warranty or Additional Liability. While redistributing
|
|
||||||
the Work or Derivative Works thereof, You may choose to offer,
|
|
||||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
||||||
or other liability obligations and/or rights consistent with this
|
|
||||||
License. However, in accepting such obligations, You may act only
|
|
||||||
on Your own behalf and on Your sole responsibility, not on behalf
|
|
||||||
of any other Contributor, and only if You agree to indemnify,
|
|
||||||
defend, and hold each Contributor harmless for any liability
|
|
||||||
incurred by, or claims asserted against, such Contributor by reason
|
|
||||||
of your accepting any such warranty or additional liability.
|
|
||||||
|
|
||||||
END OF TERMS AND CONDITIONS
|
|
||||||
|
|
||||||
APPENDIX: How to apply the Apache License to your work.
|
|
||||||
|
|
||||||
To apply the Apache License to your work, attach the following
|
|
||||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
||||||
replaced with your own identifying information. (Don't include
|
|
||||||
the brackets!) The text should be enclosed in the appropriate
|
|
||||||
comment syntax for the file format. We also recommend that a
|
|
||||||
file or class name and description of purpose be included on the
|
|
||||||
same "printed page" as the copyright notice for easier
|
|
||||||
identification within third-party archives.
|
|
||||||
|
|
||||||
Copyright [2021] [SwinIR Authors]
|
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
you may not use this file except in compliance with the License.
|
|
||||||
You may obtain a copy of the License at
|
|
||||||
|
|
||||||
http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
See the License for the specific language governing permissions and
|
|
||||||
limitations under the License.
|
|
||||||
</pre>
|
|
||||||
|
|
||||||
<h2><a href="https://github.com/AminRezaei0x443/memory-efficient-attention/blob/main/LICENSE">Memory Efficient Attention</a></h2>
|
<h2><a href="https://github.com/AminRezaei0x443/memory-efficient-attention/blob/main/LICENSE">Memory Efficient Attention</a></h2>
|
||||||
<small>The sub-quadratic cross attention optimization uses modified code from the Memory Efficient Attention package that Alex Birch optimized for 3D tensors. This license is updated to reflect that.</small>
|
<small>The sub-quadratic cross attention optimization uses modified code from the Memory Efficient Attention package that Alex Birch optimized for 3D tensors. This license is updated to reflect that.</small>
|
||||||
<pre>
|
<pre>
|
||||||
@ -661,4 +353,30 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
THE SOFTWARE.
|
THE SOFTWARE.
|
||||||
</pre>
|
</pre>
|
||||||
|
|
||||||
|
<h2><a href="https://github.com/madebyollin/taesd/blob/main/LICENSE">TAESD</a></h2>
|
||||||
|
<small>Tiny AutoEncoder for Stable Diffusion option for live previews</small>
|
||||||
|
<pre>
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2023 Ollin Boer Bohan
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
|
</pre>
|
||||||
|
@ -1,111 +1,113 @@
|
|||||||
|
|
||||||
let currentWidth = null;
|
let currentWidth = null;
|
||||||
let currentHeight = null;
|
let currentHeight = null;
|
||||||
let arFrameTimeout = setTimeout(function(){},0);
|
let arFrameTimeout = setTimeout(function() {}, 0);
|
||||||
|
|
||||||
function dimensionChange(e, is_width, is_height){
|
function dimensionChange(e, is_width, is_height) {
|
||||||
|
|
||||||
if(is_width){
|
if (is_width) {
|
||||||
currentWidth = e.target.value*1.0
|
currentWidth = e.target.value * 1.0;
|
||||||
}
|
}
|
||||||
if(is_height){
|
if (is_height) {
|
||||||
currentHeight = e.target.value*1.0
|
currentHeight = e.target.value * 1.0;
|
||||||
}
|
}
|
||||||
|
|
||||||
var inImg2img = gradioApp().querySelector("#tab_img2img").style.display == "block";
|
var inImg2img = gradioApp().querySelector("#tab_img2img").style.display == "block";
|
||||||
|
|
||||||
if(!inImg2img){
|
if (!inImg2img) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var targetElement = null;
|
var targetElement = null;
|
||||||
|
|
||||||
var tabIndex = get_tab_index('mode_img2img')
|
var tabIndex = get_tab_index('mode_img2img');
|
||||||
if(tabIndex == 0){ // img2img
|
if (tabIndex == 0) { // img2img
|
||||||
targetElement = gradioApp().querySelector('#img2img_image div[data-testid=image] img');
|
targetElement = gradioApp().querySelector('#img2img_image div[data-testid=image] img');
|
||||||
} else if(tabIndex == 1){ //Sketch
|
} else if (tabIndex == 1) { //Sketch
|
||||||
targetElement = gradioApp().querySelector('#img2img_sketch div[data-testid=image] img');
|
targetElement = gradioApp().querySelector('#img2img_sketch div[data-testid=image] img');
|
||||||
} else if(tabIndex == 2){ // Inpaint
|
} else if (tabIndex == 2) { // Inpaint
|
||||||
targetElement = gradioApp().querySelector('#img2maskimg div[data-testid=image] img');
|
targetElement = gradioApp().querySelector('#img2maskimg div[data-testid=image] img');
|
||||||
} else if(tabIndex == 3){ // Inpaint sketch
|
} else if (tabIndex == 3) { // Inpaint sketch
|
||||||
targetElement = gradioApp().querySelector('#inpaint_sketch div[data-testid=image] img');
|
targetElement = gradioApp().querySelector('#inpaint_sketch div[data-testid=image] img');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
if(targetElement){
|
if (targetElement) {
|
||||||
|
|
||||||
var arPreviewRect = gradioApp().querySelector('#imageARPreview');
|
var arPreviewRect = gradioApp().querySelector('#imageARPreview');
|
||||||
if(!arPreviewRect){
|
if (!arPreviewRect) {
|
||||||
arPreviewRect = document.createElement('div')
|
arPreviewRect = document.createElement('div');
|
||||||
arPreviewRect.id = "imageARPreview";
|
arPreviewRect.id = "imageARPreview";
|
||||||
gradioApp().appendChild(arPreviewRect)
|
gradioApp().appendChild(arPreviewRect);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
var viewportOffset = targetElement.getBoundingClientRect();
|
var viewportOffset = targetElement.getBoundingClientRect();
|
||||||
|
|
||||||
var viewportscale = Math.min( targetElement.clientWidth/targetElement.naturalWidth, targetElement.clientHeight/targetElement.naturalHeight )
|
var viewportscale = Math.min(targetElement.clientWidth / targetElement.naturalWidth, targetElement.clientHeight / targetElement.naturalHeight);
|
||||||
|
|
||||||
var scaledx = targetElement.naturalWidth*viewportscale
|
var scaledx = targetElement.naturalWidth * viewportscale;
|
||||||
var scaledy = targetElement.naturalHeight*viewportscale
|
var scaledy = targetElement.naturalHeight * viewportscale;
|
||||||
|
|
||||||
var cleintRectTop = (viewportOffset.top+window.scrollY)
|
var clientRectTop = (viewportOffset.top + window.scrollY);
|
||||||
var cleintRectLeft = (viewportOffset.left+window.scrollX)
|
var clientRectLeft = (viewportOffset.left + window.scrollX);
|
||||||
var cleintRectCentreY = cleintRectTop + (targetElement.clientHeight/2)
|
var clientRectCentreY = clientRectTop + (targetElement.clientHeight / 2);
|
||||||
var cleintRectCentreX = cleintRectLeft + (targetElement.clientWidth/2)
|
var clientRectCentreX = clientRectLeft + (targetElement.clientWidth / 2);
|
||||||
|
|
||||||
var arscale = Math.min( scaledx/currentWidth, scaledy/currentHeight )
|
var arscale = Math.min(scaledx / currentWidth, scaledy / currentHeight);
|
||||||
var arscaledx = currentWidth*arscale
|
var arscaledx = currentWidth * arscale;
|
||||||
var arscaledy = currentHeight*arscale
|
var arscaledy = currentHeight * arscale;
|
||||||
|
|
||||||
var arRectTop = cleintRectCentreY-(arscaledy/2)
|
var arRectTop = clientRectCentreY - (arscaledy / 2);
|
||||||
var arRectLeft = cleintRectCentreX-(arscaledx/2)
|
var arRectLeft = clientRectCentreX - (arscaledx / 2);
|
||||||
var arRectWidth = arscaledx
|
var arRectWidth = arscaledx;
|
||||||
var arRectHeight = arscaledy
|
var arRectHeight = arscaledy;
|
||||||
|
|
||||||
arPreviewRect.style.top = arRectTop+'px';
|
arPreviewRect.style.top = arRectTop + 'px';
|
||||||
arPreviewRect.style.left = arRectLeft+'px';
|
arPreviewRect.style.left = arRectLeft + 'px';
|
||||||
arPreviewRect.style.width = arRectWidth+'px';
|
arPreviewRect.style.width = arRectWidth + 'px';
|
||||||
arPreviewRect.style.height = arRectHeight+'px';
|
arPreviewRect.style.height = arRectHeight + 'px';
|
||||||
|
|
||||||
clearTimeout(arFrameTimeout);
|
clearTimeout(arFrameTimeout);
|
||||||
arFrameTimeout = setTimeout(function(){
|
arFrameTimeout = setTimeout(function() {
|
||||||
arPreviewRect.style.display = 'none';
|
arPreviewRect.style.display = 'none';
|
||||||
},2000);
|
}, 2000);
|
||||||
|
|
||||||
arPreviewRect.style.display = 'block';
|
arPreviewRect.style.display = 'block';
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
onUiUpdate(function(){
|
onAfterUiUpdate(function() {
|
||||||
var arPreviewRect = gradioApp().querySelector('#imageARPreview');
|
var arPreviewRect = gradioApp().querySelector('#imageARPreview');
|
||||||
if(arPreviewRect){
|
if (arPreviewRect) {
|
||||||
arPreviewRect.style.display = 'none';
|
arPreviewRect.style.display = 'none';
|
||||||
}
|
}
|
||||||
var tabImg2img = gradioApp().querySelector("#tab_img2img");
|
var tabImg2img = gradioApp().querySelector("#tab_img2img");
|
||||||
if (tabImg2img) {
|
if (tabImg2img) {
|
||||||
var inImg2img = tabImg2img.style.display == "block";
|
var inImg2img = tabImg2img.style.display == "block";
|
||||||
if(inImg2img){
|
if (inImg2img) {
|
||||||
let inputs = gradioApp().querySelectorAll('input');
|
let inputs = gradioApp().querySelectorAll('input');
|
||||||
inputs.forEach(function(e){
|
inputs.forEach(function(e) {
|
||||||
var is_width = e.parentElement.id == "img2img_width"
|
var is_width = e.parentElement.id == "img2img_width";
|
||||||
var is_height = e.parentElement.id == "img2img_height"
|
var is_height = e.parentElement.id == "img2img_height";
|
||||||
|
|
||||||
if((is_width || is_height) && !e.classList.contains('scrollwatch')){
|
if ((is_width || is_height) && !e.classList.contains('scrollwatch')) {
|
||||||
e.addEventListener('input', function(e){dimensionChange(e, is_width, is_height)} )
|
e.addEventListener('input', function(e) {
|
||||||
e.classList.add('scrollwatch')
|
dimensionChange(e, is_width, is_height);
|
||||||
}
|
});
|
||||||
if(is_width){
|
e.classList.add('scrollwatch');
|
||||||
currentWidth = e.value*1.0
|
}
|
||||||
}
|
if (is_width) {
|
||||||
if(is_height){
|
currentWidth = e.value * 1.0;
|
||||||
currentHeight = e.value*1.0
|
}
|
||||||
}
|
if (is_height) {
|
||||||
})
|
currentHeight = e.value * 1.0;
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
});
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
@ -1,166 +1,163 @@
|
|||||||
|
|
||||||
contextMenuInit = function(){
|
var contextMenuInit = function() {
|
||||||
let eventListenerApplied=false;
|
let eventListenerApplied = false;
|
||||||
let menuSpecs = new Map();
|
let menuSpecs = new Map();
|
||||||
|
|
||||||
const uid = function(){
|
const uid = function() {
|
||||||
return Date.now().toString(36) + Math.random().toString(36).substring(2);
|
return Date.now().toString(36) + Math.random().toString(36).substring(2);
|
||||||
}
|
};
|
||||||
|
|
||||||
function showContextMenu(event,element,menuEntries){
|
function showContextMenu(event, element, menuEntries) {
|
||||||
let posx = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
|
let oldMenu = gradioApp().querySelector('#context-menu');
|
||||||
let posy = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
|
if (oldMenu) {
|
||||||
|
oldMenu.remove();
|
||||||
let oldMenu = gradioApp().querySelector('#context-menu')
|
}
|
||||||
if(oldMenu){
|
|
||||||
oldMenu.remove()
|
let baseStyle = window.getComputedStyle(uiCurrentTab);
|
||||||
}
|
|
||||||
|
const contextMenu = document.createElement('nav');
|
||||||
let baseStyle = window.getComputedStyle(uiCurrentTab)
|
contextMenu.id = "context-menu";
|
||||||
|
contextMenu.style.background = baseStyle.background;
|
||||||
const contextMenu = document.createElement('nav')
|
contextMenu.style.color = baseStyle.color;
|
||||||
contextMenu.id = "context-menu"
|
contextMenu.style.fontFamily = baseStyle.fontFamily;
|
||||||
contextMenu.style.background = baseStyle.background
|
contextMenu.style.top = event.pageY + 'px';
|
||||||
contextMenu.style.color = baseStyle.color
|
contextMenu.style.left = event.pageX + 'px';
|
||||||
contextMenu.style.fontFamily = baseStyle.fontFamily
|
|
||||||
contextMenu.style.top = posy+'px'
|
const contextMenuList = document.createElement('ul');
|
||||||
contextMenu.style.left = posx+'px'
|
contextMenuList.className = 'context-menu-items';
|
||||||
|
contextMenu.append(contextMenuList);
|
||||||
|
|
||||||
|
menuEntries.forEach(function(entry) {
|
||||||
const contextMenuList = document.createElement('ul')
|
let contextMenuEntry = document.createElement('a');
|
||||||
contextMenuList.className = 'context-menu-items';
|
contextMenuEntry.innerHTML = entry['name'];
|
||||||
contextMenu.append(contextMenuList);
|
contextMenuEntry.addEventListener("click", function() {
|
||||||
|
entry['func']();
|
||||||
menuEntries.forEach(function(entry){
|
});
|
||||||
let contextMenuEntry = document.createElement('a')
|
contextMenuList.append(contextMenuEntry);
|
||||||
contextMenuEntry.innerHTML = entry['name']
|
|
||||||
contextMenuEntry.addEventListener("click", function() {
|
});
|
||||||
entry['func']();
|
|
||||||
})
|
gradioApp().appendChild(contextMenu);
|
||||||
contextMenuList.append(contextMenuEntry);
|
}
|
||||||
|
|
||||||
})
|
function appendContextMenuOption(targetElementSelector, entryName, entryFunction) {
|
||||||
|
|
||||||
gradioApp().appendChild(contextMenu)
|
var currentItems = menuSpecs.get(targetElementSelector);
|
||||||
|
|
||||||
let menuWidth = contextMenu.offsetWidth + 4;
|
if (!currentItems) {
|
||||||
let menuHeight = contextMenu.offsetHeight + 4;
|
currentItems = [];
|
||||||
|
menuSpecs.set(targetElementSelector, currentItems);
|
||||||
let windowWidth = window.innerWidth;
|
}
|
||||||
let windowHeight = window.innerHeight;
|
let newItem = {
|
||||||
|
id: targetElementSelector + '_' + uid(),
|
||||||
if ( (windowWidth - posx) < menuWidth ) {
|
name: entryName,
|
||||||
contextMenu.style.left = windowWidth - menuWidth + "px";
|
func: entryFunction,
|
||||||
}
|
isNew: true
|
||||||
|
};
|
||||||
if ( (windowHeight - posy) < menuHeight ) {
|
|
||||||
contextMenu.style.top = windowHeight - menuHeight + "px";
|
currentItems.push(newItem);
|
||||||
}
|
return newItem['id'];
|
||||||
|
}
|
||||||
}
|
|
||||||
|
function removeContextMenuOption(uid) {
|
||||||
function appendContextMenuOption(targetElementSelector,entryName,entryFunction){
|
menuSpecs.forEach(function(v) {
|
||||||
|
let index = -1;
|
||||||
var currentItems = menuSpecs.get(targetElementSelector)
|
v.forEach(function(e, ei) {
|
||||||
|
if (e['id'] == uid) {
|
||||||
if(!currentItems){
|
index = ei;
|
||||||
currentItems = []
|
}
|
||||||
menuSpecs.set(targetElementSelector,currentItems);
|
});
|
||||||
}
|
if (index >= 0) {
|
||||||
let newItem = {'id':targetElementSelector+'_'+uid(),
|
v.splice(index, 1);
|
||||||
'name':entryName,
|
}
|
||||||
'func':entryFunction,
|
});
|
||||||
'isNew':true}
|
}
|
||||||
|
|
||||||
currentItems.push(newItem)
|
function addContextMenuEventListener() {
|
||||||
return newItem['id']
|
if (eventListenerApplied) {
|
||||||
}
|
return;
|
||||||
|
}
|
||||||
function removeContextMenuOption(uid){
|
gradioApp().addEventListener("click", function(e) {
|
||||||
menuSpecs.forEach(function(v) {
|
if (!e.isTrusted) {
|
||||||
let index = -1
|
return;
|
||||||
v.forEach(function(e,ei){if(e['id']==uid){index=ei}})
|
}
|
||||||
if(index>=0){
|
|
||||||
v.splice(index, 1);
|
let oldMenu = gradioApp().querySelector('#context-menu');
|
||||||
}
|
if (oldMenu) {
|
||||||
})
|
oldMenu.remove();
|
||||||
}
|
}
|
||||||
|
});
|
||||||
function addContextMenuEventListener(){
|
['contextmenu', 'touchstart'].forEach((eventType) => {
|
||||||
if(eventListenerApplied){
|
gradioApp().addEventListener(eventType, function(e) {
|
||||||
return;
|
let ev = e;
|
||||||
}
|
if (eventType.startsWith('touch')) {
|
||||||
gradioApp().addEventListener("click", function(e) {
|
if (e.touches.length !== 2) return;
|
||||||
if(! e.isTrusted){
|
ev = e.touches[0];
|
||||||
return
|
}
|
||||||
}
|
let oldMenu = gradioApp().querySelector('#context-menu');
|
||||||
|
if (oldMenu) {
|
||||||
let oldMenu = gradioApp().querySelector('#context-menu')
|
oldMenu.remove();
|
||||||
if(oldMenu){
|
}
|
||||||
oldMenu.remove()
|
menuSpecs.forEach(function(v, k) {
|
||||||
}
|
if (e.composedPath()[0].matches(k)) {
|
||||||
});
|
showContextMenu(ev, e.composedPath()[0], v);
|
||||||
gradioApp().addEventListener("contextmenu", function(e) {
|
e.preventDefault();
|
||||||
let oldMenu = gradioApp().querySelector('#context-menu')
|
}
|
||||||
if(oldMenu){
|
});
|
||||||
oldMenu.remove()
|
});
|
||||||
}
|
});
|
||||||
menuSpecs.forEach(function(v,k) {
|
eventListenerApplied = true;
|
||||||
if(e.composedPath()[0].matches(k)){
|
|
||||||
showContextMenu(e,e.composedPath()[0],v)
|
}
|
||||||
e.preventDefault()
|
|
||||||
}
|
return [appendContextMenuOption, removeContextMenuOption, addContextMenuEventListener];
|
||||||
})
|
};
|
||||||
});
|
|
||||||
eventListenerApplied=true
|
var initResponse = contextMenuInit();
|
||||||
|
var appendContextMenuOption = initResponse[0];
|
||||||
}
|
var removeContextMenuOption = initResponse[1];
|
||||||
|
var addContextMenuEventListener = initResponse[2];
|
||||||
return [appendContextMenuOption, removeContextMenuOption, addContextMenuEventListener]
|
|
||||||
}
|
(function() {
|
||||||
|
//Start example Context Menu Items
|
||||||
initResponse = contextMenuInit();
|
let generateOnRepeat = function(genbuttonid, interruptbuttonid) {
|
||||||
appendContextMenuOption = initResponse[0];
|
let genbutton = gradioApp().querySelector(genbuttonid);
|
||||||
removeContextMenuOption = initResponse[1];
|
let interruptbutton = gradioApp().querySelector(interruptbuttonid);
|
||||||
addContextMenuEventListener = initResponse[2];
|
if (!interruptbutton.offsetParent) {
|
||||||
|
genbutton.click();
|
||||||
(function(){
|
}
|
||||||
//Start example Context Menu Items
|
clearInterval(window.generateOnRepeatInterval);
|
||||||
let generateOnRepeat = function(genbuttonid,interruptbuttonid){
|
window.generateOnRepeatInterval = setInterval(function() {
|
||||||
let genbutton = gradioApp().querySelector(genbuttonid);
|
if (!interruptbutton.offsetParent) {
|
||||||
let interruptbutton = gradioApp().querySelector(interruptbuttonid);
|
genbutton.click();
|
||||||
if(!interruptbutton.offsetParent){
|
}
|
||||||
genbutton.click();
|
},
|
||||||
}
|
500);
|
||||||
clearInterval(window.generateOnRepeatInterval)
|
};
|
||||||
window.generateOnRepeatInterval = setInterval(function(){
|
|
||||||
if(!interruptbutton.offsetParent){
|
let generateOnRepeat_txt2img = function() {
|
||||||
genbutton.click();
|
generateOnRepeat('#txt2img_generate', '#txt2img_interrupt');
|
||||||
}
|
};
|
||||||
},
|
|
||||||
500)
|
let generateOnRepeat_img2img = function() {
|
||||||
}
|
generateOnRepeat('#img2img_generate', '#img2img_interrupt');
|
||||||
|
};
|
||||||
appendContextMenuOption('#txt2img_generate','Generate forever',function(){
|
|
||||||
generateOnRepeat('#txt2img_generate','#txt2img_interrupt');
|
appendContextMenuOption('#txt2img_generate', 'Generate forever', generateOnRepeat_txt2img);
|
||||||
})
|
appendContextMenuOption('#txt2img_interrupt', 'Generate forever', generateOnRepeat_txt2img);
|
||||||
appendContextMenuOption('#img2img_generate','Generate forever',function(){
|
appendContextMenuOption('#img2img_generate', 'Generate forever', generateOnRepeat_img2img);
|
||||||
generateOnRepeat('#img2img_generate','#img2img_interrupt');
|
appendContextMenuOption('#img2img_interrupt', 'Generate forever', generateOnRepeat_img2img);
|
||||||
})
|
|
||||||
|
let cancelGenerateForever = function() {
|
||||||
let cancelGenerateForever = function(){
|
clearInterval(window.generateOnRepeatInterval);
|
||||||
clearInterval(window.generateOnRepeatInterval)
|
};
|
||||||
}
|
|
||||||
|
appendContextMenuOption('#txt2img_interrupt', 'Cancel generate forever', cancelGenerateForever);
|
||||||
appendContextMenuOption('#txt2img_interrupt','Cancel generate forever',cancelGenerateForever)
|
appendContextMenuOption('#txt2img_generate', 'Cancel generate forever', cancelGenerateForever);
|
||||||
appendContextMenuOption('#txt2img_generate', 'Cancel generate forever',cancelGenerateForever)
|
appendContextMenuOption('#img2img_interrupt', 'Cancel generate forever', cancelGenerateForever);
|
||||||
appendContextMenuOption('#img2img_interrupt','Cancel generate forever',cancelGenerateForever)
|
appendContextMenuOption('#img2img_generate', 'Cancel generate forever', cancelGenerateForever);
|
||||||
appendContextMenuOption('#img2img_generate', 'Cancel generate forever',cancelGenerateForever)
|
|
||||||
|
})();
|
||||||
})();
|
//End example Context Menu Items
|
||||||
//End example Context Menu Items
|
|
||||||
|
onAfterUiUpdate(addContextMenuEventListener);
|
||||||
onUiUpdate(function(){
|
|
||||||
addContextMenuEventListener()
|
|
||||||
});
|
|
||||||
|
131
javascript/dragdrop.js
vendored
131
javascript/dragdrop.js
vendored
@ -1,11 +1,11 @@
|
|||||||
// allows drag-dropping files into gradio image elements, and also pasting images from clipboard
|
// allows drag-dropping files into gradio image elements, and also pasting images from clipboard
|
||||||
|
|
||||||
function isValidImageList( files ) {
|
function isValidImageList(files) {
|
||||||
return files && files?.length === 1 && ['image/png', 'image/gif', 'image/jpeg'].includes(files[0].type);
|
return files && files?.length === 1 && ['image/png', 'image/gif', 'image/jpeg'].includes(files[0].type);
|
||||||
}
|
}
|
||||||
|
|
||||||
function dropReplaceImage( imgWrap, files ) {
|
function dropReplaceImage(imgWrap, files) {
|
||||||
if ( ! isValidImageList( files ) ) {
|
if (!isValidImageList(files)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -14,84 +14,143 @@ function dropReplaceImage( imgWrap, files ) {
|
|||||||
imgWrap.querySelector('.modify-upload button + button, .touch-none + div button + button')?.click();
|
imgWrap.querySelector('.modify-upload button + button, .touch-none + div button + button')?.click();
|
||||||
const callback = () => {
|
const callback = () => {
|
||||||
const fileInput = imgWrap.querySelector('input[type="file"]');
|
const fileInput = imgWrap.querySelector('input[type="file"]');
|
||||||
if ( fileInput ) {
|
if (fileInput) {
|
||||||
if ( files.length === 0 ) {
|
if (files.length === 0) {
|
||||||
files = new DataTransfer();
|
files = new DataTransfer();
|
||||||
files.items.add(tmpFile);
|
files.items.add(tmpFile);
|
||||||
fileInput.files = files.files;
|
fileInput.files = files.files;
|
||||||
} else {
|
} else {
|
||||||
fileInput.files = files;
|
fileInput.files = files;
|
||||||
}
|
}
|
||||||
fileInput.dispatchEvent(new Event('change'));
|
fileInput.dispatchEvent(new Event('change'));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if ( imgWrap.closest('#pnginfo_image') ) {
|
if (imgWrap.closest('#pnginfo_image')) {
|
||||||
// special treatment for PNG Info tab, wait for fetch request to finish
|
// special treatment for PNG Info tab, wait for fetch request to finish
|
||||||
const oldFetch = window.fetch;
|
const oldFetch = window.fetch;
|
||||||
window.fetch = async (input, options) => {
|
window.fetch = async(input, options) => {
|
||||||
const response = await oldFetch(input, options);
|
const response = await oldFetch(input, options);
|
||||||
if ( 'api/predict/' === input ) {
|
if ('api/predict/' === input) {
|
||||||
const content = await response.text();
|
const content = await response.text();
|
||||||
window.fetch = oldFetch;
|
window.fetch = oldFetch;
|
||||||
window.requestAnimationFrame( () => callback() );
|
window.requestAnimationFrame(() => callback());
|
||||||
return new Response(content, {
|
return new Response(content, {
|
||||||
status: response.status,
|
status: response.status,
|
||||||
statusText: response.statusText,
|
statusText: response.statusText,
|
||||||
headers: response.headers
|
headers: response.headers
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
return response;
|
return response;
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
window.requestAnimationFrame( () => callback() );
|
window.requestAnimationFrame(() => callback());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function eventHasFiles(e) {
|
||||||
|
if (!e.dataTransfer || !e.dataTransfer.files) return false;
|
||||||
|
if (e.dataTransfer.files.length > 0) return true;
|
||||||
|
if (e.dataTransfer.items.length > 0 && e.dataTransfer.items[0].kind == "file") return true;
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isURL(url) {
|
||||||
|
try {
|
||||||
|
const _ = new URL(url);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function dragDropTargetIsPrompt(target) {
|
||||||
|
if (target?.placeholder && target?.placeholder.indexOf("Prompt") >= 0) return true;
|
||||||
|
if (target?.parentNode?.parentNode?.className?.indexOf("prompt") > 0) return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
window.document.addEventListener('dragover', e => {
|
window.document.addEventListener('dragover', e => {
|
||||||
const target = e.composedPath()[0];
|
const target = e.composedPath()[0];
|
||||||
const imgWrap = target.closest('[data-testid="image"]');
|
if (!eventHasFiles(e)) return;
|
||||||
if ( !imgWrap && target.placeholder && target.placeholder.indexOf("Prompt") == -1) {
|
|
||||||
return;
|
var targetImage = target.closest('[data-testid="image"]');
|
||||||
}
|
if (!dragDropTargetIsPrompt(target) && !targetImage) return;
|
||||||
|
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
e.dataTransfer.dropEffect = 'copy';
|
e.dataTransfer.dropEffect = 'copy';
|
||||||
});
|
});
|
||||||
|
|
||||||
window.document.addEventListener('drop', e => {
|
window.document.addEventListener('drop', async e => {
|
||||||
const target = e.composedPath()[0];
|
const target = e.composedPath()[0];
|
||||||
if (target.placeholder.indexOf("Prompt") == -1) {
|
const url = e.dataTransfer.getData('text/uri-list') || e.dataTransfer.getData('text/plain');
|
||||||
|
if (!eventHasFiles(e) && !isURL(url)) return;
|
||||||
|
|
||||||
|
if (dragDropTargetIsPrompt(target)) {
|
||||||
|
e.stopPropagation();
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
const isImg2img = get_tab_index('tabs') == 1;
|
||||||
|
let prompt_image_target = isImg2img ? "img2img_prompt_image" : "txt2img_prompt_image";
|
||||||
|
|
||||||
|
const imgParent = gradioApp().getElementById(prompt_image_target);
|
||||||
|
const files = e.dataTransfer.files;
|
||||||
|
const fileInput = imgParent.querySelector('input[type="file"]');
|
||||||
|
if (eventHasFiles(e) && fileInput) {
|
||||||
|
fileInput.files = files;
|
||||||
|
fileInput.dispatchEvent(new Event('change'));
|
||||||
|
} else if (url) {
|
||||||
|
try {
|
||||||
|
const request = await fetch(url);
|
||||||
|
if (!request.ok) {
|
||||||
|
console.error('Error fetching URL:', url, request.status);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const data = new DataTransfer();
|
||||||
|
data.items.add(new File([await request.blob()], 'image.png'));
|
||||||
|
fileInput.files = data.files;
|
||||||
|
fileInput.dispatchEvent(new Event('change'));
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching URL:', url, error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var targetImage = target.closest('[data-testid="image"]');
|
||||||
|
if (targetImage) {
|
||||||
|
e.stopPropagation();
|
||||||
|
e.preventDefault();
|
||||||
|
const files = e.dataTransfer.files;
|
||||||
|
dropReplaceImage(targetImage, files);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const imgWrap = target.closest('[data-testid="image"]');
|
|
||||||
if ( !imgWrap ) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
e.stopPropagation();
|
|
||||||
e.preventDefault();
|
|
||||||
const files = e.dataTransfer.files;
|
|
||||||
dropReplaceImage( imgWrap, files );
|
|
||||||
});
|
});
|
||||||
|
|
||||||
window.addEventListener('paste', e => {
|
window.addEventListener('paste', e => {
|
||||||
const files = e.clipboardData.files;
|
const files = e.clipboardData.files;
|
||||||
if ( ! isValidImageList( files ) ) {
|
if (!isValidImageList(files)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const visibleImageFields = [...gradioApp().querySelectorAll('[data-testid="image"]')]
|
const visibleImageFields = [...gradioApp().querySelectorAll('[data-testid="image"]')]
|
||||||
.filter(el => uiElementIsVisible(el));
|
.filter(el => uiElementIsVisible(el))
|
||||||
if ( ! visibleImageFields.length ) {
|
.sort((a, b) => uiElementInSight(b) - uiElementInSight(a));
|
||||||
|
|
||||||
|
|
||||||
|
if (!visibleImageFields.length) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const firstFreeImageField = visibleImageFields
|
const firstFreeImageField = visibleImageFields
|
||||||
.filter(el => el.querySelector('input[type=file]'))?.[0];
|
.filter(el => !el.querySelector('img'))?.[0];
|
||||||
|
|
||||||
dropReplaceImage(
|
dropReplaceImage(
|
||||||
firstFreeImageField ?
|
firstFreeImageField ?
|
||||||
firstFreeImageField :
|
firstFreeImageField :
|
||||||
visibleImageFields[visibleImageFields.length - 1]
|
visibleImageFields[visibleImageFields.length - 1]
|
||||||
, files );
|
, files
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
@ -1,120 +1,156 @@
|
|||||||
function keyupEditAttention(event){
|
function keyupEditAttention(event) {
|
||||||
let target = event.originalTarget || event.composedPath()[0];
|
let target = event.originalTarget || event.composedPath()[0];
|
||||||
if (! target.matches("[id*='_toprow'] [id*='_prompt'] textarea")) return;
|
if (!target.matches("*:is([id*='_toprow'] [id*='_prompt'], .prompt) textarea")) return;
|
||||||
if (! (event.metaKey || event.ctrlKey)) return;
|
if (!(event.metaKey || event.ctrlKey)) return;
|
||||||
|
|
||||||
let isPlus = event.key == "ArrowUp"
|
let isPlus = event.key == "ArrowUp";
|
||||||
let isMinus = event.key == "ArrowDown"
|
let isMinus = event.key == "ArrowDown";
|
||||||
if (!isPlus && !isMinus) return;
|
if (!isPlus && !isMinus) return;
|
||||||
|
|
||||||
let selectionStart = target.selectionStart;
|
let selectionStart = target.selectionStart;
|
||||||
let selectionEnd = target.selectionEnd;
|
let selectionEnd = target.selectionEnd;
|
||||||
let text = target.value;
|
let text = target.value;
|
||||||
|
|
||||||
function selectCurrentParenthesisBlock(OPEN, CLOSE){
|
function selectCurrentParenthesisBlock(OPEN, CLOSE) {
|
||||||
if (selectionStart !== selectionEnd) return false;
|
if (selectionStart !== selectionEnd) return false;
|
||||||
|
|
||||||
// Find opening parenthesis around current cursor
|
// Find opening parenthesis around current cursor
|
||||||
const before = text.substring(0, selectionStart);
|
const before = text.substring(0, selectionStart);
|
||||||
let beforeParen = before.lastIndexOf(OPEN);
|
let beforeParen = before.lastIndexOf(OPEN);
|
||||||
if (beforeParen == -1) return false;
|
if (beforeParen == -1) return false;
|
||||||
let beforeParenClose = before.lastIndexOf(CLOSE);
|
|
||||||
while (beforeParenClose !== -1 && beforeParenClose > beforeParen) {
|
let beforeClosingParen = before.lastIndexOf(CLOSE);
|
||||||
beforeParen = before.lastIndexOf(OPEN, beforeParen - 1);
|
if (beforeClosingParen != -1 && beforeClosingParen > beforeParen) return false;
|
||||||
beforeParenClose = before.lastIndexOf(CLOSE, beforeParenClose - 1);
|
|
||||||
}
|
// Find closing parenthesis around current cursor
|
||||||
|
const after = text.substring(selectionStart);
|
||||||
// Find closing parenthesis around current cursor
|
let afterParen = after.indexOf(CLOSE);
|
||||||
const after = text.substring(selectionStart);
|
if (afterParen == -1) return false;
|
||||||
let afterParen = after.indexOf(CLOSE);
|
|
||||||
if (afterParen == -1) return false;
|
let afterOpeningParen = after.indexOf(OPEN);
|
||||||
let afterParenOpen = after.indexOf(OPEN);
|
if (afterOpeningParen != -1 && afterOpeningParen < afterParen) return false;
|
||||||
while (afterParenOpen !== -1 && afterParen > afterParenOpen) {
|
|
||||||
afterParen = after.indexOf(CLOSE, afterParen + 1);
|
// Set the selection to the text between the parenthesis
|
||||||
afterParenOpen = after.indexOf(OPEN, afterParenOpen + 1);
|
const parenContent = text.substring(beforeParen + 1, selectionStart + afterParen);
|
||||||
}
|
if (/.*:-?[\d.]+/s.test(parenContent)) {
|
||||||
if (beforeParen === -1 || afterParen === -1) return false;
|
const lastColon = parenContent.lastIndexOf(":");
|
||||||
|
selectionStart = beforeParen + 1;
|
||||||
// Set the selection to the text between the parenthesis
|
selectionEnd = selectionStart + lastColon;
|
||||||
const parenContent = text.substring(beforeParen + 1, selectionStart + afterParen);
|
} else {
|
||||||
const lastColon = parenContent.lastIndexOf(":");
|
selectionStart = beforeParen + 1;
|
||||||
selectionStart = beforeParen + 1;
|
selectionEnd = selectionStart + parenContent.length;
|
||||||
selectionEnd = selectionStart + lastColon;
|
}
|
||||||
target.setSelectionRange(selectionStart, selectionEnd);
|
|
||||||
return true;
|
target.setSelectionRange(selectionStart, selectionEnd);
|
||||||
}
|
return true;
|
||||||
|
}
|
||||||
function selectCurrentWord(){
|
|
||||||
if (selectionStart !== selectionEnd) return false;
|
function selectCurrentWord() {
|
||||||
const delimiters = opts.keyedit_delimiters + " \r\n\t";
|
if (selectionStart !== selectionEnd) return false;
|
||||||
|
const whitespace_delimiters = {"Tab": "\t", "Carriage Return": "\r", "Line Feed": "\n"};
|
||||||
// seek backward until to find beggining
|
let delimiters = opts.keyedit_delimiters;
|
||||||
while (!delimiters.includes(text[selectionStart - 1]) && selectionStart > 0) {
|
|
||||||
selectionStart--;
|
for (let i of opts.keyedit_delimiters_whitespace) {
|
||||||
}
|
delimiters += whitespace_delimiters[i];
|
||||||
|
}
|
||||||
// seek forward to find end
|
|
||||||
while (!delimiters.includes(text[selectionEnd]) && selectionEnd < text.length) {
|
// seek backward to find beginning
|
||||||
selectionEnd++;
|
while (!delimiters.includes(text[selectionStart - 1]) && selectionStart > 0) {
|
||||||
}
|
selectionStart--;
|
||||||
|
}
|
||||||
target.setSelectionRange(selectionStart, selectionEnd);
|
|
||||||
return true;
|
// seek forward to find end
|
||||||
}
|
while (!delimiters.includes(text[selectionEnd]) && selectionEnd < text.length) {
|
||||||
|
selectionEnd++;
|
||||||
// If the user hasn't selected anything, let's select their current parenthesis block or word
|
}
|
||||||
if (!selectCurrentParenthesisBlock('<', '>') && !selectCurrentParenthesisBlock('(', ')')) {
|
|
||||||
selectCurrentWord();
|
// deselect surrounding whitespace
|
||||||
}
|
while (text[selectionStart] == " " && selectionStart < selectionEnd) {
|
||||||
|
selectionStart++;
|
||||||
event.preventDefault();
|
}
|
||||||
|
while (text[selectionEnd - 1] == " " && selectionEnd > selectionStart) {
|
||||||
var closeCharacter = ')'
|
selectionEnd--;
|
||||||
var delta = opts.keyedit_precision_attention
|
}
|
||||||
|
|
||||||
if (selectionStart > 0 && text[selectionStart - 1] == '<'){
|
target.setSelectionRange(selectionStart, selectionEnd);
|
||||||
closeCharacter = '>'
|
return true;
|
||||||
delta = opts.keyedit_precision_extra
|
}
|
||||||
} else if (selectionStart == 0 || text[selectionStart - 1] != "(") {
|
|
||||||
|
// If the user hasn't selected anything, let's select their current parenthesis block or word
|
||||||
// do not include spaces at the end
|
if (!selectCurrentParenthesisBlock('<', '>') && !selectCurrentParenthesisBlock('(', ')') && !selectCurrentParenthesisBlock('[', ']')) {
|
||||||
while(selectionEnd > selectionStart && text[selectionEnd-1] == ' '){
|
selectCurrentWord();
|
||||||
selectionEnd -= 1;
|
}
|
||||||
}
|
|
||||||
if(selectionStart == selectionEnd){
|
event.preventDefault();
|
||||||
return
|
|
||||||
}
|
var closeCharacter = ')';
|
||||||
|
var delta = opts.keyedit_precision_attention;
|
||||||
text = text.slice(0, selectionStart) + "(" + text.slice(selectionStart, selectionEnd) + ":1.0)" + text.slice(selectionEnd);
|
var start = selectionStart > 0 ? text[selectionStart - 1] : "";
|
||||||
|
var end = text[selectionEnd];
|
||||||
selectionStart += 1;
|
|
||||||
selectionEnd += 1;
|
if (start == '<') {
|
||||||
}
|
closeCharacter = '>';
|
||||||
|
delta = opts.keyedit_precision_extra;
|
||||||
var end = text.slice(selectionEnd + 1).indexOf(closeCharacter) + 1;
|
} else if (start == '(' && end == ')' || start == '[' && end == ']') { // convert old-style (((emphasis)))
|
||||||
var weight = parseFloat(text.slice(selectionEnd + 1, selectionEnd + 1 + end));
|
let numParen = 0;
|
||||||
if (isNaN(weight)) return;
|
|
||||||
|
while (text[selectionStart - numParen - 1] == start && text[selectionEnd + numParen] == end) {
|
||||||
weight += isPlus ? delta : -delta;
|
numParen++;
|
||||||
weight = parseFloat(weight.toPrecision(12));
|
}
|
||||||
if(String(weight).length == 1) weight += ".0"
|
|
||||||
|
if (start == "[") {
|
||||||
if (closeCharacter == ')' && weight == 1) {
|
weight = (1 / 1.1) ** numParen;
|
||||||
text = text.slice(0, selectionStart - 1) + text.slice(selectionStart, selectionEnd) + text.slice(selectionEnd + 5);
|
} else {
|
||||||
selectionStart--;
|
weight = 1.1 ** numParen;
|
||||||
selectionEnd--;
|
}
|
||||||
} else {
|
|
||||||
text = text.slice(0, selectionEnd + 1) + weight + text.slice(selectionEnd + 1 + end - 1);
|
weight = Math.round(weight / opts.keyedit_precision_attention) * opts.keyedit_precision_attention;
|
||||||
}
|
|
||||||
|
text = text.slice(0, selectionStart - numParen) + "(" + text.slice(selectionStart, selectionEnd) + ":" + weight + ")" + text.slice(selectionEnd + numParen);
|
||||||
target.focus();
|
selectionStart -= numParen - 1;
|
||||||
target.value = text;
|
selectionEnd -= numParen - 1;
|
||||||
target.selectionStart = selectionStart;
|
} else if (start != '(') {
|
||||||
target.selectionEnd = selectionEnd;
|
// do not include spaces at the end
|
||||||
|
while (selectionEnd > selectionStart && text[selectionEnd - 1] == ' ') {
|
||||||
updateInput(target)
|
selectionEnd--;
|
||||||
}
|
}
|
||||||
|
|
||||||
addEventListener('keydown', (event) => {
|
if (selectionStart == selectionEnd) {
|
||||||
keyupEditAttention(event);
|
return;
|
||||||
});
|
}
|
||||||
|
|
||||||
|
text = text.slice(0, selectionStart) + "(" + text.slice(selectionStart, selectionEnd) + ":1.0)" + text.slice(selectionEnd);
|
||||||
|
|
||||||
|
selectionStart++;
|
||||||
|
selectionEnd++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (text[selectionEnd] != ':') return;
|
||||||
|
var weightLength = text.slice(selectionEnd + 1).indexOf(closeCharacter) + 1;
|
||||||
|
var weight = parseFloat(text.slice(selectionEnd + 1, selectionEnd + weightLength));
|
||||||
|
if (isNaN(weight)) return;
|
||||||
|
|
||||||
|
weight += isPlus ? delta : -delta;
|
||||||
|
weight = parseFloat(weight.toPrecision(12));
|
||||||
|
if (Number.isInteger(weight)) weight += ".0";
|
||||||
|
|
||||||
|
if (closeCharacter == ')' && weight == 1) {
|
||||||
|
var endParenPos = text.substring(selectionEnd).indexOf(')');
|
||||||
|
text = text.slice(0, selectionStart - 1) + text.slice(selectionStart, selectionEnd) + text.slice(selectionEnd + endParenPos + 1);
|
||||||
|
selectionStart--;
|
||||||
|
selectionEnd--;
|
||||||
|
} else {
|
||||||
|
text = text.slice(0, selectionEnd + 1) + weight + text.slice(selectionEnd + weightLength);
|
||||||
|
}
|
||||||
|
|
||||||
|
target.focus();
|
||||||
|
target.value = text;
|
||||||
|
target.selectionStart = selectionStart;
|
||||||
|
target.selectionEnd = selectionEnd;
|
||||||
|
|
||||||
|
updateInput(target);
|
||||||
|
}
|
||||||
|
|
||||||
|
addEventListener('keydown', (event) => {
|
||||||
|
keyupEditAttention(event);
|
||||||
|
});
|
||||||
|
41
javascript/edit-order.js
Normal file
41
javascript/edit-order.js
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
/* alt+left/right moves text in prompt */
|
||||||
|
|
||||||
|
function keyupEditOrder(event) {
|
||||||
|
if (!opts.keyedit_move) return;
|
||||||
|
|
||||||
|
let target = event.originalTarget || event.composedPath()[0];
|
||||||
|
if (!target.matches("*:is([id*='_toprow'] [id*='_prompt'], .prompt) textarea")) return;
|
||||||
|
if (!event.altKey) return;
|
||||||
|
|
||||||
|
let isLeft = event.key == "ArrowLeft";
|
||||||
|
let isRight = event.key == "ArrowRight";
|
||||||
|
if (!isLeft && !isRight) return;
|
||||||
|
event.preventDefault();
|
||||||
|
|
||||||
|
let selectionStart = target.selectionStart;
|
||||||
|
let selectionEnd = target.selectionEnd;
|
||||||
|
let text = target.value;
|
||||||
|
let items = text.split(",");
|
||||||
|
let indexStart = (text.slice(0, selectionStart).match(/,/g) || []).length;
|
||||||
|
let indexEnd = (text.slice(0, selectionEnd).match(/,/g) || []).length;
|
||||||
|
let range = indexEnd - indexStart + 1;
|
||||||
|
|
||||||
|
if (isLeft && indexStart > 0) {
|
||||||
|
items.splice(indexStart - 1, 0, ...items.splice(indexStart, range));
|
||||||
|
target.value = items.join();
|
||||||
|
target.selectionStart = items.slice(0, indexStart - 1).join().length + (indexStart == 1 ? 0 : 1);
|
||||||
|
target.selectionEnd = items.slice(0, indexEnd).join().length;
|
||||||
|
} else if (isRight && indexEnd < items.length - 1) {
|
||||||
|
items.splice(indexStart + 1, 0, ...items.splice(indexStart, range));
|
||||||
|
target.value = items.join();
|
||||||
|
target.selectionStart = items.slice(0, indexStart + 1).join().length + 1;
|
||||||
|
target.selectionEnd = items.slice(0, indexEnd + 2).join().length;
|
||||||
|
}
|
||||||
|
|
||||||
|
event.preventDefault();
|
||||||
|
updateInput(target);
|
||||||
|
}
|
||||||
|
|
||||||
|
addEventListener('keydown', (event) => {
|
||||||
|
keyupEditOrder(event);
|
||||||
|
});
|
@ -1,71 +1,95 @@
|
|||||||
|
|
||||||
function extensions_apply(_disabled_list, _update_list, disable_all){
|
function extensions_apply(_disabled_list, _update_list, disable_all) {
|
||||||
var disable = []
|
var disable = [];
|
||||||
var update = []
|
var update = [];
|
||||||
|
const extensions_input = gradioApp().querySelectorAll('#extensions input[type="checkbox"]');
|
||||||
gradioApp().querySelectorAll('#extensions input[type="checkbox"]').forEach(function(x){
|
if (extensions_input.length == 0) {
|
||||||
if(x.name.startsWith("enable_") && ! x.checked)
|
throw Error("Extensions page not yet loaded.");
|
||||||
disable.push(x.name.substring(7))
|
}
|
||||||
|
extensions_input.forEach(function(x) {
|
||||||
if(x.name.startsWith("update_") && x.checked)
|
if (x.name.startsWith("enable_") && !x.checked) {
|
||||||
update.push(x.name.substring(7))
|
disable.push(x.name.substring(7));
|
||||||
})
|
}
|
||||||
|
|
||||||
restart_reload()
|
if (x.name.startsWith("update_") && x.checked) {
|
||||||
|
update.push(x.name.substring(7));
|
||||||
return [JSON.stringify(disable), JSON.stringify(update), disable_all]
|
}
|
||||||
}
|
});
|
||||||
|
|
||||||
function extensions_check(){
|
restart_reload();
|
||||||
var disable = []
|
|
||||||
|
return [JSON.stringify(disable), JSON.stringify(update), disable_all];
|
||||||
gradioApp().querySelectorAll('#extensions input[type="checkbox"]').forEach(function(x){
|
}
|
||||||
if(x.name.startsWith("enable_") && ! x.checked)
|
|
||||||
disable.push(x.name.substring(7))
|
function extensions_check() {
|
||||||
})
|
var disable = [];
|
||||||
|
|
||||||
gradioApp().querySelectorAll('#extensions .extension_status').forEach(function(x){
|
gradioApp().querySelectorAll('#extensions input[type="checkbox"]').forEach(function(x) {
|
||||||
x.innerHTML = "Loading..."
|
if (x.name.startsWith("enable_") && !x.checked) {
|
||||||
})
|
disable.push(x.name.substring(7));
|
||||||
|
}
|
||||||
|
});
|
||||||
var id = randomId()
|
|
||||||
requestProgress(id, gradioApp().getElementById('extensions_installed_top'), null, function(){
|
gradioApp().querySelectorAll('#extensions .extension_status').forEach(function(x) {
|
||||||
|
x.innerHTML = "Loading...";
|
||||||
})
|
});
|
||||||
|
|
||||||
return [id, JSON.stringify(disable)]
|
|
||||||
}
|
var id = randomId();
|
||||||
|
requestProgress(id, gradioApp().getElementById('extensions_installed_html'), null, function() {
|
||||||
function install_extension_from_index(button, url){
|
|
||||||
button.disabled = "disabled"
|
});
|
||||||
button.value = "Installing..."
|
|
||||||
|
return [id, JSON.stringify(disable)];
|
||||||
var textarea = gradioApp().querySelector('#extension_to_install textarea')
|
}
|
||||||
textarea.value = url
|
|
||||||
updateInput(textarea)
|
function install_extension_from_index(button, url) {
|
||||||
|
button.disabled = "disabled";
|
||||||
gradioApp().querySelector('#install_extension_button').click()
|
button.value = "Installing...";
|
||||||
}
|
|
||||||
|
var textarea = gradioApp().querySelector('#extension_to_install textarea');
|
||||||
function config_state_confirm_restore(_, config_state_name, config_restore_type) {
|
textarea.value = url;
|
||||||
if (config_state_name == "Current") {
|
updateInput(textarea);
|
||||||
return [false, config_state_name, config_restore_type];
|
|
||||||
}
|
gradioApp().querySelector('#install_extension_button').click();
|
||||||
let restored = "";
|
}
|
||||||
if (config_restore_type == "extensions") {
|
|
||||||
restored = "all saved extension versions";
|
function config_state_confirm_restore(_, config_state_name, config_restore_type) {
|
||||||
} else if (config_restore_type == "webui") {
|
if (config_state_name == "Current") {
|
||||||
restored = "the webui version";
|
return [false, config_state_name, config_restore_type];
|
||||||
} else {
|
}
|
||||||
restored = "the webui version and all saved extension versions";
|
let restored = "";
|
||||||
}
|
if (config_restore_type == "extensions") {
|
||||||
let confirmed = confirm("Are you sure you want to restore from this state?\nThis will reset " + restored + ".");
|
restored = "all saved extension versions";
|
||||||
if (confirmed) {
|
} else if (config_restore_type == "webui") {
|
||||||
restart_reload();
|
restored = "the webui version";
|
||||||
gradioApp().querySelectorAll('#extensions .extension_status').forEach(function(x){
|
} else {
|
||||||
x.innerHTML = "Loading..."
|
restored = "the webui version and all saved extension versions";
|
||||||
})
|
}
|
||||||
}
|
let confirmed = confirm("Are you sure you want to restore from this state?\nThis will reset " + restored + ".");
|
||||||
return [confirmed, config_state_name, config_restore_type];
|
if (confirmed) {
|
||||||
}
|
restart_reload();
|
||||||
|
gradioApp().querySelectorAll('#extensions .extension_status').forEach(function(x) {
|
||||||
|
x.innerHTML = "Loading...";
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return [confirmed, config_state_name, config_restore_type];
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggle_all_extensions(event) {
|
||||||
|
gradioApp().querySelectorAll('#extensions .extension_toggle').forEach(function(checkbox_el) {
|
||||||
|
checkbox_el.checked = event.target.checked;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggle_extension() {
|
||||||
|
let all_extensions_toggled = true;
|
||||||
|
for (const checkbox_el of gradioApp().querySelectorAll('#extensions .extension_toggle')) {
|
||||||
|
if (!checkbox_el.checked) {
|
||||||
|
all_extensions_toggled = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
gradioApp().querySelector('#extensions .all_extensions_toggle').checked = all_extensions_toggled;
|
||||||
|
}
|
||||||
|
@ -1,196 +1,712 @@
|
|||||||
function setupExtraNetworksForTab(tabname){
|
function toggleCss(key, css, enable) {
|
||||||
gradioApp().querySelector('#'+tabname+'_extra_tabs').classList.add('extra-networks')
|
var style = document.getElementById(key);
|
||||||
|
if (enable && !style) {
|
||||||
var tabs = gradioApp().querySelector('#'+tabname+'_extra_tabs > div')
|
style = document.createElement('style');
|
||||||
var search = gradioApp().querySelector('#'+tabname+'_extra_search textarea')
|
style.id = key;
|
||||||
var refresh = gradioApp().getElementById(tabname+'_extra_refresh')
|
style.type = 'text/css';
|
||||||
|
document.head.appendChild(style);
|
||||||
search.classList.add('search')
|
}
|
||||||
tabs.appendChild(search)
|
if (style && !enable) {
|
||||||
tabs.appendChild(refresh)
|
document.head.removeChild(style);
|
||||||
|
}
|
||||||
var applyFilter = function(){
|
if (style) {
|
||||||
var searchTerm = search.value.toLowerCase()
|
style.innerHTML == '';
|
||||||
|
style.appendChild(document.createTextNode(css));
|
||||||
gradioApp().querySelectorAll('#'+tabname+'_extra_tabs div.card').forEach(function(elem){
|
}
|
||||||
var searchOnly = elem.querySelector('.search_only')
|
}
|
||||||
var text = elem.querySelector('.name').textContent.toLowerCase() + " " + elem.querySelector('.search_term').textContent.toLowerCase()
|
|
||||||
|
function setupExtraNetworksForTab(tabname) {
|
||||||
var visible = text.indexOf(searchTerm) != -1
|
function registerPrompt(tabname, id) {
|
||||||
|
var textarea = gradioApp().querySelector("#" + id + " > label > textarea");
|
||||||
if(searchOnly && searchTerm.length < 4){
|
|
||||||
visible = false
|
if (!activePromptTextarea[tabname]) {
|
||||||
}
|
activePromptTextarea[tabname] = textarea;
|
||||||
|
}
|
||||||
elem.style.display = visible ? "" : "none"
|
|
||||||
})
|
textarea.addEventListener("focus", function() {
|
||||||
}
|
activePromptTextarea[tabname] = textarea;
|
||||||
|
});
|
||||||
search.addEventListener("input", applyFilter);
|
}
|
||||||
applyFilter();
|
|
||||||
|
var tabnav = gradioApp().querySelector('#' + tabname + '_extra_tabs > div.tab-nav');
|
||||||
extraNetworksApplyFilter[tabname] = applyFilter;
|
var controlsDiv = document.createElement('DIV');
|
||||||
}
|
controlsDiv.classList.add('extra-networks-controls-div');
|
||||||
|
tabnav.appendChild(controlsDiv);
|
||||||
function applyExtraNetworkFilter(tabname){
|
tabnav.insertBefore(controlsDiv, null);
|
||||||
setTimeout(extraNetworksApplyFilter[tabname], 1);
|
|
||||||
}
|
var this_tab = gradioApp().querySelector('#' + tabname + '_extra_tabs');
|
||||||
|
this_tab.querySelectorAll(":scope > [id^='" + tabname + "_']").forEach(function(elem) {
|
||||||
var extraNetworksApplyFilter = {}
|
// tabname_full = {tabname}_{extra_networks_tabname}
|
||||||
var activePromptTextarea = {};
|
var tabname_full = elem.id;
|
||||||
|
var search = gradioApp().querySelector("#" + tabname_full + "_extra_search");
|
||||||
function setupExtraNetworks(){
|
var sort_dir = gradioApp().querySelector("#" + tabname_full + "_extra_sort_dir");
|
||||||
setupExtraNetworksForTab('txt2img')
|
var refresh = gradioApp().querySelector("#" + tabname_full + "_extra_refresh");
|
||||||
setupExtraNetworksForTab('img2img')
|
var currentSort = '';
|
||||||
|
|
||||||
function registerPrompt(tabname, id){
|
// If any of the buttons above don't exist, we want to skip this iteration of the loop.
|
||||||
var textarea = gradioApp().querySelector("#" + id + " > label > textarea");
|
if (!search || !sort_dir || !refresh) {
|
||||||
|
return; // `return` is equivalent of `continue` but for forEach loops.
|
||||||
if (! activePromptTextarea[tabname]){
|
}
|
||||||
activePromptTextarea[tabname] = textarea
|
|
||||||
}
|
var applyFilter = function(force) {
|
||||||
|
var searchTerm = search.value.toLowerCase();
|
||||||
textarea.addEventListener("focus", function(){
|
gradioApp().querySelectorAll('#' + tabname + '_extra_tabs div.card').forEach(function(elem) {
|
||||||
activePromptTextarea[tabname] = textarea;
|
var searchOnly = elem.querySelector('.search_only');
|
||||||
});
|
var text = Array.prototype.map.call(elem.querySelectorAll('.search_terms, .description'), function(t) {
|
||||||
}
|
return t.textContent.toLowerCase();
|
||||||
|
}).join(" ");
|
||||||
registerPrompt('txt2img', 'txt2img_prompt')
|
|
||||||
registerPrompt('txt2img', 'txt2img_neg_prompt')
|
var visible = text.indexOf(searchTerm) != -1;
|
||||||
registerPrompt('img2img', 'img2img_prompt')
|
if (searchOnly && searchTerm.length < 4) {
|
||||||
registerPrompt('img2img', 'img2img_neg_prompt')
|
visible = false;
|
||||||
}
|
}
|
||||||
|
if (visible) {
|
||||||
onUiLoaded(setupExtraNetworks)
|
elem.classList.remove("hidden");
|
||||||
|
} else {
|
||||||
var re_extranet = /<([^:]+:[^:]+):[\d\.]+>/;
|
elem.classList.add("hidden");
|
||||||
var re_extranet_g = /\s+<([^:]+:[^:]+):[\d\.]+>/g;
|
}
|
||||||
|
});
|
||||||
function tryToRemoveExtraNetworkFromPrompt(textarea, text){
|
|
||||||
var m = text.match(re_extranet)
|
applySort(force);
|
||||||
if(! m) return false
|
};
|
||||||
|
|
||||||
var partToSearch = m[1]
|
var applySort = function(force) {
|
||||||
var replaced = false
|
var cards = gradioApp().querySelectorAll('#' + tabname_full + ' div.card');
|
||||||
var newTextareaText = textarea.value.replaceAll(re_extranet_g, function(found){
|
var parent = gradioApp().querySelector('#' + tabname_full + "_cards");
|
||||||
m = found.match(re_extranet);
|
var reverse = sort_dir.dataset.sortdir == "Descending";
|
||||||
if(m[1] == partToSearch){
|
var activeSearchElem = gradioApp().querySelector('#' + tabname_full + "_controls .extra-network-control--sort.extra-network-control--enabled");
|
||||||
replaced = true;
|
var sortKey = activeSearchElem ? activeSearchElem.dataset.sortkey : "default";
|
||||||
return ""
|
var sortKeyDataField = "sort" + sortKey.charAt(0).toUpperCase() + sortKey.slice(1);
|
||||||
}
|
var sortKeyStore = sortKey + "-" + sort_dir.dataset.sortdir + "-" + cards.length;
|
||||||
return found;
|
|
||||||
})
|
if (sortKeyStore == currentSort && !force) {
|
||||||
|
return;
|
||||||
if(replaced){
|
}
|
||||||
textarea.value = newTextareaText
|
currentSort = sortKeyStore;
|
||||||
return true;
|
|
||||||
}
|
var sortedCards = Array.from(cards);
|
||||||
|
sortedCards.sort(function(cardA, cardB) {
|
||||||
return false
|
var a = cardA.dataset[sortKeyDataField];
|
||||||
}
|
var b = cardB.dataset[sortKeyDataField];
|
||||||
|
if (!isNaN(a) && !isNaN(b)) {
|
||||||
function cardClicked(tabname, textToAdd, allowNegativePrompt){
|
return parseInt(a) - parseInt(b);
|
||||||
var textarea = allowNegativePrompt ? activePromptTextarea[tabname] : gradioApp().querySelector("#" + tabname + "_prompt > label > textarea")
|
}
|
||||||
|
|
||||||
if(! tryToRemoveExtraNetworkFromPrompt(textarea, textToAdd)){
|
return (a < b ? -1 : (a > b ? 1 : 0));
|
||||||
textarea.value = textarea.value + opts.extra_networks_add_text_separator + textToAdd
|
});
|
||||||
}
|
|
||||||
|
if (reverse) {
|
||||||
updateInput(textarea)
|
sortedCards.reverse();
|
||||||
}
|
}
|
||||||
|
|
||||||
function saveCardPreview(event, tabname, filename){
|
parent.innerHTML = '';
|
||||||
var textarea = gradioApp().querySelector("#" + tabname + '_preview_filename > label > textarea')
|
|
||||||
var button = gradioApp().getElementById(tabname + '_save_preview')
|
var frag = document.createDocumentFragment();
|
||||||
|
sortedCards.forEach(function(card) {
|
||||||
textarea.value = filename
|
frag.appendChild(card);
|
||||||
updateInput(textarea)
|
});
|
||||||
|
parent.appendChild(frag);
|
||||||
button.click()
|
};
|
||||||
|
|
||||||
event.stopPropagation()
|
search.addEventListener("input", function() {
|
||||||
event.preventDefault()
|
applyFilter();
|
||||||
}
|
});
|
||||||
|
applySort();
|
||||||
function extraNetworksSearchButton(tabs_id, event){
|
applyFilter();
|
||||||
var searchTextarea = gradioApp().querySelector("#" + tabs_id + ' > div > textarea')
|
extraNetworksApplySort[tabname_full] = applySort;
|
||||||
var button = event.target
|
extraNetworksApplyFilter[tabname_full] = applyFilter;
|
||||||
var text = button.classList.contains("search-all") ? "" : button.textContent.trim()
|
|
||||||
|
var controls = gradioApp().querySelector("#" + tabname_full + "_controls");
|
||||||
searchTextarea.value = text
|
controlsDiv.insertBefore(controls, null);
|
||||||
updateInput(searchTextarea)
|
|
||||||
}
|
if (elem.style.display != "none") {
|
||||||
|
extraNetworksShowControlsForPage(tabname, tabname_full);
|
||||||
var globalPopup = null;
|
}
|
||||||
var globalPopupInner = null;
|
});
|
||||||
function popup(contents){
|
|
||||||
if(! globalPopup){
|
registerPrompt(tabname, tabname + "_prompt");
|
||||||
globalPopup = document.createElement('div')
|
registerPrompt(tabname, tabname + "_neg_prompt");
|
||||||
globalPopup.onclick = function(){ globalPopup.style.display = "none"; };
|
}
|
||||||
globalPopup.classList.add('global-popup');
|
|
||||||
|
function extraNetworksMovePromptToTab(tabname, id, showPrompt, showNegativePrompt) {
|
||||||
var close = document.createElement('div')
|
if (!gradioApp().querySelector('.toprow-compact-tools')) return; // only applicable for compact prompt layout
|
||||||
close.classList.add('global-popup-close');
|
|
||||||
close.onclick = function(){ globalPopup.style.display = "none"; };
|
var promptContainer = gradioApp().getElementById(tabname + '_prompt_container');
|
||||||
close.title = "Close";
|
var prompt = gradioApp().getElementById(tabname + '_prompt_row');
|
||||||
globalPopup.appendChild(close)
|
var negPrompt = gradioApp().getElementById(tabname + '_neg_prompt_row');
|
||||||
|
var elem = id ? gradioApp().getElementById(id) : null;
|
||||||
globalPopupInner = document.createElement('div')
|
|
||||||
globalPopupInner.onclick = function(event){ event.stopPropagation(); return false; };
|
if (showNegativePrompt && elem) {
|
||||||
globalPopupInner.classList.add('global-popup-inner');
|
elem.insertBefore(negPrompt, elem.firstChild);
|
||||||
globalPopup.appendChild(globalPopupInner)
|
} else {
|
||||||
|
promptContainer.insertBefore(negPrompt, promptContainer.firstChild);
|
||||||
gradioApp().appendChild(globalPopup);
|
}
|
||||||
}
|
|
||||||
|
if (showPrompt && elem) {
|
||||||
globalPopupInner.innerHTML = '';
|
elem.insertBefore(prompt, elem.firstChild);
|
||||||
globalPopupInner.appendChild(contents);
|
} else {
|
||||||
|
promptContainer.insertBefore(prompt, promptContainer.firstChild);
|
||||||
globalPopup.style.display = "flex";
|
}
|
||||||
}
|
|
||||||
|
if (elem) {
|
||||||
function extraNetworksShowMetadata(text){
|
elem.classList.toggle('extra-page-prompts-active', showNegativePrompt || showPrompt);
|
||||||
var elem = document.createElement('pre')
|
}
|
||||||
elem.classList.add('popup-metadata');
|
}
|
||||||
elem.textContent = text;
|
|
||||||
|
|
||||||
popup(elem);
|
function extraNetworksShowControlsForPage(tabname, tabname_full) {
|
||||||
}
|
gradioApp().querySelectorAll('#' + tabname + '_extra_tabs .extra-networks-controls-div > div').forEach(function(elem) {
|
||||||
|
var targetId = tabname_full + "_controls";
|
||||||
function requestGet(url, data, handler, errorHandler){
|
elem.style.display = elem.id == targetId ? "" : "none";
|
||||||
var xhr = new XMLHttpRequest();
|
});
|
||||||
var args = Object.keys(data).map(function(k){ return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) }).join('&')
|
}
|
||||||
xhr.open("GET", url + "?" + args, true);
|
|
||||||
|
|
||||||
xhr.onreadystatechange = function () {
|
function extraNetworksUnrelatedTabSelected(tabname) { // called from python when user selects an unrelated tab (generate)
|
||||||
if (xhr.readyState === 4) {
|
extraNetworksMovePromptToTab(tabname, '', false, false);
|
||||||
if (xhr.status === 200) {
|
|
||||||
try {
|
extraNetworksShowControlsForPage(tabname, null);
|
||||||
var js = JSON.parse(xhr.responseText);
|
}
|
||||||
handler(js)
|
|
||||||
} catch (error) {
|
function extraNetworksTabSelected(tabname, id, showPrompt, showNegativePrompt, tabname_full) { // called from python when user selects an extra networks tab
|
||||||
console.error(error);
|
extraNetworksMovePromptToTab(tabname, id, showPrompt, showNegativePrompt);
|
||||||
errorHandler()
|
|
||||||
}
|
extraNetworksShowControlsForPage(tabname, tabname_full);
|
||||||
} else{
|
}
|
||||||
errorHandler()
|
|
||||||
}
|
function applyExtraNetworkFilter(tabname_full) {
|
||||||
}
|
var doFilter = function() {
|
||||||
};
|
var applyFunction = extraNetworksApplyFilter[tabname_full];
|
||||||
var js = JSON.stringify(data);
|
|
||||||
xhr.send(js);
|
if (applyFunction) {
|
||||||
}
|
applyFunction(true);
|
||||||
|
}
|
||||||
function extraNetworksRequestMetadata(event, extraPage, cardName){
|
};
|
||||||
var showError = function(){ extraNetworksShowMetadata("there was an error getting metadata"); }
|
setTimeout(doFilter, 1);
|
||||||
|
}
|
||||||
requestGet("./sd_extra_networks/metadata", {"page": extraPage, "item": cardName}, function(data){
|
|
||||||
if(data && data.metadata){
|
function applyExtraNetworkSort(tabname_full) {
|
||||||
extraNetworksShowMetadata(data.metadata)
|
var doSort = function() {
|
||||||
} else{
|
extraNetworksApplySort[tabname_full](true);
|
||||||
showError()
|
};
|
||||||
}
|
setTimeout(doSort, 1);
|
||||||
}, showError)
|
}
|
||||||
|
|
||||||
event.stopPropagation()
|
var extraNetworksApplyFilter = {};
|
||||||
}
|
var extraNetworksApplySort = {};
|
||||||
|
var activePromptTextarea = {};
|
||||||
|
|
||||||
|
function setupExtraNetworks() {
|
||||||
|
setupExtraNetworksForTab('txt2img');
|
||||||
|
setupExtraNetworksForTab('img2img');
|
||||||
|
}
|
||||||
|
|
||||||
|
var re_extranet = /<([^:^>]+:[^:]+):[\d.]+>(.*)/;
|
||||||
|
var re_extranet_g = /<([^:^>]+:[^:]+):[\d.]+>/g;
|
||||||
|
|
||||||
|
var re_extranet_neg = /\(([^:^>]+:[\d.]+)\)/;
|
||||||
|
var re_extranet_g_neg = /\(([^:^>]+:[\d.]+)\)/g;
|
||||||
|
function tryToRemoveExtraNetworkFromPrompt(textarea, text, isNeg) {
|
||||||
|
var m = text.match(isNeg ? re_extranet_neg : re_extranet);
|
||||||
|
var replaced = false;
|
||||||
|
var newTextareaText;
|
||||||
|
var extraTextBeforeNet = opts.extra_networks_add_text_separator;
|
||||||
|
if (m) {
|
||||||
|
var extraTextAfterNet = m[2];
|
||||||
|
var partToSearch = m[1];
|
||||||
|
var foundAtPosition = -1;
|
||||||
|
newTextareaText = textarea.value.replaceAll(isNeg ? re_extranet_g_neg : re_extranet_g, function(found, net, pos) {
|
||||||
|
m = found.match(isNeg ? re_extranet_neg : re_extranet);
|
||||||
|
if (m[1] == partToSearch) {
|
||||||
|
replaced = true;
|
||||||
|
foundAtPosition = pos;
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return found;
|
||||||
|
});
|
||||||
|
if (foundAtPosition >= 0) {
|
||||||
|
if (extraTextAfterNet && newTextareaText.substr(foundAtPosition, extraTextAfterNet.length) == extraTextAfterNet) {
|
||||||
|
newTextareaText = newTextareaText.substr(0, foundAtPosition) + newTextareaText.substr(foundAtPosition + extraTextAfterNet.length);
|
||||||
|
}
|
||||||
|
if (newTextareaText.substr(foundAtPosition - extraTextBeforeNet.length, extraTextBeforeNet.length) == extraTextBeforeNet) {
|
||||||
|
newTextareaText = newTextareaText.substr(0, foundAtPosition - extraTextBeforeNet.length) + newTextareaText.substr(foundAtPosition);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
newTextareaText = textarea.value.replaceAll(new RegExp(`((?:${extraTextBeforeNet})?${text})`, "g"), "");
|
||||||
|
replaced = (newTextareaText != textarea.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (replaced) {
|
||||||
|
textarea.value = newTextareaText;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function updatePromptArea(text, textArea, isNeg) {
|
||||||
|
if (!tryToRemoveExtraNetworkFromPrompt(textArea, text, isNeg)) {
|
||||||
|
textArea.value = textArea.value + opts.extra_networks_add_text_separator + text;
|
||||||
|
}
|
||||||
|
|
||||||
|
updateInput(textArea);
|
||||||
|
}
|
||||||
|
|
||||||
|
function cardClicked(tabname, textToAdd, textToAddNegative, allowNegativePrompt) {
|
||||||
|
if (textToAddNegative.length > 0) {
|
||||||
|
updatePromptArea(textToAdd, gradioApp().querySelector("#" + tabname + "_prompt > label > textarea"));
|
||||||
|
updatePromptArea(textToAddNegative, gradioApp().querySelector("#" + tabname + "_neg_prompt > label > textarea"), true);
|
||||||
|
} else {
|
||||||
|
var textarea = allowNegativePrompt ? activePromptTextarea[tabname] : gradioApp().querySelector("#" + tabname + "_prompt > label > textarea");
|
||||||
|
updatePromptArea(textToAdd, textarea);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveCardPreview(event, tabname, filename) {
|
||||||
|
var textarea = gradioApp().querySelector("#" + tabname + '_preview_filename > label > textarea');
|
||||||
|
var button = gradioApp().getElementById(tabname + '_save_preview');
|
||||||
|
|
||||||
|
textarea.value = filename;
|
||||||
|
updateInput(textarea);
|
||||||
|
|
||||||
|
button.click();
|
||||||
|
|
||||||
|
event.stopPropagation();
|
||||||
|
event.preventDefault();
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksSearchButton(tabname, extra_networks_tabname, event) {
|
||||||
|
var searchTextarea = gradioApp().querySelector("#" + tabname + "_" + extra_networks_tabname + "_extra_search");
|
||||||
|
var button = event.target;
|
||||||
|
var text = button.classList.contains("search-all") ? "" : button.textContent.trim();
|
||||||
|
|
||||||
|
searchTextarea.value = text;
|
||||||
|
updateInput(searchTextarea);
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksTreeProcessFileClick(event, btn, tabname, extra_networks_tabname) {
|
||||||
|
/**
|
||||||
|
* Processes `onclick` events when user clicks on files in tree.
|
||||||
|
*
|
||||||
|
* @param event The generated event.
|
||||||
|
* @param btn The clicked `tree-list-item` button.
|
||||||
|
* @param tabname The name of the active tab in the sd webui. Ex: txt2img, img2img, etc.
|
||||||
|
* @param extra_networks_tabname The id of the active extraNetworks tab. Ex: lora, checkpoints, etc.
|
||||||
|
*/
|
||||||
|
// NOTE: Currently unused.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksTreeProcessDirectoryClick(event, btn, tabname, extra_networks_tabname) {
|
||||||
|
/**
|
||||||
|
* Processes `onclick` events when user clicks on directories in tree.
|
||||||
|
*
|
||||||
|
* Here is how the tree reacts to clicks for various states:
|
||||||
|
* unselected unopened directory: Directory is selected and expanded.
|
||||||
|
* unselected opened directory: Directory is selected.
|
||||||
|
* selected opened directory: Directory is collapsed and deselected.
|
||||||
|
* chevron is clicked: Directory is expanded or collapsed. Selected state unchanged.
|
||||||
|
*
|
||||||
|
* @param event The generated event.
|
||||||
|
* @param btn The clicked `tree-list-item` button.
|
||||||
|
* @param tabname The name of the active tab in the sd webui. Ex: txt2img, img2img, etc.
|
||||||
|
* @param extra_networks_tabname The id of the active extraNetworks tab. Ex: lora, checkpoints, etc.
|
||||||
|
*/
|
||||||
|
var ul = btn.nextElementSibling;
|
||||||
|
// This is the actual target that the user clicked on within the target button.
|
||||||
|
// We use this to detect if the chevron was clicked.
|
||||||
|
var true_targ = event.target;
|
||||||
|
|
||||||
|
function _expand_or_collapse(_ul, _btn) {
|
||||||
|
// Expands <ul> if it is collapsed, collapses otherwise. Updates button attributes.
|
||||||
|
if (_ul.hasAttribute("hidden")) {
|
||||||
|
_ul.removeAttribute("hidden");
|
||||||
|
_btn.dataset.expanded = "";
|
||||||
|
} else {
|
||||||
|
_ul.setAttribute("hidden", "");
|
||||||
|
delete _btn.dataset.expanded;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function _remove_selected_from_all() {
|
||||||
|
// Removes the `selected` attribute from all buttons.
|
||||||
|
var sels = document.querySelectorAll("div.tree-list-content");
|
||||||
|
[...sels].forEach(el => {
|
||||||
|
delete el.dataset.selected;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function _select_button(_btn) {
|
||||||
|
// Removes `data-selected` attribute from all buttons then adds to passed button.
|
||||||
|
_remove_selected_from_all();
|
||||||
|
_btn.dataset.selected = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function _update_search(_tabname, _extra_networks_tabname, _search_text) {
|
||||||
|
// Update search input with select button's path.
|
||||||
|
var search_input_elem = gradioApp().querySelector("#" + tabname + "_" + extra_networks_tabname + "_extra_search");
|
||||||
|
search_input_elem.value = _search_text;
|
||||||
|
updateInput(search_input_elem);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// If user clicks on the chevron, then we do not select the folder.
|
||||||
|
if (true_targ.matches(".tree-list-item-action--leading, .tree-list-item-action-chevron")) {
|
||||||
|
_expand_or_collapse(ul, btn);
|
||||||
|
} else {
|
||||||
|
// User clicked anywhere else on the button.
|
||||||
|
if ("selected" in btn.dataset && !(ul.hasAttribute("hidden"))) {
|
||||||
|
// If folder is select and open, collapse and deselect button.
|
||||||
|
_expand_or_collapse(ul, btn);
|
||||||
|
delete btn.dataset.selected;
|
||||||
|
_update_search(tabname, extra_networks_tabname, "");
|
||||||
|
} else if (!(!("selected" in btn.dataset) && !(ul.hasAttribute("hidden")))) {
|
||||||
|
// If folder is open and not selected, then we don't collapse; just select.
|
||||||
|
// NOTE: Double inversion sucks but it is the clearest way to show the branching here.
|
||||||
|
_expand_or_collapse(ul, btn);
|
||||||
|
_select_button(btn, tabname, extra_networks_tabname);
|
||||||
|
_update_search(tabname, extra_networks_tabname, btn.dataset.path);
|
||||||
|
} else {
|
||||||
|
// All other cases, just select the button.
|
||||||
|
_select_button(btn, tabname, extra_networks_tabname);
|
||||||
|
_update_search(tabname, extra_networks_tabname, btn.dataset.path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksTreeOnClick(event, tabname, extra_networks_tabname) {
|
||||||
|
/**
|
||||||
|
* Handles `onclick` events for buttons within an `extra-network-tree .tree-list--tree`.
|
||||||
|
*
|
||||||
|
* Determines whether the clicked button in the tree is for a file entry or a directory
|
||||||
|
* then calls the appropriate function.
|
||||||
|
*
|
||||||
|
* @param event The generated event.
|
||||||
|
* @param tabname The name of the active tab in the sd webui. Ex: txt2img, img2img, etc.
|
||||||
|
* @param extra_networks_tabname The id of the active extraNetworks tab. Ex: lora, checkpoints, etc.
|
||||||
|
*/
|
||||||
|
var btn = event.currentTarget;
|
||||||
|
var par = btn.parentElement;
|
||||||
|
if (par.dataset.treeEntryType === "file") {
|
||||||
|
extraNetworksTreeProcessFileClick(event, btn, tabname, extra_networks_tabname);
|
||||||
|
} else {
|
||||||
|
extraNetworksTreeProcessDirectoryClick(event, btn, tabname, extra_networks_tabname);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksControlSortOnClick(event, tabname, extra_networks_tabname) {
|
||||||
|
/** Handles `onclick` events for Sort Mode buttons. */
|
||||||
|
|
||||||
|
var self = event.currentTarget;
|
||||||
|
var parent = event.currentTarget.parentElement;
|
||||||
|
|
||||||
|
parent.querySelectorAll('.extra-network-control--sort').forEach(function(x) {
|
||||||
|
x.classList.remove('extra-network-control--enabled');
|
||||||
|
});
|
||||||
|
|
||||||
|
self.classList.add('extra-network-control--enabled');
|
||||||
|
|
||||||
|
applyExtraNetworkSort(tabname + "_" + extra_networks_tabname);
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksControlSortDirOnClick(event, tabname, extra_networks_tabname) {
|
||||||
|
/**
|
||||||
|
* Handles `onclick` events for the Sort Direction button.
|
||||||
|
*
|
||||||
|
* Modifies the data attributes of the Sort Direction button to cycle between
|
||||||
|
* ascending and descending sort directions.
|
||||||
|
*
|
||||||
|
* @param event The generated event.
|
||||||
|
* @param tabname The name of the active tab in the sd webui. Ex: txt2img, img2img, etc.
|
||||||
|
* @param extra_networks_tabname The id of the active extraNetworks tab. Ex: lora, checkpoints, etc.
|
||||||
|
*/
|
||||||
|
if (event.currentTarget.dataset.sortdir == "Ascending") {
|
||||||
|
event.currentTarget.dataset.sortdir = "Descending";
|
||||||
|
event.currentTarget.setAttribute("title", "Sort descending");
|
||||||
|
} else {
|
||||||
|
event.currentTarget.dataset.sortdir = "Ascending";
|
||||||
|
event.currentTarget.setAttribute("title", "Sort ascending");
|
||||||
|
}
|
||||||
|
applyExtraNetworkSort(tabname + "_" + extra_networks_tabname);
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksControlTreeViewOnClick(event, tabname, extra_networks_tabname) {
|
||||||
|
/**
|
||||||
|
* Handles `onclick` events for the Tree View button.
|
||||||
|
*
|
||||||
|
* Toggles the tree view in the extra networks pane.
|
||||||
|
*
|
||||||
|
* @param event The generated event.
|
||||||
|
* @param tabname The name of the active tab in the sd webui. Ex: txt2img, img2img, etc.
|
||||||
|
* @param extra_networks_tabname The id of the active extraNetworks tab. Ex: lora, checkpoints, etc.
|
||||||
|
*/
|
||||||
|
var button = event.currentTarget;
|
||||||
|
button.classList.toggle("extra-network-control--enabled");
|
||||||
|
var show = !button.classList.contains("extra-network-control--enabled");
|
||||||
|
|
||||||
|
var pane = gradioApp().getElementById(tabname + "_" + extra_networks_tabname + "_pane");
|
||||||
|
pane.classList.toggle("extra-network-dirs-hidden", show);
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksControlRefreshOnClick(event, tabname, extra_networks_tabname) {
|
||||||
|
/**
|
||||||
|
* Handles `onclick` events for the Refresh Page button.
|
||||||
|
*
|
||||||
|
* In order to actually call the python functions in `ui_extra_networks.py`
|
||||||
|
* to refresh the page, we created an empty gradio button in that file with an
|
||||||
|
* event handler that refreshes the page. So what this function here does
|
||||||
|
* is it manually raises a `click` event on that button.
|
||||||
|
*
|
||||||
|
* @param event The generated event.
|
||||||
|
* @param tabname The name of the active tab in the sd webui. Ex: txt2img, img2img, etc.
|
||||||
|
* @param extra_networks_tabname The id of the active extraNetworks tab. Ex: lora, checkpoints, etc.
|
||||||
|
*/
|
||||||
|
var btn_refresh_internal = gradioApp().getElementById(tabname + "_" + extra_networks_tabname + "_extra_refresh_internal");
|
||||||
|
btn_refresh_internal.dispatchEvent(new Event("click"));
|
||||||
|
}
|
||||||
|
|
||||||
|
var globalPopup = null;
|
||||||
|
var globalPopupInner = null;
|
||||||
|
|
||||||
|
function closePopup() {
|
||||||
|
if (!globalPopup) return;
|
||||||
|
globalPopup.style.display = "none";
|
||||||
|
}
|
||||||
|
|
||||||
|
function popup(contents) {
|
||||||
|
if (!globalPopup) {
|
||||||
|
globalPopup = document.createElement('div');
|
||||||
|
globalPopup.classList.add('global-popup');
|
||||||
|
|
||||||
|
var close = document.createElement('div');
|
||||||
|
close.classList.add('global-popup-close');
|
||||||
|
close.addEventListener("click", closePopup);
|
||||||
|
close.title = "Close";
|
||||||
|
globalPopup.appendChild(close);
|
||||||
|
|
||||||
|
globalPopupInner = document.createElement('div');
|
||||||
|
globalPopupInner.classList.add('global-popup-inner');
|
||||||
|
globalPopup.appendChild(globalPopupInner);
|
||||||
|
|
||||||
|
gradioApp().querySelector('.main').appendChild(globalPopup);
|
||||||
|
}
|
||||||
|
|
||||||
|
globalPopupInner.innerHTML = '';
|
||||||
|
globalPopupInner.appendChild(contents);
|
||||||
|
|
||||||
|
globalPopup.style.display = "flex";
|
||||||
|
}
|
||||||
|
|
||||||
|
var storedPopupIds = {};
|
||||||
|
function popupId(id) {
|
||||||
|
if (!storedPopupIds[id]) {
|
||||||
|
storedPopupIds[id] = gradioApp().getElementById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
popup(storedPopupIds[id]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksFlattenMetadata(obj) {
|
||||||
|
const result = {};
|
||||||
|
|
||||||
|
// Convert any stringified JSON objects to actual objects
|
||||||
|
for (const key of Object.keys(obj)) {
|
||||||
|
if (typeof obj[key] === 'string') {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(obj[key]);
|
||||||
|
if (parsed && typeof parsed === 'object') {
|
||||||
|
obj[key] = parsed;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Flatten the object
|
||||||
|
for (const key of Object.keys(obj)) {
|
||||||
|
if (typeof obj[key] === 'object' && obj[key] !== null) {
|
||||||
|
const nested = extraNetworksFlattenMetadata(obj[key]);
|
||||||
|
for (const nestedKey of Object.keys(nested)) {
|
||||||
|
result[`${key}/${nestedKey}`] = nested[nestedKey];
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
result[key] = obj[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Special case for handling modelspec keys
|
||||||
|
for (const key of Object.keys(result)) {
|
||||||
|
if (key.startsWith("modelspec.")) {
|
||||||
|
result[key.replaceAll(".", "/")] = result[key];
|
||||||
|
delete result[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add empty keys to designate hierarchy
|
||||||
|
for (const key of Object.keys(result)) {
|
||||||
|
const parts = key.split("/");
|
||||||
|
for (let i = 1; i < parts.length; i++) {
|
||||||
|
const parent = parts.slice(0, i).join("/");
|
||||||
|
if (!result[parent]) {
|
||||||
|
result[parent] = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksShowMetadata(text) {
|
||||||
|
try {
|
||||||
|
let parsed = JSON.parse(text);
|
||||||
|
if (parsed && typeof parsed === 'object') {
|
||||||
|
parsed = extraNetworksFlattenMetadata(parsed);
|
||||||
|
const table = createVisualizationTable(parsed, 0);
|
||||||
|
popup(table);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
var elem = document.createElement('pre');
|
||||||
|
elem.classList.add('popup-metadata');
|
||||||
|
elem.textContent = text;
|
||||||
|
|
||||||
|
popup(elem);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
function requestGet(url, data, handler, errorHandler) {
|
||||||
|
var xhr = new XMLHttpRequest();
|
||||||
|
var args = Object.keys(data).map(function(k) {
|
||||||
|
return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]);
|
||||||
|
}).join('&');
|
||||||
|
xhr.open("GET", url + "?" + args, true);
|
||||||
|
|
||||||
|
xhr.onreadystatechange = function() {
|
||||||
|
if (xhr.readyState === 4) {
|
||||||
|
if (xhr.status === 200) {
|
||||||
|
try {
|
||||||
|
var js = JSON.parse(xhr.responseText);
|
||||||
|
handler(js);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
errorHandler();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
errorHandler();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var js = JSON.stringify(data);
|
||||||
|
xhr.send(js);
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksCopyCardPath(event) {
|
||||||
|
navigator.clipboard.writeText(event.target.getAttribute("data-clipboard-text"));
|
||||||
|
event.stopPropagation();
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksRequestMetadata(event, extraPage) {
|
||||||
|
var showError = function() {
|
||||||
|
extraNetworksShowMetadata("there was an error getting metadata");
|
||||||
|
};
|
||||||
|
|
||||||
|
var cardName = event.target.parentElement.parentElement.getAttribute("data-name");
|
||||||
|
|
||||||
|
requestGet("./sd_extra_networks/metadata", {page: extraPage, item: cardName}, function(data) {
|
||||||
|
if (data && data.metadata) {
|
||||||
|
extraNetworksShowMetadata(data.metadata);
|
||||||
|
} else {
|
||||||
|
showError();
|
||||||
|
}
|
||||||
|
}, showError);
|
||||||
|
|
||||||
|
event.stopPropagation();
|
||||||
|
}
|
||||||
|
|
||||||
|
var extraPageUserMetadataEditors = {};
|
||||||
|
|
||||||
|
function extraNetworksEditUserMetadata(event, tabname, extraPage) {
|
||||||
|
var id = tabname + '_' + extraPage + '_edit_user_metadata';
|
||||||
|
|
||||||
|
var editor = extraPageUserMetadataEditors[id];
|
||||||
|
if (!editor) {
|
||||||
|
editor = {};
|
||||||
|
editor.page = gradioApp().getElementById(id);
|
||||||
|
editor.nameTextarea = gradioApp().querySelector("#" + id + "_name" + ' textarea');
|
||||||
|
editor.button = gradioApp().querySelector("#" + id + "_button");
|
||||||
|
extraPageUserMetadataEditors[id] = editor;
|
||||||
|
}
|
||||||
|
|
||||||
|
var cardName = event.target.parentElement.parentElement.getAttribute("data-name");
|
||||||
|
editor.nameTextarea.value = cardName;
|
||||||
|
updateInput(editor.nameTextarea);
|
||||||
|
|
||||||
|
editor.button.click();
|
||||||
|
|
||||||
|
popup(editor.page);
|
||||||
|
|
||||||
|
event.stopPropagation();
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksRefreshSingleCard(page, tabname, name) {
|
||||||
|
requestGet("./sd_extra_networks/get-single-card", {page: page, tabname: tabname, name: name}, function(data) {
|
||||||
|
if (data && data.html) {
|
||||||
|
var card = gradioApp().querySelector(`#${tabname}_${page.replace(" ", "_")}_cards > .card[data-name="${name}"]`);
|
||||||
|
|
||||||
|
var newDiv = document.createElement('DIV');
|
||||||
|
newDiv.innerHTML = data.html;
|
||||||
|
var newCard = newDiv.firstElementChild;
|
||||||
|
|
||||||
|
newCard.style.display = '';
|
||||||
|
card.parentElement.insertBefore(newCard, card);
|
||||||
|
card.parentElement.removeChild(card);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener("keydown", function(event) {
|
||||||
|
if (event.key == "Escape") {
|
||||||
|
closePopup();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Setup custom loading for this script.
|
||||||
|
* We need to wait for all of our HTML to be generated in the extra networks tabs
|
||||||
|
* before we can actually run the `setupExtraNetworks` function.
|
||||||
|
* The `onUiLoaded` function actually runs before all of our extra network tabs are
|
||||||
|
* finished generating. Thus we needed this new method.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
var uiAfterScriptsCallbacks = [];
|
||||||
|
var uiAfterScriptsTimeout = null;
|
||||||
|
var executedAfterScripts = false;
|
||||||
|
|
||||||
|
function scheduleAfterScriptsCallbacks() {
|
||||||
|
clearTimeout(uiAfterScriptsTimeout);
|
||||||
|
uiAfterScriptsTimeout = setTimeout(function() {
|
||||||
|
executeCallbacks(uiAfterScriptsCallbacks);
|
||||||
|
}, 200);
|
||||||
|
}
|
||||||
|
|
||||||
|
onUiLoaded(function() {
|
||||||
|
var mutationObserver = new MutationObserver(function(m) {
|
||||||
|
let existingSearchfields = gradioApp().querySelectorAll("[id$='_extra_search']").length;
|
||||||
|
let neededSearchfields = gradioApp().querySelectorAll("[id$='_extra_tabs'] > .tab-nav > button").length - 2;
|
||||||
|
|
||||||
|
if (!executedAfterScripts && existingSearchfields >= neededSearchfields) {
|
||||||
|
mutationObserver.disconnect();
|
||||||
|
executedAfterScripts = true;
|
||||||
|
scheduleAfterScriptsCallbacks();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
mutationObserver.observe(gradioApp(), {childList: true, subtree: true});
|
||||||
|
});
|
||||||
|
|
||||||
|
uiAfterScriptsCallbacks.push(setupExtraNetworks);
|
||||||
|
@ -1,33 +1,35 @@
|
|||||||
// attaches listeners to the txt2img and img2img galleries to update displayed generation param text when the image changes
|
// attaches listeners to the txt2img and img2img galleries to update displayed generation param text when the image changes
|
||||||
|
|
||||||
let txt2img_gallery, img2img_gallery, modal = undefined;
|
let txt2img_gallery, img2img_gallery, modal = undefined;
|
||||||
onUiUpdate(function(){
|
onAfterUiUpdate(function() {
|
||||||
if (!txt2img_gallery) {
|
if (!txt2img_gallery) {
|
||||||
txt2img_gallery = attachGalleryListeners("txt2img")
|
txt2img_gallery = attachGalleryListeners("txt2img");
|
||||||
}
|
}
|
||||||
if (!img2img_gallery) {
|
if (!img2img_gallery) {
|
||||||
img2img_gallery = attachGalleryListeners("img2img")
|
img2img_gallery = attachGalleryListeners("img2img");
|
||||||
}
|
}
|
||||||
if (!modal) {
|
if (!modal) {
|
||||||
modal = gradioApp().getElementById('lightboxModal')
|
modal = gradioApp().getElementById('lightboxModal');
|
||||||
modalObserver.observe(modal, { attributes : true, attributeFilter : ['style'] });
|
modalObserver.observe(modal, {attributes: true, attributeFilter: ['style']});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
let modalObserver = new MutationObserver(function(mutations) {
|
let modalObserver = new MutationObserver(function(mutations) {
|
||||||
mutations.forEach(function(mutationRecord) {
|
mutations.forEach(function(mutationRecord) {
|
||||||
let selectedTab = gradioApp().querySelector('#tabs div button.selected')?.innerText
|
let selectedTab = gradioApp().querySelector('#tabs div button.selected')?.innerText;
|
||||||
if (mutationRecord.target.style.display === 'none' && (selectedTab === 'txt2img' || selectedTab === 'img2img'))
|
if (mutationRecord.target.style.display === 'none' && (selectedTab === 'txt2img' || selectedTab === 'img2img')) {
|
||||||
gradioApp().getElementById(selectedTab+"_generation_info_button")?.click()
|
gradioApp().getElementById(selectedTab + "_generation_info_button")?.click();
|
||||||
});
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
function attachGalleryListeners(tab_name) {
|
function attachGalleryListeners(tab_name) {
|
||||||
var gallery = gradioApp().querySelector('#'+tab_name+'_gallery')
|
var gallery = gradioApp().querySelector('#' + tab_name + '_gallery');
|
||||||
gallery?.addEventListener('click', () => gradioApp().getElementById(tab_name+"_generation_info_button").click());
|
gallery?.addEventListener('click', () => gradioApp().getElementById(tab_name + "_generation_info_button").click());
|
||||||
gallery?.addEventListener('keydown', (e) => {
|
gallery?.addEventListener('keydown', (e) => {
|
||||||
if (e.keyCode == 37 || e.keyCode == 39) // left or right arrow
|
if (e.keyCode == 37 || e.keyCode == 39) { // left or right arrow
|
||||||
gradioApp().getElementById(tab_name+"_generation_info_button").click()
|
gradioApp().getElementById(tab_name + "_generation_info_button").click();
|
||||||
});
|
}
|
||||||
return gallery;
|
});
|
||||||
|
return gallery;
|
||||||
}
|
}
|
||||||
|
@ -1,20 +1,21 @@
|
|||||||
// mouseover tooltips for various UI elements
|
// mouseover tooltips for various UI elements
|
||||||
|
|
||||||
titles = {
|
var titles = {
|
||||||
"Sampling steps": "How many times to improve the generated image iteratively; higher values take longer; very low values can produce bad results",
|
"Sampling steps": "How many times to improve the generated image iteratively; higher values take longer; very low values can produce bad results",
|
||||||
"Sampling method": "Which algorithm to use to produce the image",
|
"Sampling method": "Which algorithm to use to produce the image",
|
||||||
"GFPGAN": "Restore low quality faces using GFPGAN neural network",
|
"GFPGAN": "Restore low quality faces using GFPGAN neural network",
|
||||||
"Euler a": "Euler Ancestral - very creative, each can get a completely different picture depending on step count, setting steps higher than 30-40 does not help",
|
"Euler a": "Euler Ancestral - very creative, each can get a completely different picture depending on step count, setting steps higher than 30-40 does not help",
|
||||||
"DDIM": "Denoising Diffusion Implicit Models - best at inpainting",
|
"DDIM": "Denoising Diffusion Implicit Models - best at inpainting",
|
||||||
"UniPC": "Unified Predictor-Corrector Framework for Fast Sampling of Diffusion Models",
|
"UniPC": "Unified Predictor-Corrector Framework for Fast Sampling of Diffusion Models",
|
||||||
"DPM adaptive": "Ignores step count - uses a number of steps determined by the CFG and resolution",
|
"DPM adaptive": "Ignores step count - uses a number of steps determined by the CFG and resolution",
|
||||||
|
|
||||||
"Batch count": "How many batches of images to create (has no impact on generation performance or VRAM usage)",
|
"\u{1F4D0}": "Auto detect size from img2img",
|
||||||
"Batch size": "How many image to create in a single batch (increases generation performance at cost of higher VRAM usage)",
|
"Batch count": "How many batches of images to create (has no impact on generation performance or VRAM usage)",
|
||||||
|
"Batch size": "How many image to create in a single batch (increases generation performance at cost of higher VRAM usage)",
|
||||||
"CFG Scale": "Classifier Free Guidance Scale - how strongly the image should conform to prompt - lower values produce more creative results",
|
"CFG Scale": "Classifier Free Guidance Scale - how strongly the image should conform to prompt - lower values produce more creative results",
|
||||||
"Seed": "A value that determines the output of random number generator - if you create an image with same parameters and seed as another image, you'll get the same result",
|
"Seed": "A value that determines the output of random number generator - if you create an image with same parameters and seed as another image, you'll get the same result",
|
||||||
"\u{1f3b2}\ufe0f": "Set seed to -1, which will cause a new random number to be used every time",
|
"\u{1f3b2}\ufe0f": "Set seed to -1, which will cause a new random number to be used every time",
|
||||||
"\u267b\ufe0f": "Reuse seed from last generation, mostly useful if it was randomed",
|
"\u267b\ufe0f": "Reuse seed from last generation, mostly useful if it was randomized",
|
||||||
"\u2199\ufe0f": "Read generation parameters from prompt or last generation if prompt is empty into user interface.",
|
"\u2199\ufe0f": "Read generation parameters from prompt or last generation if prompt is empty into user interface.",
|
||||||
"\u{1f4c2}": "Open images output directory",
|
"\u{1f4c2}": "Open images output directory",
|
||||||
"\u{1f4be}": "Save style",
|
"\u{1f4be}": "Save style",
|
||||||
@ -40,7 +41,7 @@ titles = {
|
|||||||
"Inpaint at full resolution": "Upscale masked region to target resolution, do inpainting, downscale back and paste into original image",
|
"Inpaint at full resolution": "Upscale masked region to target resolution, do inpainting, downscale back and paste into original image",
|
||||||
|
|
||||||
"Denoising strength": "Determines how little respect the algorithm should have for image's content. At 0, nothing will change, and at 1 you'll get an unrelated image. With values below 1.0, processing will take less steps than the Sampling Steps slider specifies.",
|
"Denoising strength": "Determines how little respect the algorithm should have for image's content. At 0, nothing will change, and at 1 you'll get an unrelated image. With values below 1.0, processing will take less steps than the Sampling Steps slider specifies.",
|
||||||
|
|
||||||
"Skip": "Stop processing current image and continue processing.",
|
"Skip": "Stop processing current image and continue processing.",
|
||||||
"Interrupt": "Stop processing images and return any results accumulated so far.",
|
"Interrupt": "Stop processing images and return any results accumulated so far.",
|
||||||
"Save": "Write image to a directory (default - log/images) and generation parameters into csv file.",
|
"Save": "Write image to a directory (default - log/images) and generation parameters into csv file.",
|
||||||
@ -66,8 +67,8 @@ titles = {
|
|||||||
|
|
||||||
"Interrogate": "Reconstruct prompt from existing image and put it into the prompt field.",
|
"Interrogate": "Reconstruct prompt from existing image and put it into the prompt field.",
|
||||||
|
|
||||||
"Images filename pattern": "Use following tags to define how filenames for images are chosen: [steps], [cfg], [denoising], [clip_skip], [batch_number], [generation_number], [prompt_hash], [prompt], [prompt_no_styles], [prompt_spaces], [width], [height], [styles], [sampler], [seed], [model_hash], [model_name], [prompt_words], [date], [datetime], [datetime<Format>], [datetime<Format><Time Zone>], [job_timestamp], [hasprompt<prompt1|default><prompt2>..]; leave empty for default.",
|
"Images filename pattern": "Use tags like [seed] and [date] to define how filenames for images are chosen. Leave empty for default.",
|
||||||
"Directory name pattern": "Use following tags to define how subdirectories for images and grids are chosen: [steps], [cfg], [denoising], [clip_skip], [batch_number], [generation_number], [prompt_hash], [prompt], [prompt_no_styles], [prompt_spaces], [width], [height], [styles], [sampler], [seed], [model_hash], [model_name], [prompt_words], [date], [datetime], [datetime<Format>], [datetime<Format><Time Zone>], [job_timestamp], [hasprompt<prompt1|default><prompt2>..]; leave empty for default.",
|
"Directory name pattern": "Use tags like [seed] and [date] to define how subdirectories for images and grids are chosen. Leave empty for default.",
|
||||||
"Max prompt words": "Set the maximum number of words to be used in the [prompt_words] option; ATTENTION: If the words are too long, they may exceed the maximum length of the file path that the system can handle",
|
"Max prompt words": "Set the maximum number of words to be used in the [prompt_words] option; ATTENTION: If the words are too long, they may exceed the maximum length of the file path that the system can handle",
|
||||||
|
|
||||||
"Loopback": "Performs img2img processing multiple times. Output images are used as input for the next loop.",
|
"Loopback": "Performs img2img processing multiple times. Output images are used as input for the next loop.",
|
||||||
@ -83,8 +84,6 @@ titles = {
|
|||||||
"Checkpoint name": "Loads weights from checkpoint before making images. You can either use hash or a part of filename (as seen in settings) for checkpoint name. Recommended to use with Y axis for less switching.",
|
"Checkpoint name": "Loads weights from checkpoint before making images. You can either use hash or a part of filename (as seen in settings) for checkpoint name. Recommended to use with Y axis for less switching.",
|
||||||
"Inpainting conditioning mask strength": "Only applies to inpainting models. Determines how strongly to mask off the original image for inpainting and img2img. 1.0 means fully masked, which is the default behaviour. 0.0 means a fully unmasked conditioning. Lower values will help preserve the overall composition of the image, but will struggle with large changes.",
|
"Inpainting conditioning mask strength": "Only applies to inpainting models. Determines how strongly to mask off the original image for inpainting and img2img. 1.0 means fully masked, which is the default behaviour. 0.0 means a fully unmasked conditioning. Lower values will help preserve the overall composition of the image, but will struggle with large changes.",
|
||||||
|
|
||||||
"vram": "Torch active: Peak amount of VRAM used by Torch during generation, excluding cached data.\nTorch reserved: Peak amount of VRAM allocated by Torch, including all active and cached data.\nSys VRAM: Peak amount of VRAM allocation across all applications / total GPU VRAM (peak utilization%).",
|
|
||||||
|
|
||||||
"Eta noise seed delta": "If this values is non-zero, it will be added to seed and used to initialize RNG for noises when using samplers with Eta. You can use this to produce even more variation of images, or you can use this to match images of other software if you know what you are doing.",
|
"Eta noise seed delta": "If this values is non-zero, it will be added to seed and used to initialize RNG for noises when using samplers with Eta. You can use this to produce even more variation of images, or you can use this to match images of other software if you know what you are doing.",
|
||||||
|
|
||||||
"Filename word regex": "This regular expression will be used extract words from filename, and they will be joined using the option below into label text used for training. Leave empty to keep filename text as it is.",
|
"Filename word regex": "This regular expression will be used extract words from filename, and they will be joined using the option below into label text used for training. Leave empty to keep filename text as it is.",
|
||||||
@ -96,7 +95,7 @@ titles = {
|
|||||||
"Add difference": "Result = A + (B - C) * M",
|
"Add difference": "Result = A + (B - C) * M",
|
||||||
"No interpolation": "Result = A",
|
"No interpolation": "Result = A",
|
||||||
|
|
||||||
"Initialization text": "If the number of tokens is more than the number of vectors, some may be skipped.\nLeave the textbox empty to start with zeroed out vectors",
|
"Initialization text": "If the number of tokens is more than the number of vectors, some may be skipped.\nLeave the textbox empty to start with zeroed out vectors",
|
||||||
"Learning rate": "How fast should training go. Low values will take longer to train, high values may fail to converge (not generate accurate results) and/or may break the embedding (This has happened if you see Loss: nan in the training info textbox. If this happens, you need to manually restore your embedding from an older not-broken backup).\n\nYou can set a single numeric value, or multiple learning rates using the syntax:\n\n rate_1:max_steps_1, rate_2:max_steps_2, ...\n\nEG: 0.005:100, 1e-3:1000, 1e-5\n\nWill train with rate of 0.005 for first 100 steps, then 1e-3 until 1000 steps, then 1e-5 for all remaining steps.",
|
"Learning rate": "How fast should training go. Low values will take longer to train, high values may fail to converge (not generate accurate results) and/or may break the embedding (This has happened if you see Loss: nan in the training info textbox. If this happens, you need to manually restore your embedding from an older not-broken backup).\n\nYou can set a single numeric value, or multiple learning rates using the syntax:\n\n rate_1:max_steps_1, rate_2:max_steps_2, ...\n\nEG: 0.005:100, 1e-3:1000, 1e-5\n\nWill train with rate of 0.005 for first 100 steps, then 1e-3 until 1000 steps, then 1e-5 for all remaining steps.",
|
||||||
|
|
||||||
"Clip skip": "Early stopping parameter for CLIP model; 1 is stop at last layer as usual, 2 is stop at penultimate layer, etc.",
|
"Clip skip": "Early stopping parameter for CLIP model; 1 is stop at last layer as usual, 2 is stop at penultimate layer, etc.",
|
||||||
@ -109,42 +108,96 @@ titles = {
|
|||||||
"Upscale by": "Adjusts the size of the image by multiplying the original width and height by the selected value. Ignored if either Resize width to or Resize height to are non-zero.",
|
"Upscale by": "Adjusts the size of the image by multiplying the original width and height by the selected value. Ignored if either Resize width to or Resize height to are non-zero.",
|
||||||
"Resize width to": "Resizes image to this width. If 0, width is inferred from either of two nearby sliders.",
|
"Resize width to": "Resizes image to this width. If 0, width is inferred from either of two nearby sliders.",
|
||||||
"Resize height to": "Resizes image to this height. If 0, height is inferred from either of two nearby sliders.",
|
"Resize height to": "Resizes image to this height. If 0, height is inferred from either of two nearby sliders.",
|
||||||
"Multiplier for extra networks": "When adding extra network such as Hypernetwork or Lora to prompt, use this multiplier for it.",
|
|
||||||
"Discard weights with matching name": "Regular expression; if weights's name matches it, the weights is not written to the resulting checkpoint. Use ^model_ema to discard EMA weights.",
|
"Discard weights with matching name": "Regular expression; if weights's name matches it, the weights is not written to the resulting checkpoint. Use ^model_ema to discard EMA weights.",
|
||||||
"Extra networks tab order": "Comma-separated list of tab names; tabs listed here will appear in the extra networks UI first and in order lsited.",
|
"Extra networks tab order": "Comma-separated list of tab names; tabs listed here will appear in the extra networks UI first and in order listed.",
|
||||||
"Negative Guidance minimum sigma": "Skip negative prompt for steps where image is already mostly denoised; the higher this value, the more skips there will be; provides increased performance in exchange for minor quality reduction."
|
"Negative Guidance minimum sigma": "Skip negative prompt for steps where image is already mostly denoised; the higher this value, the more skips there will be; provides increased performance in exchange for minor quality reduction."
|
||||||
|
};
|
||||||
|
|
||||||
|
function updateTooltip(element) {
|
||||||
|
if (element.title) return; // already has a title
|
||||||
|
|
||||||
|
let text = element.textContent;
|
||||||
|
let tooltip = localization[titles[text]] || titles[text];
|
||||||
|
|
||||||
|
if (!tooltip) {
|
||||||
|
let value = element.value;
|
||||||
|
if (value) tooltip = localization[titles[value]] || titles[value];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!tooltip) {
|
||||||
|
// Gradio dropdown options have `data-value`.
|
||||||
|
let dataValue = element.dataset.value;
|
||||||
|
if (dataValue) tooltip = localization[titles[dataValue]] || titles[dataValue];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!tooltip) {
|
||||||
|
for (const c of element.classList) {
|
||||||
|
if (c in titles) {
|
||||||
|
tooltip = localization[titles[c]] || titles[c];
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tooltip) {
|
||||||
|
element.title = tooltip;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Nodes to check for adding tooltips.
|
||||||
|
const tooltipCheckNodes = new Set();
|
||||||
|
// Timer for debouncing tooltip check.
|
||||||
|
let tooltipCheckTimer = null;
|
||||||
|
|
||||||
onUiUpdate(function(){
|
function processTooltipCheckNodes() {
|
||||||
gradioApp().querySelectorAll('span, button, select, p').forEach(function(span){
|
for (const node of tooltipCheckNodes) {
|
||||||
if (span.title) return; // already has a title
|
updateTooltip(node);
|
||||||
|
}
|
||||||
|
tooltipCheckNodes.clear();
|
||||||
|
}
|
||||||
|
|
||||||
let tooltip = localization[titles[span.textContent]] || titles[span.textContent];
|
onUiUpdate(function(mutationRecords) {
|
||||||
|
for (const record of mutationRecords) {
|
||||||
|
if (record.type === "childList" && record.target.classList.contains("options")) {
|
||||||
|
// This smells like a Gradio dropdown menu having changed,
|
||||||
|
// so let's enqueue an update for the input element that shows the current value.
|
||||||
|
let wrap = record.target.parentNode;
|
||||||
|
let input = wrap?.querySelector("input");
|
||||||
|
if (input) {
|
||||||
|
input.title = ""; // So we'll even have a chance to update it.
|
||||||
|
tooltipCheckNodes.add(input);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const node of record.addedNodes) {
|
||||||
|
if (node.nodeType === Node.ELEMENT_NODE && !node.classList.contains("hide")) {
|
||||||
|
if (!node.title) {
|
||||||
|
if (
|
||||||
|
node.tagName === "SPAN" ||
|
||||||
|
node.tagName === "BUTTON" ||
|
||||||
|
node.tagName === "P" ||
|
||||||
|
node.tagName === "INPUT" ||
|
||||||
|
(node.tagName === "LI" && node.classList.contains("item")) // Gradio dropdown item
|
||||||
|
) {
|
||||||
|
tooltipCheckNodes.add(node);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
node.querySelectorAll('span, button, p').forEach(n => tooltipCheckNodes.add(n));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (tooltipCheckNodes.size) {
|
||||||
|
clearTimeout(tooltipCheckTimer);
|
||||||
|
tooltipCheckTimer = setTimeout(processTooltipCheckNodes, 1000);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
if(!tooltip){
|
onUiLoaded(function() {
|
||||||
tooltip = localization[titles[span.value]] || titles[span.value];
|
for (var comp of window.gradio_config.components) {
|
||||||
}
|
if (comp.props.webui_tooltip && comp.props.elem_id) {
|
||||||
|
var elem = gradioApp().getElementById(comp.props.elem_id);
|
||||||
if(!tooltip){
|
if (elem) {
|
||||||
for (const c of span.classList) {
|
elem.title = comp.props.webui_tooltip;
|
||||||
if (c in titles) {
|
}
|
||||||
tooltip = localization[titles[c]] || titles[c];
|
}
|
||||||
break;
|
}
|
||||||
}
|
});
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if(tooltip){
|
|
||||||
span.title = tooltip;
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
gradioApp().querySelectorAll('select').forEach(function(select){
|
|
||||||
if (select.onchange != null) return;
|
|
||||||
|
|
||||||
select.onchange = function(){
|
|
||||||
select.title = localization[titles[select.value]] || titles[select.value] || "";
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
@ -1,18 +1,18 @@
|
|||||||
|
|
||||||
function onCalcResolutionHires(enable, width, height, hr_scale, hr_resize_x, hr_resize_y){
|
function onCalcResolutionHires(enable, width, height, hr_scale, hr_resize_x, hr_resize_y) {
|
||||||
function setInactive(elem, inactive){
|
function setInactive(elem, inactive) {
|
||||||
elem.classList.toggle('inactive', !!inactive)
|
elem.classList.toggle('inactive', !!inactive);
|
||||||
}
|
}
|
||||||
|
|
||||||
var hrUpscaleBy = gradioApp().getElementById('txt2img_hr_scale')
|
var hrUpscaleBy = gradioApp().getElementById('txt2img_hr_scale');
|
||||||
var hrResizeX = gradioApp().getElementById('txt2img_hr_resize_x')
|
var hrResizeX = gradioApp().getElementById('txt2img_hr_resize_x');
|
||||||
var hrResizeY = gradioApp().getElementById('txt2img_hr_resize_y')
|
var hrResizeY = gradioApp().getElementById('txt2img_hr_resize_y');
|
||||||
|
|
||||||
gradioApp().getElementById('txt2img_hires_fix_row2').style.display = opts.use_old_hires_fix_width_height ? "none" : ""
|
gradioApp().getElementById('txt2img_hires_fix_row2').style.display = opts.use_old_hires_fix_width_height ? "none" : "";
|
||||||
|
|
||||||
setInactive(hrUpscaleBy, opts.use_old_hires_fix_width_height || hr_resize_x > 0 || hr_resize_y > 0)
|
setInactive(hrUpscaleBy, opts.use_old_hires_fix_width_height || hr_resize_x > 0 || hr_resize_y > 0);
|
||||||
setInactive(hrResizeX, opts.use_old_hires_fix_width_height || hr_resize_x == 0)
|
setInactive(hrResizeX, opts.use_old_hires_fix_width_height || hr_resize_x == 0);
|
||||||
setInactive(hrResizeY, opts.use_old_hires_fix_width_height || hr_resize_y == 0)
|
setInactive(hrResizeY, opts.use_old_hires_fix_width_height || hr_resize_y == 0);
|
||||||
|
|
||||||
return [enable, width, height, hr_scale, hr_resize_x, hr_resize_y]
|
return [enable, width, height, hr_scale, hr_resize_x, hr_resize_y];
|
||||||
}
|
}
|
||||||
|
@ -4,17 +4,16 @@
|
|||||||
*/
|
*/
|
||||||
function imageMaskResize() {
|
function imageMaskResize() {
|
||||||
const canvases = gradioApp().querySelectorAll('#img2maskimg .touch-none canvas');
|
const canvases = gradioApp().querySelectorAll('#img2maskimg .touch-none canvas');
|
||||||
if ( ! canvases.length ) {
|
if (!canvases.length) {
|
||||||
canvases_fixed = false; // TODO: this is unused..?
|
window.removeEventListener('resize', imageMaskResize);
|
||||||
window.removeEventListener( 'resize', imageMaskResize );
|
return;
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const wrapper = canvases[0].closest('.touch-none');
|
const wrapper = canvases[0].closest('.touch-none');
|
||||||
const previewImage = wrapper.previousElementSibling;
|
const previewImage = wrapper.previousElementSibling;
|
||||||
|
|
||||||
if ( ! previewImage.complete ) {
|
if (!previewImage.complete) {
|
||||||
previewImage.addEventListener( 'load', imageMaskResize);
|
previewImage.addEventListener('load', imageMaskResize);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -24,15 +23,15 @@ function imageMaskResize() {
|
|||||||
const nh = previewImage.naturalHeight;
|
const nh = previewImage.naturalHeight;
|
||||||
const portrait = nh > nw;
|
const portrait = nh > nw;
|
||||||
|
|
||||||
const wW = Math.min(w, portrait ? h/nh*nw : w/nw*nw);
|
const wW = Math.min(w, portrait ? h / nh * nw : w / nw * nw);
|
||||||
const wH = Math.min(h, portrait ? h/nh*nh : w/nw*nh);
|
const wH = Math.min(h, portrait ? h / nh * nh : w / nw * nh);
|
||||||
|
|
||||||
wrapper.style.width = `${wW}px`;
|
wrapper.style.width = `${wW}px`;
|
||||||
wrapper.style.height = `${wH}px`;
|
wrapper.style.height = `${wH}px`;
|
||||||
wrapper.style.left = `0px`;
|
wrapper.style.left = `0px`;
|
||||||
wrapper.style.top = `0px`;
|
wrapper.style.top = `0px`;
|
||||||
|
|
||||||
canvases.forEach( c => {
|
canvases.forEach(c => {
|
||||||
c.style.width = c.style.height = '';
|
c.style.width = c.style.height = '';
|
||||||
c.style.maxWidth = '100%';
|
c.style.maxWidth = '100%';
|
||||||
c.style.maxHeight = '100%';
|
c.style.maxHeight = '100%';
|
||||||
@ -40,5 +39,5 @@ function imageMaskResize() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
onUiUpdate(imageMaskResize);
|
onAfterUiUpdate(imageMaskResize);
|
||||||
window.addEventListener( 'resize', imageMaskResize);
|
window.addEventListener('resize', imageMaskResize);
|
||||||
|
@ -1,18 +0,0 @@
|
|||||||
window.onload = (function(){
|
|
||||||
window.addEventListener('drop', e => {
|
|
||||||
const target = e.composedPath()[0];
|
|
||||||
if (target.placeholder.indexOf("Prompt") == -1) return;
|
|
||||||
|
|
||||||
let prompt_target = get_tab_index('tabs') == 1 ? "img2img_prompt_image" : "txt2img_prompt_image";
|
|
||||||
|
|
||||||
e.stopPropagation();
|
|
||||||
e.preventDefault();
|
|
||||||
const imgParent = gradioApp().getElementById(prompt_target);
|
|
||||||
const files = e.dataTransfer.files;
|
|
||||||
const fileInput = imgParent.querySelector('input[type="file"]');
|
|
||||||
if ( fileInput ) {
|
|
||||||
fileInput.files = files;
|
|
||||||
fileInput.dispatchEvent(new Event('change'));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
@ -5,24 +5,26 @@ function closeModal() {
|
|||||||
|
|
||||||
function showModal(event) {
|
function showModal(event) {
|
||||||
const source = event.target || event.srcElement;
|
const source = event.target || event.srcElement;
|
||||||
const modalImage = gradioApp().getElementById("modalImage")
|
const modalImage = gradioApp().getElementById("modalImage");
|
||||||
const lb = gradioApp().getElementById("lightboxModal")
|
const modalToggleLivePreviewBtn = gradioApp().getElementById("modal_toggle_live_preview");
|
||||||
modalImage.src = source.src
|
modalToggleLivePreviewBtn.innerHTML = opts.js_live_preview_in_modal_lightbox ? "🗇" : "🗆";
|
||||||
|
const lb = gradioApp().getElementById("lightboxModal");
|
||||||
|
modalImage.src = source.src;
|
||||||
if (modalImage.style.display === 'none') {
|
if (modalImage.style.display === 'none') {
|
||||||
lb.style.setProperty('background-image', 'url(' + source.src + ')');
|
lb.style.setProperty('background-image', 'url(' + source.src + ')');
|
||||||
}
|
}
|
||||||
lb.style.display = "flex";
|
lb.style.display = "flex";
|
||||||
lb.focus()
|
lb.focus();
|
||||||
|
|
||||||
const tabTxt2Img = gradioApp().getElementById("tab_txt2img")
|
const tabTxt2Img = gradioApp().getElementById("tab_txt2img");
|
||||||
const tabImg2Img = gradioApp().getElementById("tab_img2img")
|
const tabImg2Img = gradioApp().getElementById("tab_img2img");
|
||||||
// show the save button in modal only on txt2img or img2img tabs
|
// show the save button in modal only on txt2img or img2img tabs
|
||||||
if (tabTxt2Img.style.display != "none" || tabImg2Img.style.display != "none") {
|
if (tabTxt2Img.style.display != "none" || tabImg2Img.style.display != "none") {
|
||||||
gradioApp().getElementById("modal_save").style.display = "inline"
|
gradioApp().getElementById("modal_save").style.display = "inline";
|
||||||
} else {
|
} else {
|
||||||
gradioApp().getElementById("modal_save").style.display = "none"
|
gradioApp().getElementById("modal_save").style.display = "none";
|
||||||
}
|
}
|
||||||
event.stopPropagation()
|
event.stopPropagation();
|
||||||
}
|
}
|
||||||
|
|
||||||
function negmod(n, m) {
|
function negmod(n, m) {
|
||||||
@ -30,14 +32,18 @@ function negmod(n, m) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function updateOnBackgroundChange() {
|
function updateOnBackgroundChange() {
|
||||||
const modalImage = gradioApp().getElementById("modalImage")
|
const modalImage = gradioApp().getElementById("modalImage");
|
||||||
if (modalImage && modalImage.offsetParent) {
|
if (modalImage && modalImage.offsetParent) {
|
||||||
let currentButton = selected_gallery_button();
|
let currentButton = selected_gallery_button();
|
||||||
|
let preview = gradioApp().querySelectorAll('.livePreview > img');
|
||||||
if (currentButton?.children?.length > 0 && modalImage.src != currentButton.children[0].src) {
|
if (opts.js_live_preview_in_modal_lightbox && preview.length > 0) {
|
||||||
|
// show preview image if available
|
||||||
|
modalImage.src = preview[preview.length - 1].src;
|
||||||
|
} else if (currentButton?.children?.length > 0 && modalImage.src != currentButton.children[0].src) {
|
||||||
modalImage.src = currentButton.children[0].src;
|
modalImage.src = currentButton.children[0].src;
|
||||||
if (modalImage.style.display === 'none') {
|
if (modalImage.style.display === 'none') {
|
||||||
modal.style.setProperty('background-image', `url(${modalImage.src})`)
|
const modal = gradioApp().getElementById("lightboxModal");
|
||||||
|
modal.style.setProperty('background-image', `url(${modalImage.src})`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -47,110 +53,112 @@ function modalImageSwitch(offset) {
|
|||||||
var galleryButtons = all_gallery_buttons();
|
var galleryButtons = all_gallery_buttons();
|
||||||
|
|
||||||
if (galleryButtons.length > 1) {
|
if (galleryButtons.length > 1) {
|
||||||
var currentButton = selected_gallery_button();
|
var result = selected_gallery_index();
|
||||||
|
|
||||||
var result = -1
|
|
||||||
galleryButtons.forEach(function(v, i) {
|
|
||||||
if (v == currentButton) {
|
|
||||||
result = i
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
if (result != -1) {
|
if (result != -1) {
|
||||||
var nextButton = galleryButtons[negmod((result + offset), galleryButtons.length)]
|
var nextButton = galleryButtons[negmod((result + offset), galleryButtons.length)];
|
||||||
nextButton.click()
|
nextButton.click();
|
||||||
const modalImage = gradioApp().getElementById("modalImage");
|
const modalImage = gradioApp().getElementById("modalImage");
|
||||||
const modal = gradioApp().getElementById("lightboxModal");
|
const modal = gradioApp().getElementById("lightboxModal");
|
||||||
modalImage.src = nextButton.children[0].src;
|
modalImage.src = nextButton.children[0].src;
|
||||||
if (modalImage.style.display === 'none') {
|
if (modalImage.style.display === 'none') {
|
||||||
modal.style.setProperty('background-image', `url(${modalImage.src})`)
|
modal.style.setProperty('background-image', `url(${modalImage.src})`);
|
||||||
}
|
}
|
||||||
setTimeout(function() {
|
setTimeout(function() {
|
||||||
modal.focus()
|
modal.focus();
|
||||||
}, 10)
|
}, 10);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function saveImage(){
|
function saveImage() {
|
||||||
const tabTxt2Img = gradioApp().getElementById("tab_txt2img")
|
const tabTxt2Img = gradioApp().getElementById("tab_txt2img");
|
||||||
const tabImg2Img = gradioApp().getElementById("tab_img2img")
|
const tabImg2Img = gradioApp().getElementById("tab_img2img");
|
||||||
const saveTxt2Img = "save_txt2img"
|
const saveTxt2Img = "save_txt2img";
|
||||||
const saveImg2Img = "save_img2img"
|
const saveImg2Img = "save_img2img";
|
||||||
if (tabTxt2Img.style.display != "none") {
|
if (tabTxt2Img.style.display != "none") {
|
||||||
gradioApp().getElementById(saveTxt2Img).click()
|
gradioApp().getElementById(saveTxt2Img).click();
|
||||||
} else if (tabImg2Img.style.display != "none") {
|
} else if (tabImg2Img.style.display != "none") {
|
||||||
gradioApp().getElementById(saveImg2Img).click()
|
gradioApp().getElementById(saveImg2Img).click();
|
||||||
} else {
|
} else {
|
||||||
console.error("missing implementation for saving modal of this type")
|
console.error("missing implementation for saving modal of this type");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function modalSaveImage(event) {
|
function modalSaveImage(event) {
|
||||||
saveImage()
|
saveImage();
|
||||||
event.stopPropagation()
|
event.stopPropagation();
|
||||||
}
|
}
|
||||||
|
|
||||||
function modalNextImage(event) {
|
function modalNextImage(event) {
|
||||||
modalImageSwitch(1)
|
modalImageSwitch(1);
|
||||||
event.stopPropagation()
|
event.stopPropagation();
|
||||||
}
|
}
|
||||||
|
|
||||||
function modalPrevImage(event) {
|
function modalPrevImage(event) {
|
||||||
modalImageSwitch(-1)
|
modalImageSwitch(-1);
|
||||||
event.stopPropagation()
|
event.stopPropagation();
|
||||||
}
|
}
|
||||||
|
|
||||||
function modalKeyHandler(event) {
|
function modalKeyHandler(event) {
|
||||||
switch (event.key) {
|
switch (event.key) {
|
||||||
case "s":
|
case "s":
|
||||||
saveImage()
|
saveImage();
|
||||||
break;
|
break;
|
||||||
case "ArrowLeft":
|
case "ArrowLeft":
|
||||||
modalPrevImage(event)
|
modalPrevImage(event);
|
||||||
break;
|
break;
|
||||||
case "ArrowRight":
|
case "ArrowRight":
|
||||||
modalNextImage(event)
|
modalNextImage(event);
|
||||||
break;
|
break;
|
||||||
case "Escape":
|
case "Escape":
|
||||||
closeModal();
|
closeModal();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function setupImageForLightbox(e) {
|
function setupImageForLightbox(e) {
|
||||||
if (e.dataset.modded)
|
if (e.dataset.modded) {
|
||||||
return;
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
e.dataset.modded = true;
|
e.dataset.modded = true;
|
||||||
e.style.cursor='pointer'
|
e.style.cursor = 'pointer';
|
||||||
e.style.userSelect='none'
|
e.style.userSelect = 'none';
|
||||||
|
|
||||||
var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1
|
e.addEventListener('mousedown', function(evt) {
|
||||||
|
if (evt.button == 1) {
|
||||||
|
open(evt.target.src);
|
||||||
|
evt.preventDefault();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}, true);
|
||||||
|
|
||||||
// For Firefox, listening on click first switched to next image then shows the lightbox.
|
e.addEventListener('click', function(evt) {
|
||||||
// If you know how to fix this without switching to mousedown event, please.
|
if (!opts.js_modal_lightbox || evt.button != 0) return;
|
||||||
// For other browsers the event is click to make it possiblr to drag picture.
|
|
||||||
var event = isFirefox ? 'mousedown' : 'click'
|
|
||||||
|
|
||||||
e.addEventListener(event, function (evt) {
|
modalZoomSet(gradioApp().getElementById('modalImage'), opts.js_modal_lightbox_initially_zoomed);
|
||||||
if(!opts.js_modal_lightbox || evt.button != 0) return;
|
evt.preventDefault();
|
||||||
|
showModal(evt);
|
||||||
modalZoomSet(gradioApp().getElementById('modalImage'), opts.js_modal_lightbox_initially_zoomed)
|
}, true);
|
||||||
evt.preventDefault()
|
|
||||||
showModal(evt)
|
|
||||||
}, true);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function modalZoomSet(modalImage, enable) {
|
function modalZoomSet(modalImage, enable) {
|
||||||
if(modalImage) modalImage.classList.toggle('modalImageFullscreen', !!enable);
|
if (modalImage) modalImage.classList.toggle('modalImageFullscreen', !!enable);
|
||||||
}
|
}
|
||||||
|
|
||||||
function modalZoomToggle(event) {
|
function modalZoomToggle(event) {
|
||||||
var modalImage = gradioApp().getElementById("modalImage");
|
var modalImage = gradioApp().getElementById("modalImage");
|
||||||
modalZoomSet(modalImage, !modalImage.classList.contains('modalImageFullscreen'))
|
modalZoomSet(modalImage, !modalImage.classList.contains('modalImageFullscreen'));
|
||||||
event.stopPropagation()
|
event.stopPropagation();
|
||||||
|
}
|
||||||
|
|
||||||
|
function modalLivePreviewToggle(event) {
|
||||||
|
const modalToggleLivePreview = gradioApp().getElementById("modal_toggle_live_preview");
|
||||||
|
opts.js_live_preview_in_modal_lightbox = !opts.js_live_preview_in_modal_lightbox;
|
||||||
|
modalToggleLivePreview.innerHTML = opts.js_live_preview_in_modal_lightbox ? "🗇" : "🗆";
|
||||||
|
event.stopPropagation();
|
||||||
}
|
}
|
||||||
|
|
||||||
function modalTileImageToggle(event) {
|
function modalTileImageToggle(event) {
|
||||||
@ -159,99 +167,101 @@ function modalTileImageToggle(event) {
|
|||||||
const isTiling = modalImage.style.display === 'none';
|
const isTiling = modalImage.style.display === 'none';
|
||||||
if (isTiling) {
|
if (isTiling) {
|
||||||
modalImage.style.display = 'block';
|
modalImage.style.display = 'block';
|
||||||
modal.style.setProperty('background-image', 'none')
|
modal.style.setProperty('background-image', 'none');
|
||||||
} else {
|
} else {
|
||||||
modalImage.style.display = 'none';
|
modalImage.style.display = 'none';
|
||||||
modal.style.setProperty('background-image', `url(${modalImage.src})`)
|
modal.style.setProperty('background-image', `url(${modalImage.src})`);
|
||||||
}
|
}
|
||||||
|
|
||||||
event.stopPropagation()
|
event.stopPropagation();
|
||||||
}
|
}
|
||||||
|
|
||||||
function galleryImageHandler(e) {
|
onAfterUiUpdate(function() {
|
||||||
//if (e && e.parentElement.tagName == 'BUTTON') {
|
var fullImg_preview = gradioApp().querySelectorAll('.gradio-gallery > div > img');
|
||||||
e.onclick = showGalleryImage;
|
|
||||||
//}
|
|
||||||
}
|
|
||||||
|
|
||||||
onUiUpdate(function() {
|
|
||||||
var fullImg_preview = gradioApp().querySelectorAll('.gradio-gallery > div > img')
|
|
||||||
if (fullImg_preview != null) {
|
if (fullImg_preview != null) {
|
||||||
fullImg_preview.forEach(setupImageForLightbox);
|
fullImg_preview.forEach(setupImageForLightbox);
|
||||||
}
|
}
|
||||||
updateOnBackgroundChange();
|
updateOnBackgroundChange();
|
||||||
})
|
});
|
||||||
|
|
||||||
document.addEventListener("DOMContentLoaded", function() {
|
document.addEventListener("DOMContentLoaded", function() {
|
||||||
//const modalFragment = document.createDocumentFragment();
|
//const modalFragment = document.createDocumentFragment();
|
||||||
const modal = document.createElement('div')
|
const modal = document.createElement('div');
|
||||||
modal.onclick = closeModal;
|
modal.onclick = closeModal;
|
||||||
modal.id = "lightboxModal";
|
modal.id = "lightboxModal";
|
||||||
modal.tabIndex = 0
|
modal.tabIndex = 0;
|
||||||
modal.addEventListener('keydown', modalKeyHandler, true)
|
modal.addEventListener('keydown', modalKeyHandler, true);
|
||||||
|
|
||||||
const modalControls = document.createElement('div')
|
const modalControls = document.createElement('div');
|
||||||
modalControls.className = 'modalControls gradio-container';
|
modalControls.className = 'modalControls gradio-container';
|
||||||
modal.append(modalControls);
|
modal.append(modalControls);
|
||||||
|
|
||||||
const modalZoom = document.createElement('span')
|
const modalZoom = document.createElement('span');
|
||||||
modalZoom.className = 'modalZoom cursor';
|
modalZoom.className = 'modalZoom cursor';
|
||||||
modalZoom.innerHTML = '⤡'
|
modalZoom.innerHTML = '⤡';
|
||||||
modalZoom.addEventListener('click', modalZoomToggle, true)
|
modalZoom.addEventListener('click', modalZoomToggle, true);
|
||||||
modalZoom.title = "Toggle zoomed view";
|
modalZoom.title = "Toggle zoomed view";
|
||||||
modalControls.appendChild(modalZoom)
|
modalControls.appendChild(modalZoom);
|
||||||
|
|
||||||
const modalTileImage = document.createElement('span')
|
const modalTileImage = document.createElement('span');
|
||||||
modalTileImage.className = 'modalTileImage cursor';
|
modalTileImage.className = 'modalTileImage cursor';
|
||||||
modalTileImage.innerHTML = '⊞'
|
modalTileImage.innerHTML = '⊞';
|
||||||
modalTileImage.addEventListener('click', modalTileImageToggle, true)
|
modalTileImage.addEventListener('click', modalTileImageToggle, true);
|
||||||
modalTileImage.title = "Preview tiling";
|
modalTileImage.title = "Preview tiling";
|
||||||
modalControls.appendChild(modalTileImage)
|
modalControls.appendChild(modalTileImage);
|
||||||
|
|
||||||
const modalSave = document.createElement("span")
|
const modalSave = document.createElement("span");
|
||||||
modalSave.className = "modalSave cursor"
|
modalSave.className = "modalSave cursor";
|
||||||
modalSave.id = "modal_save"
|
modalSave.id = "modal_save";
|
||||||
modalSave.innerHTML = "🖫"
|
modalSave.innerHTML = "🖫";
|
||||||
modalSave.addEventListener("click", modalSaveImage, true)
|
modalSave.addEventListener("click", modalSaveImage, true);
|
||||||
modalSave.title = "Save Image(s)"
|
modalSave.title = "Save Image(s)";
|
||||||
modalControls.appendChild(modalSave)
|
modalControls.appendChild(modalSave);
|
||||||
|
|
||||||
const modalClose = document.createElement('span')
|
const modalToggleLivePreview = document.createElement('span');
|
||||||
|
modalToggleLivePreview.className = 'modalToggleLivePreview cursor';
|
||||||
|
modalToggleLivePreview.id = "modal_toggle_live_preview";
|
||||||
|
modalToggleLivePreview.innerHTML = "🗆";
|
||||||
|
modalToggleLivePreview.onclick = modalLivePreviewToggle;
|
||||||
|
modalToggleLivePreview.title = "Toggle live preview";
|
||||||
|
modalControls.appendChild(modalToggleLivePreview);
|
||||||
|
|
||||||
|
const modalClose = document.createElement('span');
|
||||||
modalClose.className = 'modalClose cursor';
|
modalClose.className = 'modalClose cursor';
|
||||||
modalClose.innerHTML = '×'
|
modalClose.innerHTML = '×';
|
||||||
modalClose.onclick = closeModal;
|
modalClose.onclick = closeModal;
|
||||||
modalClose.title = "Close image viewer";
|
modalClose.title = "Close image viewer";
|
||||||
modalControls.appendChild(modalClose)
|
modalControls.appendChild(modalClose);
|
||||||
|
|
||||||
const modalImage = document.createElement('img')
|
const modalImage = document.createElement('img');
|
||||||
modalImage.id = 'modalImage';
|
modalImage.id = 'modalImage';
|
||||||
modalImage.onclick = closeModal;
|
modalImage.onclick = closeModal;
|
||||||
modalImage.tabIndex = 0
|
modalImage.tabIndex = 0;
|
||||||
modalImage.addEventListener('keydown', modalKeyHandler, true)
|
modalImage.addEventListener('keydown', modalKeyHandler, true);
|
||||||
modal.appendChild(modalImage)
|
modal.appendChild(modalImage);
|
||||||
|
|
||||||
const modalPrev = document.createElement('a')
|
const modalPrev = document.createElement('a');
|
||||||
modalPrev.className = 'modalPrev';
|
modalPrev.className = 'modalPrev';
|
||||||
modalPrev.innerHTML = '❮'
|
modalPrev.innerHTML = '❮';
|
||||||
modalPrev.tabIndex = 0
|
modalPrev.tabIndex = 0;
|
||||||
modalPrev.addEventListener('click', modalPrevImage, true);
|
modalPrev.addEventListener('click', modalPrevImage, true);
|
||||||
modalPrev.addEventListener('keydown', modalKeyHandler, true)
|
modalPrev.addEventListener('keydown', modalKeyHandler, true);
|
||||||
modal.appendChild(modalPrev)
|
modal.appendChild(modalPrev);
|
||||||
|
|
||||||
const modalNext = document.createElement('a')
|
const modalNext = document.createElement('a');
|
||||||
modalNext.className = 'modalNext';
|
modalNext.className = 'modalNext';
|
||||||
modalNext.innerHTML = '❯'
|
modalNext.innerHTML = '❯';
|
||||||
modalNext.tabIndex = 0
|
modalNext.tabIndex = 0;
|
||||||
modalNext.addEventListener('click', modalNextImage, true);
|
modalNext.addEventListener('click', modalNextImage, true);
|
||||||
modalNext.addEventListener('keydown', modalKeyHandler, true)
|
modalNext.addEventListener('keydown', modalKeyHandler, true);
|
||||||
|
|
||||||
modal.appendChild(modalNext)
|
modal.appendChild(modalNext);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
gradioApp().appendChild(modal);
|
gradioApp().appendChild(modal);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
gradioApp().body.appendChild(modal);
|
gradioApp().body.appendChild(modal);
|
||||||
}
|
}
|
||||||
|
|
||||||
document.body.appendChild(modal);
|
document.body.appendChild(modal);
|
||||||
|
|
||||||
|
@ -1,7 +1,9 @@
|
|||||||
|
let gamepads = [];
|
||||||
|
|
||||||
window.addEventListener('gamepadconnected', (e) => {
|
window.addEventListener('gamepadconnected', (e) => {
|
||||||
const index = e.gamepad.index;
|
const index = e.gamepad.index;
|
||||||
let isWaiting = false;
|
let isWaiting = false;
|
||||||
setInterval(async () => {
|
gamepads[index] = setInterval(async() => {
|
||||||
if (!opts.js_modal_lightbox_gamepad || isWaiting) return;
|
if (!opts.js_modal_lightbox_gamepad || isWaiting) return;
|
||||||
const gamepad = navigator.getGamepads()[index];
|
const gamepad = navigator.getGamepads()[index];
|
||||||
const xValue = gamepad.axes[0];
|
const xValue = gamepad.axes[0];
|
||||||
@ -14,7 +16,7 @@ window.addEventListener('gamepadconnected', (e) => {
|
|||||||
}
|
}
|
||||||
if (isWaiting) {
|
if (isWaiting) {
|
||||||
await sleepUntil(() => {
|
await sleepUntil(() => {
|
||||||
const xValue = navigator.getGamepads()[index].axes[0]
|
const xValue = navigator.getGamepads()[index].axes[0];
|
||||||
if (xValue < 0.3 && xValue > -0.3) {
|
if (xValue < 0.3 && xValue > -0.3) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@ -24,6 +26,10 @@ window.addEventListener('gamepadconnected', (e) => {
|
|||||||
}, 10);
|
}, 10);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
window.addEventListener('gamepaddisconnected', (e) => {
|
||||||
|
clearInterval(gamepads[e.gamepad.index]);
|
||||||
|
});
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Primarily for vr controller type pointer devices.
|
Primarily for vr controller type pointer devices.
|
||||||
I use the wheel event because there's currently no way to do it properly with web xr.
|
I use the wheel event because there's currently no way to do it properly with web xr.
|
||||||
|
68
javascript/inputAccordion.js
Normal file
68
javascript/inputAccordion.js
Normal file
@ -0,0 +1,68 @@
|
|||||||
|
function inputAccordionChecked(id, checked) {
|
||||||
|
var accordion = gradioApp().getElementById(id);
|
||||||
|
accordion.visibleCheckbox.checked = checked;
|
||||||
|
accordion.onVisibleCheckboxChange();
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupAccordion(accordion) {
|
||||||
|
var labelWrap = accordion.querySelector('.label-wrap');
|
||||||
|
var gradioCheckbox = gradioApp().querySelector('#' + accordion.id + "-checkbox input");
|
||||||
|
var extra = gradioApp().querySelector('#' + accordion.id + "-extra");
|
||||||
|
var span = labelWrap.querySelector('span');
|
||||||
|
var linked = true;
|
||||||
|
|
||||||
|
var isOpen = function() {
|
||||||
|
return labelWrap.classList.contains('open');
|
||||||
|
};
|
||||||
|
|
||||||
|
var observerAccordionOpen = new MutationObserver(function(mutations) {
|
||||||
|
mutations.forEach(function(mutationRecord) {
|
||||||
|
accordion.classList.toggle('input-accordion-open', isOpen());
|
||||||
|
|
||||||
|
if (linked) {
|
||||||
|
accordion.visibleCheckbox.checked = isOpen();
|
||||||
|
accordion.onVisibleCheckboxChange();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
observerAccordionOpen.observe(labelWrap, {attributes: true, attributeFilter: ['class']});
|
||||||
|
|
||||||
|
if (extra) {
|
||||||
|
labelWrap.insertBefore(extra, labelWrap.lastElementChild);
|
||||||
|
}
|
||||||
|
|
||||||
|
accordion.onChecked = function(checked) {
|
||||||
|
if (isOpen() != checked) {
|
||||||
|
labelWrap.click();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
var visibleCheckbox = document.createElement('INPUT');
|
||||||
|
visibleCheckbox.type = 'checkbox';
|
||||||
|
visibleCheckbox.checked = isOpen();
|
||||||
|
visibleCheckbox.id = accordion.id + "-visible-checkbox";
|
||||||
|
visibleCheckbox.className = gradioCheckbox.className + " input-accordion-checkbox";
|
||||||
|
span.insertBefore(visibleCheckbox, span.firstChild);
|
||||||
|
|
||||||
|
accordion.visibleCheckbox = visibleCheckbox;
|
||||||
|
accordion.onVisibleCheckboxChange = function() {
|
||||||
|
if (linked && isOpen() != visibleCheckbox.checked) {
|
||||||
|
labelWrap.click();
|
||||||
|
}
|
||||||
|
|
||||||
|
gradioCheckbox.checked = visibleCheckbox.checked;
|
||||||
|
updateInput(gradioCheckbox);
|
||||||
|
};
|
||||||
|
|
||||||
|
visibleCheckbox.addEventListener('click', function(event) {
|
||||||
|
linked = false;
|
||||||
|
event.stopPropagation();
|
||||||
|
});
|
||||||
|
visibleCheckbox.addEventListener('input', accordion.onVisibleCheckboxChange);
|
||||||
|
}
|
||||||
|
|
||||||
|
onUiLoaded(function() {
|
||||||
|
for (var accordion of gradioApp().querySelectorAll('.input-accordion')) {
|
||||||
|
setupAccordion(accordion);
|
||||||
|
}
|
||||||
|
});
|
26
javascript/localStorage.js
Normal file
26
javascript/localStorage.js
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
|
||||||
|
function localSet(k, v) {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(k, v);
|
||||||
|
} catch (e) {
|
||||||
|
console.warn(`Failed to save ${k} to localStorage: ${e}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function localGet(k, def) {
|
||||||
|
try {
|
||||||
|
return localStorage.getItem(k);
|
||||||
|
} catch (e) {
|
||||||
|
console.warn(`Failed to load ${k} from localStorage: ${e}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
|
||||||
|
function localRemove(k) {
|
||||||
|
try {
|
||||||
|
return localStorage.removeItem(k);
|
||||||
|
} catch (e) {
|
||||||
|
console.warn(`Failed to remove ${k} from localStorage: ${e}`);
|
||||||
|
}
|
||||||
|
}
|
@ -1,171 +1,205 @@
|
|||||||
|
|
||||||
// localization = {} -- the dict with translations is created by the backend
|
// localization = {} -- the dict with translations is created by the backend
|
||||||
|
|
||||||
ignore_ids_for_localization={
|
var ignore_ids_for_localization = {
|
||||||
setting_sd_hypernetwork: 'OPTION',
|
setting_sd_hypernetwork: 'OPTION',
|
||||||
setting_sd_model_checkpoint: 'OPTION',
|
setting_sd_model_checkpoint: 'OPTION',
|
||||||
setting_realesrgan_enabled_models: 'OPTION',
|
modelmerger_primary_model_name: 'OPTION',
|
||||||
modelmerger_primary_model_name: 'OPTION',
|
modelmerger_secondary_model_name: 'OPTION',
|
||||||
modelmerger_secondary_model_name: 'OPTION',
|
modelmerger_tertiary_model_name: 'OPTION',
|
||||||
modelmerger_tertiary_model_name: 'OPTION',
|
train_embedding: 'OPTION',
|
||||||
train_embedding: 'OPTION',
|
train_hypernetwork: 'OPTION',
|
||||||
train_hypernetwork: 'OPTION',
|
txt2img_styles: 'OPTION',
|
||||||
txt2img_styles: 'OPTION',
|
img2img_styles: 'OPTION',
|
||||||
img2img_styles: 'OPTION',
|
setting_random_artist_categories: 'OPTION',
|
||||||
setting_random_artist_categories: 'SPAN',
|
setting_face_restoration_model: 'OPTION',
|
||||||
setting_face_restoration_model: 'SPAN',
|
setting_realesrgan_enabled_models: 'OPTION',
|
||||||
setting_realesrgan_enabled_models: 'SPAN',
|
extras_upscaler_1: 'OPTION',
|
||||||
extras_upscaler_1: 'SPAN',
|
extras_upscaler_2: 'OPTION',
|
||||||
extras_upscaler_2: 'SPAN',
|
};
|
||||||
}
|
|
||||||
|
var re_num = /^[.\d]+$/;
|
||||||
re_num = /^[\.\d]+$/
|
var re_emoji = /[\p{Extended_Pictographic}\u{1F3FB}-\u{1F3FF}\u{1F9B0}-\u{1F9B3}]/u;
|
||||||
re_emoji = /[\p{Extended_Pictographic}\u{1F3FB}-\u{1F3FF}\u{1F9B0}-\u{1F9B3}]/u
|
|
||||||
|
var original_lines = {};
|
||||||
original_lines = {}
|
var translated_lines = {};
|
||||||
translated_lines = {}
|
|
||||||
|
function hasLocalization() {
|
||||||
function hasLocalization() {
|
return window.localization && Object.keys(window.localization).length > 0;
|
||||||
return window.localization && Object.keys(window.localization).length > 0;
|
}
|
||||||
}
|
|
||||||
|
function textNodesUnder(el) {
|
||||||
function textNodesUnder(el){
|
var n, a = [], walk = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, null, false);
|
||||||
var n, a=[], walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false);
|
while ((n = walk.nextNode())) a.push(n);
|
||||||
while(n=walk.nextNode()) a.push(n);
|
return a;
|
||||||
return a;
|
}
|
||||||
}
|
|
||||||
|
function canBeTranslated(node, text) {
|
||||||
function canBeTranslated(node, text){
|
if (!text) return false;
|
||||||
if(! text) return false;
|
if (!node.parentElement) return false;
|
||||||
if(! node.parentElement) return false;
|
|
||||||
|
var parentType = node.parentElement.nodeName;
|
||||||
var parentType = node.parentElement.nodeName
|
if (parentType == 'SCRIPT' || parentType == 'STYLE' || parentType == 'TEXTAREA') return false;
|
||||||
if(parentType=='SCRIPT' || parentType=='STYLE' || parentType=='TEXTAREA') return false;
|
|
||||||
|
if (parentType == 'OPTION' || parentType == 'SPAN') {
|
||||||
if (parentType=='OPTION' || parentType=='SPAN'){
|
var pnode = node;
|
||||||
var pnode = node
|
for (var level = 0; level < 4; level++) {
|
||||||
for(var level=0; level<4; level++){
|
pnode = pnode.parentElement;
|
||||||
pnode = pnode.parentElement
|
if (!pnode) break;
|
||||||
if(! pnode) break;
|
|
||||||
|
if (ignore_ids_for_localization[pnode.id] == parentType) return false;
|
||||||
if(ignore_ids_for_localization[pnode.id] == parentType) return false;
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
if (re_num.test(text)) return false;
|
||||||
if(re_num.test(text)) return false;
|
if (re_emoji.test(text)) return false;
|
||||||
if(re_emoji.test(text)) return false;
|
return true;
|
||||||
return true
|
}
|
||||||
}
|
|
||||||
|
function getTranslation(text) {
|
||||||
function getTranslation(text){
|
if (!text) return undefined;
|
||||||
if(! text) return undefined
|
|
||||||
|
if (translated_lines[text] === undefined) {
|
||||||
if(translated_lines[text] === undefined){
|
original_lines[text] = 1;
|
||||||
original_lines[text] = 1
|
}
|
||||||
}
|
|
||||||
|
var tl = localization[text];
|
||||||
tl = localization[text]
|
if (tl !== undefined) {
|
||||||
if(tl !== undefined){
|
translated_lines[tl] = 1;
|
||||||
translated_lines[tl] = 1
|
}
|
||||||
}
|
|
||||||
|
return tl;
|
||||||
return tl
|
}
|
||||||
}
|
|
||||||
|
function processTextNode(node) {
|
||||||
function processTextNode(node){
|
var text = node.textContent.trim();
|
||||||
var text = node.textContent.trim()
|
|
||||||
|
if (!canBeTranslated(node, text)) return;
|
||||||
if(! canBeTranslated(node, text)) return
|
|
||||||
|
var tl = getTranslation(text);
|
||||||
tl = getTranslation(text)
|
if (tl !== undefined) {
|
||||||
if(tl !== undefined){
|
node.textContent = tl;
|
||||||
node.textContent = tl
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
function processNode(node) {
|
||||||
function processNode(node){
|
if (node.nodeType == 3) {
|
||||||
if(node.nodeType == 3){
|
processTextNode(node);
|
||||||
processTextNode(node)
|
return;
|
||||||
return
|
}
|
||||||
}
|
|
||||||
|
if (node.title) {
|
||||||
if(node.title){
|
let tl = getTranslation(node.title);
|
||||||
tl = getTranslation(node.title)
|
if (tl !== undefined) {
|
||||||
if(tl !== undefined){
|
node.title = tl;
|
||||||
node.title = tl
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
if (node.placeholder) {
|
||||||
if(node.placeholder){
|
let tl = getTranslation(node.placeholder);
|
||||||
tl = getTranslation(node.placeholder)
|
if (tl !== undefined) {
|
||||||
if(tl !== undefined){
|
node.placeholder = tl;
|
||||||
node.placeholder = tl
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
textNodesUnder(node).forEach(function(node) {
|
||||||
textNodesUnder(node).forEach(function(node){
|
processTextNode(node);
|
||||||
processTextNode(node)
|
});
|
||||||
})
|
}
|
||||||
}
|
|
||||||
|
function localizeWholePage() {
|
||||||
function dumpTranslations(){
|
processNode(gradioApp());
|
||||||
var dumped = {}
|
|
||||||
if (localization.rtl) {
|
function elem(comp) {
|
||||||
dumped.rtl = true
|
var elem_id = comp.props.elem_id ? comp.props.elem_id : "component-" + comp.id;
|
||||||
}
|
return gradioApp().getElementById(elem_id);
|
||||||
|
}
|
||||||
Object.keys(original_lines).forEach(function(text){
|
|
||||||
if(dumped[text] !== undefined) return
|
for (var comp of window.gradio_config.components) {
|
||||||
|
if (comp.props.webui_tooltip) {
|
||||||
dumped[text] = localization[text] || text
|
let e = elem(comp);
|
||||||
})
|
|
||||||
|
let tl = e ? getTranslation(e.title) : undefined;
|
||||||
return dumped
|
if (tl !== undefined) {
|
||||||
}
|
e.title = tl;
|
||||||
|
}
|
||||||
function download_localization() {
|
}
|
||||||
var text = JSON.stringify(dumpTranslations(), null, 4)
|
if (comp.props.placeholder) {
|
||||||
|
let e = elem(comp);
|
||||||
var element = document.createElement('a');
|
let textbox = e ? e.querySelector('[placeholder]') : null;
|
||||||
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
|
|
||||||
element.setAttribute('download', "localization.json");
|
let tl = textbox ? getTranslation(textbox.placeholder) : undefined;
|
||||||
element.style.display = 'none';
|
if (tl !== undefined) {
|
||||||
document.body.appendChild(element);
|
textbox.placeholder = tl;
|
||||||
|
}
|
||||||
element.click();
|
}
|
||||||
|
}
|
||||||
document.body.removeChild(element);
|
}
|
||||||
}
|
|
||||||
|
function dumpTranslations() {
|
||||||
if(hasLocalization()) {
|
if (!hasLocalization()) {
|
||||||
onUiUpdate(function (m) {
|
// If we don't have any localization,
|
||||||
m.forEach(function (mutation) {
|
// we will not have traversed the app to find
|
||||||
mutation.addedNodes.forEach(function (node) {
|
// original_lines, so do that now.
|
||||||
processNode(node)
|
localizeWholePage();
|
||||||
})
|
}
|
||||||
});
|
var dumped = {};
|
||||||
})
|
if (localization.rtl) {
|
||||||
|
dumped.rtl = true;
|
||||||
|
}
|
||||||
document.addEventListener("DOMContentLoaded", function () {
|
|
||||||
processNode(gradioApp())
|
for (const text in original_lines) {
|
||||||
|
if (dumped[text] !== undefined) continue;
|
||||||
if (localization.rtl) { // if the language is from right to left,
|
dumped[text] = localization[text] || text;
|
||||||
(new MutationObserver((mutations, observer) => { // wait for the style to load
|
}
|
||||||
mutations.forEach(mutation => {
|
|
||||||
mutation.addedNodes.forEach(node => {
|
return dumped;
|
||||||
if (node.tagName === 'STYLE') {
|
}
|
||||||
observer.disconnect();
|
|
||||||
|
function download_localization() {
|
||||||
for (const x of node.sheet.rules) { // find all rtl media rules
|
var text = JSON.stringify(dumpTranslations(), null, 4);
|
||||||
if (Array.from(x.media || []).includes('rtl')) {
|
|
||||||
x.media.appendMedium('all'); // enable them
|
var element = document.createElement('a');
|
||||||
}
|
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
|
||||||
}
|
element.setAttribute('download', "localization.json");
|
||||||
}
|
element.style.display = 'none';
|
||||||
})
|
document.body.appendChild(element);
|
||||||
});
|
|
||||||
})).observe(gradioApp(), { childList: true });
|
element.click();
|
||||||
}
|
|
||||||
})
|
document.body.removeChild(element);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
document.addEventListener("DOMContentLoaded", function() {
|
||||||
|
if (!hasLocalization()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
onUiUpdate(function(m) {
|
||||||
|
m.forEach(function(mutation) {
|
||||||
|
mutation.addedNodes.forEach(function(node) {
|
||||||
|
processNode(node);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
localizeWholePage();
|
||||||
|
|
||||||
|
if (localization.rtl) { // if the language is from right to left,
|
||||||
|
(new MutationObserver((mutations, observer) => { // wait for the style to load
|
||||||
|
mutations.forEach(mutation => {
|
||||||
|
mutation.addedNodes.forEach(node => {
|
||||||
|
if (node.tagName === 'STYLE') {
|
||||||
|
observer.disconnect();
|
||||||
|
|
||||||
|
for (const x of node.sheet.rules) { // find all rtl media rules
|
||||||
|
if (Array.from(x.media || []).includes('rtl')) {
|
||||||
|
x.media.appendMedium('all'); // enable them
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
})).observe(gradioApp(), {childList: true});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
@ -4,18 +4,18 @@ let lastHeadImg = null;
|
|||||||
|
|
||||||
let notificationButton = null;
|
let notificationButton = null;
|
||||||
|
|
||||||
onUiUpdate(function(){
|
onAfterUiUpdate(function() {
|
||||||
if(notificationButton == null){
|
if (notificationButton == null) {
|
||||||
notificationButton = gradioApp().getElementById('request_notifications')
|
notificationButton = gradioApp().getElementById('request_notifications');
|
||||||
|
|
||||||
if(notificationButton != null){
|
if (notificationButton != null) {
|
||||||
notificationButton.addEventListener('click', () => {
|
notificationButton.addEventListener('click', () => {
|
||||||
void Notification.requestPermission();
|
void Notification.requestPermission();
|
||||||
},true);
|
}, true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const galleryPreviews = gradioApp().querySelectorAll('div[id^="tab_"][style*="display: block"] div[id$="_results"] .thumbnail-item > img');
|
const galleryPreviews = gradioApp().querySelectorAll('div[id^="tab_"] div[id$="_results"] .thumbnail-item > img');
|
||||||
|
|
||||||
if (galleryPreviews == null) return;
|
if (galleryPreviews == null) return;
|
||||||
|
|
||||||
@ -26,7 +26,11 @@ onUiUpdate(function(){
|
|||||||
lastHeadImg = headImg;
|
lastHeadImg = headImg;
|
||||||
|
|
||||||
// play notification sound if available
|
// play notification sound if available
|
||||||
gradioApp().querySelector('#audio_notification audio')?.play();
|
const notificationAudio = gradioApp().querySelector('#audio_notification audio');
|
||||||
|
if (notificationAudio) {
|
||||||
|
notificationAudio.volume = opts.notification_volume / 100.0 || 1.0;
|
||||||
|
notificationAudio.play();
|
||||||
|
}
|
||||||
|
|
||||||
if (document.hasFocus()) return;
|
if (document.hasFocus()) return;
|
||||||
|
|
||||||
@ -42,7 +46,7 @@ onUiUpdate(function(){
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
notification.onclick = function(_){
|
notification.onclick = function(_) {
|
||||||
parent.focus();
|
parent.focus();
|
||||||
this.close();
|
this.close();
|
||||||
};
|
};
|
||||||
|
174
javascript/profilerVisualization.js
Normal file
174
javascript/profilerVisualization.js
Normal file
@ -0,0 +1,174 @@
|
|||||||
|
|
||||||
|
function createRow(table, cellName, items) {
|
||||||
|
var tr = document.createElement('tr');
|
||||||
|
var res = [];
|
||||||
|
|
||||||
|
items.forEach(function(x, i) {
|
||||||
|
if (x === undefined) {
|
||||||
|
res.push(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var td = document.createElement(cellName);
|
||||||
|
td.textContent = x;
|
||||||
|
tr.appendChild(td);
|
||||||
|
res.push(td);
|
||||||
|
|
||||||
|
var colspan = 1;
|
||||||
|
for (var n = i + 1; n < items.length; n++) {
|
||||||
|
if (items[n] !== undefined) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
colspan += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (colspan > 1) {
|
||||||
|
td.colSpan = colspan;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
table.appendChild(tr);
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createVisualizationTable(data, cutoff = 0, sort = "") {
|
||||||
|
var table = document.createElement('table');
|
||||||
|
table.className = 'popup-table';
|
||||||
|
|
||||||
|
var keys = Object.keys(data);
|
||||||
|
if (sort === "number") {
|
||||||
|
keys = keys.sort(function(a, b) {
|
||||||
|
return data[b] - data[a];
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
keys = keys.sort();
|
||||||
|
}
|
||||||
|
var items = keys.map(function(x) {
|
||||||
|
return {key: x, parts: x.split('/'), value: data[x]};
|
||||||
|
});
|
||||||
|
var maxLength = items.reduce(function(a, b) {
|
||||||
|
return Math.max(a, b.parts.length);
|
||||||
|
}, 0);
|
||||||
|
|
||||||
|
var cols = createRow(
|
||||||
|
table,
|
||||||
|
'th',
|
||||||
|
[
|
||||||
|
cutoff === 0 ? 'key' : 'record',
|
||||||
|
cutoff === 0 ? 'value' : 'seconds'
|
||||||
|
]
|
||||||
|
);
|
||||||
|
cols[0].colSpan = maxLength;
|
||||||
|
|
||||||
|
function arraysEqual(a, b) {
|
||||||
|
return !(a < b || b < a);
|
||||||
|
}
|
||||||
|
|
||||||
|
var addLevel = function(level, parent, hide) {
|
||||||
|
var matching = items.filter(function(x) {
|
||||||
|
return x.parts[level] && !x.parts[level + 1] && arraysEqual(x.parts.slice(0, level), parent);
|
||||||
|
});
|
||||||
|
if (sort === "number") {
|
||||||
|
matching = matching.sort(function(a, b) {
|
||||||
|
return b.value - a.value;
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
matching = matching.sort();
|
||||||
|
}
|
||||||
|
var othersTime = 0;
|
||||||
|
var othersList = [];
|
||||||
|
var othersRows = [];
|
||||||
|
var childrenRows = [];
|
||||||
|
matching.forEach(function(x) {
|
||||||
|
var visible = (cutoff === 0 && !hide) || (x.value >= cutoff && !hide);
|
||||||
|
|
||||||
|
var cells = [];
|
||||||
|
for (var i = 0; i < maxLength; i++) {
|
||||||
|
cells.push(x.parts[i]);
|
||||||
|
}
|
||||||
|
cells.push(cutoff === 0 ? x.value : x.value.toFixed(3));
|
||||||
|
var cols = createRow(table, 'td', cells);
|
||||||
|
for (i = 0; i < level; i++) {
|
||||||
|
cols[i].className = 'muted';
|
||||||
|
}
|
||||||
|
|
||||||
|
var tr = cols[0].parentNode;
|
||||||
|
if (!visible) {
|
||||||
|
tr.classList.add("hidden");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cutoff === 0 || x.value >= cutoff) {
|
||||||
|
childrenRows.push(tr);
|
||||||
|
} else {
|
||||||
|
othersTime += x.value;
|
||||||
|
othersList.push(x.parts[level]);
|
||||||
|
othersRows.push(tr);
|
||||||
|
}
|
||||||
|
|
||||||
|
var children = addLevel(level + 1, parent.concat([x.parts[level]]), true);
|
||||||
|
if (children.length > 0) {
|
||||||
|
var cell = cols[level];
|
||||||
|
var onclick = function() {
|
||||||
|
cell.classList.remove("link");
|
||||||
|
cell.removeEventListener("click", onclick);
|
||||||
|
children.forEach(function(x) {
|
||||||
|
x.classList.remove("hidden");
|
||||||
|
});
|
||||||
|
};
|
||||||
|
cell.classList.add("link");
|
||||||
|
cell.addEventListener("click", onclick);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (othersTime > 0) {
|
||||||
|
var cells = [];
|
||||||
|
for (var i = 0; i < maxLength; i++) {
|
||||||
|
cells.push(parent[i]);
|
||||||
|
}
|
||||||
|
cells.push(othersTime.toFixed(3));
|
||||||
|
cells[level] = 'others';
|
||||||
|
var cols = createRow(table, 'td', cells);
|
||||||
|
for (i = 0; i < level; i++) {
|
||||||
|
cols[i].className = 'muted';
|
||||||
|
}
|
||||||
|
|
||||||
|
var cell = cols[level];
|
||||||
|
var tr = cell.parentNode;
|
||||||
|
var onclick = function() {
|
||||||
|
tr.classList.add("hidden");
|
||||||
|
cell.classList.remove("link");
|
||||||
|
cell.removeEventListener("click", onclick);
|
||||||
|
othersRows.forEach(function(x) {
|
||||||
|
x.classList.remove("hidden");
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
cell.title = othersList.join(", ");
|
||||||
|
cell.classList.add("link");
|
||||||
|
cell.addEventListener("click", onclick);
|
||||||
|
|
||||||
|
if (hide) {
|
||||||
|
tr.classList.add("hidden");
|
||||||
|
}
|
||||||
|
|
||||||
|
childrenRows.push(tr);
|
||||||
|
}
|
||||||
|
|
||||||
|
return childrenRows;
|
||||||
|
};
|
||||||
|
|
||||||
|
addLevel(0, []);
|
||||||
|
|
||||||
|
return table;
|
||||||
|
}
|
||||||
|
|
||||||
|
function showProfile(path, cutoff = 0.05) {
|
||||||
|
requestGet(path, {}, function(data) {
|
||||||
|
data.records['total'] = data.total;
|
||||||
|
const table = createVisualizationTable(data.records, cutoff, "number");
|
||||||
|
popup(table);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
@ -1,29 +1,29 @@
|
|||||||
// code related to showing and updating progressbar shown as the image is being made
|
// code related to showing and updating progressbar shown as the image is being made
|
||||||
|
|
||||||
function rememberGallerySelection(){
|
function rememberGallerySelection() {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function getGallerySelectedIndex(){
|
function getGallerySelectedIndex() {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function request(url, data, handler, errorHandler){
|
function request(url, data, handler, errorHandler) {
|
||||||
var xhr = new XMLHttpRequest();
|
var xhr = new XMLHttpRequest();
|
||||||
xhr.open("POST", url, true);
|
xhr.open("POST", url, true);
|
||||||
xhr.setRequestHeader("Content-Type", "application/json");
|
xhr.setRequestHeader("Content-Type", "application/json");
|
||||||
xhr.onreadystatechange = function () {
|
xhr.onreadystatechange = function() {
|
||||||
if (xhr.readyState === 4) {
|
if (xhr.readyState === 4) {
|
||||||
if (xhr.status === 200) {
|
if (xhr.status === 200) {
|
||||||
try {
|
try {
|
||||||
var js = JSON.parse(xhr.responseText);
|
var js = JSON.parse(xhr.responseText);
|
||||||
handler(js)
|
handler(js);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
errorHandler()
|
errorHandler();
|
||||||
}
|
}
|
||||||
} else{
|
} else {
|
||||||
errorHandler()
|
errorHandler();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -31,147 +31,185 @@ function request(url, data, handler, errorHandler){
|
|||||||
xhr.send(js);
|
xhr.send(js);
|
||||||
}
|
}
|
||||||
|
|
||||||
function pad2(x){
|
function pad2(x) {
|
||||||
return x<10 ? '0'+x : x
|
return x < 10 ? '0' + x : x;
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatTime(secs){
|
function formatTime(secs) {
|
||||||
if(secs > 3600){
|
if (secs > 3600) {
|
||||||
return pad2(Math.floor(secs/60/60)) + ":" + pad2(Math.floor(secs/60)%60) + ":" + pad2(Math.floor(secs)%60)
|
return pad2(Math.floor(secs / 60 / 60)) + ":" + pad2(Math.floor(secs / 60) % 60) + ":" + pad2(Math.floor(secs) % 60);
|
||||||
} else if(secs > 60){
|
} else if (secs > 60) {
|
||||||
return pad2(Math.floor(secs/60)) + ":" + pad2(Math.floor(secs)%60)
|
return pad2(Math.floor(secs / 60)) + ":" + pad2(Math.floor(secs) % 60);
|
||||||
} else{
|
} else {
|
||||||
return Math.floor(secs) + "s"
|
return Math.floor(secs) + "s";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function setTitle(progress){
|
|
||||||
var title = 'Stable Diffusion'
|
|
||||||
|
|
||||||
if(opts.show_progress_in_title && progress){
|
var originalAppTitle = undefined;
|
||||||
|
|
||||||
|
onUiLoaded(function() {
|
||||||
|
originalAppTitle = document.title;
|
||||||
|
});
|
||||||
|
|
||||||
|
function setTitle(progress) {
|
||||||
|
var title = originalAppTitle;
|
||||||
|
|
||||||
|
if (opts.show_progress_in_title && progress) {
|
||||||
title = '[' + progress.trim() + '] ' + title;
|
title = '[' + progress.trim() + '] ' + title;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(document.title != title){
|
if (document.title != title) {
|
||||||
document.title = title;
|
document.title = title;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
function randomId(){
|
function randomId() {
|
||||||
return "task(" + Math.random().toString(36).slice(2, 7) + Math.random().toString(36).slice(2, 7) + Math.random().toString(36).slice(2, 7)+")"
|
return "task(" + Math.random().toString(36).slice(2, 7) + Math.random().toString(36).slice(2, 7) + Math.random().toString(36).slice(2, 7) + ")";
|
||||||
}
|
}
|
||||||
|
|
||||||
// starts sending progress requests to "/internal/progress" uri, creating progressbar above progressbarContainer element and
|
// starts sending progress requests to "/internal/progress" uri, creating progressbar above progressbarContainer element and
|
||||||
// preview inside gallery element. Cleans up all created stuff when the task is over and calls atEnd.
|
// preview inside gallery element. Cleans up all created stuff when the task is over and calls atEnd.
|
||||||
// calls onProgress every time there is a progress update
|
// calls onProgress every time there is a progress update
|
||||||
function requestProgress(id_task, progressbarContainer, gallery, atEnd, onProgress, inactivityTimeout=40){
|
function requestProgress(id_task, progressbarContainer, gallery, atEnd, onProgress, inactivityTimeout = 40) {
|
||||||
var dateStart = new Date()
|
var dateStart = new Date();
|
||||||
var wasEverActive = false
|
var wasEverActive = false;
|
||||||
var parentProgressbar = progressbarContainer.parentNode
|
var parentProgressbar = progressbarContainer.parentNode;
|
||||||
var parentGallery = gallery ? gallery.parentNode : null
|
var wakeLock = null;
|
||||||
|
|
||||||
var divProgress = document.createElement('div')
|
var requestWakeLock = async function() {
|
||||||
divProgress.className='progressDiv'
|
if (!opts.prevent_screen_sleep_during_generation || wakeLock) return;
|
||||||
divProgress.style.display = opts.show_progressbar ? "block" : "none"
|
try {
|
||||||
var divInner = document.createElement('div')
|
wakeLock = await navigator.wakeLock.request('screen');
|
||||||
divInner.className='progress'
|
} catch (err) {
|
||||||
|
console.error('Wake Lock is not supported.');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
divProgress.appendChild(divInner)
|
var releaseWakeLock = async function() {
|
||||||
parentProgressbar.insertBefore(divProgress, progressbarContainer)
|
if (!opts.prevent_screen_sleep_during_generation || !wakeLock) return;
|
||||||
|
try {
|
||||||
|
await wakeLock.release();
|
||||||
|
wakeLock = null;
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Wake Lock release failed', err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
if(parentGallery){
|
var divProgress = document.createElement('div');
|
||||||
var livePreview = document.createElement('div')
|
divProgress.className = 'progressDiv';
|
||||||
livePreview.className='livePreview'
|
divProgress.style.display = opts.show_progressbar ? "block" : "none";
|
||||||
parentGallery.insertBefore(livePreview, gallery)
|
var divInner = document.createElement('div');
|
||||||
}
|
divInner.className = 'progress';
|
||||||
|
|
||||||
var removeProgressBar = function(){
|
divProgress.appendChild(divInner);
|
||||||
setTitle("")
|
parentProgressbar.insertBefore(divProgress, progressbarContainer);
|
||||||
parentProgressbar.removeChild(divProgress)
|
|
||||||
if(parentGallery) parentGallery.removeChild(livePreview)
|
|
||||||
atEnd()
|
|
||||||
}
|
|
||||||
|
|
||||||
var fun = function(id_task, id_live_preview){
|
var livePreview = null;
|
||||||
request("./internal/progress", {"id_task": id_task, "id_live_preview": id_live_preview}, function(res){
|
|
||||||
if(res.completed){
|
var removeProgressBar = function() {
|
||||||
removeProgressBar()
|
releaseWakeLock();
|
||||||
return
|
if (!divProgress) return;
|
||||||
|
|
||||||
|
setTitle("");
|
||||||
|
parentProgressbar.removeChild(divProgress);
|
||||||
|
if (gallery && livePreview) gallery.removeChild(livePreview);
|
||||||
|
atEnd();
|
||||||
|
|
||||||
|
divProgress = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
var funProgress = function(id_task) {
|
||||||
|
requestWakeLock();
|
||||||
|
request("./internal/progress", {id_task: id_task, live_preview: false}, function(res) {
|
||||||
|
if (res.completed) {
|
||||||
|
removeProgressBar();
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var rect = progressbarContainer.getBoundingClientRect()
|
let progressText = "";
|
||||||
|
|
||||||
if(rect.width){
|
divInner.style.width = ((res.progress || 0) * 100.0) + '%';
|
||||||
divProgress.style.width = rect.width + "px";
|
divInner.style.background = res.progress ? "" : "transparent";
|
||||||
|
|
||||||
|
if (res.progress > 0) {
|
||||||
|
progressText = ((res.progress || 0) * 100.0).toFixed(0) + '%';
|
||||||
}
|
}
|
||||||
|
|
||||||
let progressText = ""
|
if (res.eta) {
|
||||||
|
progressText += " ETA: " + formatTime(res.eta);
|
||||||
divInner.style.width = ((res.progress || 0) * 100.0) + '%'
|
|
||||||
divInner.style.background = res.progress ? "" : "transparent"
|
|
||||||
|
|
||||||
if(res.progress > 0){
|
|
||||||
progressText = ((res.progress || 0) * 100.0).toFixed(0) + '%'
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if(res.eta){
|
setTitle(progressText);
|
||||||
progressText += " ETA: " + formatTime(res.eta)
|
|
||||||
|
if (res.textinfo && res.textinfo.indexOf("\n") == -1) {
|
||||||
|
progressText = res.textinfo + " " + progressText;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
divInner.textContent = progressText;
|
||||||
|
|
||||||
setTitle(progressText)
|
var elapsedFromStart = (new Date() - dateStart) / 1000;
|
||||||
|
|
||||||
if(res.textinfo && res.textinfo.indexOf("\n") == -1){
|
if (res.active) wasEverActive = true;
|
||||||
progressText = res.textinfo + " " + progressText
|
|
||||||
|
if (!res.active && wasEverActive) {
|
||||||
|
removeProgressBar();
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
divInner.textContent = progressText
|
if (elapsedFromStart > inactivityTimeout && !res.queued && !res.active) {
|
||||||
|
removeProgressBar();
|
||||||
var elapsedFromStart = (new Date() - dateStart) / 1000
|
return;
|
||||||
|
|
||||||
if(res.active) wasEverActive = true;
|
|
||||||
|
|
||||||
if(! res.active && wasEverActive){
|
|
||||||
removeProgressBar()
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if(elapsedFromStart > inactivityTimeout && !res.queued && !res.active){
|
if (onProgress) {
|
||||||
removeProgressBar()
|
onProgress(res);
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
if(res.live_preview && gallery){
|
|
||||||
var rect = gallery.getBoundingClientRect()
|
|
||||||
if(rect.width){
|
|
||||||
livePreview.style.width = rect.width + "px"
|
|
||||||
livePreview.style.height = rect.height + "px"
|
|
||||||
}
|
|
||||||
|
|
||||||
var img = new Image();
|
|
||||||
img.onload = function() {
|
|
||||||
livePreview.appendChild(img)
|
|
||||||
if(livePreview.childElementCount > 2){
|
|
||||||
livePreview.removeChild(livePreview.firstElementChild)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
img.src = res.live_preview;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
if(onProgress){
|
|
||||||
onProgress(res)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
fun(id_task, res.id_live_preview);
|
funProgress(id_task, res.id_live_preview);
|
||||||
}, opts.live_preview_refresh_period || 500)
|
}, opts.live_preview_refresh_period || 500);
|
||||||
}, function(){
|
}, function() {
|
||||||
removeProgressBar()
|
removeProgressBar();
|
||||||
})
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
var funLivePreview = function(id_task, id_live_preview) {
|
||||||
|
request("./internal/progress", {id_task: id_task, id_live_preview: id_live_preview}, function(res) {
|
||||||
|
if (!divProgress) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (res.live_preview && gallery) {
|
||||||
|
var img = new Image();
|
||||||
|
img.onload = function() {
|
||||||
|
if (!livePreview) {
|
||||||
|
livePreview = document.createElement('div');
|
||||||
|
livePreview.className = 'livePreview';
|
||||||
|
gallery.insertBefore(livePreview, gallery.firstElementChild);
|
||||||
|
}
|
||||||
|
|
||||||
|
livePreview.appendChild(img);
|
||||||
|
if (livePreview.childElementCount > 2) {
|
||||||
|
livePreview.removeChild(livePreview.firstElementChild);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
img.src = res.live_preview;
|
||||||
|
}
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
funLivePreview(id_task, res.id_live_preview);
|
||||||
|
}, opts.live_preview_refresh_period || 500);
|
||||||
|
}, function() {
|
||||||
|
removeProgressBar();
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
funProgress(id_task, 0);
|
||||||
|
|
||||||
|
if (gallery) {
|
||||||
|
funLivePreview(id_task, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
fun(id_task, 0)
|
|
||||||
}
|
}
|
||||||
|
205
javascript/resizeHandle.js
Normal file
205
javascript/resizeHandle.js
Normal file
@ -0,0 +1,205 @@
|
|||||||
|
(function() {
|
||||||
|
const GRADIO_MIN_WIDTH = 320;
|
||||||
|
const PAD = 16;
|
||||||
|
const DEBOUNCE_TIME = 100;
|
||||||
|
const DOUBLE_TAP_DELAY = 200; //ms
|
||||||
|
|
||||||
|
const R = {
|
||||||
|
tracking: false,
|
||||||
|
parent: null,
|
||||||
|
parentWidth: null,
|
||||||
|
leftCol: null,
|
||||||
|
leftColStartWidth: null,
|
||||||
|
screenX: null,
|
||||||
|
lastTapTime: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
let resizeTimer;
|
||||||
|
let parents = [];
|
||||||
|
|
||||||
|
function setLeftColGridTemplate(el, width) {
|
||||||
|
el.style.gridTemplateColumns = `${width}px 16px 1fr`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function displayResizeHandle(parent) {
|
||||||
|
if (!parent.needHideOnMoblie) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (window.innerWidth < GRADIO_MIN_WIDTH * 2 + PAD * 4) {
|
||||||
|
parent.style.display = 'flex';
|
||||||
|
parent.resizeHandle.style.display = "none";
|
||||||
|
return false;
|
||||||
|
} else {
|
||||||
|
parent.style.display = 'grid';
|
||||||
|
parent.resizeHandle.style.display = "block";
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function afterResize(parent) {
|
||||||
|
if (displayResizeHandle(parent) && parent.style.gridTemplateColumns != parent.style.originalGridTemplateColumns) {
|
||||||
|
const oldParentWidth = R.parentWidth;
|
||||||
|
const newParentWidth = parent.offsetWidth;
|
||||||
|
const widthL = parseInt(parent.style.gridTemplateColumns.split(' ')[0]);
|
||||||
|
|
||||||
|
const ratio = newParentWidth / oldParentWidth;
|
||||||
|
|
||||||
|
const newWidthL = Math.max(Math.floor(ratio * widthL), parent.minLeftColWidth);
|
||||||
|
setLeftColGridTemplate(parent, newWidthL);
|
||||||
|
|
||||||
|
R.parentWidth = newParentWidth;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setup(parent) {
|
||||||
|
|
||||||
|
function onDoubleClick(evt) {
|
||||||
|
evt.preventDefault();
|
||||||
|
evt.stopPropagation();
|
||||||
|
|
||||||
|
parent.style.gridTemplateColumns = parent.style.originalGridTemplateColumns;
|
||||||
|
}
|
||||||
|
|
||||||
|
const leftCol = parent.firstElementChild;
|
||||||
|
const rightCol = parent.lastElementChild;
|
||||||
|
|
||||||
|
parents.push(parent);
|
||||||
|
|
||||||
|
parent.style.display = 'grid';
|
||||||
|
parent.style.gap = '0';
|
||||||
|
let leftColTemplate = "";
|
||||||
|
if (parent.children[0].style.flexGrow) {
|
||||||
|
leftColTemplate = `${parent.children[0].style.flexGrow}fr`;
|
||||||
|
parent.minLeftColWidth = GRADIO_MIN_WIDTH;
|
||||||
|
parent.minRightColWidth = GRADIO_MIN_WIDTH;
|
||||||
|
parent.needHideOnMoblie = true;
|
||||||
|
} else {
|
||||||
|
leftColTemplate = parent.children[0].style.flexBasis;
|
||||||
|
parent.minLeftColWidth = parent.children[0].style.flexBasis.slice(0, -2) / 2;
|
||||||
|
parent.minRightColWidth = 0;
|
||||||
|
parent.needHideOnMoblie = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!leftColTemplate) {
|
||||||
|
leftColTemplate = '1fr';
|
||||||
|
}
|
||||||
|
|
||||||
|
const gridTemplateColumns = `${leftColTemplate} ${PAD}px ${parent.children[1].style.flexGrow}fr`;
|
||||||
|
parent.style.gridTemplateColumns = gridTemplateColumns;
|
||||||
|
parent.style.originalGridTemplateColumns = gridTemplateColumns;
|
||||||
|
|
||||||
|
const resizeHandle = document.createElement('div');
|
||||||
|
resizeHandle.classList.add('resize-handle');
|
||||||
|
parent.insertBefore(resizeHandle, rightCol);
|
||||||
|
parent.resizeHandle = resizeHandle;
|
||||||
|
|
||||||
|
['mousedown', 'touchstart'].forEach((eventType) => {
|
||||||
|
resizeHandle.addEventListener(eventType, (evt) => {
|
||||||
|
if (eventType.startsWith('mouse')) {
|
||||||
|
if (evt.button !== 0) return;
|
||||||
|
} else {
|
||||||
|
if (evt.changedTouches.length !== 1) return;
|
||||||
|
|
||||||
|
const currentTime = new Date().getTime();
|
||||||
|
if (R.lastTapTime && currentTime - R.lastTapTime <= DOUBLE_TAP_DELAY) {
|
||||||
|
onDoubleClick(evt);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
R.lastTapTime = currentTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
evt.preventDefault();
|
||||||
|
evt.stopPropagation();
|
||||||
|
|
||||||
|
document.body.classList.add('resizing');
|
||||||
|
|
||||||
|
R.tracking = true;
|
||||||
|
R.parent = parent;
|
||||||
|
R.parentWidth = parent.offsetWidth;
|
||||||
|
R.leftCol = leftCol;
|
||||||
|
R.leftColStartWidth = leftCol.offsetWidth;
|
||||||
|
if (eventType.startsWith('mouse')) {
|
||||||
|
R.screenX = evt.screenX;
|
||||||
|
} else {
|
||||||
|
R.screenX = evt.changedTouches[0].screenX;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
resizeHandle.addEventListener('dblclick', onDoubleClick);
|
||||||
|
|
||||||
|
afterResize(parent);
|
||||||
|
}
|
||||||
|
|
||||||
|
['mousemove', 'touchmove'].forEach((eventType) => {
|
||||||
|
window.addEventListener(eventType, (evt) => {
|
||||||
|
if (eventType.startsWith('mouse')) {
|
||||||
|
if (evt.button !== 0) return;
|
||||||
|
} else {
|
||||||
|
if (evt.changedTouches.length !== 1) return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (R.tracking) {
|
||||||
|
if (eventType.startsWith('mouse')) {
|
||||||
|
evt.preventDefault();
|
||||||
|
}
|
||||||
|
evt.stopPropagation();
|
||||||
|
|
||||||
|
let delta = 0;
|
||||||
|
if (eventType.startsWith('mouse')) {
|
||||||
|
delta = R.screenX - evt.screenX;
|
||||||
|
} else {
|
||||||
|
delta = R.screenX - evt.changedTouches[0].screenX;
|
||||||
|
}
|
||||||
|
const leftColWidth = Math.max(Math.min(R.leftColStartWidth - delta, R.parent.offsetWidth - R.parent.minRightColWidth - PAD), R.parent.minLeftColWidth);
|
||||||
|
setLeftColGridTemplate(R.parent, leftColWidth);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
['mouseup', 'touchend'].forEach((eventType) => {
|
||||||
|
window.addEventListener(eventType, (evt) => {
|
||||||
|
if (eventType.startsWith('mouse')) {
|
||||||
|
if (evt.button !== 0) return;
|
||||||
|
} else {
|
||||||
|
if (evt.changedTouches.length !== 1) return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (R.tracking) {
|
||||||
|
evt.preventDefault();
|
||||||
|
evt.stopPropagation();
|
||||||
|
|
||||||
|
R.tracking = false;
|
||||||
|
|
||||||
|
document.body.classList.remove('resizing');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
window.addEventListener('resize', () => {
|
||||||
|
clearTimeout(resizeTimer);
|
||||||
|
|
||||||
|
resizeTimer = setTimeout(function() {
|
||||||
|
for (const parent of parents) {
|
||||||
|
afterResize(parent);
|
||||||
|
}
|
||||||
|
}, DEBOUNCE_TIME);
|
||||||
|
});
|
||||||
|
|
||||||
|
setupResizeHandle = setup;
|
||||||
|
})();
|
||||||
|
|
||||||
|
|
||||||
|
function setupAllResizeHandles() {
|
||||||
|
for (var elem of gradioApp().querySelectorAll('.resize-handle-row')) {
|
||||||
|
if (!elem.querySelector('.resize-handle') && !elem.children[0].classList.contains("hidden")) {
|
||||||
|
setupResizeHandle(elem);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
onUiLoaded(setupAllResizeHandles);
|
||||||
|
|
71
javascript/settings.js
Normal file
71
javascript/settings.js
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
let settingsExcludeTabsFromShowAll = {
|
||||||
|
settings_tab_defaults: 1,
|
||||||
|
settings_tab_sysinfo: 1,
|
||||||
|
settings_tab_actions: 1,
|
||||||
|
settings_tab_licenses: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
function settingsShowAllTabs() {
|
||||||
|
gradioApp().querySelectorAll('#settings > div').forEach(function(elem) {
|
||||||
|
if (settingsExcludeTabsFromShowAll[elem.id]) return;
|
||||||
|
|
||||||
|
elem.style.display = "block";
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function settingsShowOneTab() {
|
||||||
|
gradioApp().querySelector('#settings_show_one_page').click();
|
||||||
|
}
|
||||||
|
|
||||||
|
onUiLoaded(function() {
|
||||||
|
var edit = gradioApp().querySelector('#settings_search');
|
||||||
|
var editTextarea = gradioApp().querySelector('#settings_search > label > input');
|
||||||
|
var buttonShowAllPages = gradioApp().getElementById('settings_show_all_pages');
|
||||||
|
var settings_tabs = gradioApp().querySelector('#settings div');
|
||||||
|
|
||||||
|
onEdit('settingsSearch', editTextarea, 250, function() {
|
||||||
|
var searchText = (editTextarea.value || "").trim().toLowerCase();
|
||||||
|
|
||||||
|
gradioApp().querySelectorAll('#settings > div[id^=settings_] div[id^=column_settings_] > *').forEach(function(elem) {
|
||||||
|
var visible = elem.textContent.trim().toLowerCase().indexOf(searchText) != -1;
|
||||||
|
elem.style.display = visible ? "" : "none";
|
||||||
|
});
|
||||||
|
|
||||||
|
if (searchText != "") {
|
||||||
|
settingsShowAllTabs();
|
||||||
|
} else {
|
||||||
|
settingsShowOneTab();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
settings_tabs.insertBefore(edit, settings_tabs.firstChild);
|
||||||
|
settings_tabs.appendChild(buttonShowAllPages);
|
||||||
|
|
||||||
|
|
||||||
|
buttonShowAllPages.addEventListener("click", settingsShowAllTabs);
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
onOptionsChanged(function() {
|
||||||
|
if (gradioApp().querySelector('#settings .settings-category')) return;
|
||||||
|
|
||||||
|
var sectionMap = {};
|
||||||
|
gradioApp().querySelectorAll('#settings > div > button').forEach(function(x) {
|
||||||
|
sectionMap[x.textContent.trim()] = x;
|
||||||
|
});
|
||||||
|
|
||||||
|
opts._categories.forEach(function(x) {
|
||||||
|
var section = localization[x[0]] ?? x[0];
|
||||||
|
var category = localization[x[1]] ?? x[1];
|
||||||
|
|
||||||
|
var span = document.createElement('SPAN');
|
||||||
|
span.textContent = category;
|
||||||
|
span.className = 'settings-category';
|
||||||
|
|
||||||
|
var sectionElem = sectionMap[section];
|
||||||
|
if (!sectionElem) return;
|
||||||
|
|
||||||
|
sectionElem.parentElement.insertBefore(span, sectionElem);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -1,17 +1,17 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
function start_training_textual_inversion(){
|
function start_training_textual_inversion() {
|
||||||
gradioApp().querySelector('#ti_error').innerHTML=''
|
gradioApp().querySelector('#ti_error').innerHTML = '';
|
||||||
|
|
||||||
var id = randomId()
|
var id = randomId();
|
||||||
requestProgress(id, gradioApp().getElementById('ti_output'), gradioApp().getElementById('ti_gallery'), function(){}, function(progress){
|
requestProgress(id, gradioApp().getElementById('ti_output'), gradioApp().getElementById('ti_gallery'), function() {}, function(progress) {
|
||||||
gradioApp().getElementById('ti_progress').innerHTML = progress.textinfo
|
gradioApp().getElementById('ti_progress').innerHTML = progress.textinfo;
|
||||||
})
|
});
|
||||||
|
|
||||||
var res = args_to_array(arguments)
|
var res = Array.from(arguments);
|
||||||
|
|
||||||
res[0] = id
|
res[0] = id;
|
||||||
|
|
||||||
return res
|
return res;
|
||||||
}
|
}
|
||||||
|
87
javascript/token-counters.js
Normal file
87
javascript/token-counters.js
Normal file
@ -0,0 +1,87 @@
|
|||||||
|
let promptTokenCountUpdateFunctions = {};
|
||||||
|
|
||||||
|
function update_txt2img_tokens(...args) {
|
||||||
|
// Called from Gradio
|
||||||
|
update_token_counter("txt2img_token_button");
|
||||||
|
update_token_counter("txt2img_negative_token_button");
|
||||||
|
if (args.length == 2) {
|
||||||
|
return args[0];
|
||||||
|
}
|
||||||
|
return args;
|
||||||
|
}
|
||||||
|
|
||||||
|
function update_img2img_tokens(...args) {
|
||||||
|
// Called from Gradio
|
||||||
|
update_token_counter("img2img_token_button");
|
||||||
|
update_token_counter("img2img_negative_token_button");
|
||||||
|
if (args.length == 2) {
|
||||||
|
return args[0];
|
||||||
|
}
|
||||||
|
return args;
|
||||||
|
}
|
||||||
|
|
||||||
|
function update_token_counter(button_id) {
|
||||||
|
promptTokenCountUpdateFunctions[button_id]?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function recalculatePromptTokens(name) {
|
||||||
|
promptTokenCountUpdateFunctions[name]?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
function recalculate_prompts_txt2img() {
|
||||||
|
// Called from Gradio
|
||||||
|
recalculatePromptTokens('txt2img_prompt');
|
||||||
|
recalculatePromptTokens('txt2img_neg_prompt');
|
||||||
|
return Array.from(arguments);
|
||||||
|
}
|
||||||
|
|
||||||
|
function recalculate_prompts_img2img() {
|
||||||
|
// Called from Gradio
|
||||||
|
recalculatePromptTokens('img2img_prompt');
|
||||||
|
recalculatePromptTokens('img2img_neg_prompt');
|
||||||
|
return Array.from(arguments);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupTokenCounting(id, id_counter, id_button) {
|
||||||
|
var prompt = gradioApp().getElementById(id);
|
||||||
|
var counter = gradioApp().getElementById(id_counter);
|
||||||
|
var textarea = gradioApp().querySelector(`#${id} > label > textarea`);
|
||||||
|
|
||||||
|
if (counter.parentElement == prompt.parentElement) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
prompt.parentElement.insertBefore(counter, prompt);
|
||||||
|
prompt.parentElement.style.position = "relative";
|
||||||
|
|
||||||
|
var func = onEdit(id, textarea, 800, function() {
|
||||||
|
if (counter.classList.contains("token-counter-visible")) {
|
||||||
|
gradioApp().getElementById(id_button)?.click();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
promptTokenCountUpdateFunctions[id] = func;
|
||||||
|
promptTokenCountUpdateFunctions[id_button] = func;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleTokenCountingVisibility(id, id_counter, id_button) {
|
||||||
|
var counter = gradioApp().getElementById(id_counter);
|
||||||
|
|
||||||
|
counter.style.display = opts.disable_token_counters ? "none" : "block";
|
||||||
|
counter.classList.toggle("token-counter-visible", !opts.disable_token_counters);
|
||||||
|
}
|
||||||
|
|
||||||
|
function runCodeForTokenCounters(fun) {
|
||||||
|
fun('txt2img_prompt', 'txt2img_token_counter', 'txt2img_token_button');
|
||||||
|
fun('txt2img_neg_prompt', 'txt2img_negative_token_counter', 'txt2img_negative_token_button');
|
||||||
|
fun('img2img_prompt', 'img2img_token_counter', 'img2img_token_button');
|
||||||
|
fun('img2img_neg_prompt', 'img2img_negative_token_counter', 'img2img_negative_token_button');
|
||||||
|
}
|
||||||
|
|
||||||
|
onUiLoaded(function() {
|
||||||
|
runCodeForTokenCounters(setupTokenCounting);
|
||||||
|
});
|
||||||
|
|
||||||
|
onOptionsChanged(function() {
|
||||||
|
runCodeForTokenCounters(toggleTokenCountingVisibility);
|
||||||
|
});
|
553
javascript/ui.js
553
javascript/ui.js
@ -1,9 +1,9 @@
|
|||||||
// various functions for interaction with ui.py not large enough to warrant putting them in separate files
|
// various functions for interaction with ui.py not large enough to warrant putting them in separate files
|
||||||
|
|
||||||
function set_theme(theme){
|
function set_theme(theme) {
|
||||||
var gradioURL = window.location.href
|
var gradioURL = window.location.href;
|
||||||
if (!gradioURL.includes('?__theme=')) {
|
if (!gradioURL.includes('?__theme=')) {
|
||||||
window.location.replace(gradioURL + '?__theme=' + theme);
|
window.location.replace(gradioURL + '?__theme=' + theme);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -14,42 +14,37 @@ function all_gallery_buttons() {
|
|||||||
if (elem.parentElement.offsetParent) {
|
if (elem.parentElement.offsetParent) {
|
||||||
visibleGalleryButtons.push(elem);
|
visibleGalleryButtons.push(elem);
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
return visibleGalleryButtons;
|
return visibleGalleryButtons;
|
||||||
}
|
}
|
||||||
|
|
||||||
function selected_gallery_button() {
|
function selected_gallery_button() {
|
||||||
var allCurrentButtons = gradioApp().querySelectorAll('[style="display: block;"].tabitem div[id$=_gallery].gradio-gallery .thumbnail-item.thumbnail-small.selected');
|
return all_gallery_buttons().find(elem => elem.classList.contains('selected')) ?? null;
|
||||||
var visibleCurrentButton = null;
|
|
||||||
allCurrentButtons.forEach(function(elem) {
|
|
||||||
if (elem.parentElement.offsetParent) {
|
|
||||||
visibleCurrentButton = elem;
|
|
||||||
}
|
|
||||||
})
|
|
||||||
return visibleCurrentButton;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function selected_gallery_index(){
|
function selected_gallery_index() {
|
||||||
var buttons = all_gallery_buttons();
|
return all_gallery_buttons().findIndex(elem => elem.classList.contains('selected'));
|
||||||
var button = selected_gallery_button();
|
|
||||||
|
|
||||||
var result = -1
|
|
||||||
buttons.forEach(function(v, i){ if(v==button) { result = i } })
|
|
||||||
|
|
||||||
return result
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function extract_image_from_gallery(gallery){
|
function gallery_container_buttons(gallery_container) {
|
||||||
if (gallery.length == 0){
|
return gradioApp().querySelectorAll(`#${gallery_container} .thumbnail-item.thumbnail-small`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function selected_gallery_index_id(gallery_container) {
|
||||||
|
return Array.from(gallery_container_buttons(gallery_container)).findIndex(elem => elem.classList.contains('selected'));
|
||||||
|
}
|
||||||
|
|
||||||
|
function extract_image_from_gallery(gallery) {
|
||||||
|
if (gallery.length == 0) {
|
||||||
return [null];
|
return [null];
|
||||||
}
|
}
|
||||||
if (gallery.length == 1){
|
if (gallery.length == 1) {
|
||||||
return [gallery[0]];
|
return [gallery[0]];
|
||||||
}
|
}
|
||||||
|
|
||||||
var index = selected_gallery_index()
|
var index = selected_gallery_index();
|
||||||
|
|
||||||
if (index < 0 || index >= gallery.length){
|
if (index < 0 || index >= gallery.length) {
|
||||||
// Use the first image in the gallery as the default
|
// Use the first image in the gallery as the default
|
||||||
index = 0;
|
index = 0;
|
||||||
}
|
}
|
||||||
@ -57,249 +52,263 @@ function extract_image_from_gallery(gallery){
|
|||||||
return [gallery[index]];
|
return [gallery[index]];
|
||||||
}
|
}
|
||||||
|
|
||||||
function args_to_array(args){
|
window.args_to_array = Array.from; // Compatibility with e.g. extensions that may expect this to be around
|
||||||
var res = []
|
|
||||||
for(var i=0;i<args.length;i++){
|
|
||||||
res.push(args[i])
|
|
||||||
}
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
function switch_to_txt2img(){
|
function switch_to_txt2img() {
|
||||||
gradioApp().querySelector('#tabs').querySelectorAll('button')[0].click();
|
gradioApp().querySelector('#tabs').querySelectorAll('button')[0].click();
|
||||||
|
|
||||||
return args_to_array(arguments);
|
return Array.from(arguments);
|
||||||
}
|
}
|
||||||
|
|
||||||
function switch_to_img2img_tab(no){
|
function switch_to_img2img_tab(no) {
|
||||||
gradioApp().querySelector('#tabs').querySelectorAll('button')[1].click();
|
gradioApp().querySelector('#tabs').querySelectorAll('button')[1].click();
|
||||||
gradioApp().getElementById('mode_img2img').querySelectorAll('button')[no].click();
|
gradioApp().getElementById('mode_img2img').querySelectorAll('button')[no].click();
|
||||||
}
|
}
|
||||||
function switch_to_img2img(){
|
function switch_to_img2img() {
|
||||||
switch_to_img2img_tab(0);
|
switch_to_img2img_tab(0);
|
||||||
return args_to_array(arguments);
|
return Array.from(arguments);
|
||||||
}
|
}
|
||||||
|
|
||||||
function switch_to_sketch(){
|
function switch_to_sketch() {
|
||||||
switch_to_img2img_tab(1);
|
switch_to_img2img_tab(1);
|
||||||
return args_to_array(arguments);
|
return Array.from(arguments);
|
||||||
}
|
}
|
||||||
|
|
||||||
function switch_to_inpaint(){
|
function switch_to_inpaint() {
|
||||||
switch_to_img2img_tab(2);
|
switch_to_img2img_tab(2);
|
||||||
return args_to_array(arguments);
|
return Array.from(arguments);
|
||||||
}
|
}
|
||||||
|
|
||||||
function switch_to_inpaint_sketch(){
|
function switch_to_inpaint_sketch() {
|
||||||
switch_to_img2img_tab(3);
|
switch_to_img2img_tab(3);
|
||||||
return args_to_array(arguments);
|
return Array.from(arguments);
|
||||||
}
|
}
|
||||||
|
|
||||||
function switch_to_inpaint(){
|
function switch_to_extras() {
|
||||||
gradioApp().querySelector('#tabs').querySelectorAll('button')[1].click();
|
|
||||||
gradioApp().getElementById('mode_img2img').querySelectorAll('button')[2].click();
|
|
||||||
|
|
||||||
return args_to_array(arguments);
|
|
||||||
}
|
|
||||||
|
|
||||||
function switch_to_extras(){
|
|
||||||
gradioApp().querySelector('#tabs').querySelectorAll('button')[2].click();
|
gradioApp().querySelector('#tabs').querySelectorAll('button')[2].click();
|
||||||
|
|
||||||
return args_to_array(arguments);
|
return Array.from(arguments);
|
||||||
}
|
}
|
||||||
|
|
||||||
function get_tab_index(tabId){
|
function get_tab_index(tabId) {
|
||||||
var res = 0
|
let buttons = gradioApp().getElementById(tabId).querySelector('div').querySelectorAll('button');
|
||||||
|
for (let i = 0; i < buttons.length; i++) {
|
||||||
gradioApp().getElementById(tabId).querySelector('div').querySelectorAll('button').forEach(function(button, i){
|
if (buttons[i].classList.contains('selected')) {
|
||||||
if(button.className.indexOf('selected') != -1)
|
return i;
|
||||||
res = i
|
}
|
||||||
})
|
|
||||||
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
function create_tab_index_args(tabId, args){
|
|
||||||
var res = []
|
|
||||||
for(var i=0; i<args.length; i++){
|
|
||||||
res.push(args[i])
|
|
||||||
}
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
res[0] = get_tab_index(tabId)
|
function create_tab_index_args(tabId, args) {
|
||||||
|
var res = Array.from(args);
|
||||||
return res
|
res[0] = get_tab_index(tabId);
|
||||||
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
function get_img2img_tab_index() {
|
function get_img2img_tab_index() {
|
||||||
let res = args_to_array(arguments)
|
let res = Array.from(arguments);
|
||||||
res.splice(-2)
|
res.splice(-2);
|
||||||
res[0] = get_tab_index('mode_img2img')
|
res[0] = get_tab_index('mode_img2img');
|
||||||
return res
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
function create_submit_args(args){
|
function create_submit_args(args) {
|
||||||
var res = []
|
var res = Array.from(args);
|
||||||
for(var i=0;i<args.length;i++){
|
|
||||||
res.push(args[i])
|
|
||||||
}
|
|
||||||
|
|
||||||
// As it is currently, txt2img and img2img send back the previous output args (txt2img_gallery, generation_info, html_info) whenever you generate a new image.
|
// As it is currently, txt2img and img2img send back the previous output args (txt2img_gallery, generation_info, html_info) whenever you generate a new image.
|
||||||
// This can lead to uploading a huge gallery of previously generated images, which leads to an unnecessary delay between submitting and beginning to generate.
|
// This can lead to uploading a huge gallery of previously generated images, which leads to an unnecessary delay between submitting and beginning to generate.
|
||||||
// I don't know why gradio is sending outputs along with inputs, but we can prevent sending the image gallery here, which seems to be an issue for some.
|
// I don't know why gradio is sending outputs along with inputs, but we can prevent sending the image gallery here, which seems to be an issue for some.
|
||||||
// If gradio at some point stops sending outputs, this may break something
|
// If gradio at some point stops sending outputs, this may break something
|
||||||
if(Array.isArray(res[res.length - 3])){
|
if (Array.isArray(res[res.length - 3])) {
|
||||||
res[res.length - 3] = null
|
res[res.length - 3] = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return res
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
function showSubmitButtons(tabname, show){
|
function setSubmitButtonsVisibility(tabname, showInterrupt, showSkip, showInterrupting) {
|
||||||
gradioApp().getElementById(tabname+'_interrupt').style.display = show ? "none" : "block"
|
gradioApp().getElementById(tabname + '_interrupt').style.display = showInterrupt ? "block" : "none";
|
||||||
gradioApp().getElementById(tabname+'_skip').style.display = show ? "none" : "block"
|
gradioApp().getElementById(tabname + '_skip').style.display = showSkip ? "block" : "none";
|
||||||
|
gradioApp().getElementById(tabname + '_interrupting').style.display = showInterrupting ? "block" : "none";
|
||||||
}
|
}
|
||||||
|
|
||||||
function showRestoreProgressButton(tabname, show){
|
function showSubmitButtons(tabname, show) {
|
||||||
var button = gradioApp().getElementById(tabname + "_restore_progress")
|
setSubmitButtonsVisibility(tabname, !show, !show, false);
|
||||||
if(! button) return
|
|
||||||
|
|
||||||
button.style.display = show ? "flex" : "none"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function submit(){
|
function showSubmitInterruptingPlaceholder(tabname) {
|
||||||
rememberGallerySelection('txt2img_gallery')
|
setSubmitButtonsVisibility(tabname, false, true, true);
|
||||||
showSubmitButtons('txt2img', false)
|
|
||||||
|
|
||||||
var id = randomId()
|
|
||||||
localStorage.setItem("txt2img_task_id", id);
|
|
||||||
|
|
||||||
requestProgress(id, gradioApp().getElementById('txt2img_gallery_container'), gradioApp().getElementById('txt2img_gallery'), function(){
|
|
||||||
showSubmitButtons('txt2img', true)
|
|
||||||
localStorage.removeItem("txt2img_task_id")
|
|
||||||
showRestoreProgressButton('txt2img', false)
|
|
||||||
})
|
|
||||||
|
|
||||||
var res = create_submit_args(arguments)
|
|
||||||
|
|
||||||
res[0] = id
|
|
||||||
|
|
||||||
return res
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function submit_img2img(){
|
function showRestoreProgressButton(tabname, show) {
|
||||||
rememberGallerySelection('img2img_gallery')
|
var button = gradioApp().getElementById(tabname + "_restore_progress");
|
||||||
showSubmitButtons('img2img', false)
|
if (!button) return;
|
||||||
|
button.style.setProperty('display', show ? 'flex' : 'none', 'important');
|
||||||
var id = randomId()
|
|
||||||
localStorage.setItem("img2img_task_id", id);
|
|
||||||
|
|
||||||
requestProgress(id, gradioApp().getElementById('img2img_gallery_container'), gradioApp().getElementById('img2img_gallery'), function(){
|
|
||||||
showSubmitButtons('img2img', true)
|
|
||||||
localStorage.removeItem("img2img_task_id")
|
|
||||||
showRestoreProgressButton('img2img', false)
|
|
||||||
})
|
|
||||||
|
|
||||||
var res = create_submit_args(arguments)
|
|
||||||
|
|
||||||
res[0] = id
|
|
||||||
res[1] = get_tab_index('mode_img2img')
|
|
||||||
|
|
||||||
return res
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function restoreProgressTxt2img(){
|
function submit() {
|
||||||
showRestoreProgressButton("txt2img", false)
|
showSubmitButtons('txt2img', false);
|
||||||
var id = localStorage.getItem("txt2img_task_id")
|
|
||||||
|
|
||||||
id = localStorage.getItem("txt2img_task_id")
|
var id = randomId();
|
||||||
|
localSet("txt2img_task_id", id);
|
||||||
|
|
||||||
if(id) {
|
requestProgress(id, gradioApp().getElementById('txt2img_gallery_container'), gradioApp().getElementById('txt2img_gallery'), function() {
|
||||||
requestProgress(id, gradioApp().getElementById('txt2img_gallery_container'), gradioApp().getElementById('txt2img_gallery'), function(){
|
showSubmitButtons('txt2img', true);
|
||||||
showSubmitButtons('txt2img', true)
|
localRemove("txt2img_task_id");
|
||||||
}, null, 0)
|
showRestoreProgressButton('txt2img', false);
|
||||||
|
});
|
||||||
|
|
||||||
|
var res = create_submit_args(arguments);
|
||||||
|
|
||||||
|
res[0] = id;
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
function submit_txt2img_upscale() {
|
||||||
|
var res = submit(...arguments);
|
||||||
|
|
||||||
|
res[2] = selected_gallery_index();
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
function submit_img2img() {
|
||||||
|
showSubmitButtons('img2img', false);
|
||||||
|
|
||||||
|
var id = randomId();
|
||||||
|
localSet("img2img_task_id", id);
|
||||||
|
|
||||||
|
requestProgress(id, gradioApp().getElementById('img2img_gallery_container'), gradioApp().getElementById('img2img_gallery'), function() {
|
||||||
|
showSubmitButtons('img2img', true);
|
||||||
|
localRemove("img2img_task_id");
|
||||||
|
showRestoreProgressButton('img2img', false);
|
||||||
|
});
|
||||||
|
|
||||||
|
var res = create_submit_args(arguments);
|
||||||
|
|
||||||
|
res[0] = id;
|
||||||
|
res[1] = get_tab_index('mode_img2img');
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
function submit_extras() {
|
||||||
|
showSubmitButtons('extras', false);
|
||||||
|
|
||||||
|
var id = randomId();
|
||||||
|
|
||||||
|
requestProgress(id, gradioApp().getElementById('extras_gallery_container'), gradioApp().getElementById('extras_gallery'), function() {
|
||||||
|
showSubmitButtons('extras', true);
|
||||||
|
});
|
||||||
|
|
||||||
|
var res = create_submit_args(arguments);
|
||||||
|
|
||||||
|
res[0] = id;
|
||||||
|
|
||||||
|
console.log(res);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
function restoreProgressTxt2img() {
|
||||||
|
showRestoreProgressButton("txt2img", false);
|
||||||
|
var id = localGet("txt2img_task_id");
|
||||||
|
|
||||||
|
if (id) {
|
||||||
|
showSubmitInterruptingPlaceholder('txt2img');
|
||||||
|
requestProgress(id, gradioApp().getElementById('txt2img_gallery_container'), gradioApp().getElementById('txt2img_gallery'), function() {
|
||||||
|
showSubmitButtons('txt2img', true);
|
||||||
|
}, null, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
return id
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
function restoreProgressImg2img(){
|
function restoreProgressImg2img() {
|
||||||
showRestoreProgressButton("img2img", false)
|
showRestoreProgressButton("img2img", false);
|
||||||
|
|
||||||
var id = localStorage.getItem("img2img_task_id")
|
|
||||||
|
|
||||||
if(id) {
|
var id = localGet("img2img_task_id");
|
||||||
requestProgress(id, gradioApp().getElementById('img2img_gallery_container'), gradioApp().getElementById('img2img_gallery'), function(){
|
|
||||||
showSubmitButtons('img2img', true)
|
if (id) {
|
||||||
}, null, 0)
|
showSubmitInterruptingPlaceholder('img2img');
|
||||||
|
requestProgress(id, gradioApp().getElementById('img2img_gallery_container'), gradioApp().getElementById('img2img_gallery'), function() {
|
||||||
|
showSubmitButtons('img2img', true);
|
||||||
|
}, null, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
return id
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
onUiLoaded(function () {
|
/**
|
||||||
showRestoreProgressButton('txt2img', localStorage.getItem("txt2img_task_id"))
|
* Configure the width and height elements on `tabname` to accept
|
||||||
showRestoreProgressButton('img2img', localStorage.getItem("img2img_task_id"))
|
* pasting of resolutions in the form of "width x height".
|
||||||
|
*/
|
||||||
|
function setupResolutionPasting(tabname) {
|
||||||
|
var width = gradioApp().querySelector(`#${tabname}_width input[type=number]`);
|
||||||
|
var height = gradioApp().querySelector(`#${tabname}_height input[type=number]`);
|
||||||
|
for (const el of [width, height]) {
|
||||||
|
el.addEventListener('paste', function(event) {
|
||||||
|
var pasteData = event.clipboardData.getData('text/plain');
|
||||||
|
var parsed = pasteData.match(/^\s*(\d+)\D+(\d+)\s*$/);
|
||||||
|
if (parsed) {
|
||||||
|
width.value = parsed[1];
|
||||||
|
height.value = parsed[2];
|
||||||
|
updateInput(width);
|
||||||
|
updateInput(height);
|
||||||
|
event.preventDefault();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onUiLoaded(function() {
|
||||||
|
showRestoreProgressButton('txt2img', localGet("txt2img_task_id"));
|
||||||
|
showRestoreProgressButton('img2img', localGet("img2img_task_id"));
|
||||||
|
setupResolutionPasting('txt2img');
|
||||||
|
setupResolutionPasting('img2img');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
function modelmerger(){
|
function modelmerger() {
|
||||||
var id = randomId()
|
var id = randomId();
|
||||||
requestProgress(id, gradioApp().getElementById('modelmerger_results_panel'), null, function(){})
|
requestProgress(id, gradioApp().getElementById('modelmerger_results_panel'), null, function() {});
|
||||||
|
|
||||||
var res = create_submit_args(arguments)
|
var res = create_submit_args(arguments);
|
||||||
res[0] = id
|
res[0] = id;
|
||||||
return res
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
function ask_for_style_name(_, prompt_text, negative_prompt_text) {
|
function ask_for_style_name(_, prompt_text, negative_prompt_text) {
|
||||||
var name_ = prompt('Style name:')
|
var name_ = prompt('Style name:');
|
||||||
return [name_, prompt_text, negative_prompt_text]
|
return [name_, prompt_text, negative_prompt_text];
|
||||||
}
|
}
|
||||||
|
|
||||||
function confirm_clear_prompt(prompt, negative_prompt) {
|
function confirm_clear_prompt(prompt, negative_prompt) {
|
||||||
if(confirm("Delete prompt?")) {
|
if (confirm("Delete prompt?")) {
|
||||||
prompt = ""
|
prompt = "";
|
||||||
negative_prompt = ""
|
negative_prompt = "";
|
||||||
}
|
}
|
||||||
|
|
||||||
return [prompt, negative_prompt]
|
return [prompt, negative_prompt];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
promptTokecountUpdateFuncs = {}
|
var opts = {};
|
||||||
|
onAfterUiUpdate(function() {
|
||||||
|
if (Object.keys(opts).length != 0) return;
|
||||||
|
|
||||||
function recalculatePromptTokens(name){
|
var json_elem = gradioApp().getElementById('settings_json');
|
||||||
if(promptTokecountUpdateFuncs[name]){
|
if (json_elem == null) return;
|
||||||
promptTokecountUpdateFuncs[name]()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function recalculate_prompts_txt2img(){
|
var textarea = json_elem.querySelector('textarea');
|
||||||
recalculatePromptTokens('txt2img_prompt')
|
var jsdata = textarea.value;
|
||||||
recalculatePromptTokens('txt2img_neg_prompt')
|
opts = JSON.parse(jsdata);
|
||||||
return args_to_array(arguments);
|
|
||||||
}
|
|
||||||
|
|
||||||
function recalculate_prompts_img2img(){
|
executeCallbacks(optionsAvailableCallbacks); /*global optionsAvailableCallbacks*/
|
||||||
recalculatePromptTokens('img2img_prompt')
|
executeCallbacks(optionsChangedCallbacks); /*global optionsChangedCallbacks*/
|
||||||
recalculatePromptTokens('img2img_neg_prompt')
|
|
||||||
return args_to_array(arguments);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
var opts = {}
|
|
||||||
onUiUpdate(function(){
|
|
||||||
if(Object.keys(opts).length != 0) return;
|
|
||||||
|
|
||||||
var json_elem = gradioApp().getElementById('settings_json')
|
|
||||||
if(json_elem == null) return;
|
|
||||||
|
|
||||||
var textarea = json_elem.querySelector('textarea')
|
|
||||||
var jsdata = textarea.value
|
|
||||||
opts = JSON.parse(jsdata)
|
|
||||||
executeCallbacks(optionsChangedCallbacks);
|
|
||||||
|
|
||||||
Object.defineProperty(textarea, 'value', {
|
Object.defineProperty(textarea, 'value', {
|
||||||
set: function(newValue) {
|
set: function(newValue) {
|
||||||
@ -308,7 +317,7 @@ onUiUpdate(function(){
|
|||||||
valueProp.set.call(textarea, newValue);
|
valueProp.set.call(textarea, newValue);
|
||||||
|
|
||||||
if (oldValue != newValue) {
|
if (oldValue != newValue) {
|
||||||
opts = JSON.parse(textarea.value)
|
opts = JSON.parse(textarea.value);
|
||||||
}
|
}
|
||||||
|
|
||||||
executeCallbacks(optionsChangedCallbacks);
|
executeCallbacks(optionsChangedCallbacks);
|
||||||
@ -319,123 +328,109 @@ onUiUpdate(function(){
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
json_elem.parentElement.style.display="none"
|
json_elem.parentElement.style.display = "none";
|
||||||
|
});
|
||||||
|
|
||||||
function registerTextarea(id, id_counter, id_button){
|
onOptionsChanged(function() {
|
||||||
var prompt = gradioApp().getElementById(id)
|
var elem = gradioApp().getElementById('sd_checkpoint_hash');
|
||||||
var counter = gradioApp().getElementById(id_counter)
|
var sd_checkpoint_hash = opts.sd_checkpoint_hash || "";
|
||||||
var textarea = gradioApp().querySelector("#" + id + " > label > textarea");
|
var shorthash = sd_checkpoint_hash.substring(0, 10);
|
||||||
|
|
||||||
if(counter.parentElement == prompt.parentElement){
|
if (elem && elem.textContent != shorthash) {
|
||||||
return
|
elem.textContent = shorthash;
|
||||||
}
|
elem.title = sd_checkpoint_hash;
|
||||||
|
elem.href = "https://google.com/search?q=" + sd_checkpoint_hash;
|
||||||
prompt.parentElement.insertBefore(counter, prompt)
|
|
||||||
prompt.parentElement.style.position = "relative"
|
|
||||||
|
|
||||||
promptTokecountUpdateFuncs[id] = function(){ update_token_counter(id_button); }
|
|
||||||
textarea.addEventListener("input", promptTokecountUpdateFuncs[id]);
|
|
||||||
}
|
}
|
||||||
|
});
|
||||||
registerTextarea('txt2img_prompt', 'txt2img_token_counter', 'txt2img_token_button')
|
|
||||||
registerTextarea('txt2img_neg_prompt', 'txt2img_negative_token_counter', 'txt2img_negative_token_button')
|
|
||||||
registerTextarea('img2img_prompt', 'img2img_token_counter', 'img2img_token_button')
|
|
||||||
registerTextarea('img2img_neg_prompt', 'img2img_negative_token_counter', 'img2img_negative_token_button')
|
|
||||||
|
|
||||||
var show_all_pages = gradioApp().getElementById('settings_show_all_pages')
|
|
||||||
var settings_tabs = gradioApp().querySelector('#settings div')
|
|
||||||
if(show_all_pages && settings_tabs){
|
|
||||||
settings_tabs.appendChild(show_all_pages)
|
|
||||||
show_all_pages.onclick = function(){
|
|
||||||
gradioApp().querySelectorAll('#settings > div').forEach(function(elem){
|
|
||||||
if(elem.id == "settings_tab_licenses")
|
|
||||||
return;
|
|
||||||
|
|
||||||
elem.style.display = "block";
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
onOptionsChanged(function(){
|
|
||||||
var elem = gradioApp().getElementById('sd_checkpoint_hash')
|
|
||||||
var sd_checkpoint_hash = opts.sd_checkpoint_hash || ""
|
|
||||||
var shorthash = sd_checkpoint_hash.substring(0,10)
|
|
||||||
|
|
||||||
if(elem && elem.textContent != shorthash){
|
|
||||||
elem.textContent = shorthash
|
|
||||||
elem.title = sd_checkpoint_hash
|
|
||||||
elem.href = "https://google.com/search?q=" + sd_checkpoint_hash
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
let txt2img_textarea, img2img_textarea = undefined;
|
let txt2img_textarea, img2img_textarea = undefined;
|
||||||
let wait_time = 800
|
|
||||||
let token_timeouts = {};
|
|
||||||
|
|
||||||
function update_txt2img_tokens(...args) {
|
function restart_reload() {
|
||||||
update_token_counter("txt2img_token_button")
|
document.body.style.backgroundColor = "var(--background-fill-primary)";
|
||||||
if (args.length == 2)
|
document.body.innerHTML = '<h1 style="font-family:monospace;margin-top:20%;color:lightgray;text-align:center;">Reloading...</h1>';
|
||||||
return args[0]
|
var requestPing = function() {
|
||||||
return args;
|
requestGet("./internal/ping", {}, function(data) {
|
||||||
}
|
|
||||||
|
|
||||||
function update_img2img_tokens(...args) {
|
|
||||||
update_token_counter("img2img_token_button")
|
|
||||||
if (args.length == 2)
|
|
||||||
return args[0]
|
|
||||||
return args;
|
|
||||||
}
|
|
||||||
|
|
||||||
function update_token_counter(button_id) {
|
|
||||||
if (token_timeouts[button_id])
|
|
||||||
clearTimeout(token_timeouts[button_id]);
|
|
||||||
token_timeouts[button_id] = setTimeout(() => gradioApp().getElementById(button_id)?.click(), wait_time);
|
|
||||||
}
|
|
||||||
|
|
||||||
function restart_reload(){
|
|
||||||
document.body.innerHTML='<h1 style="font-family:monospace;margin-top:20%;color:lightgray;text-align:center;">Reloading...</h1>';
|
|
||||||
|
|
||||||
var requestPing = function(){
|
|
||||||
requestGet("./internal/ping", {}, function(data){
|
|
||||||
location.reload();
|
location.reload();
|
||||||
}, function(){
|
}, function() {
|
||||||
setTimeout(requestPing, 500);
|
setTimeout(requestPing, 500);
|
||||||
})
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
setTimeout(requestPing, 2000);
|
setTimeout(requestPing, 2000);
|
||||||
|
|
||||||
return []
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Simulate an `input` DOM event for Gradio Textbox component. Needed after you edit its contents in javascript, otherwise your edits
|
// Simulate an `input` DOM event for Gradio Textbox component. Needed after you edit its contents in javascript, otherwise your edits
|
||||||
// will only visible on web page and not sent to python.
|
// will only visible on web page and not sent to python.
|
||||||
function updateInput(target){
|
function updateInput(target) {
|
||||||
let e = new Event("input", { bubbles: true })
|
let e = new Event("input", {bubbles: true});
|
||||||
Object.defineProperty(e, "target", {value: target})
|
Object.defineProperty(e, "target", {value: target});
|
||||||
target.dispatchEvent(e);
|
target.dispatchEvent(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
var desiredCheckpointName = null;
|
var desiredCheckpointName = null;
|
||||||
function selectCheckpoint(name){
|
function selectCheckpoint(name) {
|
||||||
desiredCheckpointName = name;
|
desiredCheckpointName = name;
|
||||||
gradioApp().getElementById('change_checkpoint').click()
|
gradioApp().getElementById('change_checkpoint').click();
|
||||||
}
|
}
|
||||||
|
|
||||||
function currentImg2imgSourceResolution(_, _, scaleBy){
|
function currentImg2imgSourceResolution(w, h, scaleBy) {
|
||||||
var img = gradioApp().querySelector('#mode_img2img > div[style="display: block;"] img')
|
var img = gradioApp().querySelector('#mode_img2img > div[style="display: block;"] img');
|
||||||
return img ? [img.naturalWidth, img.naturalHeight, scaleBy] : [0, 0, scaleBy]
|
return img ? [img.naturalWidth, img.naturalHeight, scaleBy] : [0, 0, scaleBy];
|
||||||
}
|
}
|
||||||
|
|
||||||
function updateImg2imgResizeToTextAfterChangingImage(){
|
function updateImg2imgResizeToTextAfterChangingImage() {
|
||||||
// At the time this is called from gradio, the image has no yet been replaced.
|
// At the time this is called from gradio, the image has no yet been replaced.
|
||||||
// There may be a better solution, but this is simple and straightforward so I'm going with it.
|
// There may be a better solution, but this is simple and straightforward so I'm going with it.
|
||||||
|
|
||||||
setTimeout(function() {
|
setTimeout(function() {
|
||||||
gradioApp().getElementById('img2img_update_resize_to').click()
|
gradioApp().getElementById('img2img_update_resize_to').click();
|
||||||
}, 500);
|
}, 500);
|
||||||
|
|
||||||
return []
|
return [];
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
function setRandomSeed(elem_id) {
|
||||||
|
var input = gradioApp().querySelector("#" + elem_id + " input");
|
||||||
|
if (!input) return [];
|
||||||
|
|
||||||
|
input.value = "-1";
|
||||||
|
updateInput(input);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
function switchWidthHeight(tabname) {
|
||||||
|
var width = gradioApp().querySelector("#" + tabname + "_width input[type=number]");
|
||||||
|
var height = gradioApp().querySelector("#" + tabname + "_height input[type=number]");
|
||||||
|
if (!width || !height) return [];
|
||||||
|
|
||||||
|
var tmp = width.value;
|
||||||
|
width.value = height.value;
|
||||||
|
height.value = tmp;
|
||||||
|
|
||||||
|
updateInput(width);
|
||||||
|
updateInput(height);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
var onEditTimers = {};
|
||||||
|
|
||||||
|
// calls func after afterMs milliseconds has passed since the input elem has been edited by user
|
||||||
|
function onEdit(editId, elem, afterMs, func) {
|
||||||
|
var edited = function() {
|
||||||
|
var existingTimer = onEditTimers[editId];
|
||||||
|
if (existingTimer) clearTimeout(existingTimer);
|
||||||
|
|
||||||
|
onEditTimers[editId] = setTimeout(func, afterMs);
|
||||||
|
};
|
||||||
|
|
||||||
|
elem.addEventListener("input", edited);
|
||||||
|
|
||||||
|
return edited;
|
||||||
}
|
}
|
||||||
|
@ -1,41 +1,62 @@
|
|||||||
// various hints and extra info for the settings tab
|
// various hints and extra info for the settings tab
|
||||||
|
|
||||||
onUiLoaded(function(){
|
var settingsHintsSetup = false;
|
||||||
createLink = function(elem_id, text, href){
|
|
||||||
var a = document.createElement('A')
|
onOptionsChanged(function() {
|
||||||
a.textContent = text
|
if (settingsHintsSetup) return;
|
||||||
a.target = '_blank';
|
settingsHintsSetup = true;
|
||||||
|
|
||||||
elem = gradioApp().querySelector('#'+elem_id)
|
gradioApp().querySelectorAll('#settings [id^=setting_]').forEach(function(div) {
|
||||||
elem.insertBefore(a, elem.querySelector('label'))
|
var name = div.id.substr(8);
|
||||||
|
var commentBefore = opts._comments_before[name];
|
||||||
return a
|
var commentAfter = opts._comments_after[name];
|
||||||
}
|
|
||||||
|
if (!commentBefore && !commentAfter) return;
|
||||||
createLink("setting_samples_filename_pattern", "[wiki] ").href = "https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Custom-Images-Filename-Name-and-Subdirectory"
|
|
||||||
createLink("setting_directories_filename_pattern", "[wiki] ").href = "https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Custom-Images-Filename-Name-and-Subdirectory"
|
var span = null;
|
||||||
|
if (div.classList.contains('gradio-checkbox')) span = div.querySelector('label span');
|
||||||
createLink("setting_quicksettings_list", "[info] ").addEventListener("click", function(event){
|
else if (div.classList.contains('gradio-checkboxgroup')) span = div.querySelector('span').firstChild;
|
||||||
requestGet("./internal/quicksettings-hint", {}, function(data){
|
else if (div.classList.contains('gradio-radio')) span = div.querySelector('span').firstChild;
|
||||||
var table = document.createElement('table')
|
else span = div.querySelector('label span').firstChild;
|
||||||
table.className = 'settings-value-table'
|
|
||||||
|
if (!span) return;
|
||||||
data.forEach(function(obj){
|
|
||||||
var tr = document.createElement('tr')
|
if (commentBefore) {
|
||||||
var td = document.createElement('td')
|
var comment = document.createElement('DIV');
|
||||||
td.textContent = obj.name
|
comment.className = 'settings-comment';
|
||||||
tr.appendChild(td)
|
comment.innerHTML = commentBefore;
|
||||||
|
span.parentElement.insertBefore(document.createTextNode('\xa0'), span);
|
||||||
var td = document.createElement('td')
|
span.parentElement.insertBefore(comment, span);
|
||||||
td.textContent = obj.label
|
span.parentElement.insertBefore(document.createTextNode('\xa0'), span);
|
||||||
tr.appendChild(td)
|
}
|
||||||
|
if (commentAfter) {
|
||||||
table.appendChild(tr)
|
comment = document.createElement('DIV');
|
||||||
})
|
comment.className = 'settings-comment';
|
||||||
|
comment.innerHTML = commentAfter;
|
||||||
popup(table);
|
span.parentElement.insertBefore(comment, span.nextSibling);
|
||||||
})
|
span.parentElement.insertBefore(document.createTextNode('\xa0'), span.nextSibling);
|
||||||
});
|
}
|
||||||
})
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function settingsHintsShowQuicksettings() {
|
||||||
|
requestGet("./internal/quicksettings-hint", {}, function(data) {
|
||||||
|
var table = document.createElement('table');
|
||||||
|
table.className = 'popup-table';
|
||||||
|
|
||||||
|
data.forEach(function(obj) {
|
||||||
|
var tr = document.createElement('tr');
|
||||||
|
var td = document.createElement('td');
|
||||||
|
td.textContent = obj.name;
|
||||||
|
tr.appendChild(td);
|
||||||
|
|
||||||
|
td = document.createElement('td');
|
||||||
|
td.textContent = obj.label;
|
||||||
|
tr.appendChild(td);
|
||||||
|
|
||||||
|
table.appendChild(tr);
|
||||||
|
});
|
||||||
|
|
||||||
|
popup(table);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user