Compare commits

..
858 Commits
Author SHA1 Message Date
Bepis 76a64d5c75 Add a pull request template 2022-10-10 23:12:29 +11:00
AUTOMATIC 5993df24a1 integrate the new samplers PR 2022-10-06 14:12:52 +03:00
C43H66N12O12S2 a971e4a767 update k-diff once again 2022-10-06 13:42:21 +03:00
C43H66N12O12S2 3ddf80a9db add variant setting 2022-10-06 13:42:21 +03:00
C43H66N12O12S2 71901b3d3b add karras scheduling variants 2022-10-06 13:42:21 +03:00
C43H66N12O12S2 c1a068ed0a Create alternate_sampler_noise_schedules.py 2022-10-06 13:42:21 +03:00
C43H66N12O12S2 c30c06db20 update k-diffusion 2022-10-06 13:42:21 +03:00
AUTOMATIC 2a53280495 reorder imports to fix the bug with k-diffusion on some version 2022-10-06 13:21:32 +03:00
AUTOMATIC 2d3ea42a2d workaround for a mysterious bug where prompt weights can't be matched 2022-10-06 13:21:12 +03:00
AUTOMATIC 5f24b7bcf4 option to let users select which samplers they want to hide 2022-10-06 12:08:59 +03:00
AUTOMATIC 6e7057b31b support for downloading new commit hash for git repos 2022-10-06 12:08:58 +03:00
Jocke a93c3ffbfd Outpainting mk2, prevent generation of a completely random image every time even when global seed is static 2022-10-06 11:23:47 +03:00
Raphael Stoeckli 4288e53fc2 removed unused import, fixed typo 2022-10-06 08:52:29 +03:00
Raphael Stoeckli 2499fb4e19 Add sanitizer for captions in Textual inversion 2022-10-06 08:52:29 +03:00
AUTOMATIC1111 0e92c36707 Merge pull request #1755 from AUTOMATIC1111/use-typing-list
use typing.list in prompt_parser.py for wider python version support
2022-10-06 08:50:06 +03:00
DepFA 55400c981b Set gradio-img2img-tool default to 'editor' 2022-10-06 08:46:32 +03:00
DepFA af02ee1297 Merge branch 'master' into use-typing-list 2022-10-05 23:02:45 +01:00
DepFA 34c358d10d use typing.list in prompt_parser.py for wider python version support 2022-10-05 22:11:30 +01:00
AUTOMATIC 20f8ec877a remove type annotations in new code because presumably they don't work in 3.7 2022-10-06 00:09:32 +03:00
AUTOMATIC f8e41a96bb fix various float parsing errors 2022-10-05 23:52:05 +03:00
AUTOMATIC c26732fbee added support for AND from https://energy-based-model.github.io/Compositional-Visual-Generation-with-Composable-Diffusion-Models/ 2022-10-05 23:16:27 +03:00
DepFA 67d011b02e Show generation progress in window title 2022-10-05 11:42:11 +03:00
DepFA bbdbbd36ed shared.state.interrupt when restart is requested 2022-10-05 11:37:18 +03:00
xpscyho ef40e4cd4d Display time taken in mins, secs when relevant
Fixes #1656
2022-10-04 23:41:42 +03:00
AUTOMATIC b32852ef03 add editor to img2img 2022-10-04 20:49:54 +03:00
Rae Fu 90e911fd54 prompt_parser: allow spaces in schedules, add test, log/ignore errors
Only build the parser once (at import time) instead of for each step.

doctest is run by simply executing modules/prompt_parser.py
2022-10-04 20:26:15 +03:00
AUTOMATIC 1eb588cbf1 remove functools.cache as some people are having issues with it 2022-10-04 18:02:01 +03:00
AUTOMATIC e1b128d8e4 do not touch p.seed/p.subseed during processing #1181 2022-10-04 17:36:39 +03:00
AUTOMATIC 957e29a8e9 option to not show images in web ui 2022-10-04 17:23:48 +03:00
AUTOMATIC 52cef36f6b emergency fix for img2img 2022-10-04 16:54:31 +03:00
AUTOMATIC1111 e6cbef785a Merge pull request #1550 from RnDMonkey/#1484_fix_empty_styles_pattern
#1484 fix empty styles pattern
2022-10-04 15:26:48 +03:00
Milly eec1b39bd5 Apply prompt pattern last 2022-10-04 15:22:49 +03:00
Justin Riddiough ea6b0d98a6 Remove pycharm note, fix typo 2022-10-04 15:21:34 +03:00
Justin Riddiough accd00d6b8 Explain how to use second progress bar in pycharm 2022-10-04 15:21:34 +03:00
AUTOMATIC1111 bc4d457de8 Merge pull request #1616 from brkirch/cpu-cmdline-opt
Add --use-cpu command line option
2022-10-04 15:20:10 +03:00
brkirch e9e2a7ec9a Merge branch 'master' into cpu-cmdline-opt 2022-10-04 07:42:53 -04:00
AUTOMATIC d5bba20a58 ignore errors in parse for purposes of token counting for #1564 2022-10-04 14:35:12 +03:00
AUTOMATIC b7f3996982 Merge remote-tracking branch 'origin/master' 2022-10-04 14:23:29 +03:00
AUTOMATIC 6165246124 support interrupting after the previous change 2022-10-04 14:23:22 +03:00
dan 2f1b61d979 Allow nested structures inside schedules 2022-10-04 14:22:41 +03:00
AUTOMATIC 6c6ae28bf5 send all three of GFPGAN's and codeformer's models to CPU memory instead of just one for #1283 2022-10-04 12:32:22 +03:00
brkirch dc9c5a9774 Modify --add-cpu description 2022-10-04 05:22:50 -04:00
brkirch 27ddc24fde Add BSRGAN to --add-cpu 2022-10-04 05:18:17 -04:00
brkirch 2adb249740 Merge branch 'cpu-cmdline-opt' of https://github.com/brkirch/stable-diffusion-webui into cpu-cmdline-opt 2022-10-04 04:26:54 -04:00
brkirch 35a00b0130 Merge branch 'AUTOMATIC1111:master' into cpu-cmdline-opt 2022-10-04 04:25:27 -04:00
brkirch eeab7aedf5 Add --use-cpu command line option
Remove MPS detection to use CPU for GFPGAN / CodeFormer and add a --use-cpu command line option.
2022-10-04 04:24:35 -04:00
AUTOMATIC 556c36b960 add hint, refactor code for #1607 2022-10-04 09:18:00 +03:00
DoTheSneedful 56371153b5 XY plot prompt order simplify logic 2022-10-04 08:56:01 +03:00
DoTheSneedful 1a6d40db35 Fix token ordering in prompt order XY plot 2022-10-04 08:56:01 +03:00
DoTheSneedful 1c5604791d Add a prompt order option to XY plot script 2022-10-04 08:56:01 +03:00
AUTOMATIC 5ef0baf5ea add support for gelbooru tags in filenames for textual inversion 2022-10-04 08:52:27 +03:00
brkirch b88e4ea7d6 Merge branch 'master' into master 2022-10-04 01:04:19 -04:00
AUTOMATIC 2865ef4b9a fix broken date in TI 2022-10-03 13:10:03 +03:00
AUTOMATIC 43a74fa595 batch processing for img2img with an empty output directory, by request 2022-10-03 11:48:19 +03:00
AUTOMATIC d15c125db7 Merge remote-tracking branch 'origin/master' 2022-10-03 08:54:06 +03:00
AUTOMATIC 6491b09c24 use existing function for gfpgan 2022-10-03 08:53:52 +03:00
RnDMonkey 80c418c0d3 Merge branch 'AUTOMATIC1111:master' into #1484_fix_empty_styles_pattern 2022-10-02 22:22:14 -07:00
RnDMonkey 36ea4ac0f5 moved no-style return outside join function 2022-10-02 22:21:16 -07:00
hentailord85ez 34c638142e Fixed when eta = 0
Unexpected behavior when using eta = 0 in something like XY, but your default eta was set to something not 0.
2022-10-03 08:20:19 +03:00
Hanusz Leszek e615d4f9d1 Convert folder icon surrogate pair to valid utf8 2022-10-03 07:59:13 +03:00
AUTOMATIC 2cd6a00f37 Merge remote-tracking branch 'origin/master' 2022-10-03 07:58:06 +03:00
AUTOMATIC 138662734c use dropdown instead of radio for img2img upscaler selection 2022-10-03 07:57:59 +03:00
AUTOMATIC1111 b2338ea48e Merge pull request #1490 from RnDMonkey/#1484_fix_empty_styles_pattern
#1484 fix empty styles pattern
2022-10-03 07:55:04 +03:00
AUTOMATIC1111 3fac3764b3 Merge branch 'master' into #1484_fix_empty_styles_pattern 2022-10-03 07:54:57 +03:00
AUTOMATIC 4c2eccf8e9 credit Rinon Gal 2022-10-02 23:22:48 +03:00
AUTOMATIC 166283653c remove LDSR warning 2022-10-02 23:18:13 +03:00
AUTOMATIC 6785331e22 keep textual inversion dataset latents in CPU memory to save a bit of VRAM 2022-10-02 22:59:01 +03:00
AUTOMATIC c7543d4940 preprocessing for textual inversion added 2022-10-02 22:41:21 +03:00
AUTOMATIC c4445225f7 change wording for options 2022-10-02 21:50:14 +03:00
Lopyter 91f327f22b make save to dirs optional for imgs saved from ui 2022-10-02 21:47:52 +03:00
Jocke 2ef69df9a7 Prevent upscaling when None is selected for SD upscale 2022-10-02 21:46:32 +03:00
AUTOMATIC c0389eb307 hello 2022-10-02 21:35:29 +03:00
AUTOMATIC1111 ad0503c1b5 Merge pull request #1454 from AUTOMATIC1111/1404-script-reload-without-restart
Gradio+custom script+js+css reload without model reloading
2022-10-02 21:33:32 +03:00
AUTOMATIC1111 688c4a914a Merge branch 'master' into 1404-script-reload-without-restart 2022-10-02 21:33:22 +03:00
DepFA a634c3226f correct indent 2022-10-02 19:26:38 +01:00
DepFA e808096cf6 correct indent 2022-10-02 19:26:06 +01:00
AUTOMATIC 852fd90c0d emergency fix for disabling SD model download after multiple complaints 2022-10-02 21:22:20 +03:00
AUTOMATIC 0a435f0988 Merge remote-tracking branch 'origin/master' 2022-10-02 21:21:10 +03:00
AUTOMATIC1111 0b94fc5033 Merge pull request #1324 from liamkerr/token_updates
Fixing Bugs with Token Counter
2022-10-02 21:20:05 +03:00
AUTOMATIC a1cde7e646 disabled SD model download after multiple complaints 2022-10-02 21:09:10 +03:00
d8ahazard 6365a41f59 Update esrgan_model.py
Use alternate ESRGAN Model download path.
2022-10-02 21:02:03 +03:00
AUTOMATIC 3ff0de2c59 added --disable-console-progressbars to disable progressbars in console
disabled printing prompts to console by default, enabled by --enable-console-prompts
2022-10-02 20:23:40 +03:00
AUTOMATIC 4ec4af6e0b add checkpoint info to saved embeddings 2022-10-02 20:15:25 +03:00
AUTOMATIC 71fe7fa49f fix using aaaa-100 embedding when the prompt has aaaa-10000 and you have both aaaa-100 and aaaa-10000 in the directory with embeddings. 2022-10-02 19:56:37 +03:00
AUTOMATIC 88ec0cf557 fix for incorrect embedding token length calculation (will break seeds that use embeddings, you're welcome!)
add option to input initialization text for embeddings
2022-10-02 19:40:51 +03:00
AUTOMATIC 53a3dc601f move CLIP out of requirements and into launcher to make it possible to launch the program offline 2022-10-02 18:21:56 +03:00
AUTOMATIC1111 6e063124ac Merge pull request #1403 from d8ahazard/ScuNET
Add ScuNET Denoiser/Upscaler, Fix some Model Loader issues
2022-10-02 17:39:34 +03:00
liamkerr a32a068ed1 Merge branch 'master' into token_updates 2022-10-02 10:26:20 -04:00
AUTOMATIC f34e2293d0 Merge remote-tracking branch 'origin/master' 2022-10-02 17:25:28 +03:00
AUTOMATIC 0758f6e641 fix --ckpt option breaking model selection 2022-10-02 17:24:50 +03:00
AUTOMATIC1111 1955ca62a8 Merge pull request #1214 from WDevelopsWebApps/saving
Save Button file and directory naming
2022-10-02 17:03:09 +03:00
AUTOMATIC1111 a9d7eb722f Merge branch 'master' into saving 2022-10-02 17:03:01 +03:00
liamkerr 7308aeefd9 Merge branch 'master' into token_updates 2022-10-02 10:02:38 -04:00
ClashSAN 4e72a1aab6 Grammar Fix 2022-10-02 16:00:16 +03:00
d8ahazard 5d26ba2b4b Merge branch 'master' into ScuNET 2022-10-02 07:56:22 -05:00
AUTOMATIC 5f561ee95d Merge remote-tracking branch 'origin/master' 2022-10-02 15:49:59 +03:00
AUTOMATIC 0114057ad6 fix incorrect use of glob in modelloader for #1410 2022-10-02 15:49:42 +03:00
AUTOMATIC1111 46588c582d Merge pull request #1459 from asimard1/master
Add progress bar for SwinIR upscale in cmd
2022-10-02 15:35:55 +03:00
AUTOMATIC 820f1dc96b initial support for training textual inversion 2022-10-02 15:03:39 +03:00
RnDMonkey 32edf1732f os.path.normpath wasn't working, reverting to manual strip 2022-10-01 21:37:14 -07:00
RnDMonkey 70f5267047 use os.path.normpath for better safety checking 2022-10-01 21:18:15 -07:00
RnDMonkey 3cf1a96006 added safety for blank directory naming patterns 2022-10-01 21:11:03 -07:00
DepFA 2deea86781 Put reload buttons in row and add secondary style 2022-10-02 01:36:30 +01:00
DepFA 07e40ad7f2 add custom script body only refresh option 2022-10-02 01:19:55 +01:00
DepFA cf33268d68 add script body only refresh 2022-10-02 01:18:42 +01:00
DepFA 0aa354bd5e remove styling from python side 2022-10-02 00:13:47 +01:00
DepFA 55b046312c move JavaScript into ui.js 2022-10-02 00:12:49 +01:00
DepFA 027c5aae55 update reloading message style 2022-10-01 23:29:26 +01:00
DepFA 6048002dad Add scope warning to refresh button 2022-10-01 23:10:07 +01:00
DepFA 30f2e35658 add importlib.reload 2022-10-01 22:50:03 +01:00
DepFA afaa03c5fd add redefinition guard to gradio_routes_templates_response 2022-10-01 22:43:45 +01:00
DepFA a9044475c0 add time import 2022-10-01 21:47:42 +01:00
Alexandre Simard b8a2b0453b Set launch options to default 2022-10-01 14:07:20 -04:00
Alexandre Simard b64a16d1e8 Merge branch 'master' of https://github.com/asimard1/stable-diffusion-webui 2022-10-01 14:05:22 -04:00
Alexandre Simard 121ed7d36f Add progress bar for SwinIR in cmd
I do not know how to add them to the UI...
2022-10-01 14:04:20 -04:00
DepFA 4f8490cd56 add restart button 2022-10-01 18:33:31 +01:00
DepFA 95f35d04ab Host busy thread, check for reload 2022-10-01 18:31:58 +01:00
DepFA 4c2478a68a add script reload method 2022-10-01 18:30:53 +01:00
DepFA 3f417566b0 Delete alternate_sampler_noise_schedules.py 2022-10-01 08:08:50 +03:00
DepFA bd4fc6633f add script alternate_sampler_noise_schedules 2022-10-01 08:08:50 +03:00
DepFA bc38c80cfc add sampler_noise_scheduler_override switch 2022-10-01 08:08:50 +03:00
DepFA 9de1e56e2d add sampler_noise_scheduler_override property 2022-10-01 08:08:50 +03:00
brkirch bdaa36c844 When device is MPS, use CPU for GFPGAN instead
GFPGAN will not work if the device is MPS, so default to CPU instead.
2022-09-30 23:53:25 -04:00
Liam 3c6a049fc3 consolidated token counter functions 2022-09-30 18:22:50 -04:00
Liam ff8dc1908a fixed token counter for prompt editing 2022-09-30 18:22:50 -04:00
Liam abdbf1de64 token counters now update when roll artist and style buttons are pressed https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/1194#issuecomment-1261203893 2022-09-30 18:22:40 -04:00
AUTOMATIC 84e97a98c5 features updates
unused code removed from outpainting mk2
2022-10-01 00:38:48 +03:00
AUTOMATIC 6b02966fcd fix #1405 submitting both tabs 2022-10-01 00:14:44 +03:00
AUTOMATIC1111 20f378a399 Merge pull request #1405 from tsngo/return-key-prompt-submit
ALT + return will submit prompt when it's in focus
2022-09-30 23:59:59 +03:00
Trung Ngo d1db330010 ALT + return will submit prompt when it's in focus 2022-09-30 15:39:57 -05:00
d8ahazard 8deae07700 Add ScuNET DeNoiser/Upscaler
Q&D Implementation of ScuNET, thanks to our handy model loader. :P

https://github.com/cszn/SCUNet
2022-09-30 15:28:37 -05:00
d8ahazard e82ea20299 Optimize model loader
Child classes only get populated to __subclassess__ when they are imported. We don't actually need to import any of them to webui any more, so clean up webUI imports and make sure loader imports children.

Also, fix command line paths not actually being passed to the scalers.
2022-09-30 15:26:18 -05:00
AUTOMATIC 89f0acc6bf remove extra print from BSRGAN 2022-09-30 23:18:47 +03:00
AUTOMATIC1111 f253790b40 Merge pull request #1371 from d8ahazard/master
Fix LDSR, BSRGAN, recursive SD checkpoint Loading
2022-09-30 23:09:18 +03:00
AUTOMATIC 3f64e23f81 fix model checkpoint merger tab failing to save model 2022-09-30 22:57:25 +03:00
d8ahazard a9a0320d26 Merge branch 'master' into master 2022-09-30 14:27:27 -05:00
AUTOMATIC 2b03f0bbda if --ckpt option is specified, load that model 2022-09-30 22:16:03 +03:00
d8ahazard 7ab91d9e1b Update bsrgan_model.py 2022-09-30 13:29:33 -05:00
d8ahazard 3665551b12 Merge branch 'master' of https://github.com/d8ahazard/stable-diffusion-webui 2022-09-30 12:51:57 -05:00
d8ahazard 8f1d412e7b Fix BSRGAN Model loading. 2022-09-30 12:51:54 -05:00
d8ahazard 2162be514a Merge branch 'master' into master 2022-09-30 11:33:41 -05:00
AUTOMATIC 3a876b16a9 Merge remote-tracking branch 'origin/master' 2022-09-30 18:56:23 +03:00
AUTOMATIC 4794202ebc hello #1109 2022-09-30 18:56:10 +03:00
AUTOMATIC ac21d308cd fix for one error with BSRGAN, though it fails to work anyway #1109 2022-09-30 18:55:46 +03:00
AUTOMATIC 43c87ef0fc change default inpaint mode to original 2022-09-30 18:07:49 +03:00
d8ahazard 9fc1e49bd2 Set default value for ckpt-dir 2022-09-30 09:38:57 -05:00
d8ahazard f71d02b85f Remove unused LDSR opt 2022-09-30 09:29:31 -05:00
d8ahazard 5d52231bcb Logging....
Cleanup. Sorry.
2022-09-30 09:28:48 -05:00
d8ahazard ca87c09c0e Fix recursive model loading
Ensure we find checkpoints within subdirectories.
2022-09-30 09:28:28 -05:00
d8ahazard 19eb1467f1 Fix BSRGAN variable not found. 2022-09-30 09:05:00 -05:00
d8ahazard 99aa132df7 Remove useless print message 2022-09-30 08:56:39 -05:00
d8ahazard 8d60645106 Fix model paths, ensure we have the right files.
Also, clean up logging in the ldsr arch file.
2022-09-30 08:55:04 -05:00
d8ahazard 64c6b13312 Remove LDSR project.yaml if too large.
If we accidentally downloaded the wrong file and saved it as project.yaml, this will delete it so it can be re-downloaded.
2022-09-30 08:41:25 -05:00
d8ahazard 41f9449d96 Fix LDSR YAML path 2022-09-30 08:33:06 -05:00
AUTOMATIC 980cd1697a prevent neural network resizing when it is not necessary #1109 2022-09-30 14:23:41 +03:00
AUTOMATIC 98cc6c6e74 add embeddings dir 2022-09-30 14:16:26 +03:00
RnDMonkey 5c0c778a65 fixed so that {prompt} can be anywhere in style 2022-09-30 13:00:43 +03:00
RnDMonkey ff4df06c57 refined [styles] pattern and added [prompt_no_styles] 2022-09-30 13:00:43 +03:00
Andrew Savchyn d18daafb8b Uppercase for env var LAUNCH_SCRIPT 2022-09-30 12:59:47 +03:00
Andrew Savchyn fcfe2e9ffd Configurable launch script 2022-09-30 12:59:47 +03:00
AUTOMATIC b197f398ec place the Put Stable Diffusion checkpoints here.txt in the right place 2022-09-30 12:57:30 +03:00
AUTOMATIC b60cd0809f return the dropdown that mysteriously disappeared 2022-09-30 12:56:36 +03:00
AUTOMATIC 9a54077d4d repair broken highres fix #1109 2022-09-30 12:26:41 +03:00
C43H66N12O12S2 828d6cce72 fix sd_upscale 2022-09-30 12:19:49 +03:00
AUTOMATIC cef838a6ab revert the annotation not supported by old pythons 2022-09-30 12:15:29 +03:00
AUTOMATIC 5b6d34f675 added contributing to readme 2022-09-30 11:57:19 +03:00
AUTOMATIC d1f098540a remove unwanted formatting/functionality from the PR 2022-09-30 11:42:40 +03:00
AUTOMATIC 2552204fcb fix for broken codeformer in PR 2022-09-30 11:03:00 +03:00
AUTOMATIC aec811c5e6 undo upscaler model filename tampering 2022-09-30 10:52:45 +03:00
AUTOMATIC a5e7b371d6 fix the bug with broken rescaling in PR 2022-09-30 10:38:48 +03:00
AUTOMATIC 8f1b315318 fix bugs in the PR 2022-09-30 09:46:52 +03:00
AUTOMATIC1111 25414bcd05 Merge pull request #1109 from d8ahazard/ModelLoader
Model Loader, Fixes
2022-09-30 09:35:58 +03:00
AUTOMATIC f80c3696f6 fix the sys not found error when importing sd_samplers that appeared after PR 2022-09-30 08:21:05 +03:00
AUTOMATIC f295d90971 add advertisement for custom scripts to readme 2022-09-30 08:18:05 +03:00
C43H66N12O12S2 28307a9f10 force usage of cloned k-diffusion 2022-09-30 07:57:39 +03:00
DepFA ebd2c48115 return shortest checkpoint title match 2022-09-30 07:37:05 +03:00
DepFA f710ba11b9 use closest match checkpoint method 2022-09-30 07:37:05 +03:00
DepFA 642b7e333e add get_closet_checkpoint_match 2022-09-30 07:37:05 +03:00
Mackerel 190fda38cb artists.csv: remove duplicated artists 2022-09-30 07:34:11 +03:00
d8ahazard 435fd2112a Fixes, cleanup. 2022-09-29 19:59:53 -05:00
d8ahazard d73741794d Merge remote-tracking branch 'upstream/master' into ModelLoader 2022-09-29 19:59:36 -05:00
d8ahazard 0dce0df1ee Holy $hit.
Yep.

Fix gfpgan_model_arch requirement(s).
Add Upscaler base class, move from images.
Add a lot of methods to Upscaler.
Re-work all the child upscalers to be proper classes.
Add BSRGAN scaler.
Add ldsr_model_arch class, removing the dependency for another repo that just uses regular latent-diffusion stuff.
Add one universal method that will always find and load new upscaler models without having to add new "setup_model" calls. Still need to add command line params, but that could probably be automated.
Add a "self.scale" property to all Upscalers so the scalers themselves can do "things" in response to the requested upscaling size.
Ensure LDSR doesn't get stuck in a longer loop of "upscale/downscale/upscale" as we try to reach the target upscale size.
Add typehints for IDE sanity.
PEP-8 improvements.
Moar.
2022-09-29 17:46:23 -05:00
Nick Renieris 498515e7a1 scripts/xy_grid: Handle edge-case with non-empty axis values
Fixes bug where if Type is Nothing and axis values are filled out (from ie. previously using another Type), it will still needlessly run it N times (with identical results).
2022-09-29 21:18:29 +03:00
Justin Maier a112168d28 Save parameters as comments when saving as jpg 2022-09-29 19:07:29 +03:00
Justin Maier ca5901b5c8 Save should use desired sample format fixes #1028 2022-09-29 19:07:29 +03:00
AUTOMATIC dc1ee79e96 added --exit for notebooks 2022-09-29 18:33:29 +03:00
AUTOMATIC 8a50371e4e fix version of gradio in requirements.txt because this is important and an older would work poorly. 2022-09-29 18:22:05 +03:00
AUTOMATIC c715ef04d1 fix for incorrect model weight loading for #814 2022-09-29 15:40:28 +03:00
C43H66N12O12S2 965dcf4469 improve code quality 2022-09-29 13:52:51 +03:00
C43H66N12O12S2 b6f80bdcc2 update k-diffusion 2022-09-29 13:52:51 +03:00
C43H66N12O12S2 b05355770c add new samplers 2022-09-29 13:52:51 +03:00
WDevelopsWebApps f28ce3e3a1 Merge branch 'master' into saving 2022-09-29 12:19:13 +02:00
Hanusz Leszek be5555fce4 drop the print 2022-09-29 12:48:42 +03:00
Hanusz Leszek e9919f2ab7 Sort scripts loading order 2022-09-29 12:48:42 +03:00
safentisAuth 66fed8ffb8 Add custom name and try-except 2022-09-29 12:41:47 +03:00
Michoko 819fd3af40 Add output folder icons
Changed the hidden element class name to a more generic one, so people can reuse it if they want to hide further elements in the future
2022-09-29 12:10:00 +03:00
Michoko 02c4b757b6 Add output folder icons
Handling of the --hide-ui-dir-config flag and added multi-platform code for opening a folder
2022-09-29 12:10:00 +03:00
Michoko f8acbb8f88 Add output folder icons
Adds icons on the first 3 tabs to directly open the corresponding images output directory
2022-09-29 12:10:00 +03:00
AUTOMATIC 4127f4aff8 fix program breaking on empty prompt 2022-09-29 11:39:55 +03:00
AUTOMATIC 2f2d356e4c call torch_gc before/after each gpu gradio operation 2022-09-29 11:32:12 +03:00
AUTOMATIC c1c27dad3b new implementation for attention/emphasis 2022-09-29 11:31:48 +03:00
AUTOMATIC 29ce8a687d remove unneded debug print 2022-09-29 08:03:23 +03:00
William Moorehouse 041d2aefc0 Respect --ckpt-dir command-line argument when merging models (#1261)
* Update .gitignore to ignore *all* checkpoint files in /models
* Fixed typo in UI
2022-09-29 01:00:48 +03:00
AUTOMATIC 7acfaca05a update lists of models after merging them in checkpoints tab
support saving as half
2022-09-29 00:59:44 +03:00
AUTOMATIC 0dc904aa3d Merge remote-tracking branch 'origin/master' 2022-09-29 00:31:46 +03:00
AUTOMATIC 791808c890 correctly list and display model names for #1261 2022-09-29 00:21:54 +03:00
AUTOMATIC1111 d944b84992 Merge pull request #1260 from uservar/master
Specify transformers version in requirements.txt
2022-09-29 00:06:51 +03:00
AUTOMATIC 43e273004b remove k-diffusion from requirements because we are not cloning the repo 2022-09-28 23:36:47 +03:00
uservar ed26121d4e Update requirements.txt 2022-09-28 20:17:31 +00:00
AUTOMATIC d62954c2bc fix broken DDIM with img2img 2022-09-28 22:30:52 +03:00
AUTOMATIC a703f56d73 clone k-diffusion instead of installing it via pip, and do not install its requirements.txt 2022-09-28 21:38:26 +03:00
AUTOMATIC1111 278e7c7114 Merge pull request #1194 from liamkerr/token_count
Token count
2022-09-28 19:22:55 +03:00
AUTOMATIC 1deac2b645 do nor add log messages to saved iamge parameters 2022-09-28 18:20:30 +03:00
AUTOMATIC d64b451681 added support for automatically installing latest k-diffusion
added eta parameter to parameters output for generated images
split eta settings into ancestral and ddim (because they have different default values)
2022-09-28 18:09:06 +03:00
AUTOMATIC 9be0d1b89e Merge remote-tracking branch 'origin/master' 2022-09-28 17:05:32 +03:00
AUTOMATIC aea5b2510e save parameters for images when using the Save button. 2022-09-28 17:05:23 +03:00
Liam 7ca9858c4c removed unused import; now using javascript to watch prompt textarea 2022-09-28 09:43:54 -04:00
AUTOMATIC1111 e22ea454a2 Merge pull request #1222 from bmaltais/inverse-sigmoid-interpolation
(feat): Checkpoint merge using Inverse sigmoid interpolation
2022-09-28 16:19:47 +03:00
Bernard Maltais 228a2f30e7 Remove unintended code commit for this PR 2022-09-28 08:56:07 -04:00
AUTOMATIC 5eb9d1aeac change the version of k-diffusion. It still won't be installed unless you are installing from scratch, though. 2022-09-28 15:53:01 +03:00
Bernard Maltais fe2f0e1729 Adding support for inverse sigmoid interpolation 2022-09-28 08:52:46 -04:00
Bernard Maltais c3bcc7e9fc Switch active checkpoint selection to dropdown
- Provides a better user experience
- Better suited to variable list of options
- Keep the UI "stable" as list contract or expand
2022-09-28 07:07:19 -04:00
WDevelopsWebApps 03ee67bfd3 add advanced saving for save button 2022-09-28 10:53:40 +02:00
AUTOMATIC 2ab64ec81a emergency fix for #1199 2022-09-28 10:49:07 +03:00
AUTOMATIC1111 15f333a266 Merge pull request #1185 from bmaltais/checkpoint-merger-ui-improvement
(feat): Rework Checkpoint Merger UI for better clarity and usability
2022-09-28 08:42:26 +03:00
AUTOMATIC1111 d4e36db6de Merge pull request #1199 from C43H66N12O12S2/k-eta
Add Eta parameter to K Ancestral samplers
2022-09-28 08:31:40 +03:00
Bernard Maltais 4c9c2a6702 -Fix interp_amount rounding in filename
-Sort list of checkpoints in list
2022-09-27 22:16:25 -04:00
C43H66N12O12S2 047ca73388 Update shared.py 2022-09-28 05:11:40 +03:00
C43H66N12O12S2 5391c0bf3e Update processing.py 2022-09-28 05:11:03 +03:00
C43H66N12O12S2 8644e494be add eta to k ancestral 2022-09-28 05:09:22 +03:00
Bernard Maltais 8c48ede135 Fix variable conversion code issue 2022-09-27 21:34:24 -04:00
Bernard Maltais d641af6a7d - Add gradio dropdown list to select checkpoints
- Update checkpoint model fields labels
2022-09-27 21:09:28 -04:00
Bernard Maltais 591c138e32 -Add gradio dropdown list to select checkpoints to merge
-Update the name of the model feilds
-Update the associated variable names
2022-09-27 21:08:07 -04:00
Liam e5707b66d6 switched the token counter to use hidden buttons instead of api call 2022-09-27 19:29:53 -04:00
Liam 981fe9c4a3 Merge remote-tracking branch 'upstream/master' into token_count 2022-09-27 16:37:24 -04:00
Liam 5034f7d759 added token counter next to txt2img and img2img prompts 2022-09-27 15:56:18 -04:00
Bernard Maltais e258f89080 Fix file name 2022-09-27 15:31:00 -04:00
Bernard Maltais 20b41b7be7 (feat): Rework Checkpoint Merger UI for better clarity
- Rename variables to better align with field input
- Improve merged checkpoint output file name
2022-09-27 15:21:25 -04:00
AUTOMATIC1111 f2a4a2c3a6 Merge pull request #1165 from baumandm/patch-1
Fix downssample typo in options
2022-09-27 20:57:28 +03:00
AUTOMATIC1111 a902cbff4f Merge pull request #1166 from bmaltais/model-merge-upd
Add interpolation method and weight to merged model output filename
2022-09-27 20:55:54 +03:00
AUTOMATIC1111 ca358c1451 Merge pull request #1170 from offshore/patch-1
Fix COMMANDINE_ARGS -> COMMANDLINE_ARGS
2022-09-27 20:54:50 +03:00
d8ahazard 31ad536c33 Remove debugging message 2022-09-27 11:05:25 -05:00
d8ahazard 5756d517a6 Merge remote-tracking branch 'upstream/master' into ModelLoader 2022-09-27 11:02:41 -05:00
d8ahazard 11875f5863 Use model loader with stable-diffusion too.
Hook the model loader into the SD_models file.
Add default url/download if checkpoint is not found.
Add matching stablediffusion-models-path argument.
Add message that --ckpt-dir will be removed in the future, but have it pipe to stablediffusion-models-path for now.
Update help strings for models-path args so they're more or less uniform.
Move sd_model "setup" call to webUI with the others.
Ensure "cleanup_models" method moves existing models to the new locations, including SD, and that we aren't deleting folders that still have stuff in them.
2022-09-27 11:01:13 -05:00
Alex Offshore b8bb14960a Fix variable name typo in error message for launch.py
COMMANDINE_ARGS -> COMMANDLINE_ARGS
2022-09-27 17:47:07 +03:00
Bernard Maltais 0bd8aa937f Add interpolation method and weight to output filename 2022-09-27 10:29:52 -04:00
Dave Bauman c055132606 Fix downssample typo in options
Updated `downssample` to `down-sample`, matching spelling in other places.
2022-09-27 09:50:06 -04:00
AUTOMATIC ada901ed66 added console outputs, more clear indication of progress, and ability to specify full filename to checkpoint merger
restore "Loading..." text
2022-09-27 10:44:00 +03:00
AUTOMATIC1111 a9dc307a21 Merge pull request #1066 from moorehousew/master
Add support for checkpoint merging
2022-09-27 09:59:37 +03:00
AUTOMATIC1111 dbe072dcff Merge pull request #1126 from AUTOMATIC1111/notification-sound
adds support for a notification.mp3 in the root directory that will play upon completion (fixes #1013)
2022-09-27 09:57:16 +03:00
DepFA adbd26a68f add missing s_tmax 2022-09-27 09:30:45 +03:00
DepFA 48d5796f0d pass eta to tex2img sampler 2022-09-27 09:30:45 +03:00
DepFA 76d6f7b407 Add DDIM Eta to txt2img in xy_grid 2022-09-27 09:30:45 +03:00
DepFA 61585e5778 rename DDIM eta label 2022-09-27 09:30:45 +03:00
DepFA fc2aa6b8f3 Add extra sampler params to xy_grid 2022-09-27 09:30:45 +03:00
DepFA a860839f1f take extra sampler properties from StableDiffusionProcessing 2022-09-27 09:30:45 +03:00
DepFA 4ea36a37d6 add sampler properties to StableDiffusionProcessing and Processed 2022-09-27 09:30:45 +03:00
DepFA 2ab3d593f9 pass extra KDiffusionSampler function parameters 2022-09-27 09:30:45 +03:00
DepFA 6b78833e33 Add extra kdiffusion parameters 2022-09-27 09:30:45 +03:00
DepFA ed5736139c pass ddim_eta and ddim_discretize 2022-09-27 09:30:45 +03:00
DepFA 619668ccfe Add options for exposed ddim sampler params
ddim_eta & ddim_discretize
2022-09-27 09:30:45 +03:00
DepFA 175baaaca2 xy_grid - Show blank cells when grid is incomplete 2022-09-27 09:06:44 +03:00
48DESIGN e4145c8453 Merge branch 'master' into notification-sound 2022-09-27 08:05:19 +02:00
Connum c0b1177a32 refactored image paste handling to fill unset images successively, then replace last existing image (fixes #981) 2022-09-27 08:59:40 +03:00
Daniel 8dcac9ac81 Grids saving to subdirectory when setting unchecked
Fixed grids saving to subdirectory when the setting is unchecked but "save images to subdirectory" was checked.
2022-09-27 08:58:47 +03:00
Martin Cairns 258a2d4f06 Add option to img2imgalt.py to use sigma adjustment instead of original method for #736 2022-09-27 08:53:35 +03:00
Alexandre Simard c74becca23 Solve issue #962
Fix by @MrAcademy
2022-09-27 08:52:43 +03:00
DepFA 16e7ac09df job_timestamp initialization change 2022-09-27 08:51:59 +03:00
Alexandre Simard 9e737cbadc Solve issue #962
Fix by @MrAcademy
2022-09-26 17:18:57 -04:00
Connum 2846ca5702 adds support for a notification.mp3 in the root directory that will play upon completion (fixes #1013) 2022-09-26 22:57:31 +02:00
d8ahazard f860f94c64 Cleanup gitignore, old files 2022-09-26 10:34:26 -05:00
d8ahazard 8604e469fd Update .gitignore 2022-09-26 10:30:39 -05:00
d8ahazard 7d5c29b674 Cleanup existing directories, fixes 2022-09-26 10:27:18 -05:00
William Moorehouse dc11748dea Added smoothstep interpolation to checkpoint merging 2022-09-26 10:50:21 -04:00
d8ahazard 740070ea9c Re-implement universal model loading 2022-09-26 09:29:50 -05:00
d8ahazard bfb7f15d46 Rename swinir -> swinir_model 2022-09-26 09:29:22 -05:00
d8ahazard bff8d0ce42 Fix swinir arch name 2022-09-26 09:27:50 -05:00
tateisu 78d6aef302 use strftime. update hints.js 2022-09-26 16:24:21 +03:00
tateisu b39f06cea7 add [datetime] to image file name pattern 2022-09-26 16:24:21 +03:00
DepFA e61da308ba Disable sentry logging 2022-09-26 16:19:47 +03:00
DepFA b8a8f749ef Update webui.bat 2022-09-26 16:19:47 +03:00
Liam db4ab47f09 copy over fields when sending to img2img: https://github.com/AUTOMATIC1111/stable-diffusion-webui/issues/1029 2022-09-26 08:33:02 +03:00
William Moorehouse 91643f651d Add support for checkpoint merging 2022-09-25 19:22:12 -04:00
AUTOMATIC ca3e5519e8 Merge remote-tracking branch 'origin/master' 2022-09-25 19:45:22 +03:00
AUTOMATIC ff107845b4 added hiding items to ui-config.json 2022-09-25 19:43:42 +03:00
Eyrie 1877a3767e Changed job_id to timestamp 2022-09-25 17:11:07 +03:00
Eyrie 4c3d4aad60 fix formatting 2022-09-25 17:11:07 +03:00
Eyrie e13912dfde fix formatting 2022-09-25 17:11:07 +03:00
Eyrie ba34b790d3 Added hints for file & dir patterns 2022-09-25 17:11:07 +03:00
Eyrie 40166dbf08 Added job_id pattern for directories 2022-09-25 17:11:07 +03:00
AUTOMATIC 073f6eac22 potential fix for embeddings no loading on AMD cards 2022-09-25 15:04:39 +03:00
DepFA 50ae19acf6 add custom script source to config path keys 2022-09-25 09:59:31 +03:00
DepFA 31a0fbf1ad add attribute to custom script controls 2022-09-25 09:59:31 +03:00
guaneec 615b2fc9ce Fix token max length 2022-09-25 09:30:02 +03:00
AUTOMATIC b8eae5de93 Merge remote-tracking branch 'origin/master' 2022-09-25 09:25:47 +03:00
AUTOMATIC 600cc0342d added support for setting hires fix from pasted prompts
added more robust detection of last line with parameters for pasted prompts
2022-09-25 09:25:28 +03:00
DepFA 72e2a96284 Correct indent 2022-09-25 08:46:09 +03:00
DepFA ab5a472556 Persist default Number values 2022-09-25 08:46:09 +03:00
DepFA ca13264609 Add attr to skip 2022-09-25 08:46:09 +03:00
DepFA b1320d79b5 Apply to all checkboxes and textboxes 2022-09-25 08:46:09 +03:00
DepFA 714dcda068 Add attributes to checkboxes for persisting 2022-09-25 08:46:09 +03:00
achaiah 5194a58278 removing duplicates
removing duplicated requirements (transformers, diffusers) and reorganizing alphabetically to be able to spot duplicates in the future.
2022-09-25 08:44:54 +03:00
AUTOMATIC 53be15c204 by popular request, moves width/height sliders higher 2022-09-25 08:40:29 +03:00
EyeDeck b5d705e263 Disable 'batch img2img' when launched with --hide-ui-dir-config
Prevent writing to arbitrary directories, as usual
2022-09-24 19:06:36 +03:00
RnDMonkey a2bea2f97a added [styles] filename pattern 2022-09-24 11:12:58 +03:00
AUTOMATIC 410bef0853 do not hide preview image too early 2022-09-24 09:16:54 +03:00
AUTOMATIC 31ac0baba0 Reformat some changes from the previous commit. 2022-09-24 08:23:01 +03:00
RnDMonkey ed8b8b3b8c Fix to XY_Grid script console progress bar and other progress bar improvements (#890)
Fix to XY_Grid script console progress bar and other progress bar improvements #890
2022-09-24 08:09:59 +03:00
jcianca 7aec029423 Update README.md 2022-09-24 07:58:30 +03:00
jcianca e94ec98102 Update README.md 2022-09-24 07:58:30 +03:00
jcianca db341bd0d8 Add files via upload 2022-09-24 07:58:30 +03:00
innovaciones 3e4b7fb869 Remove double loading message 2022-09-24 07:58:07 +03:00
Connum 910a3d9427 make callback queue handling reusable and implement onUiTabChange() 2022-09-24 07:44:05 +03:00
Jacob Tyndall 0f77e1852f Clear no longer needed VRAM during a 'highres fix' generation created during the first sampling before doing the second (img2img) sampling. Makes it possible to use the feature on an 8GB card. 2022-09-24 07:41:59 +03:00
AUTOMATIC 74f940e818 Merge remote-tracking branch 'origin/master' 2022-09-24 00:13:47 +03:00
AUTOMATIC 71cfb9ebac fix for settings sometimes not applying on javascript side 2022-09-24 00:13:32 +03:00
innovaciones b04a36be37 Tweak margin 2022-09-23 23:41:10 +03:00
innovaciones e1d49c5262 Fix border 2022-09-23 23:41:10 +03:00
innovaciones 6cd613811b Fix preview images position 2022-09-23 23:41:10 +03:00
DepFA e560eb8b60 Only switch between visible gallery entries
Since the other tabs are kept in the dom now filtering is needed.
2022-09-23 23:38:45 +03:00
AUTOMATIC e12793e937 delete unwanted console.log 2022-09-23 23:34:33 +03:00
AUTOMATIC c8c662901b fix for inpaint at full resolution breaking if you have an NN upscaler. 2022-09-23 23:29:53 +03:00
AUTOMATIC 39ce23f42d add the bitton to paste parameters into UI for txt2img, img2img, and pnginfo tabs
fixed some [send to..] buttons to work properly with all tabs
2022-09-23 22:49:21 +03:00
AUTOMATIC 9c92a1a9aa removed some information that its owner decided he did not want to share 2022-09-23 20:55:54 +03:00
AUTOMATIC 8ffc07b7b1 one change didn't make it into the previous commit 2022-09-23 20:54:17 +03:00
AUTOMATIC 0065327726 upgrade to gradio==3.4b3 t fixthe inpain bugs
rework progressbar/preview to work with new gradio
remove unnecessary create style button
added link to alternative colab
2022-09-23 20:46:02 +03:00
AUTOMATIC 1a0353675d Option to use advanced upscalers with normal img2img 2022-09-23 17:37:47 +03:00
AUTOMATIC 6fa20d51dc prevent saving settings with bogus values 2022-09-23 17:27:30 +03:00
AUTOMATIC1111 79e7c39298 Merge pull request #847 from rewbs/rewbs-optionally-save-before-color-correction
Add option to save before color correction. This helps with some posterisation issues in img2img loopback.
2022-09-23 14:41:06 +03:00
Seki 03faf20251 add extrastab send to inpaint 2022-09-23 14:19:33 +03:00
Seki 8708386609 add extrastab send to img2img 2022-09-23 14:19:33 +03:00
AUTOMATIC d4205e66fa gfpgan: just download the damn model 2022-09-23 10:26:00 +03:00
William Moorehouse d6fd71f36f Update .gitignore to ignore downloaded GFPGAN models 2022-09-23 09:23:16 +03:00
AUTOMATIC 7ef361dfc3 add warning for when user's settings are broken 2022-09-23 09:15:00 +03:00
AUTOMATIC c82e32652e prevent weird behavior when pressing interrupt just as image finishes 2022-09-23 08:48:19 +03:00
AUTOMATIC 02f58cde8d Merge remote-tracking branch 'origin/dfaker-patch-1' 2022-09-23 08:37:40 +03:00
AUTOMATIC 8e8d64199a Merge remote-tracking branch 'origin/dfaker-patch-2' 2022-09-23 08:37:32 +03:00
innovaciones 0ce9e05a42 Fix typo 2022-09-23 08:33:08 +03:00
innovaciones 6e86fc9fd0 Show interrupt button without progress bar 2022-09-23 08:33:08 +03:00
innovaciones ebf19c1145 Show interrupt button without progress bar 2022-09-23 08:33:08 +03:00
DepFA a2d084a07c Change default bug report template label to bug-report
for later confirmation or denial as an actual bug
2022-09-23 08:30:54 +03:00
DepFA 42b7902922 sort JavaScript includes to assure script sequence
Who knows what filesystem they're on
2022-09-23 08:30:32 +03:00
DepFA 08e27c3252 sort JavaScript includes to assure script sequence
Who knows what filesystem they're on
2022-09-23 03:05:42 +01:00
DepFA ea2426fa61 Change default bug report template label to bug-report
for later confirmation or denial as an actual bug
2022-09-23 02:19:00 +01:00
Robin Fernandes d26d89377b Remove unnecessary duplication 2022-09-23 00:57:42 +00:00
Robin Fernandes 03738668c0 Merge from master 2022-09-23 00:54:32 +00:00
C43H66N12O12S2 19fc3e8279 credit parlance-zz as they requested it 2022-09-23 01:42:55 +03:00
Connum e16b9dc819 resize mask canvases to fit underlying image (fixes #668) 2022-09-22 22:36:47 +03:00
AUTOMATIC 77cf346d93 settings categories split to columns, remade categories 2022-09-22 21:32:44 +03:00
AUTOMATIC 75b90a5e40 emergency fix for the settings screen breaking the program 2022-09-22 20:41:22 +03:00
DepFA 6d1c01c955 Add section splitting to settings ui 2022-09-22 20:26:21 +03:00
DepFA dec7584903 Add Section keys and headers to settings 2022-09-22 20:26:21 +03:00
Prof-Cheese ae32b8a53f Fixed directory name generation process.
'Max prompt words' has been added to config and modified to be used in the directory name generation process.
2022-09-22 20:15:37 +03:00
DepFA cae09e1651 Update selectors after ui and core overhaul 2022-09-22 19:29:20 +03:00
Johan Aires Rastén a213d3a21c Add option to always log generation info 2022-09-22 16:34:54 +03:00
Robin Fernandes 25eb1e3d90 Add option to save before color correction. Add suffix param when saving files, used for special saves without color correction and face restoration. 2022-09-22 20:54:50 +10:00
AUTOMATIC1111 34d5a31ea2 Merge pull request #834 from AUTOMATIC1111/dylancl-patch-2
Update README to link to wiki page for Apple Silicon installs
2022-09-22 13:45:25 +03:00
AUTOMATIC 3582befdcd move Notification.requestPermission() entirely to javascript to possibly fix problem with secure context people are having on non-localhost 2022-09-22 13:15:33 +03:00
Dylan Cathelijn 699aecd4ae Update README to link to wiki page for Apple Silicon installs 2022-09-22 11:35:12 +02:00
AUTOMATIC b0765a6788 remove labels from output gallery 2022-09-22 12:30:11 +03:00
AUTOMATIC 91bfc71261 A big rework, just what you were secretly hoping for!
SD upscale moved to scripts
Batch processing script removed
Batch processing added to main img2img and now works with scripts
img2img page UI reworked to use tabs
2022-09-22 12:11:48 +03:00
AUTOMATIC1111 e235d4e691 Merge pull request #824 from dfaker/patch-6
Aspect ratio overlay on img2img
2022-09-22 08:15:35 +03:00
AUTOMATIC1111 013e9a4bda Merge branch 'master' into patch-6 2022-09-22 08:15:22 +03:00
innovaciones aa1d1bf44e New position and interrupt integration 2022-09-22 08:12:10 +03:00
innovaciones c9ee98440b New position and interrupt integration 2022-09-22 08:12:10 +03:00
innovaciones 8af8fa2055 New position and interrupt integration 2022-09-22 08:12:10 +03:00
innovaciones 70e39f6cfe Use generate button as progress bar 2022-09-22 08:12:10 +03:00
innovaciones 12622105dc Use generate button as progress bar 2022-09-22 08:12:10 +03:00
innovaciones 057206cb73 Update progressbar.js 2022-09-22 08:12:10 +03:00
innovaciones b9aed0c692 Fix progress bar position 2022-09-22 08:12:10 +03:00
innovaciones f183e09fcc Fix progress bar position 2022-09-22 08:12:10 +03:00
AUTOMATIC 3eaae8ae65 reworking #775 2022-09-22 07:59:27 +03:00
AUTOMATIC 81c7961c25 revert transformers version change that prevents the program from starting. 2022-09-22 07:28:19 +03:00
d8ahazard c214c428bc Basic settings for realesrgan model selection.
I don't like that you have to restart the app, but it works.
2022-09-22 07:21:54 +03:00
d8ahazard 4f434c8aea Fix/Revert opts name from GAN to ESRGAN 2022-09-22 07:21:54 +03:00
d8ahazard 9a93a82b82 Cleanup Imports 2022-09-22 07:21:54 +03:00
d8ahazard 3cc68300cb Typo Fix 2022-09-22 07:21:54 +03:00
d8ahazard dd5566814a Add new models, fix shared opts issues
Add General x4x3, GeneralWDN x4x3, and AnimeVideo models from newer ESRGAN releases.

Fix issues caused by renaming ESRGAN_tille values to GAN_tile without using an IDE...
2022-09-22 07:21:54 +03:00
d8ahazard cc287d53a5 Bump Versions 2022-09-22 07:21:54 +03:00
ClashSAN ef744b96d6 Update README.md 2022-09-22 07:18:00 +03:00
ClashSAN ca22b820f4 Update README.md 2022-09-22 07:18:00 +03:00
ClashSAN 76c9d1a991 Update README.md 2022-09-22 07:18:00 +03:00
ClashSAN be3f080909 Update README.md
Added SwinIR and new features to readme
2022-09-22 07:18:00 +03:00
DepFA 2d271c0e62 Add aspect ratio overlay js 2022-09-22 01:51:49 +01:00
DepFA 4985d7cd04 Add aspect ratio overlay styles 2022-09-22 01:50:42 +01:00
d8ahazard 5a1951f175 Update launch.py 2022-09-21 16:50:30 +03:00
d8ahazard 1a1f7e85c7 Add LDSR and "GoLatent?" Upscaling (#763)
* Add LDSR Upscaling
2022-09-21 16:06:37 +03:00
benbot d6e8d85e30 removed TORCH_COMMAND section from webui.sh and
added correct torchvision version to default torch install command
2022-09-21 16:04:13 +03:00
AUTOMATIC 06186582ad prevent outpainting mk2 from breaking on different image resolutions. 2022-09-21 15:40:31 +03:00
AUTOMATIC 1ebb5cc669 update tiling button for imageviewer.js to use an icon in same style as others, add mouseover hints 2022-09-21 14:22:16 +03:00
Adam Snodgrass 390ead187c add button to toggle tiling images in the imageviewer modal 2022-09-21 14:09:25 +03:00
Dement242 5fb6f39607 Added CodeFormer to Credits
request from Shangchen Zhou
2022-09-21 13:35:35 +03:00
AUTOMATIC 75dd274dd6 prevent seed extras from having effect when extras checkbox is not checked 2022-09-21 13:34:10 +03:00
AUTOMATIC 45c46f4cb3 oops 2022-09-21 10:32:58 +03:00
AUTOMATIC a8ff013963 added --skip-torch-cuda-test to launcher for #746 2022-09-21 10:25:45 +03:00
AUTOMATIC 4b26b50df0 Merge remote-tracking branch 'origin/master' 2022-09-21 09:49:07 +03:00
AUTOMATIC 254da5d127 --opt-split-attention now on by default for torch.cuda, off for others (cpu and MPS; because the option does not work there according to reports) 2022-09-21 09:49:02 +03:00
Connum b5693699b8 Revert "Reset image input when dragover new image"
This reverts commit 9035afbab5.
2022-09-21 09:13:13 +03:00
Connum e9ba2d42d6 fix image replacement via clipboard paste or drag and drop on PNG Info tab 2022-09-21 09:13:13 +03:00
C43H66N12O12S2 29d6084f47 disallow no tiling as we don't support it 2022-09-21 09:09:39 +03:00
C43H66N12O12S2 a5313351b3 Update swinir.py 2022-09-21 09:09:39 +03:00
C43H66N12O12S2 403bb02948 breakout tile options 2022-09-21 09:09:39 +03:00
AUTOMATIC 6785fabefb Revert "fix for swininr PR breaking ESRGAN for new users"
This reverts commit 8d1d64f9a2.
2022-09-21 09:09:20 +03:00
AUTOMATIC 8d1d64f9a2 fix for swininr PR breaking ESRGAN for new users 2022-09-21 08:39:47 +03:00
AUTOMATIC 1578859305 fix for too large embeddings causing an error 2022-09-21 00:20:11 +03:00
C43H66N12O12S2 e452c961ed Create put_swinir_models_here.txt 2022-09-20 23:31:06 +03:00
C43H66N12O12S2 d8ed699839 Update swinir.py 2022-09-20 23:31:06 +03:00
C43H66N12O12S2 5f71ecfe6f Update webui.py 2022-09-20 23:31:06 +03:00
C43H66N12O12S2 55dc847c48 Update shared.py 2022-09-20 23:31:06 +03:00
C43H66N12O12S2 62ca23ac5b add swinir import 2022-09-20 23:31:06 +03:00
C43H66N12O12S2 ae8e21abdd hack 2022-09-20 23:31:06 +03:00
C43H66N12O12S2 efab42ff66 Rename swinir_arch.py to modules/swinir_arch.py 2022-09-20 23:31:06 +03:00
C43H66N12O12S2 948eff4b3c make swinir actually useful 2022-09-20 23:31:06 +03:00
C43H66N12O12S2 7267b7d2d9 extremely basic and incomplete swinir implementation 2022-09-20 23:31:06 +03:00
trufty 9035afbab5 Reset image input when dragover new image 2022-09-20 23:30:36 +03:00
AUTOMATIC 19a75d38d7 added --use-textbox-seed option to make long seeds possible from web ui 2022-09-20 20:10:01 +03:00
AUTOMATIC 06cd206107 Enable neural network upscalers for highres. fix 2022-09-20 19:32:26 +03:00
AUTOMATIC 2c9777fcc7 Merge remote-tracking branch 'origin/master' 2022-09-20 19:07:18 +03:00
AUTOMATIC b9674e2900 add extra generation params 2022-09-20 19:07:09 +03:00
Rahul Kolasseri c2775528c9 added __name__ == __main__ to launch.py so it can be imported without launching the webUI 2022-09-20 17:23:26 +03:00
orionaskatu f2ad00bc8e Remove default git variables to prevent issues 2022-09-20 17:23:01 +03:00
orionaskatu d0a12763fe Comment variables with default values 2022-09-20 17:23:01 +03:00
AUTOMATIC 90401d96a6 fix a off by one error with embedding at the start of the sentence 2022-09-20 12:12:31 +03:00
AUTOMATIC 54a097a818 Merge remote-tracking branch 'origin/master' 2022-09-20 09:53:37 +03:00
AUTOMATIC ab38392119 add the part that was missing for word textual inversion checksums 2022-09-20 09:53:29 +03:00
Dave Sescleifer d7f36dac21 Send a browser notification when the images are ready 2022-09-20 09:52:52 +03:00
Milly a8a75ec43a Fixed filename part sanitizing
The following file patterns are invalid on Windows.
- Begin or end with the ASCII Space (0x20)
- End with the ASCII Period (0x2E)

For example, if `[prompt_spaces]` is specified as the directory name pattern, sometimes file saving may fail.
2022-09-20 09:46:44 +03:00
olivier 06e076e48a Keep legacy behaviour wrt reuse of filename during batch processes 2022-09-20 07:44:19 +03:00
olivier 5fe2c75da0 Support reusing filename stems during batch processing in Extras tab 2022-09-20 07:44:19 +03:00
C43H66N12O12S2 53651696dc avoid exception if empty 2022-09-19 22:49:53 +03:00
C43H66N12O12S2 942acd4e12 Update README.md 2022-09-19 22:49:53 +03:00
C43H66N12O12S2 acbe44b835 automatically match any version gfpgan 2022-09-19 22:49:53 +03:00
trufty 6486ec9a56 Automatically show PNGinfo when uploading image 2022-09-19 22:49:05 +03:00
DepFA dd911a47b3 lightbox image scaling fix 2022-09-19 19:14:33 +03:00
AUTOMATIC 01c93a8400 use model's dtype for #707 2022-09-19 18:39:21 +03:00
C43H66N12O12S2 cf28445f10 fix cpu usage 2022-09-19 18:36:32 +03:00
AUTOMATIC 422d17487f [BUG] HighRes fix Feature Breaks Scripts #706 2022-09-19 18:23:51 +03:00
AUTOMATIC 5b6dea5698 do not show denoising strength when highres fix is not enabled 2022-09-19 17:41:46 +03:00
AUTOMATIC 028fc25f28 fix the issue with incorrect js options on page load
add a setting for lightbox max size images
use setting for lightbox max size images late to let user change it and see results
2022-09-19 17:16:04 +03:00
DepFA bf1f3b8daf Rely on opts being pre-populated 2022-09-19 16:43:08 +03:00
DepFA 86021511af bring modal z-index above progress bar 2022-09-19 16:43:08 +03:00
DepFA 931e5aebb3 initialize modal state from options 2022-09-19 16:43:08 +03:00
DepFA 2f35b1c6be Add logic for zoom toggle 2022-09-19 16:43:08 +03:00
DepFA 326236ed31 add styles for image zoom 2022-09-19 16:43:08 +03:00
AUTOMATIC 6d7ca54a1a added highres fix feature 2022-09-19 16:42:56 +03:00
AUTOMATIC 8a32a71ca3 Merge remote-tracking branch 'origin/master' 2022-09-19 09:02:22 +03:00
AUTOMATIC 7539f04e28 made 'reuse seed' button give you the seed/subseed of the currently selected picture rather than the first 2022-09-19 09:02:10 +03:00
EyeDeck 5a759687a2 Move memmon tooltip to hints.js
Move memmon tooltip to hints.js

so it's with the other tooltips, and doesn't have to be re-sent from the server every time.

Also, allowed tooltips to be applied by matching a class name if all else fails.
2022-09-19 07:29:22 +03:00
berkybear 1878994f9b fix grammer 2022-09-19 00:40:30 +03:00
berkybear 21244f50c4 fix some typos and remove unused import 2022-09-19 00:40:30 +03:00
AUTOMATIC 7ae3dc2866 display a more informative message when a checkpoint is not found 2022-09-18 23:52:01 +03:00
AUTOMATIC 2430fc20f1 fixed a bug with seed reproducibility with bacth_size>0 and bacth_count>0 2022-09-18 23:43:37 +03:00
AUTOMATIC cfb6cc8ce5 replace argparse.BooleanOptionalAction with 'store_true' 2022-09-18 23:06:49 +03:00
Connum f3965cce01 added command line argument --autolaunch to open the webui URL in the system's default browser upon launch (implements #274) 2022-09-18 22:39:34 +03:00
AUTOMATIC1111 8e3caace74 Merge pull request #672 from 48design/fix-inpaint-dragdrop-paste
replace existing image via paste or drop in inpaint mode (fixes #649)
2022-09-18 22:38:52 +03:00
AUTOMATIC f3d83fd68a add read access to settings for jsavascript
add an option to disable lightbox modal
2022-09-18 22:25:18 +03:00
Connum ce47976249 replace existing image via paste or drop in inpaint mode (fixes #649) 2022-09-18 20:00:51 +02:00
AUTOMATIC 21086e60a9 Merge remote-tracking branch 'origin/master' 2022-09-18 20:55:55 +03:00
AUTOMATIC cae5c5fa8d Making opt split attention the default. Are you upset about this? Sorry. 2022-09-18 20:55:46 +03:00
AUTOMATIC 6a28aac866 prevent black screen when seed and variation seed are the same. 2022-09-18 20:44:57 +03:00
AUTOMATIC1111 4380b6598c Merge pull request #664 from overra/escape-imageviewer
Close ImageViewer on escape
2022-09-18 20:40:27 +03:00
AUTOMATIC1111 c3be3d36c2 Merge pull request #667 from berkybear/fixSubSeedNoneTypeIssue
handle NoneType when subseed is not initialized
2022-09-18 20:39:49 +03:00
berkybear 4c17ce4949 handle NoneType when subseed is not initialized. Set it to -1 in that case 2022-09-18 09:57:50 -07:00
Adam Snodgrass 7e42a0f35a close on escape 2022-09-18 11:42:55 -05:00
AUTOMATIC c76a616bc9 fix many paths in code breaking because Processing constructor changed 2022-09-18 19:03:37 +03:00
AUTOMATIC ba97889137 fix tooltip not appearing for the shuffle button 2022-09-18 18:10:22 +03:00
AUTOMATIC1111 abd5cc6b2b Merge pull request #585 from JohanAR/ui_seed_changes
Polish seed UI options
2022-09-18 17:56:47 +03:00
AUTOMATIC1111 cf651a5e23 Merge pull request #658 from SafentisFox/fixLinuxLaunch
Fix webui.sh not working
2022-09-18 17:54:55 +03:00
AUTOMATIC1111 50c8d808c0 Merge pull request #660 from jamesmoore/master
.gitignore - Exclude checkpoint files in models folder
2022-09-18 17:52:11 +03:00
James Moore f0aa524ee1 Exclude checkpoint files in models 2022-09-18 15:20:46 +01:00
safentisFox 7b0f402b66 Fix bad bad torch command variable 2022-09-18 16:55:57 +03:00
AUTOMATIC e78c368eb3 prevent live previews from showing previous picture 2022-09-18 16:36:34 +03:00
Johan Aires Rastén a96076f49c Add buttons for random and reuse seed.
Random button sets seed to -1, reuse copies the seed from the last
generated image.
2022-09-18 15:13:28 +02:00
AUTOMATIC 7476593014 change () to "" in .sh scripts because export AAA=(BBB CCC) sets AAA to BBB and does not export anything
whoever put that in .sh files - shame on you
2022-09-18 15:07:14 +03:00
AUTOMATIC1111 9e892d90ce Merge pull request #651 from EyeDeck/master
Add some error handling for VRAM monitor
2022-09-18 14:35:04 +03:00
EyeDeck 46db1405df ...and make sure it can't get stuck on
in case someone sets opts.memmon_poll_rate to 0 during generation
2022-09-18 07:03:17 -04:00
AUTOMATIC1111 83a65919bb Merge pull request #648 from 48design/fix-img2img-paste
fix pasting of images from the clipboard in img2img (fixes #645)
2022-09-18 12:54:57 +03:00
Connum 3b56b54557 fix pasting of images from the clipboard in img2img (fixes #645) 2022-09-18 11:42:05 +02:00
EyeDeck fabaf4bddb Add some error handling for VRAM monitor 2022-09-18 05:20:33 -04:00
AUTOMATIC 3f29aa791b altered progressbar to not rely on first progress request coming after the job has started; may help with broken progressbar some people say they have 2022-09-18 11:14:42 +03:00
AUTOMATIC b273458d2d make inpaint at full resolution option not discard useful pixels from the image
split masking helper function from processing.py into new masking.py
2022-09-18 10:49:00 +03:00
AUTOMATIC 7e77938230 Merge remote-tracking branch 'origin/master' 2022-09-18 09:09:34 +03:00
AUTOMATIC 9f9a2084c7 add info about where to get models to instructions. 2022-09-18 09:09:10 +03:00
AUTOMATIC1111 c89b1a6f3d Merge pull request #643 from melchiar/master
fixed typos in processing.py
2022-09-18 09:00:23 +03:00
AUTOMATIC 5e80c286ee script.js split work - ui.js 2022-09-18 09:00:06 +03:00
Andrey ce799a63e9 Split history script.js to javascript/ui.js 2022-09-18 08:51:47 +03:00
Andrey f7d48b94a8 Split history script.js to javascript/ui.js 2022-09-18 08:51:47 +03:00
Andrey 1f851193b9 Split history script.js to javascript/ui.js 2022-09-18 08:51:47 +03:00
Andrey b0c9a097f2 Split history script.js to javascript/ui.js 2022-09-18 08:51:47 +03:00
AUTOMATIC ae63d82741 script.js split work - progress.js 2022-09-18 08:51:11 +03:00
Andrey 3b9ad0b235 Split history script.js to javascript/progressbar.js 2022-09-18 08:48:47 +03:00
Andrey efc11f2b9f Split history script.js to javascript/progressbar.js 2022-09-18 08:48:47 +03:00
Andrey bab13135ac Split history script.js to javascript/progressbar.js 2022-09-18 08:48:47 +03:00
Andrey 8b734949ba Split history script.js to javascript/progressbar.js 2022-09-18 08:48:47 +03:00
AUTOMATIC 26b52fd1ec script.js split work - hints.js 2022-09-18 08:48:13 +03:00
Andrey 3641a91bc2 Split history script.js to javascript/hints.js 2022-09-18 08:41:23 +03:00
Andrey 8207628603 Split history script.js to javascript/hints.js 2022-09-18 08:41:23 +03:00
Andrey bd219076db Split history script.js to javascript/hints.js 2022-09-18 08:41:23 +03:00
Andrey 85abd7c175 Split history script.js to javascript/hints.js 2022-09-18 08:41:23 +03:00
AUTOMATIC 74c538e84f script.js split work - dragdrop.js 2022-09-18 08:41:08 +03:00
Andrey 27b9b233f2 Split history script.js to javascript/dragdrop.js 2022-09-18 08:37:57 +03:00
Andrey d12426976a Split history script.js to javascript/dragdrop.js 2022-09-18 08:37:57 +03:00
Andrey 759dda9a7e Split history script.js to javascript/dragdrop.js 2022-09-18 08:37:57 +03:00
Andrey 7a0bcd3893 Split history script.js to javascript/dragdrop.js 2022-09-18 08:37:57 +03:00
AUTOMATIC be0bfa871b script.js split work 2022-09-18 08:37:26 +03:00
AUTOMATIC a86c279419 script.js split work 2022-09-18 08:37:03 +03:00
Steve Eberhardt f39b2ca088 fixed typos in processing.py 2022-09-17 22:09:52 -07:00
Andrey 3f91de3c91 Split history script.js to javascript/dragdrop.js 2022-09-18 07:55:08 +03:00
Andrey 4095150d37 Split history script.js to javascript/dragdrop.js 2022-09-18 07:55:08 +03:00
Andrey ca8451ece0 Split history script.js to javascript/dragdrop.js 2022-09-18 07:55:08 +03:00
Andrey 4133472a6e Split history script.js to javascript/dragdrop.js 2022-09-18 07:55:07 +03:00
AUTOMATIC1111 1e18d23738 Merge pull request #628 from 48design/drop-paste-replace-existing-image
Replace existing images when pasting from clipboard or dropping a new one (fixes #573)
2022-09-18 07:44:35 +03:00
AUTOMATIC1111 e9a9764e00 Merge pull request #625 from bdrupieski/fix-batch-processing-color-correction
fix batch color correction
2022-09-18 07:31:01 +03:00
AUTOMATIC1111 c57ae054e9 Merge pull request #634 from Dement242/Dement242-patch-1
Fixed "CodeFormer visibility:" rounding to 2 decimals.
2022-09-18 07:30:05 +03:00
AUTOMATIC1111 17b60490fa Merge pull request #635 from C43H66N12O12S2/attention
Move scale multiplication to the front
2022-09-18 07:28:53 +03:00
C43H66N12O12S2 18d6fe4346 ..... 2022-09-18 01:21:50 +03:00
Brian Drupieski 2dbc9c5903 only set loopback color corrections if corrections enabled 2022-09-17 18:20:43 -04:00
Brian Drupieski cf70528bce remove whitespace 2022-09-17 18:19:21 -04:00
Brian Drupieski 7bc5739fe2 set loopback color corrections on each iteration 2022-09-17 18:18:30 -04:00
C43H66N12O12S2 d63dbb3acc Move scale multiplication to the front 2022-09-18 01:05:31 +03:00
Dement242 3a050d19c6 Merge branch 'AUTOMATIC1111:master' into Dement242-patch-1 2022-09-17 23:18:56 +02:00
AUTOMATIC1111 8ff6f09320 Merge pull request #587 from JashoBell/Base
Basic documentation for custom_code.py template
2022-09-17 23:45:10 +03:00
JashoBell 98a6644bcf Move comments to scripts.py 2022-09-17 12:43:57 -07:00
Connum 88e315a8d5 Replace existing images when pasting from clipboard or dropping a new one (fixes #573) 2022-09-17 21:09:47 +02:00
Dement242 33434fc6fc Fixed "CodeFormer visibility:" rounding to 2 decimals. 2022-09-17 21:02:46 +02:00
JashoBell d2c7ad2fec Merge branch 'master' of https://github.com/AUTOMATIC1111/stable-diffusion-webui into Base 2022-09-17 11:16:35 -07:00
Brian Drupieski 663af7c1c8 fix batch color correction 2022-09-17 13:57:01 -04:00
AUTOMATIC1111 23a0ec04c0 Merge pull request #616 from dfaker/patch-3
Block event propagation when lightbox is triggered
2022-09-17 20:30:25 +03:00
AUTOMATIC1111 1dd721d136 Merge pull request #618 from EyeDeck/master
Fix gallery not scrolling left
2022-09-17 20:29:40 +03:00
AUTOMATIC1111 933949f39c Merge pull request #621 from SafentisFox/responsiveCss
Make image gallery bigger on 2k+ displays
2022-09-17 20:28:44 +03:00
DepFA f9cae046cb typo 2022-09-17 18:03:52 +01:00
DepFA 0e5527b4df Add previous and next to modal with key shortcuts 2022-09-17 17:58:33 +01:00
DepFA fb668c58ef add previous and next styles 2022-09-17 17:56:53 +01:00
safentisAuth 0469972e91 Make gallery bigger on 2k+ displays 2022-09-17 19:27:08 +03:00
EyeDeck e24c3b79f6 Fix gallery not scrolling left 2022-09-17 11:58:46 -04:00
DepFA f96d8a601c Block event propagation when lightbox is triggered 2022-09-17 15:29:06 +01:00
AUTOMATIC 56ff118845 typo 2022-09-17 16:35:58 +03:00
AUTOMATIC 8d197b6a92 added user.css support 2022-09-17 16:28:19 +03:00
AUTOMATIC 77dcb21688 Merge remote-tracking branch 'origin/master' 2022-09-17 15:39:30 +03:00
AUTOMATIC 2f18823e69 fix for broken export for 4chan 2022-09-17 15:39:20 +03:00
AUTOMATIC1111 d94b41472e Merge pull request #586 from jjisnow/image_info_tab
image info tab
2022-09-17 14:57:30 +03:00
AUTOMATIC1111 0d7fdb1791 Merge branch 'master' into image_info_tab 2022-09-17 14:57:10 +03:00
DepFA 1ef79f926e generalise to work on all non-masked images on all tabs 2022-09-17 14:56:11 +03:00
DepFA a66d857345 make background semi-transparent not black; 2022-09-17 14:56:11 +03:00
DepFA 1a51337077 Add modal creation and functions 2022-09-17 14:56:11 +03:00
DepFA 65be5312dc Add modal css classes 2022-09-17 14:56:11 +03:00
Tony Beeman ba295b3268 * Fix process_images where the number of images is not a multiple of (batch_size * n_iter), which would cause us to throw an exception.
* Add a textbox option to Prompts from file (ease of use and it makes it much easier to use on a mobile device)
* Fix the fact that Prompts from file was sometimes passing an empty batch.
2022-09-17 14:55:54 +03:00
AUTOMATIC 140f893153 process all values for x/y plot right away to error out if any are bad before any processing begins 2022-09-17 14:55:40 +03:00
AUTOMATIC 304222ef94 X/Y plot support for switching checkpoints. 2022-09-17 13:49:36 +03:00
AUTOMATIC 99585b3514 moved progressbar to top by request 2022-09-17 12:38:15 +03:00
AUTOMATIC f8f17e3b9e updated readme to reflect new model location 2022-09-17 12:12:55 +03:00
AUTOMATIC 247f58a5e7 add support for switching model checkpoints at runtime 2022-09-17 12:05:18 +03:00
AUTOMATIC b8be33dad1 hide VRAM text if polling is disabled 2022-09-17 09:23:31 +03:00
EyeDeck ed6787ca2f Add VRAM monitoring 2022-09-17 09:15:16 +03:00
jjisnow ac61e4663c Update webui.py 2022-09-17 16:10:46 +10:00
jjisnow b172cd56e8 Update webui.py 2022-09-17 16:09:53 +10:00
jjisnow 588d6de4a8 Update ui.py
Reverse run_pnginfo for compatibility reasons
2022-09-17 16:08:56 +10:00
jjisnow 047a623f7a Restore run_pnginfo 2022-09-17 16:07:07 +10:00
AUTOMATIC 1fc1c537c7 fix 2022-09-17 09:01:10 +03:00
AUTOMATIC 3c665b8dd6 the last PR broke saving EXiF completely for me. I don't know if it was broken already or some condition changed, but it seems like the person who originally added EXIF said, saving it with PIL may not work. I switched to using piexif to add data after the file written. 2022-09-17 08:35:52 +03:00
JJ 4f1f348b6a image.save parameter fix
* image.save takes exif as a parameter
* piexif takes the bytes as a parameter, not the exif_bytes function itself
* reduce calls to create_exif_bytes
2022-09-17 08:06:50 +03:00
AUTOMATIC c441ba065c add a comment and some checks for the functionality of the last PR 2022-09-17 08:03:47 +03:00
uservar 6168d09218 Prevent uploading previous output from javascript
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.
2022-09-17 07:54:03 +03:00
JashoBell 5a797a5612 Basic explanation for custom_code.py template 2022-09-16 14:06:21 -07:00
JJ de5bfdf917 image info tab
* handles exceptions if jpeg jfif data not present
* removes further non-comment related exif data.
2022-09-17 06:58:35 +10:00
AUTOMATIC 449719b2fc added Noise generation for outpainting mk2 to credits 2022-09-16 23:17:10 +03:00
AUTOMATIC 2ee9fc8eb8 new outpainting script 2022-09-16 22:18:30 +03:00
AUTOMATIC b64994b973 added original negative prompt to img2img alt 2022-09-16 19:24:48 +03:00
AUTOMATIC e49b1c5d73 an option to do exactly the amount of specified steps in img2img 2022-09-16 13:38:02 +03:00
AUTOMATIC be0f82df12 Merge remote-tracking branch 'origin/master' 2022-09-16 12:43:37 +03:00
AUTOMATIC 2288bc96fd fix extras tab showing original images instead of upscales 2022-09-16 12:43:24 +03:00
AUTOMATIC d8b427f8aa remove the warning at startup related to previous PR with batch processing 2022-09-16 10:21:59 +03:00
Elias Sundqvist a441cd563a Reduce code duplication 2022-09-16 10:19:13 +03:00
Elias Sundqvist 2aec11d263 Add randomness and denoising strength support to alternative img2img 2022-09-16 10:19:13 +03:00
AUTOMATIC b8cf2ea8ea add a bit of a comment about what's being done with tensor noise 2022-09-16 10:04:07 +03:00
AUTOMATIC 83bce1a604 Merge branch 'batch-seed-attempt' 2022-09-16 09:48:46 +03:00
AUTOMATIC 87e8b9a2ab prevent replacing torch_randn globally (instead replacing k_diffusion.sampling.torch) and add a setting to disable this all 2022-09-16 09:47:03 +03:00
AUTOMATIC b44ddcb443 Prompt editing only applies to images in first batch of desired batch size when batch count > 1 #535 2022-09-16 08:51:21 +03:00
AUTOMATIC b153ebe3b6 fix loopback color correction to store color_correction info for initial image and use that instead of extracting from previous image in a loop #481 #541 2022-09-16 08:33:47 +03:00
ArrowM 3763837003 Add batch processing to Extras tab 2022-09-16 07:42:48 +03:00
Twizzes deea9f4d70 Replace invalid filename chars with an underscore
... instead of removing them altogether.
This makes the prompt editing filenames [old:new:step] easier to read
2022-09-16 07:25:58 +03:00
AUTOMATIC 7fe00d0840 [Bug] Alternative img2img error #508 2022-09-15 22:39:46 +03:00
AUTOMATIC 6452fa2fb7 Merge remote-tracking branch 'origin/master' 2022-09-15 22:31:18 +03:00
AUTOMATIC 6991f2cb27 SD upscale with Batch count>1 results broken images #512 2022-09-15 22:31:06 +03:00
OWKenobi 2ddaeb318a Update scripts.py
fixes bug #464, which happens when controls is None, which leads to args_to being None.
2022-09-15 21:08:45 +03:00
Rickey Bowers Jr 874651e4d2 match one based numbering or other batches 2022-09-15 18:56:52 +03:00
AUTOMATIC 0fde1f3eac oh hey i broke batches with this 2022-09-15 18:05:42 +03:00
AUTOMATIC cde49dcbe6 add prompt editing to readme 2022-09-15 15:54:11 +03:00
AUTOMATIC dc769e097c Merge branch 'prompt_editing' 2022-09-15 15:39:30 +03:00
AUTOMATIC d4dc4c1c63 fix for Error Interrogating when user has garbage in text files #479 2022-09-15 15:13:06 +03:00
AUTOMATIC d7f7378828 quantization off by default 2022-09-15 14:55:38 +03:00
C43H66N12O12S2 81baaff9b3 Respect quantization setting 2022-09-15 14:54:52 +03:00
C43H66N12O12S2 829d7150bc Add setting for quantization 2022-09-15 14:54:52 +03:00
C43H66N12O12S2 3c37c68fe0 Construct CompVisDenoiser with quantization 2022-09-15 14:54:52 +03:00
AUTOMATIC cdaab233c4 Merge remote-tracking branch 'origin/master' 2022-09-15 14:54:33 +03:00
AUTOMATIC 6d2eb339d6 fix for failing to save 4chan downscale for large iamges 2022-09-15 14:54:29 +03:00
Chris Oelerich 56b0b0feb5 Comment out empty envars in user config.
Setting empty envars causes the `os.environ.get('ENVAR', "some default")` pattern in launch.py to ignore it's fallback value.
2022-09-15 14:53:26 +03:00
JJ 9611008445 exif fix for webp
* fix for odd error only in webp files whereby piexif.insert inserts the bytes correctly, but image.save inserts extra "Exif" in the image metadata which results in an error on reading
2022-09-15 14:53:06 +03:00
Mavpt 4448ffa52f Rewrote a large portion of the README to point towards the wiki. 2022-09-15 14:17:22 +03:00
C43H66N12O12S2 72d7f8c761 fix typo 2022-09-15 14:14:27 +03:00
C43H66N12O12S2 7ec6282ec2 pass dtype to torch.zeros as well 2022-09-15 14:14:27 +03:00
AUTOMATIC f2693bec08 prompt editing 2022-09-15 13:10:16 +03:00
AUTOMATIC b28cf84c36 prevent repeating messages about too many tokens 2022-09-15 08:57:03 +03:00
EyeDeck dfb2e830d9 Improved directory sanitization when --hide_ui_dir_config
Fixes an issue where it's still possible to write to arbitrary directories through careful use of \.. or /.. in directory patterns

...and fix the regex to work better

reeeegex
2022-09-15 07:39:57 +03:00
Steve Eberhardt 4a626f6ea6 Corrected typos in shared.py and README 2022-09-15 07:38:17 +03:00
AUTOMATIC 6a4db7b9a5 Add info about AMD to readme. 2022-09-14 20:37:56 +03:00
AUTOMATIC d51847c184 fix caching for img2imgalt 2022-09-14 19:41:55 +03:00
AUTOMATIC 91c56c51c7 Merge remote-tracking branch 'origin/master' 2022-09-14 19:13:35 +03:00
AUTOMATIC 3030dcfefd added a background color fix for dark scheme users 2022-09-14 19:13:23 +03:00
NebulousDev 5dde56afe3 Fixed typo in text attention setting 2022-09-14 18:41:40 +03:00
AUTOMATIC 16fb8d24d4 and make the image not be upscaled in gallery 2022-09-14 18:35:04 +03:00
AUTOMATIC f3de9bf7d9 make the gallery taller 2022-09-14 18:17:24 +03:00
AUTOMATIC 9f267af3f7 added a second style field
added the ability to use {prompt} in styles
added a button to apply style to textbox
rearranged top row for UI
2022-09-14 17:56:21 +03:00
Michoko 6153d9d9e9 Update images.py
Better code
2022-09-14 15:51:45 +03:00
Michoko d5520d43fd Update images.py
Handles grids names. Code more robust and doesn't fail if mixed with other files.
2022-09-14 15:51:45 +03:00
Michoko 94aeb5dec9 Update images.py
Better computing of images indexes in filenames
2022-09-14 15:51:45 +03:00
DepFA e16d762800 add draw legend toggle 2022-09-14 15:33:37 +03:00
DepFA 35229d9488 Add square bracket range+count syntax 2022-09-14 15:33:37 +03:00
Elias Oenal 3daf9cac46 Removed stray references to shared.device_codeformer. 2022-09-14 15:24:55 +03:00
Elias Oenal 26f733a026 fix for codeformer switching torch devices on metal systems. 2022-09-14 15:24:55 +03:00
AUTOMATIC bb2732c1c7 updates for exif comments #446 2022-09-14 15:20:05 +03:00
JJ c4e90bf689 format exif string
* UserComment needs an ID code at the start of the tag area. This is provided by piexif.helper.UserComment, otherwise an "Warning 	 Invalid EXIF text encoding for UserComment" is thrown upon reading the exif data
2022-09-14 15:14:26 +03:00
AUTOMATIC c9430e53f6 loopback moved to scripts, added support for multiple batches, changed to honor save grids and how grids in web setting 2022-09-14 14:47:54 +03:00
AUTOMATIC c253d6bdab do not die on failing to load script #426 2022-09-14 13:20:24 +03:00
AUTOMATIC f6aa0cdb0b Overall progress incorrect with X/Y plot and batch count > 1 #441 2022-09-14 13:08:05 +03:00
AUTOMATIC 4c51752464 option name updates for #432 2022-09-14 11:31:49 +03:00
jtkelm2 493032a7af Update ui.py 2022-09-14 11:27:41 +03:00
jtkelm2 df81de0d2f Update ui.py 2022-09-14 11:27:41 +03:00
jtkelm2 74c5f7974c Added selected image saving 2022-09-14 11:27:41 +03:00
AUTOMATIC 0cfbd59d6d Merge remote-tracking branch 'origin/master' 2022-09-14 11:18:40 +03:00
AUTOMATIC 928b246c9e [FEATURE REQUEST] Script settings should also be written to the text files #437 2022-09-14 11:08:36 +03:00
orionaskatu a0e819de90 remove model files check 2022-09-14 10:45:25 +03:00
orionaskatu d62fbcc5aa fix on torch_command + tested on debian 2022-09-14 10:45:25 +03:00
orionaskatu 7bf76af40a rewrite for launch.py - untested 2022-09-14 10:45:25 +03:00
orionaskatu cf150757b5 webui-user.sh gitignore 2022-09-14 10:45:25 +03:00
orionaskatu efc8ed13e1 install/launch scripts for linux 2022-09-14 10:45:25 +03:00
AUTOMATIC 6bea45d495 prevent making grid if there is no need for it #428 2022-09-14 10:34:44 +03:00
JustAnOkapi 21f2a706bb Revert "Update webui-user.bat"
This reverts commit 51a960df1f.
2022-09-14 08:58:13 +03:00
JustAnOkapi f9f9d04b5f prevent extras from saving in dir
Extras have none of the vars used in dir names, so they cant be saved into dirs.
+grid code cleanup
2022-09-14 08:58:13 +03:00
JustAnOkapi e73e2ce2fd Update webui-user.bat 2022-09-14 08:58:13 +03:00
JJ 859fff3700 add webp to file formats with exif saved 2022-09-14 08:49:00 +03:00
camenduru f07d789b79 added cmd arg to load custom styles file 2022-09-14 08:48:42 +03:00
Austere Grim 66b09bbfec Typo of prompt 2022-09-14 08:35:27 +03:00
AUTOMATIC 9d40212485 first attempt to produce crrect seeds in batch 2022-09-13 21:49:58 +03:00
AUTOMATIC 85b97cc49c bandaid for broken ddim sampling #389 2022-09-13 20:12:24 +03:00
AUTOMATIC 950064ee96 img2img_color_correction off by default for #394 2022-09-13 20:00:19 +03:00
AUTOMATIC 29022300ba revert the breaking change in font sneaked in by the person who did EXIF #407 2022-09-13 19:53:42 +03:00
AUTOMATIC fdedecf96c readme info about launcher 2022-09-13 19:44:36 +03:00
AUTOMATIC 70e72db7bd Merge remote-tracking branch 'origin/master' 2022-09-13 19:24:03 +03:00
AUTOMATIC b6b9faa779 add support for reading saved jpeg comments 2022-09-13 19:23:55 +03:00
JJ 7a5852a4ee change np.float to np.float32
* numpy deprecation warning fix. Alternately, you could also specify float
2022-09-13 18:21:59 +03:00
JJ eeabe62b4d add piexif to requirements_versions.txt 2022-09-13 18:11:46 +03:00
JJ de956b28e5 add piexif to requirements.txt 2022-09-13 18:11:46 +03:00
JJ 27c2a0680a save the exif data upon image write 2022-09-13 18:11:46 +03:00
JJ 34cf684419 add metadata to jpg and non-png image files
* needs a piexif module install
* dumps the info in an Exif "UserComment"
* update to webui.bat
2022-09-13 18:11:46 +03:00
AUTOMATIC1111 55e08dd61f Merge pull request #400 from rick2047/requirements-sklearn-version
Add minimum requirements for skimage version
2022-09-13 18:05:52 +03:00
AUTOMATIC 6e68cc88e6 revert to old 1.3.5 basicsr because the new one still causes problems for some python version 2022-09-13 17:41:21 +03:00
AUTOMATIC 918a092ed4 emergency fix for running in dir with spaces 2022-09-13 17:32:40 +03:00
AUTOMATIC1111 a5f34b4636 Merge pull request #392 from C43H66N12O12S2/attention-update
Complete cross attention update
2022-09-13 17:25:30 +03:00
Paresh Mathur 8568d88af1 Update with definitely right requirements for skimage
In my defense I was doing this on my phone.
2022-09-13 19:49:52 +05:30
Paresh Mathur 128e46d6a4 Now with the correct version of skimage 2022-09-13 19:44:02 +05:30
Paresh Mathur e6b6eb23fc Add skimage minimum requirement
Related to https://github.com/AUTOMATIC1111/stable-diffusion-webui/issues/393
2022-09-13 19:32:20 +05:30
AUTOMATIC 33e6b6e9a6 moved most of functionality from webui.bat into cross-platform launch.py
moved stable diffusion dependencies into requirements.txt
added checkout with specific commit hashes to all external repos
2022-09-13 16:48:18 +03:00
C43H66N12O12S2 3b1b1444d4 Complete cross attention update 2022-09-13 14:29:56 +03:00
AUTOMATIC c84e333622 color correction option for all img2img modes #363 2022-09-13 12:51:57 +03:00
AUTOMATIC 823cf946ec Embeddings directory can't be found if running webui.py from another directory (+potential fix) #374 2022-09-13 09:42:51 +03:00
AUTOMATIC afbb3504da Prompts from file not working #379 2022-09-13 09:41:38 +03:00
AUTOMATIC 9ea44c7ce7 Merge remote-tracking branch 'origin/master' 2022-09-13 08:45:43 +03:00
AUTOMATIC 8c1d989839 add link to custom scripts 2022-09-13 08:45:31 +03:00
AUTOMATIC1111 52ae941c31 Merge pull request #366 from ProGamerGov/patch-1
Fix multiple grammar & spelling errors in ReadMe
2022-09-13 08:35:51 +03:00
AUTOMATIC b5a8b99d3f put safety checker into a separate file because it's already crowded in processing 2022-09-13 08:34:41 +03:00
AUTOMATIC1111 b03bc4e79a Merge pull request #367 from GRMrGecko/nsfw_filter
Adds NSFW content filter option
2022-09-13 08:22:39 +03:00
AUTOMATIC1111 fc8acdb574 Merge pull request #378 from oobabooga/master
Fix #368
2022-09-13 07:42:50 +03:00
oobabooga 3e1f9ab8b3 Fix #368 2022-09-13 01:34:35 -03:00
GRMrGecko fc18e2d483 Adds NSFW content filter option 2022-09-12 19:15:35 -05:00
ProGamerGov 0f76bbffc3 Fix multiple grammar & spelling errors in ReadMe 2022-09-12 18:00:40 -06:00
AUTOMATIC1111 fa8be8acd6 Merge pull request #356 from nnuudev/master
Swap width and height sliders in the UI
2022-09-13 00:48:36 +03:00
AUTOMATIC db8f8dd972 Ability to save images into a folder named after the date they were created #353 2022-09-13 00:44:08 +03:00
AUTOMATIC ac9b2ec010 fixed version for GFPGAN and k-diffusion
made launcher always install requirements
bumped basicsr to 1.4.2 because someone wanted it
2022-09-13 00:24:37 +03:00
AUTOMATIC 19a817d97d X/Y plot with denoising adds incorrect image data to individual outputs #331 2022-09-12 23:44:36 +03:00
AUTOMATIC 744ac1f89a Bug: Show show image creation progress every N sampling steps. Set 0 to disable #358 2022-09-12 23:30:17 +03:00
AUTOMATIC 0de109c210 Codeformer face restoration not working: AttributeError: module 'modules.shared' has no attribute 'device_codeformer' #348 2022-09-12 23:24:54 +03:00
nnuudev a97e2a562b Swap width and height sliders in the UI 2022-09-12 21:41:59 +02:00
AUTOMATIC c249bbb4d4 Revert "Merge pull request #343 from oobabooga/master"
This reverts commit 338fb1db63, reversing
changes made to c2a1b37382.
2022-09-12 20:48:10 +03:00
AUTOMATIC 3de44fc580 Include the model name (or the SHA256 of the file) in the metadata #271 2022-09-12 20:47:46 +03:00
AUTOMATIC1111 35a4649c9e Merge pull request #339 from Thielak/master
Update README
2022-09-12 20:41:06 +03:00
Kaleith 7e03c71346 Update README.md
Revision of the previous commit to make it less misleading and mention the option of using .bin files
2022-09-12 19:33:02 +02:00
AUTOMATIC1111 338fb1db63 Merge pull request #343 from oobabooga/master
Fix ugly img2img resize options
2022-09-12 20:17:29 +03:00
AUTOMATIC c2a1b37382 remove check for model in bat entirely #240 2022-09-12 20:16:28 +03:00
oobabooga cf0266f7dc Make prompt and negative prompt take same space 2022-09-12 14:13:34 -03:00
AUTOMATIC c7e0e28ccd changes for #294 2022-09-12 20:09:32 +03:00
AUTOMATIC1111 11e03b9abd Merge pull request #294 from EliasOenal/master
Fixes for mps/Metal: use of seeds, img2img, CodeFormer
2022-09-12 19:58:06 +03:00
AUTOMATIC a655e90fbe add negative prompt to log when clicking save #249 2022-09-12 19:57:31 +03:00
Kaleith 12e326ae9a Updated README
- small update to reflect the revised commit for gradio authentication
2022-09-12 18:50:57 +02:00
AUTOMATIC 45e8fa0e07 X/Y plot can not output the final result with this error message #244 2022-09-12 19:17:02 +03:00
AUTOMATIC 095830e1e8 Prompts from file. How to? #248 2022-09-12 19:13:03 +03:00
AUTOMATIC 482a6ce8cb [Feature Request] Save defaults for extras & keep image parameters after using extras #251 2022-09-12 18:59:53 +03:00
oobabooga 64591ce324 Fix ugly img2img tab 2022-09-12 12:54:01 -03:00
AUTOMATIC 843b2b64fc Instance of CUDA out of memory on a low-res batch, even with --opt-split-attention-v1 (found cause) #255 2022-09-12 18:40:06 +03:00
Kaleith 917087c5b6 Update README
- Documented a couple of new optional flags
- Added a link to a third party repository of embeddings
- Reworded a few parts
- Fixed some typos
2022-09-12 17:14:05 +02:00
AUTOMATIC 535b25ad26 add more context for img2img alt mode test 2022-09-12 18:02:39 +03:00
AUTOMATIC 75a9b1bbd9 Noisy image previews #257 2022-09-12 18:00:53 +03:00
AUTOMATIC 40f4d3ed98 [FEATURE] Save both images, (Skip_Save optional). #265 2022-09-12 17:47:36 +03:00
Elias Oenal b7f95869b4 Refactored Metal/mps fixes. 2022-09-12 16:32:44 +02:00
AUTOMATIC1111 a26f157a5e Merge pull request #335 from C43H66N12O12S2/attention-update
Update cross attention to the newest version
2022-09-12 17:24:38 +03:00
AUTOMATIC 834b6e396b aaaaaaaaaaaaaaaaa 2022-09-12 16:52:06 +03:00
AUTOMATIC 89d94e13a7 rename --channelslast to --opt-channelslast to be in line with other torch optimizations 2022-09-12 16:51:23 +03:00
C43H66N12O12S2 aaea8b4494 Update cross attention to the newest version 2022-09-12 16:48:21 +03:00
AUTOMATIC a5a760a7d4 rename --channelslast to --opt-channelslast to be in line with other torch optimizations 2022-09-12 16:43:11 +03:00
AUTOMATIC1111 01f8de3229 Merge pull request #334 from C43H66N12O12S2/channels-last
Channels last support
2022-09-12 16:40:01 +03:00
AUTOMATIC b70b51cc72 Allow TF32 in CUDA for increased performance #279 2022-09-12 16:34:13 +03:00
C43H66N12O12S2 8c995be44d Add cmd option for channels last 2022-09-12 16:27:23 +03:00
C43H66N12O12S2 fbeadef130 webui.py channels last support 2022-09-12 16:26:42 +03:00
AUTOMATIC 11e648f6c7 allow resizing into non-integer sizes 2022-09-12 16:17:32 +03:00
AUTOMATIC a1305060ce Variations are not working properly #305 2022-09-12 16:00:46 +03:00
AUTOMATIC 2938dc39fc fixed gradio auth bug in PR 2022-09-12 15:52:16 +03:00
AUTOMATIC1111 264d255919 Merge pull request #329 from EyeDeck/master
Add --gradio-auth command line argument to enable Gradio authentication
2022-09-12 15:45:11 +03:00
AUTOMATIC a4416f3585 [BUG] Not Working As Intended - create a directory with name derived from the prompt #306 2022-09-12 15:41:30 +03:00
EyeDeck fc49844aa8 Merge branch 'master' into master 2022-09-12 08:19:14 -04:00
AUTOMATIC c205a07fbc Merge remote-tracking branch 'origin/master' 2022-09-12 15:10:16 +03:00
AUTOMATIC 372a2c3e2e [Feature Request] Please add "--share-password" for Gradio server security #315 2022-09-12 15:10:05 +03:00
EyeDeck e3646e79aa Add --auth command line argument to enable Gradio authentication
Allows you to pass in Gradio authentication like:
`--auth username:password`
Supports multiple sets of credentials by comma-delimiting, like:
`--auth user1:pass1,user2:pass3`...
2022-09-12 08:08:41 -04:00
AUTOMATIC1111 ab87ff0100 Update issue templates 2022-09-12 14:39:02 +03:00
AUTOMATIC e4f080f61a print git commit revision when launching webui 2022-09-12 14:36:40 +03:00
AUTOMATIC1111 051e9195f1 Merge pull request #295 from EyeDeck/master
Add --hide-ui-dir-config command line flag
2022-09-12 13:24:14 +03:00
AUTOMATIC1111 c094f00e10 Merge branch 'master' into master 2022-09-12 13:23:58 +03:00
AUTOMATIC ddc86f2edb --gradio-debug for collab users 2022-09-12 12:40:55 +03:00
AUTOMATIC c50fa7a932 remove mistaken error message 2022-09-12 12:26:37 +03:00
AUTOMATIC e68484500f Merge remote-tracking branch 'origin/master' 2022-09-12 11:55:35 +03:00
AUTOMATIC 9bb20be090 memory optimization for CLIP interrogator
changed default cfg_scale to a higher value
2022-09-12 11:55:27 +03:00
Stephan Reinwald 655ef8e8cb Added cmd arg to load custom ui settings file 2022-09-12 10:20:38 +03:00
AUTOMATIC ab0a79cdf4 keep interrogate models not in vram by default 2022-09-12 09:00:11 +03:00
AUTOMATIC 9c48383608 initial work on img2imgalt 2022-09-12 01:55:34 +03:00
EyeDeck e05e46aa3f Merge branch 'master' into master 2022-09-11 18:15:30 -04:00
AUTOMATIC 303b75c149 save sd upscales as samples not grids 2022-09-12 00:20:05 +03:00
AUTOMATIC 81d91cea29 Merge remote-tracking branch 'origin/master' 2022-09-11 23:25:35 +03:00
Michoko 4535239d8a Add a samples filename format option
Adds a "samples filename format" option in the settings. This format can be defined by tags for maximum flexibility and scalability.
2022-09-11 23:25:20 +03:00
AUTOMATIC 8fb9c57ed6 add half() supporrt for CLIP interrogation 2022-09-11 23:24:24 +03:00
EyeDeck 29a2933e23 Add --hide-ui-dir-config command line flag
Adds `--hide-ui-dir-config` flag to disable editing directory configs from the web UI. This can be set to prevent users from setting the directory to somewhere they shouldn't, for public (or semi-public) interfaces.

Directories are still read from config.json, so the server admin can still set them in the web UI and then relaunch with the hide flag, or edit the config manually.

Also:
- fix OptionInfo `component_args` keyword argument not being read if `component` isn't also set
- ensure that hidden settings aren't still read from the web UI (otherwise they could still be changed by tampering with the interface)
2022-09-11 16:00:42 -04:00
Elias Oenal 5dc05c0d0d Implemented workaround to allow the use of seeds with the mps/metal backend. Fixed img2img's use of unsupported precision float64 with mps backend. 2022-09-11 21:11:02 +02:00
Elias Oenal 2920ca7892 CodeFormer does not support mps/metal backend, implemented fallback to cpu backend. 2022-09-11 21:10:21 +02:00
cryzed cacd14bee8 Only create backup if path exists 2022-09-11 21:23:49 +03:00
cryzed 5fbed65236 Add support for saving styles with negative prompts 2022-09-11 20:56:34 +03:00
AUTOMATIC d97c6f221f added instructions for manual installation 2022-09-11 18:52:40 +03:00
AUTOMATIC f194457229 CLIP interrogator 2022-09-11 18:48:36 +03:00
JohannesGaessler 13008bab90 Fixed prompt_style type hints: int -> str 2022-09-11 12:39:09 +03:00
AUTOMATIC ae6b879b85 i will fix the typo 2022-09-11 12:31:28 +03:00
AUTOMATIC 599666cd3f let me tell you about realesrgan 2022-09-11 12:13:26 +03:00
AUTOMATIC f185874418 [Feature Request] Save defaults for extras & keep image parameters after using extras #251 2022-09-11 11:31:16 +03:00
AUTOMATIC 2e6153e343 Merge remote-tracking branch 'origin/master' 2022-09-11 10:25:02 +03:00
AUTOMATIC a094b3ab8e Add another instruction for workaround for #259 2022-09-11 09:54:51 +03:00
Abdullah Barhoum b5d1af11b7 Modular device management 2022-09-11 09:49:43 +03:00
Seki 065e310a3f Change "send to " 2022-09-11 09:27:58 +03:00
Seki e8884c2b01 Change "send to " 2022-09-11 09:27:58 +03:00
AUTOMATIC 06fadd2dc5 added --opt-split-attention-v1 2022-09-11 00:29:10 +03:00
AUTOMATIC 77f8a72fa8 fix a bug with error message 2022-09-11 00:26:24 +03:00
AUTOMATIC d41568de29 Attempt to fix negative prompt UI for #238 2022-09-10 20:18:38 +03:00
AUTOMATIC dfefc5175a extra info for de-noising strength tooltip 2022-09-10 17:31:03 +03:00
AUTOMATIC 1b963c205f fixed broken empty directory when prompt does not start with letter, this time for real 2022-09-10 16:33:45 +03:00
AUTOMATIC b3311a50dc fix repeating subseeds for every batch #221 2022-09-10 16:16:18 +03:00
AUTOMATIC df58e0bfff fix settings styling for #227 2022-09-10 15:54:46 +03:00
AUTOMATIC 43bdbe934a enabled negative prompt by default
fixed broken empty directory when prompt does not start withl etter
2022-09-10 15:41:29 +03:00
AUTOMATIC 13eec4f3d4 changed <p> to <br> in info field to prevent double line breaks when copying
added new features to the list.
2022-09-10 14:53:38 +03:00
AUTOMATIC 4d2c0c7a72 undo CodeFormer's upscaling of images with dimensions less than 512. 2022-09-10 13:53:10 +03:00
AUTOMATIC decbbe81f5 separated options for sample and grid dir saving for #222 2022-09-10 13:36:16 +03:00
AUTOMATIC c92f2ff196 Update to cross attention from https://github.com/Doggettx/stable-diffusion #219 2022-09-10 12:06:19 +03:00
AUTOMATIC ef0cdb8a42 add batch count to sd upscale #169
fix writing empty prompt pictures to rroot directory instead of 'empty'
suppress 'Denoising strength change factor' text inimage info unless using loopback mode
2022-09-10 11:37:06 +03:00
AUTOMATIC 955f644ce1 split settings into three columns
added a different workaround for gradio mask bug with info in UI
switched to newer gradio version
2022-09-10 11:10:00 +03:00
AUTOMATIC 695c05fb30 prioritize repositories/stable-diffusion path when searching for SD 2022-09-10 10:29:19 +03:00
AUTOMATIC 22faf30c0b add script for batch file processing 2022-09-10 08:45:55 +03:00
AUTOMATIC 6f678ec79c Emoji are not being sorted correctly #192 2022-09-10 08:45:16 +03:00
AUTOMATIC ee8a6fa89f Images in Prompt Matrix grid using different seeds. #208 2022-09-10 08:29:12 +03:00
AUTOMATIC 26ce47eb6c [Feature Request] Ability to pass a custom ui-config.json via command line args #212 2022-09-10 08:18:54 +03:00
elucida d55a731081 fix typo
GFPGAN
2022-09-10 08:12:07 +03:00
AUTOMATIC 022bc97c27 update for code that was supposed to be hiding mask for the gradio bug but isn't. 2022-09-10 08:10:54 +03:00
AUTOMATIC 1fcb48347d prevent styles from adding an extra comma 2022-09-10 00:51:07 +03:00
AUTOMATIC 8e13f54a1d add webui-user.bat to gitignore to possibly remedy #204 2022-09-10 00:38:16 +03:00
AUTOMATIC 364bce105c put manual instructions above WSL, clarify they work for windows and linux 2022-09-10 00:31:58 +03:00
Bernard Maltais cbfd0caef9 Update readme to remove redundant parts. 2022-09-10 00:27:54 +03:00
Bernard Maltais c529532f8b Updare README with conda install instructions 2022-09-10 00:27:54 +03:00
Bernard Maltais fed90189c3 Update readme.md to use environment-wsl2.yaml 2022-09-10 00:27:54 +03:00
Bernard Maltais 046ee991fa Add Windows 11 specification 2022-09-10 00:27:54 +03:00
Bernard Maltais 203c8a3bad Automate GFPGAN download 2022-09-10 00:27:54 +03:00
Bernard Maltais 924aa65e22 Fix README.md 2022-09-10 00:27:54 +03:00
Bernard Maltais 17eb6a0481 fix .gitignore copy 2022-09-10 00:27:54 +03:00
Bernard Maltais 8214447bba Add config and instructions for WSL2 setup 2022-09-10 00:27:54 +03:00
AUTOMATIC 55ef99d51c error in path in manual instruction for install 2022-09-10 00:05:00 +03:00
AUTOMATIC a5316bbf63 add missing reqs from PR
add missing check to autoinstall that will install fonts for existing users
remove unusaed line from another PR
2022-09-09 23:45:44 +03:00
Lukas Meller fbdec2ef20 Fix prompt matrix script 2022-09-09 23:40:03 +03:00
orionaskatu 89f4bb3ca1 Cleaner condition 2022-09-09 23:27:18 +03:00
orionaskatu 79cca25704 Embed roboto 2022-09-09 23:27:18 +03:00
AUTOMATIC 86867e153f support for prompt styles
fix broken prompt matrix
2022-09-09 23:16:02 +03:00
AUTOMATIC d714ea4c41 ability to upload mask for inpainting 2022-09-09 19:43:16 +03:00
AUTOMATIC 5b6a585ae5 Merge remote-tracking branch 'origin/master' into seeds 2022-09-09 19:13:40 +03:00
David Yates 17a7477c72 Include negative prompt in parameters text file 2022-09-09 18:19:37 +03:00
AUTOMATIC efde17e839 i will also fix floating point significant digits 2022-09-09 18:05:43 +03:00
AUTOMATIC b1707553cf added resize seeds and variation seeds features 2022-09-09 17:54:04 +03:00
AUTOMATIC1111 ab623db52c Merge pull request #175 from Thielak/master
Removed mention of CUDA in the README
2022-09-09 12:48:35 +03:00
Kaleith 16792691c7 Removed mention of CUDA in the README
The requirement to install CUDA was removed with https://github.com/AUTOMATIC1111/stable-diffusion-webui/commit/e92d4cf7476f1897fce376916dfb40755ea7920f#diff-b335630551682c19a781afebcf4d07bf978fb1f8ac04c6bf87428ed5106870f5L63 so that mention in README should be superfluous
2022-09-09 10:39:41 +02:00
AUTOMATIC 003b60b94e add an option to show negative prompt 2022-09-09 09:15:36 +03:00
AUTOMATIC 41434ba3cd make X/Y plot's S/R apply to negative prompt as well. 2022-09-09 08:58:31 +03:00
AUTOMATIC bcb8a5eb0a change default font capitalization to possibly help linux users #157 2022-09-09 08:45:39 +03:00
AUTOMATIC 1fd2c22919 brought manual instructions up to date
reworked launching with different parameters
2022-09-09 08:37:19 +03:00
AUTOMATIC 0c63aa95e1 Merge remote-tracking branch 'origin/master' 2022-09-09 07:22:46 +03:00
AUTOMATIC1111 116a2b89c0 Merge pull request #167 from orionaskatu/patch-1
Some typos
2022-09-09 07:21:34 +03:00
AUTOMATIC1111 93524bfb73 Merge pull request #153 from SafentisFox/fix_output_display
Fix webui.bat ignoring cmd line arguments, fix output img overflowing
2022-09-09 07:19:46 +03:00
orionaskatu 764a64b02e Some typos 2022-09-09 01:17:38 +02:00
safentisAuth 5d49003e0d Update README.md 2022-09-09 01:45:18 +03:00
AUTOMATIC 02bcd51a5a fix aggressive caching for extras tab 2022-09-08 23:29:36 +03:00
AUTOMATIC ec33d6e842 fix inconsistency in readme (thx #153) 2022-09-08 20:13:54 +03:00
AUTOMATIC1111 7c8b6b2abb Merge pull request #161 from JohannesGaessler/typo-fix
Fixed typos in JavaScript descriptions
2022-09-08 20:08:12 +03:00
AUTOMATIC fe4e3c2673 fix for PLMS live previews in txt2img 2022-09-08 19:34:20 +03:00
AUTOMATIC ca3861e05f fix for DDIM live previews in txt2img 2022-09-08 19:20:41 +03:00
JohannesGaessler bb46ad9504 Fixed typos in JavaScript descriptions 2022-09-08 18:19:53 +02:00
AUTOMATIC1111 701f76b29a Merge pull request #158 from JohannesGaessler/progress-printing
More informative progress printing
2022-09-08 18:34:45 +03:00
JohannesGaessler f211c498b9 More informative progress printing 2022-09-08 17:05:17 +02:00
AUTOMATIC1111 20b86e81c3 Merge pull request #154 from rewbs/img2img2-loopback-denoise-strength-change-factor
Turn the loopback denoising strength change factor into a parameter rather than hardcoding to 0.95. Set the default to 1.
2022-09-08 17:02:15 +03:00
AUTOMATIC ad02b249f5 add a helpful message when user puts RealESRGAN model into ESRGAN directory. 2022-09-08 15:49:47 +03:00
AUTOMATIC 62ce77e245 support for sd-concepts as alternatives for textual inversion #151 2022-09-08 15:36:50 +03:00
AUTOMATIC f5001246e2 honor tiling settings for RealESRGAN also
load scripts earlier to get errors before model loads
2022-09-08 15:19:36 +03:00
safentisAuth 6dc5cf558d Fix webui.bat ignoring cmd line arguments, fix output img overflowing 2022-09-08 15:08:23 +03:00
rewbs ed01f69542 Turn the loopback denoise strength change factor into a parameter rather than hardcoding to 0.95. Set the default to 1. 2022-09-08 12:02:06 +00:00
AUTOMATIC1111 3eea3c4dab Merge pull request #148 from dgrenner/add-settings-file
Add settings file
2022-09-08 12:27:45 +03:00
Daniel Grenner e817a28b8e Add settings file
Signed-off-by: Daniel Grenner <daniel.grenner@ingka.ikea.com>
2022-09-08 11:18:50 +02:00
AUTOMATIC 3a4c6d9ef5 add webui() function for more simple cell in the notebook 2022-09-08 12:17:26 +03:00
AUTOMATIC1111 a196c45f15 Merge pull request #146 from orionaskatu/orionaskatu-port-option
--port option for #131
2022-09-08 11:46:51 +03:00
orionaskatu cce6f1df41 fix default 2022-09-08 10:46:23 +02:00
AUTOMATIC 27dfcf69da readme update 2022-09-08 11:43:59 +03:00
orionaskatu 50178b7f5b Port defaults to 7860 2022-09-08 10:43:12 +02:00
orionaskatu 567c1fbc1c Port defaults to none 2022-09-08 10:42:21 +02:00
orionaskatu 48317a5176 Port defaults to none 2022-09-08 10:40:56 +02:00
orionaskatu 9c510011ac update readme for --port option 2022-09-08 09:51:33 +02:00
orionaskatu db92896e30 help message for ports < 1024 2022-09-08 09:47:56 +02:00
orionaskatu 4f3cebd51d Add server_port param to webui.py 2022-09-08 09:46:28 +02:00
orionaskatu 5d087731a5 add --port argument to shared.py
defaults to 7860
2022-09-08 09:44:14 +02:00
AUTOMATIC 61785cef65 Merge remote-tracking branch 'origin/master' 2022-09-08 10:31:20 +03:00
AUTOMATIC 0fedd50886 another change for inpainting at full resolution 2022-09-08 10:03:21 +03:00
AUTOMATIC1111 9ddaf8269e Merge pull request #135 from rewbs/img2img2-color-correction
Add color correction to img2img loopback to avoid a progressive skew to magenta. Based on codedealer's PR to hlky's repo here: https://github.com/sd-webui/stable-diffusion-webui/pull/698/files.
2022-09-08 09:45:55 +03:00
Robin Fernandes 21a375e6b2 Merge branch 'master' into img2img2-color-correction 2022-09-08 15:59:42 +10:00
rewbs bc12eddb40 Add scikit-image dependency to requirements_versions.txt for windows users. 2022-09-08 05:57:22 +00:00
AUTOMATIC1111 0959fa2d02 Merge pull request #124 from fuzzytent/alpha-mask
Also use alpha channel from img2img input image as mask
2022-09-08 08:09:28 +03:00
AUTOMATIC1111 782b819a55 Merge pull request #123 from fuzzytent/paste-images
Allow copy-pasting images into file inputs
2022-09-08 07:49:12 +03:00
AUTOMATIC1111 02fecac1c7 Merge pull request #129 from Cikmo/master
Fix not being able to have spaces directory
2022-09-08 07:48:21 +03:00
rewbs 1e7a36fd79 Remove debug print. 2022-09-08 02:53:13 +00:00
rewbs 52e071da2a Add color correction to img2img loopback to avoid a progressive skew to magenta. Based on codedealer's PR to hlky's repo here: https://github.com/sd-webui/stable-diffusion-webui/pull/698/files. 2022-09-08 02:35:26 +00:00
Christian d03e9502b1 Fix not being able to have spaces directory
Adds quotes around the PYTHON path so that there can be spaces in parent folders.
2022-09-08 00:31:25 +02:00
fuzzytent 7045c84643 Also use alpha channel from img2img input image as mask 2022-09-07 22:37:54 +02:00
fuzzytent 4d5a366f00 Allow copy-pasting images into file inputs 2022-09-07 21:58:11 +02:00
AUTOMATIC1111 296d012423 Merge pull request #108 from xeonvs/mps-support
Added support for launching on Apple Silicon M1/M2
2022-09-07 22:29:44 +03:00
xeonvs ba1124b326 directly convert list to tensor 2022-09-07 20:40:32 +02:00
AUTOMATIC ee29bb77bf FIX GRADIO CRASHING WHEN SWITCHING FROM TAB WITH MASK THANK YOU 2022-09-07 21:26:19 +03:00
AUTOMATIC 795d49aa24 MAde poor man's outpainting do less extra useless work. 2022-09-07 19:22:45 +03:00
xeonvs b681a8f4f2 rollback requirements 2022-09-07 18:22:36 +02:00
AUTOMATIC e92d4cf747 Remove requirement for CUDA in readme. 2022-09-07 19:13:37 +03:00
xeonvs aaeeef82fa Miss device type for option --medvram 2022-09-07 18:09:30 +02:00
AUTOMATIC 700c47a674 big improvements to inpainting and outpainting 2022-09-07 17:00:51 +03:00
xeonvs 65fbefd033 Added support for launching on Apple Silicon 2022-09-07 15:58:25 +02:00
AUTOMATIC 2cbda50cdd clarification about not running as root 2022-09-07 15:30:25 +03:00
83 changed files with 9716 additions and 1566 deletions

No files matched your search

+32
View File
@@ -0,0 +1,32 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug-report
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. Windows, Linux]
- Browser [e.g. chrome, safari]
- Commit revision [looks like this: e68484500f76a33ba477d5a99340ab30451e557b; can be seen when launching webui.bat, or obtained manually by running `git rev-parse HEAD`]
**Additional context**
Add any other context about the problem here.
+20
View File
@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
@@ -0,0 +1,28 @@
# Please read the [contributing wiki page](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Contributing) before submitting a pull request!
If you have a large change, pay special attention to this paragraph:
> 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.
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.**
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.
**Additional notes and description of your changes**
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.
+18 -1
View File
@@ -1,11 +1,28 @@
__pycache__ __pycache__
/ESRGAN *.ckpt
*.pth
/ESRGAN/*
/SwinIR/*
/repositories /repositories
/venv /venv
/tmp /tmp
/model.ckpt /model.ckpt
/models/**/*
/GFPGANv1.3.pth /GFPGANv1.3.pth
/gfpgan/weights/*.pth
/ui-config.json /ui-config.json
/outputs /outputs
/config.json /config.json
/log /log
/webui.settings.bat
/embeddings
/styles.csv
/styles.csv.bak
/webui-user.bat
/webui-user.sh
/interrogate
/user.css
/.idea
notification.mp3
/SwinIR
/textual_inversion
+81 -177
View File
@@ -1,217 +1,121 @@
# Stable Diffusion web UI # Stable Diffusion web UI
A browser interface based on Gradio library for Stable Diffusion. A browser interface based on Gradio library for Stable Diffusion.
![](screenshot.png) ![](txt2img_Screenshot.png)
## Feature showcase Check the [custom scripts](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Custom-Scripts) wiki page for extra scripts developed by users.
[Detailed feature showcase with images, art by Greg Rutkowski](https://github.com/AUTOMATIC1111/stable-diffusion-webui-feature-showcase)
## Features
[Detailed feature showcase with images](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Features):
- Original txt2img and img2img modes - Original txt2img and img2img modes
- One click install and run script (but you still must install python, git and CUDA) - One click install and run script (but you still must install python and git)
- Outpainting - Outpainting
- Inpainting - Inpainting
- Prompt matrix - Prompt Matrix
- Stable Diffusion upscale - Stable Diffusion Upscale
- Attention - Attention, specify parts of text that the model should pay more attention to
- Loopback - a man in a ((tuxedo)) - will pay more attention to tuxedo
- X/Y plot - a man in a (tuxedo:1.21) - alternative syntax
- Loopback, run img2img processing multiple times
- X/Y plot, a way to draw a 2 dimensional plot of images with different parameters
- Textual Inversion - Textual Inversion
- have as many embeddings as you want and use any names you like for them
- use multiple embeddings with different numbers of vectors per token
- works with half precision floating point numbers
- Extras tab with: - Extras tab with:
- GFPGAN, neural network that fixes faces - GFPGAN, neural network that fixes faces
- CodeFormer, face restoration tool as an alternative to GFPGAN
- RealESRGAN, neural network upscaler - RealESRGAN, neural network upscaler
- ESRGAN, neural network with a lot of third party models - ESRGAN, neural network upscaler with a lot of third party models
- SwinIR, neural network upscaler
- LDSR, Latent diffusion super resolution upscaling
- Resizing aspect ratio options - Resizing aspect ratio options
- Sampling method selection - Sampling method selection
- Interrupt processing at any time - Interrupt processing at any time
- 4GB videocard support - 4GB video card support (also reports of 2GB working)
- Correct seeds for batches - Correct seeds for batches
- Prompt length validation - Prompt length validation
- Generation parameters added as text to PNG - get length of prompt in tokens as you type
- Tab to view an existing picture's generation parameters - get a warning after generation if some text was truncated
- Generation parameters
- parameters you used to generate images are saved with that image
- in PNG chunks for PNG, in EXIF for JPEG
- can drag the image to PNG info tab to restore generation parameters and automatically copy them into UI
- can be disabled in settings
- Settings page - Settings page
- Running custom code from UI - Running arbitrary python code from UI (must run with --allow-code to enable)
- Mouseover hints fo most UI elements - Mouseover hints for most UI elements
- Possible to change defaults/mix/max/step values for UI elements via text config - Possible to change defaults/mix/max/step values for UI elements via text config
- Random artist button - Random artist button
- Tiling support: UI checkbox to create images that can be tiled like textures - Tiling support, a checkbox to create images that can be tiled like textures
- Progress bar and live image generation preview - Progress bar and live image generation preview
- Negative prompt, an extra text field that allows you to list what you don't want to see in generated image
- Styles, a way to save part of prompt and easily apply them via dropdown later
- Variations, a way to generate same image but with tiny differences
- Seed resizing, a way to generate same image but at slightly different resolution
- CLIP interrogator, a button that tries to guess prompt from an image
- Prompt Editing, a way to change prompt mid-generation, say to start making a watermelon and switch to anime girl midway
- Batch Processing, process a group of files using img2img
- Img2img Alternative
- Highres Fix, a convenience option to produce high resolution pictures in one click without usual distortions
- Reloading checkpoints on the fly
- Checkpoint Merger, a tab that allows you to merge two checkpoints into one
- [Custom scripts](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Custom-Scripts) with many extensions from community
## Installing 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.
You need [python](https://www.python.org/downloads/windows/) and [git](https://git-scm.com/download/win) Alternatively, use Google Colab:
installed to run this, and an NVidia videocard.
I tested the installation to work Windows with Python 3.8.10, and with Python 3.10.6. You may be able - [Colab, maintained by Akaibu](https://colab.research.google.com/drive/1kw3egmSn-KgWsikYvOMjJkVDsPLjEMzl)
to have success with different versions. - [Colab, original by me, outdated](https://colab.research.google.com/drive/1Iy-xW9t1-OQWhb0hNxueGij8phCyluOh).
You need `model.ckpt`, Stable Diffusion model checkpoint, a big file containing the neural network weights. You ### Automatic Installation on Windows
can obtain it from the following places: 1. Install [Python 3.10.6](https://www.python.org/downloads/windows/), checking "Add Python to PATH"
- [official download](https://huggingface.co/CompVis/stable-diffusion-v-1-4-original) 2. Install [git](https://git-scm.com/download/win).
- [file storage](https://drive.yerf.org/wl/?id=EBfTrmcCCUAGaQBXVIj5lJmEhjoP1tgl) 3. Download the stable-diffusion-webui repository, for example by running `git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git`.
- magnet:?xt=urn:btih:3a4a612d75ed088ea542acac52f9f45987488d1c&dn=sd-v1-4.ckpt&tr=udp%3a%2f%2ftracker.openbittorrent.com%3a6969%2fannounce&tr=udp%3a%2f%2ftracker.opentrackr.org%3a1337 4. Place `model.ckpt` in the `models` directory (see [dependencies](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Dependencies) for where to get it).
5. _*(Optional)*_ Place `GFPGANv1.4.pth` in the base directory, alongside `webui.py` (see [dependencies](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Dependencies) for where to get it).
6. Run `webui-user.bat` from Windows Explorer as normal, non-administrator, user.
You optionally can use GPFGAN to improve faces, then you'll need to download the model from [here](https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth). ### Automatic Installation on Linux
1. Install the dependencies:
To use ESRGAN models, put them into ESRGAN directory in the same location as webui.py. A file will be loaded ```bash
as model if it has .pth extension. Grab models from the [Model Database](https://upscale.wiki/wiki/Model_Database). # Debian-based:
sudo apt install wget git python3 python3-venv
### Automatic installation/launch # Red Hat-based:
sudo dnf install wget git python3
- install [Python 3.10.6](https://www.python.org/downloads/windows/) and check "Add Python to PATH" during installation. You must install this exact version. # Arch-based:
- install [git](https://git-scm.com/download/win) sudo pacman -S wget git python3
- install [CUDA 11.3](https://developer.nvidia.com/cuda-11.3.0-download-archive?target_os=Windows&target_arch=x86_64) ```
- place `model.ckpt` into webui directory, next to `webui.bat`. 2. To install in `/home/$(whoami)/stable-diffusion-webui/`, run:
- _*(optional)*_ place `GFPGANv1.3.pth` into webui directory, next to `webui.bat`. ```bash
- run `webui.bat` from Windows Explorer. bash <(wget -qO- https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/master/webui.sh)
#### Troublehooting:
- According to reports, intallation currently does not work in a directory with spaces in filenames.
- if your version of Python is not in PATH (or if another version is), edit `webui.bat`, change the line `set PYTHON=python` to say the full path to your python executable: `set PYTHON=B:\soft\Python310\python.exe`. You can do this for python, but not for git.
- if you get out of memory errors and your videocard has low amount of VRAM (4GB), edit `webui.bat`, change line 5 to from `set COMMANDLINE_ARGS=` to `set COMMANDLINE_ARGS=--medvram` (see below for other possible options)
- installer creates python virtual environment, so none of installed modules will affect your system installation of python if you had one prior to installing this.
- to prevent the creation of virtual environment and use your system python, edit `webui.bat` replacing `set VENV_DIR=venv` with `set VENV_DIR=`.
- webui.bat installs requirements from files `requirements_versions.txt`, which lists versions for modules specifically compatible with Python 3.10.6. If you choose to install for a different version of python, editing `webui.bat` to have `set REQS_FILE=requirements.txt` instead of `set REQS_FILE=requirements_versions.txt` may help (but I still reccomend you to just use the recommended version of python).
- if you feel you broke something and want to reinstall from scratch, delete directories: `venv`, `repositories`.
### Google collab
If you don't want or can't run locally, here is google collab that allows you to run the webui:
https://colab.research.google.com/drive/1Iy-xW9t1-OQWhb0hNxueGij8phCyluOh
### What options to use for low VRAM videocards?
- If you have 4GB VRAM and want to make 512x512 (or maybe up to 640x640) images, use `--medvram`.
- If you have 4GB VRAM and want to make 512x512 images, but you get an out of memory error with `--medvram`, use `--medvram --opt-split-attention` instead.
- If you have 4GB VRAM and want to make 512x512 images, and you still get an out of memory error, use `--lowvram --always-batch-cond-uncond --opt-split-attention` instead.
- If you have 4GB VRAM and want to make images larger than you can with `--medvram`, use `--lowvram --opt-split-attention`.
- If you have more VRAM and want to make larger images than you can usually make, use `--medvram --opt-split-attention`. You can use `--lowvram`
also but the effect will likely be barely noticeable.
- Otherwise, do not use any of those.
Extra: if you get a green screen instead of generated pictures, you have a card that doesn't support half
precision floating point numbers. You must use `--precision full --no-half` in addition to other flags,
and the model will take much more space in VRAM.
### Running online
Use `--share` option to run online. You will get a xxx.app.gradio link. This is the intended way to use the
program in collabs.
Use `--listen` to make the server listen to network connections. This will allow computers on local newtork
to access the UI, and if you configure port forwarding, also computers on the internet.
### Textual Inversion
To make use of pretrained embeddings, create `embeddings` directory (in the same palce as `webui.py`)
and put your embeddings into it. They must be .pt files, each with only one trained embedding,
and the filename (without .pt) will be the term you'd use in prompt to get that embedding.
As an example, I trained one for about 5000 steps: https://files.catbox.moe/e2ui6r.pt; it does not produce
very good results, but it does work. Download and rename it to Usada Pekora.pt, and put it into embeddings dir
and use Usada Pekora in prompt.
### How to change UI defaults?
After running once, a `ui-config.json` file appears in webui directory:
```json
{
"txt2img/Sampling Steps/value": 20,
"txt2img/Sampling Steps/minimum": 1,
"txt2img/Sampling Steps/maximum": 150,
"txt2img/Sampling Steps/step": 1,
"txt2img/Batch count/value": 1,
"txt2img/Batch count/minimum": 1,
"txt2img/Batch count/maximum": 32,
"txt2img/Batch count/step": 1,
"txt2img/Batch size/value": 1,
"txt2img/Batch size/minimum": 1,
``` ```
Edit values to your liking and the next time you launch the program they will be applied. ### Installation on Apple Silicon
Find the instructions [here](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Installation-on-Apple-Silicon).
### Manual instructions ## Contributing
Alternatively, if you don't want to run webui.bat, here are instructions for installing Here's how to add code to this repo: [Contributing](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Contributing)
everything by hand:
```commandline
:: crate a directory somewhere for stable diffusion and open cmd in it;
:: make sure you are in the right directory; the command must output the directory you chose
echo %cd%
:: install torch with CUDA support. See https://pytorch.org/get-started/locally/ for more instructions if this fails.
pip install torch --extra-index-url https://download.pytorch.org/whl/cu113
:: check if torch supports GPU; this must output "True". You need CUDA 11. installed for this. You might be able to use
:: a different version, but this is what I tested.
python -c "import torch; print(torch.cuda.is_available())"
:: clone Stable Diffusion repositories
git clone https://github.com/CompVis/stable-diffusion.git
git clone https://github.com/CompVis/taming-transformers
:: install requirements of Stable Diffusion
pip install transformers==4.19.2 diffusers invisible-watermark
:: install k-diffusion
pip install git+https://github.com/crowsonkb/k-diffusion.git
:: (optional) install GFPGAN to fix faces
pip install git+https://github.com/TencentARC/GFPGAN.git
:: go into stable diffusion's repo directory
cd stable-diffusion
:: clone web ui
git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git
:: install requirements of web ui
pip install -r stable-diffusion-webui/requirements.txt
:: update numpy to latest version
pip install -U numpy
:: (outside of command line) put stable diffusion model into models/ldm/stable-diffusion-v1/model.ckpt; you'll have
:: to create one missing directory;
:: the command below must output something like: 1 File(s) 4,265,380,512 bytes
dir models\ldm\stable-diffusion-v1\model.ckpt
:: (outside of command line) put the GFPGAN model into same directory as webui script
:: the command below must output something like: 1 File(s) 348,632,874 bytes
dir stable-diffusion-webui\GFPGANv1.3.pth
```
After that the installation is finished.
Run the command to start web ui:
```
python stable-diffusion-webui/webui.py
```
If you have a 4GB video card, run the command with either `--lowvram` or `--medvram` argument:
```
python stable-diffusion-webui/webui.py --medvram
```
After a while, you will get a message like this:
```
Running on local URL: http://127.0.0.1:7860/
```
Open the URL in browser, and you are good to go.
## Documentation
The documentation was moved from this README over to the project's [wiki](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki).
## Credits ## Credits
- Stable Diffusion - https://github.com/CompVis/stable-diffusion, https://github.com/CompVis/taming-transformers - Stable Diffusion - https://github.com/CompVis/stable-diffusion, https://github.com/CompVis/taming-transformers
- 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 - GFPGAN - https://github.com/TencentARC/GFPGAN.git
- CodeFormer - https://github.com/sczhou/CodeFormer
- ESRGAN - https://github.com/xinntao/ESRGAN - ESRGAN - https://github.com/xinntao/ESRGAN
- Ideas for optimizations and some code (from users) - https://github.com/basujindal/stable-diffusion - SwinIR - https://github.com/JingyunLiang/SwinIR
- LDSR - https://github.com/Hafiidz/latent-diffusion
- Ideas for optimizations - https://github.com/basujindal/stable-diffusion
- Doggettx - Cross Attention layer optimization - https://github.com/Doggettx/stable-diffusion, original idea for prompt editing.
- Rinon Gal - Textual Inversion - https://github.com/rinongal/textual_inversion (we're not using his code, but we are using his ideas).
- Idea for SD upscale - https://github.com/jquesnelle/txt2imghd - Idea for SD upscale - https://github.com/jquesnelle/txt2imghd
- Noise generation for outpainting mk2 - https://github.com/parlance-zz/g-diffuser-bot
- CLIP interrogator idea and borrowing some code - https://github.com/pharmapsychotic/clip-interrogator
- 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)
-2
View File
@@ -359,7 +359,6 @@ Antanas Sutkus,0.7369492,black-white
Leonora Carrington,0.73726475,scribbles Leonora Carrington,0.73726475,scribbles
Hieronymus Bosch,0.7369955,scribbles Hieronymus Bosch,0.7369955,scribbles
A. J. Casson,0.73666203,scribbles A. J. Casson,0.73666203,scribbles
A.J.Casson,0.73666203,scribbles
Chaim Soutine,0.73662066,scribbles Chaim Soutine,0.73662066,scribbles
Artur Bordalo,0.7364549,weird Artur Bordalo,0.7364549,weird
Thomas Allom,0.68792284,fineart Thomas Allom,0.68792284,fineart
@@ -1907,7 +1906,6 @@ Alex Schomburg,0.46614102,digipa-low-impact
Bastien L. Deharme,0.583349,special Bastien L. Deharme,0.583349,special
František Jakub Prokyš,0.58782333,fineart František Jakub Prokyš,0.58782333,fineart
Jesper Ejsing,0.58782053,fineart Jesper Ejsing,0.58782053,fineart
Jesper Ejsing,0.58782053,fineart
Odd Nerdrum,0.53551745,digipa-high-impact Odd Nerdrum,0.53551745,digipa-high-impact
Tom Lovell,0.5877577,fineart Tom Lovell,0.5877577,fineart
Ayami Kojima,0.5877416,fineart Ayami Kojima,0.5877416,fineart
1 artist score category
359 Leonora Carrington 0.73726475 scribbles
360 Hieronymus Bosch 0.7369955 scribbles
361 A. J. Casson 0.73666203 scribbles
A.J.Casson 0.73666203 scribbles
362 Chaim Soutine 0.73662066 scribbles
363 Artur Bordalo 0.7364549 weird
364 Thomas Allom 0.68792284 fineart
1906 Bastien L. Deharme 0.583349 special
1907 František Jakub Prokyš 0.58782333 fineart
1908 Jesper Ejsing 0.58782053 fineart
Jesper Ejsing 0.58782053 fineart
1909 Odd Nerdrum 0.53551745 digipa-high-impact
1910 Tom Lovell 0.5877577 fineart
1911 Ayami Kojima 0.5877416 fineart
+11
View File
@@ -0,0 +1,11 @@
name: automatic
channels:
- pytorch
- defaults
dependencies:
- python=3.8.5
- pip=20.3
- cudatoolkit=11.3
- pytorch=1.11.0
- torchvision=0.12.0
- numpy=1.19.2
+119
View File
@@ -0,0 +1,119 @@
let currentWidth = null;
let currentHeight = null;
let arFrameTimeout = setTimeout(function(){},0);
function dimensionChange(e,dimname){
if(dimname == 'Width'){
currentWidth = e.target.value*1.0
}
if(dimname == 'Height'){
currentHeight = e.target.value*1.0
}
var inImg2img = Boolean(gradioApp().querySelector("button.rounded-t-lg.border-gray-200"))
if(!inImg2img){
return;
}
var img2imgMode = gradioApp().querySelector('#mode_img2img.tabs > div > button.rounded-t-lg.border-gray-200')
if(img2imgMode){
img2imgMode=img2imgMode.innerText
}else{
return;
}
var redrawImage = gradioApp().querySelector('div[data-testid=image] img');
var inpaintImage = gradioApp().querySelector('#img2maskimg div[data-testid=image] img')
var targetElement = null;
if(img2imgMode=='img2img' && redrawImage){
targetElement = redrawImage;
}else if(img2imgMode=='Inpaint' && inpaintImage){
targetElement = inpaintImage;
}
if(targetElement){
var arPreviewRect = gradioApp().querySelector('#imageARPreview');
if(!arPreviewRect){
arPreviewRect = document.createElement('div')
arPreviewRect.id = "imageARPreview";
gradioApp().getRootNode().appendChild(arPreviewRect)
}
var viewportOffset = targetElement.getBoundingClientRect();
viewportscale = Math.min( targetElement.clientWidth/targetElement.naturalWidth, targetElement.clientHeight/targetElement.naturalHeight )
scaledx = targetElement.naturalWidth*viewportscale
scaledy = targetElement.naturalHeight*viewportscale
cleintRectTop = (viewportOffset.top+window.scrollY)
cleintRectLeft = (viewportOffset.left+window.scrollX)
cleintRectCentreY = cleintRectTop + (targetElement.clientHeight/2)
cleintRectCentreX = cleintRectLeft + (targetElement.clientWidth/2)
viewRectTop = cleintRectCentreY-(scaledy/2)
viewRectLeft = cleintRectCentreX-(scaledx/2)
arRectWidth = scaledx
arRectHeight = scaledy
arscale = Math.min( arRectWidth/currentWidth, arRectHeight/currentHeight )
arscaledx = currentWidth*arscale
arscaledy = currentHeight*arscale
arRectTop = cleintRectCentreY-(arscaledy/2)
arRectLeft = cleintRectCentreX-(arscaledx/2)
arRectWidth = arscaledx
arRectHeight = arscaledy
arPreviewRect.style.top = arRectTop+'px';
arPreviewRect.style.left = arRectLeft+'px';
arPreviewRect.style.width = arRectWidth+'px';
arPreviewRect.style.height = arRectHeight+'px';
clearTimeout(arFrameTimeout);
arFrameTimeout = setTimeout(function(){
arPreviewRect.style.display = 'none';
},2000);
arPreviewRect.style.display = 'block';
}
}
onUiUpdate(function(){
var arPreviewRect = gradioApp().querySelector('#imageARPreview');
if(arPreviewRect){
arPreviewRect.style.display = 'none';
}
var inImg2img = Boolean(gradioApp().querySelector("button.rounded-t-lg.border-gray-200"))
if(inImg2img){
let inputs = gradioApp().querySelectorAll('input');
inputs.forEach(function(e){
let parentLabel = e.parentElement.querySelector('label')
if(parentLabel && parentLabel.innerText){
if(!e.classList.contains('scrollwatch')){
if(parentLabel.innerText == 'Width' || parentLabel.innerText == 'Height'){
e.addEventListener('input', function(e){dimensionChange(e,parentLabel.innerText)} )
e.classList.add('scrollwatch')
}
if(parentLabel.innerText == 'Width'){
currentWidth = e.value*1.0
}
if(parentLabel.innerText == 'Height'){
currentHeight = e.value*1.0
}
}
}
})
}
});
+86
View File
@@ -0,0 +1,86 @@
// allows drag-dropping files into gradio image elements, and also pasting images from clipboard
function isValidImageList( files ) {
return files && files?.length === 1 && ['image/png', 'image/gif', 'image/jpeg'].includes(files[0].type);
}
function dropReplaceImage( imgWrap, files ) {
if ( ! isValidImageList( files ) ) {
return;
}
imgWrap.querySelector('.modify-upload button + button, .touch-none + div button + button')?.click();
const callback = () => {
const fileInput = imgWrap.querySelector('input[type="file"]');
if ( fileInput ) {
fileInput.files = files;
fileInput.dispatchEvent(new Event('change'));
}
};
if ( imgWrap.closest('#pnginfo_image') ) {
// special treatment for PNG Info tab, wait for fetch request to finish
const oldFetch = window.fetch;
window.fetch = async (input, options) => {
const response = await oldFetch(input, options);
if ( 'api/predict/' === input ) {
const content = await response.text();
window.fetch = oldFetch;
window.requestAnimationFrame( () => callback() );
return new Response(content, {
status: response.status,
statusText: response.statusText,
headers: response.headers
})
}
return response;
};
} else {
window.requestAnimationFrame( () => callback() );
}
}
window.document.addEventListener('dragover', e => {
const target = e.composedPath()[0];
const imgWrap = target.closest('[data-testid="image"]');
if ( !imgWrap ) {
return;
}
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
});
window.document.addEventListener('drop', e => {
const target = e.composedPath()[0];
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 => {
const files = e.clipboardData.files;
if ( ! isValidImageList( files ) ) {
return;
}
const visibleImageFields = [...gradioApp().querySelectorAll('[data-testid="image"]')]
.filter(el => uiElementIsVisible(el));
if ( ! visibleImageFields.length ) {
return;
}
const firstFreeImageField = visibleImageFields
.filter(el => el.querySelector('input[type=file]'))?.[0];
dropReplaceImage(
firstFreeImageField ?
firstFreeImageField :
visibleImageFields[visibleImageFields.length - 1]
, files );
});
+113
View File
@@ -0,0 +1,113 @@
// mouseover tooltips for various UI elements
titles = {
"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",
"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 to higher than 30-40 does not help",
"DDIM": "Denoising Diffusion Implicit Models - best at inpainting",
"Batch count": "How many batches of images to create",
"Batch size": "How many image to create in a single batch",
"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",
"\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",
"\u{1f3a8}": "Add a random artist to the prompt.",
"\u2199\ufe0f": "Read generation parameters from prompt into user interface.",
"\u{1f4c2}": "Open images output directory",
"Inpaint a part of image": "Draw a mask over an image, and the script will regenerate the masked area with content according to prompt",
"SD upscale": "Upscale image normally, split result into tiles, improve each tile using img2img, merge whole image back",
"Just resize": "Resize image to target resolution. Unless height and width match, you will get incorrect aspect ratio.",
"Crop and resize": "Resize the image so that entirety of target resolution is filled with the image. Crop parts that stick out.",
"Resize and fill": "Resize the image so that entirety of image is inside target resolution. Fill empty space with image's colors.",
"Mask blur": "How much to blur the mask before processing, in pixels.",
"Masked content": "What to put inside the masked area before processing it with Stable Diffusion.",
"fill": "fill it with colors of the image",
"original": "keep whatever was there originally",
"latent noise": "fill it with latent space noise",
"latent nothing": "fill it with latent space zeroes",
"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 change factor": "In loopback mode, on each loop the denoising strength is multiplied by this value. <1 means decreasing variety so your sequence will converge on a fixed picture. >1 means increasing variety so your sequence will become more and more chaotic.",
"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.",
"X values": "Separate values for X axis using commas.",
"Y values": "Separate values for Y axis using commas.",
"None": "Do not do anything special",
"Prompt matrix": "Separate prompts into parts using vertical pipe character (|) and the script will create a picture for every combination of them (except for the first part, which will be present in all combinations)",
"X/Y plot": "Create a grid where images will have different parameters. Use inputs below to specify which parameters will be shared by columns and rows",
"Custom code": "Run Python code. Advanced user only. Must run program with --allow-code for this to work",
"Prompt S/R": "Separate a list of words with commas, and the first word will be used as a keyword: script will search for this word in the prompt, and replace it with others",
"Prompt order": "Separate a list of words with commas, and the script will make a variation of prompt with those words for their every possible order",
"Tiling": "Produce an image that can be tiled.",
"Tile overlap": "For SD upscale, how much overlap in pixels should there be between tiles. Tiles overlap so that when they are merged back into one picture, there is no clearly visible seam.",
"Variation seed": "Seed of a different picture to be mixed into the generation.",
"Variation strength": "How strong of a variation to produce. At 0, there will be no effect. At 1, you will get the complete picture with variation seed (except for ancestral samplers, where you will just get something).",
"Resize seed from height": "Make an attempt to produce a picture similar to what would have been produced with same seed at specified resolution",
"Resize seed from width": "Make an attempt to produce a picture similar to what would have been produced with same seed at specified resolution",
"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], [prompt], [prompt_no_styles], [prompt_spaces], [width], [height], [styles], [sampler], [seed], [model_hash], [prompt_words], [date], [datetime], [job_timestamp]; leave empty for default.",
"Directory name pattern": "Use following tags to define how subdirectories for images and grids are chosen: [steps], [cfg], [prompt], [prompt_no_styles], [prompt_spaces], [width], [height], [styles], [sampler], [seed], [model_hash], [prompt_words], [date], [datetime], [job_timestamp]; 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",
"Loopback": "Process an image, use it as an input, repeat.",
"Loops": "How many times to repeat processing an image and using it as input for the next iteration",
"Style 1": "Style to apply; styles have components for both positive and negative prompts and apply to both",
"Style 2": "Style to apply; styles have components for both positive and negative prompts and apply to both",
"Apply style": "Insert selected styles into prompt fields",
"Create style": "Save current prompts as a style. If you add the token {prompt} to the text, the style use that as placeholder for your prompt when you use the style in the future.",
"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.",
"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%).",
"Highres. fix": "Use a two step process to partially create an image at smaller resolution, upscale, and then improve details in it without changing composition",
"Scale latent": "Uscale the image in latent space. Alternative is to produce the full image from latent representation, upscale that, and then move it back to latent space.",
}
onUiUpdate(function(){
gradioApp().querySelectorAll('span, button, select, p').forEach(function(span){
tooltip = titles[span.textContent];
if(!tooltip){
tooltip = titles[span.value];
}
if(!tooltip){
for (const c of span.classList) {
if (c in titles) {
tooltip = titles[c];
break;
}
}
}
if(tooltip){
span.title = tooltip;
}
})
gradioApp().querySelectorAll('select').forEach(function(select){
if (select.onchange != null) return;
select.onchange = function(){
select.title = titles[select.value] || "";
}
})
})
+45
View File
@@ -0,0 +1,45 @@
/**
* temporary fix for https://github.com/AUTOMATIC1111/stable-diffusion-webui/issues/668
* @see https://github.com/gradio-app/gradio/issues/1721
*/
window.addEventListener( 'resize', () => imageMaskResize());
function imageMaskResize() {
const canvases = gradioApp().querySelectorAll('#img2maskimg .touch-none canvas');
if ( ! canvases.length ) {
canvases_fixed = false;
window.removeEventListener( 'resize', imageMaskResize );
return;
}
const wrapper = canvases[0].closest('.touch-none');
const previewImage = wrapper.previousElementSibling;
if ( ! previewImage.complete ) {
previewImage.addEventListener( 'load', () => imageMaskResize());
return;
}
const w = previewImage.width;
const h = previewImage.height;
const nw = previewImage.naturalWidth;
const nh = previewImage.naturalHeight;
const portrait = nh > nw;
const factor = portrait;
const wW = Math.min(w, portrait ? h/nh*nw : w/nw*nw);
const wH = Math.min(h, portrait ? h/nh*nh : w/nw*nh);
wrapper.style.width = `${wW}px`;
wrapper.style.height = `${wH}px`;
wrapper.style.left = `${(w-wW)/2}px`;
wrapper.style.top = `${(h-wH)/2}px`;
canvases.forEach( c => {
c.style.width = c.style.height = '';
c.style.maxWidth = '100%';
c.style.maxHeight = '100%';
c.style.objectFit = 'contain';
});
}
onUiUpdate(() => imageMaskResize());
+209
View File
@@ -0,0 +1,209 @@
// A full size 'lightbox' preview modal shown when left clicking on gallery previews
function closeModal() {
gradioApp().getElementById("lightboxModal").style.display = "none";
}
function showModal(event) {
const source = event.target || event.srcElement;
const modalImage = gradioApp().getElementById("modalImage")
const lb = gradioApp().getElementById("lightboxModal")
modalImage.src = source.src
if (modalImage.style.display === 'none') {
lb.style.setProperty('background-image', 'url(' + source.src + ')');
}
lb.style.display = "block";
lb.focus()
event.stopPropagation()
}
function negmod(n, m) {
return ((n % m) + m) % m;
}
function modalImageSwitch(offset){
var allgalleryButtons = gradioApp().querySelectorAll(".gallery-item.transition-all")
var galleryButtons = []
allgalleryButtons.forEach(function(elem){
if(elem.parentElement.offsetParent){
galleryButtons.push(elem);
}
})
if(galleryButtons.length>1){
var allcurrentButtons = gradioApp().querySelectorAll(".gallery-item.transition-all.\\!ring-2")
var currentButton = null
allcurrentButtons.forEach(function(elem){
if(elem.parentElement.offsetParent){
currentButton = elem;
}
})
var result = -1
galleryButtons.forEach(function(v, i){ if(v==currentButton) { result = i } })
if(result != -1){
nextButton = galleryButtons[negmod((result+offset),galleryButtons.length)]
nextButton.click()
const modalImage = gradioApp().getElementById("modalImage");
const modal = gradioApp().getElementById("lightboxModal");
modalImage.src = nextButton.children[0].src;
if (modalImage.style.display === 'none') {
modal.style.setProperty('background-image', `url(${modalImage.src})`)
}
setTimeout( function(){modal.focus()},10)
}
}
}
function modalNextImage(event){
modalImageSwitch(1)
event.stopPropagation()
}
function modalPrevImage(event){
modalImageSwitch(-1)
event.stopPropagation()
}
function modalKeyHandler(event){
switch (event.key) {
case "ArrowLeft":
modalPrevImage(event)
break;
case "ArrowRight":
modalNextImage(event)
break;
case "Escape":
closeModal();
break;
}
}
function showGalleryImage(){
setTimeout(function() {
fullImg_preview = gradioApp().querySelectorAll('img.w-full.object-contain')
if(fullImg_preview != null){
fullImg_preview.forEach(function function_name(e) {
if(e && e.parentElement.tagName == 'DIV'){
e.style.cursor='pointer'
e.addEventListener('click', function (evt) {
if(!opts.js_modal_lightbox) return;
modalZoomSet(gradioApp().getElementById('modalImage'), opts.js_modal_lightbox_initialy_zoomed)
showModal(evt)
},true);
}
});
}
}, 100);
}
function modalZoomSet(modalImage, enable){
if( enable ){
modalImage.classList.add('modalImageFullscreen');
} else{
modalImage.classList.remove('modalImageFullscreen');
}
}
function modalZoomToggle(event){
modalImage = gradioApp().getElementById("modalImage");
modalZoomSet(modalImage, !modalImage.classList.contains('modalImageFullscreen'))
event.stopPropagation()
}
function modalTileImageToggle(event){
const modalImage = gradioApp().getElementById("modalImage");
const modal = gradioApp().getElementById("lightboxModal");
const isTiling = modalImage.style.display === 'none';
if (isTiling) {
modalImage.style.display = 'block';
modal.style.setProperty('background-image', 'none')
} else {
modalImage.style.display = 'none';
modal.style.setProperty('background-image', `url(${modalImage.src})`)
}
event.stopPropagation()
}
function galleryImageHandler(e){
if(e && e.parentElement.tagName == 'BUTTON'){
e.onclick = showGalleryImage;
}
}
onUiUpdate(function(){
fullImg_preview = gradioApp().querySelectorAll('img.w-full')
if(fullImg_preview != null){
fullImg_preview.forEach(galleryImageHandler);
}
})
document.addEventListener("DOMContentLoaded", function() {
const modalFragment = document.createDocumentFragment();
const modal = document.createElement('div')
modal.onclick = closeModal;
modal.id = "lightboxModal";
modal.tabIndex=0
modal.addEventListener('keydown', modalKeyHandler, true)
const modalControls = document.createElement('div')
modalControls.className = 'modalControls gradio-container';
modal.append(modalControls);
const modalZoom = document.createElement('span')
modalZoom.className = 'modalZoom cursor';
modalZoom.innerHTML = '&#10529;'
modalZoom.addEventListener('click', modalZoomToggle, true)
modalZoom.title = "Toggle zoomed view";
modalControls.appendChild(modalZoom)
const modalTileImage = document.createElement('span')
modalTileImage.className = 'modalTileImage cursor';
modalTileImage.innerHTML = '&#8862;'
modalTileImage.addEventListener('click', modalTileImageToggle, true)
modalTileImage.title = "Preview tiling";
modalControls.appendChild(modalTileImage)
const modalClose = document.createElement('span')
modalClose.className = 'modalClose cursor';
modalClose.innerHTML = '&times;'
modalClose.onclick = closeModal;
modalClose.title = "Close image viewer";
modalControls.appendChild(modalClose)
const modalImage = document.createElement('img')
modalImage.id = 'modalImage';
modalImage.onclick = closeModal;
modalImage.tabIndex=0
modalImage.addEventListener('keydown', modalKeyHandler, true)
modal.appendChild(modalImage)
const modalPrev = document.createElement('a')
modalPrev.className = 'modalPrev';
modalPrev.innerHTML = '&#10094;'
modalPrev.tabIndex=0
modalPrev.addEventListener('click',modalPrevImage,true);
modalPrev.addEventListener('keydown', modalKeyHandler, true)
modal.appendChild(modalPrev)
const modalNext = document.createElement('a')
modalNext.className = 'modalNext';
modalNext.innerHTML = '&#10095;'
modalNext.tabIndex=0
modalNext.addEventListener('click',modalNextImage,true);
modalNext.addEventListener('keydown', modalKeyHandler, true)
modal.appendChild(modalNext)
gradioApp().getRootNode().appendChild(modal)
document.body.appendChild(modalFragment);
});
+49
View File
@@ -0,0 +1,49 @@
// Monitors the gallery and sends a browser notification when the leading image is new.
let lastHeadImg = null;
notificationButton = null
onUiUpdate(function(){
if(notificationButton == null){
notificationButton = gradioApp().getElementById('request_notifications')
if(notificationButton != null){
notificationButton.addEventListener('click', function (evt) {
Notification.requestPermission();
},true);
}
}
const galleryPreviews = gradioApp().querySelectorAll('img.h-full.w-full.overflow-hidden');
if (galleryPreviews == null) return;
const headImg = galleryPreviews[0]?.src;
if (headImg == null || headImg == lastHeadImg) return;
lastHeadImg = headImg;
// play notification sound if available
gradioApp().querySelector('#audio_notification audio')?.play();
if (document.hasFocus()) return;
// Multiple copies of the images are in the DOM when one is selected. Dedup with a Set to get the real number generated.
const imgs = new Set(Array.from(galleryPreviews).map(img => img.src));
const notification = new Notification(
'Stable Diffusion',
{
body: `Generated ${imgs.size > 1 ? imgs.size - 1 : 1} image${imgs.size > 1 ? 's' : ''}`,
icon: headImg,
image: headImg,
}
);
notification.onclick = function(_){
parent.focus();
this.close();
};
});
+68
View File
@@ -0,0 +1,68 @@
// code related to showing and updating progressbar shown as the image is being made
global_progressbars = {}
function check_progressbar(id_part, id_progressbar, id_progressbar_span, id_interrupt, id_preview, id_gallery){
var progressbar = gradioApp().getElementById(id_progressbar)
var interrupt = gradioApp().getElementById(id_interrupt)
if(progressbar && progressbar.offsetParent){
if(progressbar.innerText){
let newtitle = 'Stable Diffusion - ' + progressbar.innerText
if(document.title != newtitle){
document.title = newtitle;
}
}else{
let newtitle = 'Stable Diffusion'
if(document.title != newtitle){
document.title = newtitle;
}
}
}
if(progressbar!= null && progressbar != global_progressbars[id_progressbar]){
global_progressbars[id_progressbar] = progressbar
var mutationObserver = new MutationObserver(function(m){
preview = gradioApp().getElementById(id_preview)
gallery = gradioApp().getElementById(id_gallery)
if(preview != null && gallery != null){
preview.style.width = gallery.clientWidth + "px"
preview.style.height = gallery.clientHeight + "px"
var progressDiv = gradioApp().querySelectorAll('#' + id_progressbar_span).length > 0;
if(!progressDiv){
interrupt.style.display = "none"
}
}
window.setTimeout(function(){ requestMoreProgress(id_part, id_progressbar_span, id_interrupt) }, 500)
});
mutationObserver.observe( progressbar, { childList:true, subtree:true })
}
}
onUiUpdate(function(){
check_progressbar('txt2img', 'txt2img_progressbar', 'txt2img_progress_span', 'txt2img_interrupt', 'txt2img_preview', 'txt2img_gallery')
check_progressbar('img2img', 'img2img_progressbar', 'img2img_progress_span', 'img2img_interrupt', 'img2img_preview', 'img2img_gallery')
check_progressbar('ti', 'ti_progressbar', 'ti_progress_span', 'ti_interrupt', 'ti_preview', 'ti_gallery')
})
function requestMoreProgress(id_part, id_progressbar_span, id_interrupt){
btn = gradioApp().getElementById(id_part+"_check_progress");
if(btn==null) return;
btn.click();
var progressDiv = gradioApp().querySelectorAll('#' + id_progressbar_span).length > 0;
var interrupt = gradioApp().getElementById(id_interrupt)
if(progressDiv && interrupt){
interrupt.style.display = "block"
}
}
function requestProgress(id_part){
btn = gradioApp().getElementById(id_part+"_check_progress_initial");
if(btn==null) return;
btn.click();
}
+8
View File
@@ -0,0 +1,8 @@
function start_training_textual_inversion(){
requestProgress('ti')
gradioApp().querySelector('#ti_error').innerHTML=''
return args_to_array(arguments)
}
+233
View File
@@ -0,0 +1,233 @@
// various functions for interation with ui.py not large enough to warrant putting them in separate files
function selected_gallery_index(){
var buttons = gradioApp().querySelectorAll('[style="display: block;"].tabitem .gallery-item')
var button = gradioApp().querySelector('[style="display: block;"].tabitem .gallery-item.\\!ring-2')
var result = -1
buttons.forEach(function(v, i){ if(v==button) { result = i } })
return result
}
function extract_image_from_gallery(gallery){
if(gallery.length == 1){
return gallery[0]
}
index = selected_gallery_index()
if (index < 0 || index >= gallery.length){
return [null]
}
return gallery[index];
}
function args_to_array(args){
res = []
for(var i=0;i<args.length;i++){
res.push(args[i])
}
return res
}
function switch_to_txt2img(){
gradioApp().querySelectorAll('button')[0].click();
return args_to_array(arguments);
}
function switch_to_img2img_img2img(){
gradioApp().querySelectorAll('button')[1].click();
gradioApp().getElementById('mode_img2img').querySelectorAll('button')[0].click();
return args_to_array(arguments);
}
function switch_to_img2img_inpaint(){
gradioApp().querySelectorAll('button')[1].click();
gradioApp().getElementById('mode_img2img').querySelectorAll('button')[1].click();
return args_to_array(arguments);
}
function switch_to_extras(){
gradioApp().querySelectorAll('button')[2].click();
return args_to_array(arguments);
}
function extract_image_from_gallery_txt2img(gallery){
switch_to_txt2img()
return extract_image_from_gallery(gallery);
}
function extract_image_from_gallery_img2img(gallery){
switch_to_img2img_img2img()
return extract_image_from_gallery(gallery);
}
function extract_image_from_gallery_inpaint(gallery){
switch_to_img2img_inpaint()
return extract_image_from_gallery(gallery);
}
function extract_image_from_gallery_extras(gallery){
switch_to_extras()
return extract_image_from_gallery(gallery);
}
function get_tab_index(tabId){
var res = 0
gradioApp().getElementById(tabId).querySelector('div').querySelectorAll('button').forEach(function(button, i){
if(button.className.indexOf('bg-white') != -1)
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])
}
res[0] = get_tab_index(tabId)
return res
}
function get_extras_tab_index(){
return create_tab_index_args('mode_extras', arguments)
}
function create_submit_args(args){
res = []
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.
// 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 seding 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(Array.isArray(res[res.length - 3])){
res[res.length - 3] = null
}
return res
}
function submit(){
requestProgress('txt2img')
return create_submit_args(arguments)
}
function submit_img2img(){
requestProgress('img2img')
res = create_submit_args(arguments)
res[0] = get_tab_index('mode_img2img')
return res
}
function ask_for_style_name(_, prompt_text, negative_prompt_text) {
name_ = prompt('Style name:')
return name_ === null ? [null, null, null]: [name_, prompt_text, negative_prompt_text]
}
opts = {}
function apply_settings(jsdata){
console.log(jsdata)
opts = JSON.parse(jsdata)
return jsdata
}
onUiUpdate(function(){
if(Object.keys(opts).length != 0) return;
json_elem = gradioApp().getElementById('settings_json')
if(json_elem == null) return;
textarea = json_elem.querySelector('textarea')
jsdata = textarea.value
opts = JSON.parse(jsdata)
Object.defineProperty(textarea, 'value', {
set: function(newValue) {
var valueProp = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value');
var oldValue = valueProp.get.call(textarea);
valueProp.set.call(textarea, newValue);
if (oldValue != newValue) {
opts = JSON.parse(textarea.value)
}
},
get: function() {
var valueProp = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value');
return valueProp.get.call(textarea);
}
});
json_elem.parentElement.style.display="none"
if (!txt2img_textarea) {
txt2img_textarea = gradioApp().querySelector("#txt2img_prompt > label > textarea");
txt2img_textarea?.addEventListener("input", () => update_token_counter("txt2img_token_button"));
txt2img_textarea?.addEventListener("keyup", (event) => submit_prompt(event, "txt2img_generate"));
}
if (!img2img_textarea) {
img2img_textarea = gradioApp().querySelector("#img2img_prompt > label > textarea");
img2img_textarea?.addEventListener("input", () => update_token_counter("img2img_token_button"));
img2img_textarea?.addEventListener("keyup", (event) => submit_prompt(event, "img2img_generate"));
}
})
let txt2img_textarea, img2img_textarea = undefined;
let wait_time = 800
let token_timeout;
function update_txt2img_tokens(...args) {
update_token_counter("txt2img_token_button")
if (args.length == 2)
return args[0]
return args;
}
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_timeout)
clearTimeout(token_timeout);
token_timeout = setTimeout(() => gradioApp().getElementById(button_id)?.click(), wait_time);
}
function submit_prompt(event, generate_button_id) {
if (event.altKey && event.keyCode === 13) {
event.preventDefault();
gradioApp().getElementById(generate_button_id).click();
return;
}
}
function restart_reload(){
document.body.innerHTML='<h1 style="font-family:monospace;margin-top:20%;color:lightgray;text-align:center;">Reloading...</h1>';
setTimeout(function(){location.reload()},2000)
}
+152
View File
@@ -0,0 +1,152 @@
# this scripts installs necessary requirements and launches main program in webui.py
import subprocess
import os
import sys
import importlib.util
import shlex
dir_repos = "repositories"
dir_tmp = "tmp"
python = sys.executable
git = os.environ.get('GIT', "git")
torch_command = os.environ.get('TORCH_COMMAND', "pip install torch==1.12.1+cu113 torchvision==0.13.1+cu113 --extra-index-url https://download.pytorch.org/whl/cu113")
requirements_file = os.environ.get('REQS_FILE', "requirements_versions.txt")
commandline_args = os.environ.get('COMMANDLINE_ARGS', "")
gfpgan_package = os.environ.get('GFPGAN_PACKAGE', "git+https://github.com/TencentARC/GFPGAN.git@8d2447a2d918f8eba5a4a01463fd48e45126a379")
clip_package = os.environ.get('CLIP_PACKAGE', "git+https://github.com/openai/CLIP.git@d50d76daa670286dd6cacf3bcd80b5e4823fc8e1")
stable_diffusion_commit_hash = os.environ.get('STABLE_DIFFUSION_COMMIT_HASH', "69ae4b35e0a0f6ee1af8bb9a5d0016ccb27e36dc")
taming_transformers_commit_hash = os.environ.get('TAMING_TRANSFORMERS_COMMIT_HASH', "24268930bf1dce879235a7fddd0b2355b84d7ea6")
k_diffusion_commit_hash = os.environ.get('K_DIFFUSION_COMMIT_HASH', "f4e99857772fc3a126ba886aadf795a332774878")
codeformer_commit_hash = os.environ.get('CODEFORMER_COMMIT_HASH', "c5b4593074ba6214284d6acd5f1719b6c5d739af")
blip_commit_hash = os.environ.get('BLIP_COMMIT_HASH', "48211a1594f1321b00f14c9f7a5b4813144b2fb9")
args = shlex.split(commandline_args)
def extract_arg(args, name):
return [x for x in args if x != name], name in args
args, skip_torch_cuda_test = extract_arg(args, '--skip-torch-cuda-test')
def repo_dir(name):
return os.path.join(dir_repos, name)
def run(command, desc=None, errdesc=None):
if desc is not None:
print(desc)
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
if result.returncode != 0:
message = f"""{errdesc or 'Error running command'}.
Command: {command}
Error code: {result.returncode}
stdout: {result.stdout.decode(encoding="utf8", errors="ignore") if len(result.stdout)>0 else '<empty>'}
stderr: {result.stderr.decode(encoding="utf8", errors="ignore") if len(result.stderr)>0 else '<empty>'}
"""
raise RuntimeError(message)
return result.stdout.decode(encoding="utf8", errors="ignore")
def run_python(code, desc=None, errdesc=None):
return run(f'"{python}" -c "{code}"', desc, errdesc)
def run_pip(args, desc=None):
return run(f'"{python}" -m pip {args} --prefer-binary', desc=f"Installing {desc}", errdesc=f"Couldn't install {desc}")
def check_run(command):
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
return result.returncode == 0
def check_run_python(code):
return check_run(f'"{python}" -c "{code}"')
def is_installed(package):
try:
spec = importlib.util.find_spec(package)
except ModuleNotFoundError:
return False
return spec is not None
def git_clone(url, dir, name, commithash=None):
# TODO clone into temporary dir and move if successful
if os.path.exists(dir):
if commithash is None:
return
current_hash = run(f'"{git}" -C {dir} rev-parse HEAD', None, "Couldn't determine {name}'s hash: {commithash}").strip()
if current_hash == commithash:
return
run(f'"{git}" -C {dir} fetch', f"Fetching updates for {name}...", f"Couldn't fetch {name}")
run(f'"{git}" -C {dir} checkout {commithash}', f"Checking out commint for {name} with hash: {commithash}...", f"Couldn't checkout commit {commithash} for {name}")
return
run(f'"{git}" clone "{url}" "{dir}"', f"Cloning {name} into {dir}...", f"Couldn't clone {name}")
if commithash is not None:
run(f'"{git}" -C {dir} checkout {commithash}', None, "Couldn't checkout {name}'s hash: {commithash}")
try:
commit = run(f"{git} rev-parse HEAD").strip()
except Exception:
commit = "<none>"
print(f"Python {sys.version}")
print(f"Commit hash: {commit}")
if not is_installed("torch") or not is_installed("torchvision"):
run(f'"{python}" -m {torch_command}', "Installing torch and torchvision", "Couldn't install torch")
if not skip_torch_cuda_test:
run_python("import torch; assert torch.cuda.is_available(), 'Torch is not able to use GPU; add --skip-torch-cuda-test to COMMANDLINE_ARGS variable to disable this check'")
if not is_installed("gfpgan"):
run_pip(f"install {gfpgan_package}", "gfpgan")
if not is_installed("clip"):
run_pip(f"install {clip_package}", "clip")
os.makedirs(dir_repos, exist_ok=True)
git_clone("https://github.com/CompVis/stable-diffusion.git", repo_dir('stable-diffusion'), "Stable Diffusion", stable_diffusion_commit_hash)
git_clone("https://github.com/CompVis/taming-transformers.git", repo_dir('taming-transformers'), "Taming Transformers", taming_transformers_commit_hash)
git_clone("https://github.com/crowsonkb/k-diffusion.git", repo_dir('k-diffusion'), "K-diffusion", k_diffusion_commit_hash)
git_clone("https://github.com/sczhou/CodeFormer.git", repo_dir('CodeFormer'), "CodeFormer", codeformer_commit_hash)
git_clone("https://github.com/salesforce/BLIP.git", repo_dir('BLIP'), "BLIP", blip_commit_hash)
if not is_installed("lpips"):
run_pip(f"install -r {os.path.join(repo_dir('CodeFormer'), 'requirements.txt')}", "requirements for CodeFormer")
run_pip(f"install -r {requirements_file}", "requirements for Web UI")
sys.argv += args
if "--exit" in args:
print("Exiting because of --exit argument")
exit(0)
def start_webui():
print(f"Launching Web UI with arguments: {' '.join(sys.argv[1:])}")
import webui
webui.webui()
if __name__ == "__main__":
start_webui()
Whitespace-only changes.
+78
View File
@@ -0,0 +1,78 @@
import os.path
import sys
import traceback
import PIL.Image
import numpy as np
import torch
from basicsr.utils.download_util import load_file_from_url
import modules.upscaler
from modules import devices, modelloader
from modules.bsrgan_model_arch import RRDBNet
from modules.paths import models_path
class UpscalerBSRGAN(modules.upscaler.Upscaler):
def __init__(self, dirname):
self.name = "BSRGAN"
self.model_path = os.path.join(models_path, self.name)
self.model_name = "BSRGAN 4x"
self.model_url = "https://github.com/cszn/KAIR/releases/download/v1.0/BSRGAN.pth"
self.user_path = dirname
super().__init__()
model_paths = self.find_models(ext_filter=[".pt", ".pth"])
scalers = []
if len(model_paths) == 0:
scaler_data = modules.upscaler.UpscalerData(self.model_name, self.model_url, self, 4)
scalers.append(scaler_data)
for file in model_paths:
if "http" in file:
name = self.model_name
else:
name = modelloader.friendly_name(file)
try:
scaler_data = modules.upscaler.UpscalerData(name, file, self, 4)
scalers.append(scaler_data)
except Exception:
print(f"Error loading BSRGAN model: {file}", file=sys.stderr)
print(traceback.format_exc(), file=sys.stderr)
self.scalers = scalers
def do_upscale(self, img: PIL.Image, selected_file):
torch.cuda.empty_cache()
model = self.load_model(selected_file)
if model is None:
return img
model.to(devices.device_bsrgan)
torch.cuda.empty_cache()
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(devices.device_bsrgan)
with torch.no_grad():
output = model(img)
output = output.squeeze().float().cpu().clamp_(0, 1).numpy()
output = 255. * np.moveaxis(output, 0, 2)
output = output.astype(np.uint8)
output = output[:, :, ::-1]
torch.cuda.empty_cache()
return PIL.Image.fromarray(output, 'RGB')
def load_model(self, path: str):
if "http" in path:
filename = load_file_from_url(url=self.model_url, model_dir=self.model_path, file_name="%s.pth" % self.name,
progress=True)
else:
filename = path
if not os.path.exists(filename) or filename is None:
print(f"BSRGAN: Unable to load model from {filename}", file=sys.stderr)
return None
model = RRDBNet(in_nc=3, out_nc=3, nf=64, nb=23, gc=32, sf=4) # define network
model.load_state_dict(torch.load(filename), strict=True)
model.eval()
for k, v in model.named_parameters():
v.requires_grad = False
return model
+102
View File
@@ -0,0 +1,102 @@
import functools
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
def initialize_weights(net_l, scale=1):
if not isinstance(net_l, list):
net_l = [net_l]
for net in net_l:
for m in net.modules():
if isinstance(m, nn.Conv2d):
init.kaiming_normal_(m.weight, a=0, mode='fan_in')
m.weight.data *= scale # for residual block
if m.bias is not None:
m.bias.data.zero_()
elif isinstance(m, nn.Linear):
init.kaiming_normal_(m.weight, a=0, mode='fan_in')
m.weight.data *= scale
if m.bias is not None:
m.bias.data.zero_()
elif isinstance(m, nn.BatchNorm2d):
init.constant_(m.weight, 1)
init.constant_(m.bias.data, 0.0)
def make_layer(block, n_layers):
layers = []
for _ in range(n_layers):
layers.append(block())
return nn.Sequential(*layers)
class ResidualDenseBlock_5C(nn.Module):
def __init__(self, nf=64, gc=32, bias=True):
super(ResidualDenseBlock_5C, self).__init__()
# gc: growth channel, i.e. intermediate channels
self.conv1 = nn.Conv2d(nf, gc, 3, 1, 1, bias=bias)
self.conv2 = nn.Conv2d(nf + gc, gc, 3, 1, 1, bias=bias)
self.conv3 = nn.Conv2d(nf + 2 * gc, gc, 3, 1, 1, bias=bias)
self.conv4 = nn.Conv2d(nf + 3 * gc, gc, 3, 1, 1, bias=bias)
self.conv5 = nn.Conv2d(nf + 4 * gc, nf, 3, 1, 1, bias=bias)
self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
# initialization
initialize_weights([self.conv1, self.conv2, self.conv3, self.conv4, self.conv5], 0.1)
def forward(self, x):
x1 = self.lrelu(self.conv1(x))
x2 = self.lrelu(self.conv2(torch.cat((x, x1), 1)))
x3 = self.lrelu(self.conv3(torch.cat((x, x1, x2), 1)))
x4 = self.lrelu(self.conv4(torch.cat((x, x1, x2, x3), 1)))
x5 = self.conv5(torch.cat((x, x1, x2, x3, x4), 1))
return x5 * 0.2 + x
class RRDB(nn.Module):
'''Residual in Residual Dense Block'''
def __init__(self, nf, gc=32):
super(RRDB, self).__init__()
self.RDB1 = ResidualDenseBlock_5C(nf, gc)
self.RDB2 = ResidualDenseBlock_5C(nf, gc)
self.RDB3 = ResidualDenseBlock_5C(nf, gc)
def forward(self, x):
out = self.RDB1(x)
out = self.RDB2(out)
out = self.RDB3(out)
return out * 0.2 + x
class RRDBNet(nn.Module):
def __init__(self, in_nc=3, out_nc=3, nf=64, nb=23, gc=32, sf=4):
super(RRDBNet, self).__init__()
RRDB_block_f = functools.partial(RRDB, nf=nf, gc=gc)
self.sf = sf
self.conv_first = nn.Conv2d(in_nc, nf, 3, 1, 1, bias=True)
self.RRDB_trunk = make_layer(RRDB_block_f, nb)
self.trunk_conv = nn.Conv2d(nf, nf, 3, 1, 1, bias=True)
#### upsampling
self.upconv1 = nn.Conv2d(nf, nf, 3, 1, 1, bias=True)
if self.sf==4:
self.upconv2 = nn.Conv2d(nf, nf, 3, 1, 1, bias=True)
self.HRconv = nn.Conv2d(nf, nf, 3, 1, 1, bias=True)
self.conv_last = nn.Conv2d(nf, out_nc, 3, 1, 1, bias=True)
self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
def forward(self, x):
fea = self.conv_first(x)
trunk = self.trunk_conv(self.RRDB_trunk(fea))
fea = fea + trunk
fea = self.lrelu(self.upconv1(F.interpolate(fea, scale_factor=2, mode='nearest')))
if self.sf==4:
fea = self.lrelu(self.upconv2(F.interpolate(fea, scale_factor=2, mode='nearest')))
out = self.conv_last(self.lrelu(self.HRconv(fea)))
return out
+60 -32
View File
@@ -1,33 +1,35 @@
import os import os
import sys import sys
import traceback import traceback
import cv2
import torch import torch
from modules import shared
from modules.paths import script_path
import modules.shared
import modules.face_restoration import modules.face_restoration
from importlib import reload import modules.shared
from modules import shared, devices, modelloader
from modules.paths import script_path, models_path
# codeformer people made a choice to include modified basicsr librry to their projectwhich makes # codeformer people made a choice to include modified basicsr library to their project which makes
# it utterly impossiblr to use it alongside with other libraries that also use basicsr, like GFPGAN. # it utterly impossible to use it alongside with other libraries that also use basicsr, like GFPGAN.
# I am making a choice to include some files from codeformer to work around this issue. # I am making a choice to include some files from codeformer to work around this issue.
model_dir = "Codeformer"
pretrain_model_url = 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth' model_path = os.path.join(models_path, model_dir)
model_url = 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth'
have_codeformer = False have_codeformer = False
codeformer = None codeformer = None
def setup_codeformer():
def setup_model(dirname):
global model_path
if not os.path.exists(model_path):
os.makedirs(model_path)
path = modules.paths.paths.get("CodeFormer", None) path = modules.paths.paths.get("CodeFormer", None)
if path is None: if path is None:
return return
# both GFPGAN and CodeFormer use bascisr, one has it installed from pip the other uses its own
#stored_sys_path = sys.path
#sys.path = [path] + sys.path
try: try:
from torchvision.transforms.functional import normalize from torchvision.transforms.functional import normalize
from modules.codeformer.codeformer_arch import CodeFormer from modules.codeformer.codeformer_arch import CodeFormer
@@ -42,46 +44,63 @@ def setup_codeformer():
def name(self): def name(self):
return "CodeFormer" return "CodeFormer"
def __init__(self): def __init__(self, dirname):
self.net = None self.net = None
self.face_helper = None self.face_helper = None
self.cmd_dir = dirname
def create_models(self): def create_models(self):
if self.net is not None and self.face_helper is not None: if self.net is not None and self.face_helper is not None:
self.net.to(devices.device_codeformer)
return self.net, self.face_helper return self.net, self.face_helper
model_paths = modelloader.load_models(model_path, model_url, self.cmd_dir, download_name='codeformer-v0.1.0.pth')
net = net_class(dim_embd=512, codebook_size=1024, n_head=8, n_layers=9, connect_list=['32', '64', '128', '256']).to(shared.device) if len(model_paths) != 0:
ckpt_path = load_file_from_url(url=pretrain_model_url, model_dir=os.path.join(path, 'weights/CodeFormer'), progress=True) ckpt_path = model_paths[0]
else:
print("Unable to load codeformer model.")
return None, None
net = net_class(dim_embd=512, codebook_size=1024, n_head=8, n_layers=9, connect_list=['32', '64', '128', '256']).to(devices.device_codeformer)
checkpoint = torch.load(ckpt_path)['params_ema'] checkpoint = torch.load(ckpt_path)['params_ema']
net.load_state_dict(checkpoint) net.load_state_dict(checkpoint)
net.eval() net.eval()
face_helper = FaceRestoreHelper(1, face_size=512, crop_ratio=(1, 1), det_model='retinaface_resnet50', save_ext='png', use_parse=True, device=shared.device) face_helper = FaceRestoreHelper(1, face_size=512, crop_ratio=(1, 1), det_model='retinaface_resnet50', save_ext='png', use_parse=True, device=devices.device_codeformer)
if not cmd_opts.unload_gfpgan:
self.net = net self.net = net
self.face_helper = face_helper self.face_helper = face_helper
return net, face_helper return net, face_helper
def send_model_to(self, device):
self.net.to(device)
self.face_helper.face_det.to(device)
self.face_helper.face_parse.to(device)
def restore(self, np_image, w=None): def restore(self, np_image, w=None):
np_image = np_image[:, :, ::-1] np_image = np_image[:, :, ::-1]
net, face_helper = self.create_models() original_resolution = np_image.shape[0:2]
face_helper.clean_all()
face_helper.read_image(np_image)
face_helper.get_face_landmarks_5(only_center_face=False, resize=640, eye_dist_threshold=5)
face_helper.align_warp_face()
for idx, cropped_face in enumerate(face_helper.cropped_faces): self.create_models()
if self.net is None or self.face_helper is None:
return np_image
self.send_model_to(devices.device_codeformer)
self.face_helper.clean_all()
self.face_helper.read_image(np_image)
self.face_helper.get_face_landmarks_5(only_center_face=False, resize=640, eye_dist_threshold=5)
self.face_helper.align_warp_face()
for idx, cropped_face in enumerate(self.face_helper.cropped_faces):
cropped_face_t = img2tensor(cropped_face / 255., bgr2rgb=True, float32=True) cropped_face_t = img2tensor(cropped_face / 255., bgr2rgb=True, float32=True)
normalize(cropped_face_t, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True) normalize(cropped_face_t, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)
cropped_face_t = cropped_face_t.unsqueeze(0).to(shared.device) cropped_face_t = cropped_face_t.unsqueeze(0).to(devices.device_codeformer)
try: try:
with torch.no_grad(): with torch.no_grad():
output = net(cropped_face_t, w=w if w is not None else shared.opts.code_former_weight, adain=True)[0] output = self.net(cropped_face_t, w=w if w is not None else shared.opts.code_former_weight, adain=True)[0]
restored_face = tensor2img(output, rgb2bgr=True, min_max=(-1, 1)) restored_face = tensor2img(output, rgb2bgr=True, min_max=(-1, 1))
del output del output
torch.cuda.empty_cache() torch.cuda.empty_cache()
@@ -90,19 +109,28 @@ def setup_codeformer():
restored_face = tensor2img(cropped_face_t, rgb2bgr=True, min_max=(-1, 1)) restored_face = tensor2img(cropped_face_t, rgb2bgr=True, min_max=(-1, 1))
restored_face = restored_face.astype('uint8') restored_face = restored_face.astype('uint8')
face_helper.add_restored_face(restored_face) self.face_helper.add_restored_face(restored_face)
face_helper.get_inverse_affine(None) self.face_helper.get_inverse_affine(None)
restored_img = face_helper.paste_faces_to_input_image() restored_img = self.face_helper.paste_faces_to_input_image()
restored_img = restored_img[:, :, ::-1] restored_img = restored_img[:, :, ::-1]
if original_resolution != restored_img.shape[0:2]:
restored_img = cv2.resize(restored_img, (0, 0), fx=original_resolution[1]/restored_img.shape[1], fy=original_resolution[0]/restored_img.shape[0], interpolation=cv2.INTER_LINEAR)
self.face_helper.clean_all()
if shared.opts.face_restoration_unload:
self.send_model_to(devices.cpu)
return restored_img return restored_img
global have_codeformer global have_codeformer
have_codeformer = True have_codeformer = True
global codeformer global codeformer
codeformer = FaceRestorerCodeFormer() codeformer = FaceRestorerCodeFormer(dirname)
shared.face_restorers.append(codeformer) shared.face_restorers.append(codeformer)
except Exception: except Exception:
+68
View File
@@ -0,0 +1,68 @@
import contextlib
import torch
from modules import errors
# has_mps is only available in nightly pytorch (for now), `getattr` for compatibility
has_mps = getattr(torch, 'has_mps', False)
cpu = torch.device("cpu")
def get_optimal_device():
if torch.cuda.is_available():
return torch.device("cuda")
if has_mps:
return torch.device("mps")
return cpu
def torch_gc():
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
def enable_tf32():
if torch.cuda.is_available():
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
errors.run(enable_tf32, "Enabling TF32")
device = device_gfpgan = device_bsrgan = device_esrgan = device_scunet = device_codeformer = get_optimal_device()
dtype = torch.float16
def randn(seed, shape):
# Pytorch currently doesn't handle setting randomness correctly when the metal backend is used.
if device.type == 'mps':
generator = torch.Generator(device=cpu)
generator.manual_seed(seed)
noise = torch.randn(shape, generator=generator, device=cpu).to(device)
return noise
torch.manual_seed(seed)
return torch.randn(shape, device=device)
def randn_without_seed(shape):
# Pytorch currently doesn't handle setting randomness correctly when the metal backend is used.
if device.type == 'mps':
generator = torch.Generator(device=cpu)
noise = torch.randn(shape, generator=generator, device=cpu).to(device)
return noise
return torch.randn(shape, device=device)
def autocast():
from modules import shared
if dtype == torch.float32 or shared.cmd_opts.precision == "full":
return contextlib.nullcontext()
return torch.autocast("cuda")
+10
View File
@@ -0,0 +1,10 @@
import sys
import traceback
def run(code, task):
try:
code()
except Exception as e:
print(f"{task}: {type(e).__name__}", file=sys.stderr)
print(traceback.format_exc(), file=sys.stderr)
+68 -42
View File
@@ -1,26 +1,28 @@
import os import os
import sys
import traceback
import numpy as np 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
import modules.esrgam_model_arch as arch import modules.esrgam_model_arch as arch
from modules import shared from modules import shared, modelloader, images, devices
from modules.paths import models_path
from modules.upscaler import Upscaler, UpscalerData
from modules.shared import opts from modules.shared import opts
import modules.images
def load_model(filename): def fix_model_layers(crt_model, pretrained_net):
# this code is adapted from https://github.com/xinntao/ESRGAN # this code is adapted from https://github.com/xinntao/ESRGAN
pretrained_net = torch.load(filename)
crt_model = arch.RRDBNet(3, 3, 64, 23, gc=32)
if 'conv_first.weight' in pretrained_net: if 'conv_first.weight' in pretrained_net:
crt_model.load_state_dict(pretrained_net) return pretrained_net
return crt_model
if 'model.0.weight' not in pretrained_net:
is_realesrgan = "params_ema" in pretrained_net and 'body.0.rdb1.conv1.weight' in pretrained_net["params_ema"]
if is_realesrgan:
raise Exception("The file is a RealESRGAN model, it can't be used as a ESRGAN model.")
else:
raise Exception("The file is not a ESRGAN model.")
crt_net = crt_model.state_dict() crt_net = crt_model.state_dict()
load_net_clean = {} load_net_clean = {}
@@ -65,16 +67,66 @@ def load_model(filename):
crt_net['conv_last.weight'] = pretrained_net['model.10.weight'] crt_net['conv_last.weight'] = pretrained_net['model.10.weight']
crt_net['conv_last.bias'] = pretrained_net['model.10.bias'] crt_net['conv_last.bias'] = pretrained_net['model.10.bias']
crt_model.load_state_dict(crt_net) return crt_net
class UpscalerESRGAN(Upscaler):
def __init__(self, dirname):
self.name = "ESRGAN"
self.model_url = "https://github.com/cszn/KAIR/releases/download/v1.0/ESRGAN.pth"
self.model_name = "ESRGAN_4x"
self.scalers = []
self.user_path = dirname
self.model_path = os.path.join(models_path, self.name)
super().__init__()
model_paths = self.find_models(ext_filter=[".pt", ".pth"])
scalers = []
if len(model_paths) == 0:
scaler_data = UpscalerData(self.model_name, self.model_url, self, 4)
scalers.append(scaler_data)
for file in model_paths:
if "http" in file:
name = self.model_name
else:
name = modelloader.friendly_name(file)
scaler_data = UpscalerData(name, file, self, 4)
self.scalers.append(scaler_data)
def do_upscale(self, img, selected_model):
model = self.load_model(selected_model)
if model is None:
return img
model.to(devices.device_esrgan)
img = esrgan_upscale(model, img)
return img
def load_model(self, path: str):
if "http" in path:
filename = load_file_from_url(url=self.model_url, model_dir=self.model_path,
file_name="%s.pth" % self.model_name,
progress=True)
else:
filename = path
if not os.path.exists(filename) or filename is None:
print("Unable to load %s from %s" % (self.model_path, filename))
return None
pretrained_net = torch.load(filename, map_location='cpu' if shared.device.type == 'mps' else None)
crt_model = arch.RRDBNet(3, 3, 64, 23, gc=32)
pretrained_net = fix_model_layers(crt_model, pretrained_net)
crt_model.load_state_dict(pretrained_net)
crt_model.eval() crt_model.eval()
return crt_model return crt_model
def upscale_without_tiling(model, img): def upscale_without_tiling(model, img):
img = np.array(img) img = np.array(img)
img = img[:, :, ::-1] img = img[:, :, ::-1]
img = np.moveaxis(img, 2, 0) / 255 img = np.moveaxis(img, 2, 0) / 255
img = torch.from_numpy(img).float() img = torch.from_numpy(img).float()
img = img.unsqueeze(0).to(shared.device) img = img.unsqueeze(0).to(devices.device_esrgan)
with torch.no_grad(): with torch.no_grad():
output = model(img) output = model(img)
output = output.squeeze().float().cpu().clamp_(0, 1).numpy() output = output.squeeze().float().cpu().clamp_(0, 1).numpy()
@@ -88,7 +140,7 @@ def esrgan_upscale(model, img):
if opts.ESRGAN_tile == 0: if opts.ESRGAN_tile == 0:
return upscale_without_tiling(model, img) return upscale_without_tiling(model, img)
grid = modules.images.split_grid(img, opts.ESRGAN_tile, opts.ESRGAN_tile, opts.ESRGAN_tile_overlap) grid = images.split_grid(img, opts.ESRGAN_tile, opts.ESRGAN_tile, opts.ESRGAN_tile_overlap)
newtiles = [] newtiles = []
scale_factor = 1 scale_factor = 1
@@ -103,32 +155,6 @@ def esrgan_upscale(model, img):
newrow.append([x * scale_factor, w * scale_factor, output]) newrow.append([x * scale_factor, w * scale_factor, output])
newtiles.append([y * scale_factor, h * scale_factor, newrow]) newtiles.append([y * scale_factor, h * scale_factor, newrow])
newgrid = modules.images.Grid(newtiles, grid.tile_w * scale_factor, grid.tile_h * scale_factor, grid.image_w * scale_factor, grid.image_h * scale_factor, grid.overlap * scale_factor) newgrid = images.Grid(newtiles, grid.tile_w * scale_factor, grid.tile_h * scale_factor, grid.image_w * scale_factor, grid.image_h * scale_factor, grid.overlap * scale_factor)
output = modules.images.combine_grid(newgrid) output = images.combine_grid(newgrid)
return output return output
class UpscalerESRGAN(modules.images.Upscaler):
def __init__(self, filename, title):
self.name = title
self.model = load_model(filename)
def do_upscale(self, img):
model = self.model.to(shared.device)
img = esrgan_upscale(model, img)
return img
def load_models(dirname):
for file in os.listdir(dirname):
path = os.path.join(dirname, file)
model_name, extension = os.path.splitext(file)
if extension != '.pt' and extension != '.pth':
continue
try:
modules.shared.sd_upscalers.append(UpscalerESRGAN(path, model_name))
except Exception:
print(f"Error loading ESRGAN model: {path}", file=sys.stderr)
print(traceback.format_exc(), file=sys.stderr)
+206
View File
@@ -0,0 +1,206 @@
import os
import numpy as np
from PIL import Image
import torch
import tqdm
from modules import processing, shared, images, devices, sd_models
from modules.shared import opts
import modules.gfpgan_model
from modules.ui import plaintext_to_html
import modules.codeformer_model
import piexif
import piexif.helper
import gradio as gr
cached_images = {}
def run_extras(extras_mode, image, image_folder, gfpgan_visibility, codeformer_visibility, codeformer_weight, upscaling_resize, extras_upscaler_1, extras_upscaler_2, extras_upscaler_2_visibility):
devices.torch_gc()
imageArr = []
# Also keep track of original file names
imageNameArr = []
if extras_mode == 1:
#convert file to pillow image
for img in image_folder:
image = Image.fromarray(np.array(Image.open(img)))
imageArr.append(image)
imageNameArr.append(os.path.splitext(img.orig_name)[0])
else:
imageArr.append(image)
imageNameArr.append(None)
outpath = opts.outdir_samples or opts.outdir_extras_samples
outputs = []
for image, image_name in zip(imageArr, imageNameArr):
if image is None:
return outputs, "Please select an input image.", ''
existing_pnginfo = image.info or {}
image = image.convert("RGB")
info = ""
if gfpgan_visibility > 0:
restored_img = modules.gfpgan_model.gfpgan_fix_faces(np.array(image, dtype=np.uint8))
res = Image.fromarray(restored_img)
if gfpgan_visibility < 1.0:
res = Image.blend(image, res, gfpgan_visibility)
info += f"GFPGAN visibility:{round(gfpgan_visibility, 2)}\n"
image = res
if codeformer_visibility > 0:
restored_img = modules.codeformer_model.codeformer.restore(np.array(image, dtype=np.uint8), w=codeformer_weight)
res = Image.fromarray(restored_img)
if codeformer_visibility < 1.0:
res = Image.blend(image, res, codeformer_visibility)
info += f"CodeFormer w: {round(codeformer_weight, 2)}, CodeFormer visibility:{round(codeformer_visibility, 2)}\n"
image = res
if upscaling_resize != 1.0:
def upscale(image, scaler_index, resize):
small = image.crop((image.width // 2, image.height // 2, image.width // 2 + 10, image.height // 2 + 10))
pixels = tuple(np.array(small).flatten().tolist())
key = (resize, scaler_index, image.width, image.height, gfpgan_visibility, codeformer_visibility, codeformer_weight) + pixels
c = cached_images.get(key)
if c is None:
upscaler = shared.sd_upscalers[scaler_index]
c = upscaler.scaler.upscale(image, resize, upscaler.data_path)
cached_images[key] = c
return c
info += f"Upscale: {round(upscaling_resize, 3)}, model:{shared.sd_upscalers[extras_upscaler_1].name}\n"
res = upscale(image, extras_upscaler_1, upscaling_resize)
if extras_upscaler_2 != 0 and extras_upscaler_2_visibility > 0:
res2 = upscale(image, extras_upscaler_2, upscaling_resize)
info += f"Upscale: {round(upscaling_resize, 3)}, visibility: {round(extras_upscaler_2_visibility, 3)}, model:{shared.sd_upscalers[extras_upscaler_2].name}\n"
res = Image.blend(res, res2, extras_upscaler_2_visibility)
image = res
while len(cached_images) > 2:
del cached_images[next(iter(cached_images.keys()))]
images.save_image(image, path=outpath, basename="", seed=None, prompt=None, extension=opts.samples_format, info=info, short_filename=True,
no_prompt=True, grid=False, pnginfo_section_name="extras", existing_info=existing_pnginfo,
forced_filename=image_name if opts.use_original_name_batch else None)
outputs.append(image)
return outputs, plaintext_to_html(info), ''
def run_pnginfo(image):
if image is None:
return '', '', ''
items = image.info
geninfo = ''
if "exif" in image.info:
exif = piexif.load(image.info["exif"])
exif_comment = (exif or {}).get("Exif", {}).get(piexif.ExifIFD.UserComment, b'')
try:
exif_comment = piexif.helper.UserComment.load(exif_comment)
except ValueError:
exif_comment = exif_comment.decode('utf8', errors="ignore")
items['exif comment'] = exif_comment
geninfo = exif_comment
for field in ['jfif', 'jfif_version', 'jfif_unit', 'jfif_density', 'dpi', 'exif',
'loop', 'background', 'timestamp', 'duration']:
items.pop(field, None)
geninfo = items.get('parameters', geninfo)
info = ''
for key, text in items.items():
info += f"""
<div>
<p><b>{plaintext_to_html(str(key))}</b></p>
<p>{plaintext_to_html(str(text))}</p>
</div>
""".strip()+"\n"
if len(info) == 0:
message = "Nothing found in the image."
info = f"<div><p>{message}<p></div>"
return '', geninfo, info
def run_modelmerger(primary_model_name, secondary_model_name, interp_method, interp_amount, save_as_half, custom_name):
# Linear interpolation (https://en.wikipedia.org/wiki/Linear_interpolation)
def weighted_sum(theta0, theta1, alpha):
return ((1 - alpha) * theta0) + (alpha * theta1)
# Smoothstep (https://en.wikipedia.org/wiki/Smoothstep)
def sigmoid(theta0, theta1, alpha):
alpha = alpha * alpha * (3 - (2 * alpha))
return theta0 + ((theta1 - theta0) * alpha)
# Inverse Smoothstep (https://en.wikipedia.org/wiki/Smoothstep)
def inv_sigmoid(theta0, theta1, alpha):
import math
alpha = 0.5 - math.sin(math.asin(1.0 - 2.0 * alpha) / 3.0)
return theta0 + ((theta1 - theta0) * alpha)
primary_model_info = sd_models.checkpoints_list[primary_model_name]
secondary_model_info = sd_models.checkpoints_list[secondary_model_name]
print(f"Loading {primary_model_info.filename}...")
primary_model = torch.load(primary_model_info.filename, map_location='cpu')
print(f"Loading {secondary_model_info.filename}...")
secondary_model = torch.load(secondary_model_info.filename, map_location='cpu')
theta_0 = primary_model['state_dict']
theta_1 = secondary_model['state_dict']
theta_funcs = {
"Weighted Sum": weighted_sum,
"Sigmoid": sigmoid,
"Inverse Sigmoid": inv_sigmoid,
}
theta_func = theta_funcs[interp_method]
print(f"Merging...")
for key in tqdm.tqdm(theta_0.keys()):
if 'model' in key and key in theta_1:
theta_0[key] = theta_func(theta_0[key], theta_1[key], (float(1.0) - interp_amount)) # Need to reverse the interp_amount to match the desired mix ration in the merged checkpoint
if save_as_half:
theta_0[key] = theta_0[key].half()
for key in theta_1.keys():
if 'model' in key and key not in theta_0:
theta_0[key] = theta_1[key]
if save_as_half:
theta_0[key] = theta_0[key].half()
ckpt_dir = shared.cmd_opts.ckpt_dir or sd_models.model_path
filename = primary_model_info.model_name + '_' + str(round(interp_amount, 2)) + '-' + secondary_model_info.model_name + '_' + str(round((float(1.0) - interp_amount), 2)) + '-' + interp_method.replace(" ", "_") + '-merged.ckpt'
filename = filename if custom_name == '' else (custom_name + '.ckpt')
output_modelname = os.path.join(ckpt_dir, filename)
print(f"Saving to {output_modelname}...")
torch.save(primary_model, output_modelname)
sd_models.list_models()
print(f"Checkpoint saved.")
return ["Checkpoint saved to " + output_modelname] + [gr.Dropdown.update(choices=sd_models.checkpoint_tiles()) for _ in range(3)]
@@ -0,0 +1,92 @@
import re
import gradio as gr
re_param_code = r"\s*([\w ]+):\s*([^,]+)(?:,|$)"
re_param = re.compile(re_param_code)
re_params = re.compile(r"^(?:" + re_param_code + "){3,}$")
re_imagesize = re.compile(r"^(\d+)x(\d+)$")
type_of_gr_update = type(gr.update())
def parse_generation_parameters(x: str):
"""parses generation parameters string, the one you see in text field under the picture in UI:
```
girl with an artist's beret, determined, blue eyes, desert scene, computer monitors, heavy makeup, by Alphonse Mucha and Charlie Bowater, ((eyeshadow)), (coquettish), detailed, intricate
Negative prompt: ugly, fat, obese, chubby, (((deformed))), [blurry], bad anatomy, disfigured, poorly drawn face, mutation, mutated, (extra_limb), (ugly), (poorly drawn hands), messy drawing
Steps: 20, Sampler: Euler a, CFG scale: 7, Seed: 965400086, Size: 512x512, Model hash: 45dee52b
```
returns a dict with field values
"""
res = {}
prompt = ""
negative_prompt = ""
done_with_prompt = False
*lines, lastline = x.strip().split("\n")
if not re_params.match(lastline):
lines.append(lastline)
lastline = ''
for i, line in enumerate(lines):
line = line.strip()
if line.startswith("Negative prompt:"):
done_with_prompt = True
line = line[16:].strip()
if done_with_prompt:
negative_prompt += ("" if negative_prompt == "" else "\n") + line
else:
prompt += ("" if prompt == "" else "\n") + line
if len(prompt) > 0:
res["Prompt"] = prompt
if len(negative_prompt) > 0:
res["Negative prompt"] = negative_prompt
for k, v in re_param.findall(lastline):
m = re_imagesize.match(v)
if m is not None:
res[k+"-1"] = m.group(1)
res[k+"-2"] = m.group(2)
else:
res[k] = v
return res
def connect_paste(button, paste_fields, input_comp, js=None):
def paste_func(prompt):
params = parse_generation_parameters(prompt)
res = []
for output, key in paste_fields:
if callable(key):
v = key(params)
else:
v = params.get(key, None)
if v is None:
res.append(gr.update())
elif isinstance(v, type_of_gr_update):
res.append(v)
else:
try:
valtype = type(output.value)
val = valtype(v)
res.append(gr.update(value=val))
except Exception:
res.append(gr.update())
return res
button.click(
fn=paste_func,
_js=js,
inputs=[input_comp],
outputs=[x[0] for x in paste_fields],
)
+69 -37
View File
@@ -2,68 +2,104 @@ import os
import sys import sys
import traceback import traceback
from modules import shared import facexlib
from modules.shared import cmd_opts import gfpgan
from modules.paths import script_path
import modules.face_restoration import modules.face_restoration
from modules import shared, devices, modelloader
from modules.paths import models_path
model_dir = "GFPGAN"
def gfpgan_model_path(): user_path = None
from modules.shared import cmd_opts model_path = os.path.join(models_path, model_dir)
model_url = "https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth"
places = [script_path, '.', os.path.join(cmd_opts.gfpgan_dir, 'experiments/pretrained_models')] have_gfpgan = False
files = [cmd_opts.gfpgan_model] + [os.path.join(dirname, cmd_opts.gfpgan_model) for dirname in places]
found = [x for x in files if os.path.exists(x)]
if len(found) == 0:
raise Exception("GFPGAN model not found in paths: " + ", ".join(files))
return found[0]
loaded_gfpgan_model = None loaded_gfpgan_model = None
def gfpgan(): def gfpgann():
global loaded_gfpgan_model global loaded_gfpgan_model
global model_path
if loaded_gfpgan_model is not None: if loaded_gfpgan_model is not None:
loaded_gfpgan_model.gfpgan.to(devices.device_gfpgan)
return loaded_gfpgan_model return loaded_gfpgan_model
if gfpgan_constructor is None: if gfpgan_constructor is None:
return None return None
model = gfpgan_constructor(model_path=gfpgan_model_path(), upscale=1, arch='clean', channel_multiplier=2, bg_upsampler=None) models = modelloader.load_models(model_path, model_url, user_path, ext_filter="GFPGAN")
if len(models) == 1 and "http" in models[0]:
if not cmd_opts.unload_gfpgan: model_file = models[0]
elif len(models) != 0:
latest_file = max(models, key=os.path.getctime)
model_file = latest_file
else:
print("Unable to load gfpgan model!")
return None
model = gfpgan_constructor(model_path=model_file, upscale=1, arch='clean', channel_multiplier=2, bg_upsampler=None)
loaded_gfpgan_model = model loaded_gfpgan_model = model
return model return model
def send_model_to(model, device):
model.gfpgan.to(device)
model.face_helper.face_det.to(device)
model.face_helper.face_parse.to(device)
def gfpgan_fix_faces(np_image): def gfpgan_fix_faces(np_image):
model = gfpgann()
if model is None:
return np_image
send_model_to(model, devices.device_gfpgan)
np_image_bgr = np_image[:, :, ::-1] np_image_bgr = np_image[:, :, ::-1]
cropped_faces, restored_faces, gfpgan_output_bgr = gfpgan().enhance(np_image_bgr, has_aligned=False, only_center_face=False, paste_back=True) cropped_faces, restored_faces, gfpgan_output_bgr = model.enhance(np_image_bgr, has_aligned=False, only_center_face=False, paste_back=True)
np_image = gfpgan_output_bgr[:, :, ::-1] np_image = gfpgan_output_bgr[:, :, ::-1]
model.face_helper.clean_all()
if shared.opts.face_restoration_unload:
send_model_to(model, devices.cpu)
return np_image return np_image
have_gfpgan = False
gfpgan_constructor = None gfpgan_constructor = None
def setup_gfpgan():
def setup_model(dirname):
global model_path
if not os.path.exists(model_path):
os.makedirs(model_path)
try: try:
gfpgan_model_path()
if os.path.exists(cmd_opts.gfpgan_dir):
sys.path.append(os.path.abspath(cmd_opts.gfpgan_dir))
from gfpgan import GFPGANer from gfpgan import GFPGANer
from facexlib import detection, parsing
global user_path
global have_gfpgan global have_gfpgan
have_gfpgan = True
global gfpgan_constructor global gfpgan_constructor
load_file_from_url_orig = gfpgan.utils.load_file_from_url
facex_load_file_from_url_orig = facexlib.detection.load_file_from_url
facex_load_file_from_url_orig2 = facexlib.parsing.load_file_from_url
def my_load_file_from_url(**kwargs):
return load_file_from_url_orig(**dict(kwargs, model_dir=model_path))
def facex_load_file_from_url(**kwargs):
return facex_load_file_from_url_orig(**dict(kwargs, save_dir=model_path, model_dir=None))
def facex_load_file_from_url2(**kwargs):
return facex_load_file_from_url_orig2(**dict(kwargs, save_dir=model_path, model_dir=None))
gfpgan.utils.load_file_from_url = my_load_file_from_url
facexlib.detection.load_file_from_url = facex_load_file_from_url
facexlib.parsing.load_file_from_url = facex_load_file_from_url2
user_path = dirname
have_gfpgan = True
gfpgan_constructor = GFPGANer gfpgan_constructor = GFPGANer
class FaceRestorerGFPGAN(modules.face_restoration.FaceRestoration): class FaceRestorerGFPGAN(modules.face_restoration.FaceRestoration):
@@ -71,11 +107,7 @@ def setup_gfpgan():
return "GFPGAN" return "GFPGAN"
def restore(self, np_image): def restore(self, np_image):
np_image_bgr = np_image[:, :, ::-1] return gfpgan_fix_faces(np_image)
cropped_faces, restored_faces, gfpgan_output_bgr = gfpgan().enhance(np_image_bgr, has_aligned=False, only_center_face=False, paste_back=True)
np_image = gfpgan_output_bgr[:, :, ::-1]
return np_image
shared.face_restorers.append(FaceRestorerGFPGAN()) shared.face_restorers.append(FaceRestorerGFPGAN())
except Exception: except Exception:
+165 -54
View File
@@ -1,13 +1,18 @@
import datetime
import math import math
import os import os
from collections import namedtuple from collections import namedtuple
import re import re
import numpy as np import numpy as np
import piexif
import piexif.helper
from PIL import Image, ImageFont, ImageDraw, PngImagePlugin from PIL import Image, ImageFont, ImageDraw, PngImagePlugin
from fonts.ttf import Roboto
import string
import modules.shared from modules import sd_samplers, shared
from modules.shared import opts from modules.shared import opts, cmd_opts
LANCZOS = (Image.Resampling.LANCZOS if hasattr(Image, 'Resampling') else Image.LANCZOS) LANCZOS = (Image.Resampling.LANCZOS if hasattr(Image, 'Resampling') else Image.LANCZOS)
@@ -46,8 +51,8 @@ def split_grid(image, tile_w=512, tile_h=512, overlap=64):
cols = math.ceil((w - overlap) / non_overlap_width) cols = math.ceil((w - overlap) / non_overlap_width)
rows = math.ceil((h - overlap) / non_overlap_height) rows = math.ceil((h - overlap) / non_overlap_height)
dx = (w - tile_w) / (cols-1) if cols > 1 else 0 dx = (w - tile_w) / (cols - 1) if cols > 1 else 0
dy = (h - tile_h) / (rows-1) if rows > 1 else 0 dy = (h - tile_h) / (rows - 1) if rows > 1 else 0
grid = Grid([], tile_w, tile_h, w, h, overlap) grid = Grid([], tile_w, tile_h, w, h, overlap)
for row in range(rows): for row in range(rows):
@@ -61,7 +66,7 @@ def split_grid(image, tile_w=512, tile_h=512, overlap=64):
for col in range(cols): for col in range(cols):
x = int(col * dx) x = int(col * dx)
if x+tile_w >= w: if x + tile_w >= w:
x = w - tile_w x = w - tile_w
tile = image.crop((x, y, x + tile_w, y + tile_h)) tile = image.crop((x, y, x + tile_w, y + tile_h))
@@ -126,17 +131,22 @@ def draw_grid_annotations(im, width, height, hor_texts, ver_texts):
drawing.multiline_text((draw_x, draw_y + line.size[1] / 2), line.text, font=fnt, fill=color_active if line.is_active else color_inactive, anchor="mm", align="center") drawing.multiline_text((draw_x, draw_y + line.size[1] / 2), line.text, font=fnt, fill=color_active if line.is_active else color_inactive, anchor="mm", align="center")
if not line.is_active: if not line.is_active:
drawing.line((draw_x - line.size[0]//2, draw_y + line.size[1]//2, draw_x + line.size[0]//2, draw_y + line.size[1]//2), fill=color_inactive, width=4) drawing.line((draw_x - line.size[0] // 2, draw_y + line.size[1] // 2, draw_x + line.size[0] // 2, draw_y + line.size[1] // 2), fill=color_inactive, width=4)
draw_y += line.size[1] + line_spacing draw_y += line.size[1] + line_spacing
fontsize = (width + height) // 25 fontsize = (width + height) // 25
line_spacing = fontsize // 2 line_spacing = fontsize // 2
fnt = ImageFont.truetype(opts.font, fontsize)
try:
fnt = ImageFont.truetype(opts.font or Roboto, fontsize)
except Exception:
fnt = ImageFont.truetype(Roboto, fontsize)
color_active = (0, 0, 0) color_active = (0, 0, 0)
color_inactive = (153, 153, 153) color_inactive = (153, 153, 153)
pad_left = width * 3 // 4 if len(ver_texts) > 0 else 0 pad_left = 0 if sum([sum([len(line.text) for line in lines]) for lines in ver_texts]) == 0 else width * 3 // 4
cols = im.width // width cols = im.width // width
rows = im.height // height rows = im.height // height
@@ -160,7 +170,8 @@ def draw_grid_annotations(im, width, height, hor_texts, ver_texts):
line.size = (bbox[2] - bbox[0], bbox[3] - bbox[1]) line.size = (bbox[2] - bbox[0], bbox[3] - bbox[1])
hor_text_heights = [sum([line.size[1] + line_spacing for line in lines]) - line_spacing for lines in hor_texts] hor_text_heights = [sum([line.size[1] + line_spacing for line in lines]) - line_spacing for lines in hor_texts]
ver_text_heights = [sum([line.size[1] + line_spacing for line in lines]) - line_spacing * len(lines) for lines in ver_texts] ver_text_heights = [sum([line.size[1] + line_spacing for line in lines]) - line_spacing * len(lines) for lines in
ver_texts]
pad_top = max(hor_text_heights) + line_spacing * 2 pad_top = max(hor_text_heights) + line_spacing * 2
@@ -198,8 +209,27 @@ def draw_prompt_matrix(im, width, height, all_prompts):
def resize_image(resize_mode, im, width, height): def resize_image(resize_mode, im, width, height):
def resize(im, w, h):
if opts.upscaler_for_img2img is None or opts.upscaler_for_img2img == "None" or im.mode == 'L':
return im.resize((w, h), resample=LANCZOS)
scale = max(w / im.width, h / im.height)
if scale > 1.0:
upscalers = [x for x in shared.sd_upscalers if x.name == opts.upscaler_for_img2img]
assert len(upscalers) > 0, f"could not find upscaler named {opts.upscaler_for_img2img}"
upscaler = upscalers[0]
im = upscaler.scaler.upscale(im, scale, upscaler.data_path)
if im.width != w or im.height != h:
im = im.resize((w, h), resample=LANCZOS)
return im
if resize_mode == 0: if resize_mode == 0:
res = im.resize((width, height), resample=LANCZOS) res = resize(im, width, height)
elif resize_mode == 1: elif resize_mode == 1:
ratio = width / height ratio = width / height
src_ratio = im.width / im.height src_ratio = im.width / im.height
@@ -207,9 +237,10 @@ def resize_image(resize_mode, im, width, height):
src_w = width if ratio > src_ratio else im.width * height // im.height src_w = width if ratio > src_ratio else im.width * height // im.height
src_h = height if ratio <= src_ratio else im.height * width // im.width src_h = height if ratio <= src_ratio else im.height * width // im.width
resized = im.resize((src_w, src_h), resample=LANCZOS) resized = resize(im, src_w, src_h)
res = Image.new("RGB", (width, height)) res = Image.new("RGB", (width, height))
res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2)) res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
else: else:
ratio = width / height ratio = width / height
src_ratio = im.width / im.height src_ratio = im.width / im.height
@@ -217,7 +248,7 @@ def resize_image(resize_mode, im, width, height):
src_w = width if ratio < src_ratio else im.width * height // im.height src_w = width if ratio < src_ratio else im.width * height // im.height
src_h = height if ratio >= src_ratio else im.height * width // im.width src_h = height if ratio >= src_ratio else im.height * width // im.width
resized = im.resize((src_w, src_h), resample=LANCZOS) resized = resize(im, src_w, src_h)
res = Image.new("RGB", (width, height)) res = Image.new("RGB", (width, height))
res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2)) res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
@@ -234,46 +265,152 @@ def resize_image(resize_mode, im, width, height):
invalid_filename_chars = '<>:"/\\|?*\n' invalid_filename_chars = '<>:"/\\|?*\n'
invalid_filename_prefix = ' '
invalid_filename_postfix = ' .'
re_nonletters = re.compile(r'[\s' + string.punctuation + ']+')
max_filename_part_length = 128
def sanitize_filename_part(text): def sanitize_filename_part(text, replace_spaces=True):
return text.replace(' ', '_').translate({ord(x): '' for x in invalid_filename_chars})[:128] if replace_spaces:
text = text.replace(' ', '_')
text = text.translate({ord(x): '_' for x in invalid_filename_chars})
text = text.lstrip(invalid_filename_prefix)[:max_filename_part_length]
text = text.rstrip(invalid_filename_postfix)
return text
def save_image(image, path, basename, seed=None, prompt=None, extension='png', info=None, short_filename=False, no_prompt=False): def apply_filename_pattern(x, p, seed, prompt):
max_prompt_words = opts.directories_max_prompt_words
if seed is not None:
x = x.replace("[seed]", str(seed))
if p is not None:
x = x.replace("[steps]", str(p.steps))
x = x.replace("[cfg]", str(p.cfg_scale))
x = x.replace("[width]", str(p.width))
x = x.replace("[height]", str(p.height))
#currently disabled if using the save button, will work otherwise
# if enabled it will cause a bug because styles is not included in the save_files data dictionary
if hasattr(p, "styles"):
x = x.replace("[styles]", sanitize_filename_part(", ".join([x for x in p.styles if not x == "None"]) or "None", replace_spaces=False))
x = x.replace("[sampler]", sanitize_filename_part(sd_samplers.samplers[p.sampler_index].name, replace_spaces=False))
x = x.replace("[model_hash]", shared.sd_model.sd_model_hash)
x = x.replace("[date]", datetime.date.today().isoformat())
x = x.replace("[datetime]", datetime.datetime.now().strftime("%Y%m%d%H%M%S"))
x = x.replace("[job_timestamp]", shared.state.job_timestamp)
# Apply [prompt] at last. Because it may contain any replacement word.^M
if prompt is not None:
x = x.replace("[prompt]", sanitize_filename_part(prompt))
if "[prompt_no_styles]" in x:
prompt_no_style = prompt
for style in shared.prompt_styles.get_style_prompts(p.styles):
if len(style) > 0:
style_parts = [y for y in style.split("{prompt}")]
for part in style_parts:
prompt_no_style = prompt_no_style.replace(part, "").replace(", ,", ",").strip().strip(',')
prompt_no_style = prompt_no_style.replace(style, "").strip().strip(',').strip()
x = x.replace("[prompt_no_styles]", sanitize_filename_part(prompt_no_style, replace_spaces=False))
x = x.replace("[prompt_spaces]", sanitize_filename_part(prompt, replace_spaces=False))
if "[prompt_words]" in x:
words = [x for x in re_nonletters.split(prompt or "") if len(x) > 0]
if len(words) == 0:
words = ["empty"]
x = x.replace("[prompt_words]", sanitize_filename_part(" ".join(words[0:max_prompt_words]), replace_spaces=False))
if cmd_opts.hide_ui_dir_config:
x = re.sub(r'^[\\/]+|\.{2,}[\\/]+|[\\/]+\.{2,}', '', x)
return x
def get_next_sequence_number(path, basename):
"""
Determines and returns the next sequence number to use when saving an image in the specified directory.
The sequence starts at 0.
"""
result = -1
if basename != '':
basename = basename + "-"
prefix_length = len(basename)
for p in os.listdir(path):
if p.startswith(basename):
l = os.path.splitext(p[prefix_length:])[0].split('-') # splits the filename (removing the basename first if one is defined, so the sequence number is always the first element)
try:
result = max(int(l[0]), result)
except ValueError:
pass
return result + 1
def save_image(image, path, basename, seed=None, prompt=None, extension='png', info=None, short_filename=False, no_prompt=False, grid=False, pnginfo_section_name='parameters', p=None, existing_info=None, forced_filename=None, suffix=""):
if short_filename or prompt is None or seed is None: if short_filename or prompt is None or seed is None:
file_decoration = "" file_decoration = ""
elif opts.save_to_dirs: elif opts.save_to_dirs:
file_decoration = f"-{seed}" file_decoration = opts.samples_filename_pattern or "[seed]"
else: else:
file_decoration = f"-{seed}-{sanitize_filename_part(prompt)[:128]}" file_decoration = opts.samples_filename_pattern or "[seed]-[prompt_spaces]"
if file_decoration != "":
file_decoration = "-" + file_decoration.lower()
file_decoration = apply_filename_pattern(file_decoration, p, seed, prompt) + suffix
if extension == 'png' and opts.enable_pnginfo and info is not None: if extension == 'png' and opts.enable_pnginfo and info is not None:
pnginfo = PngImagePlugin.PngInfo() pnginfo = PngImagePlugin.PngInfo()
pnginfo.add_text("parameters", info)
if existing_info is not None:
for k, v in existing_info.items():
pnginfo.add_text(k, str(v))
pnginfo.add_text(pnginfo_section_name, info)
else: else:
pnginfo = None pnginfo = None
if opts.save_to_dirs and not no_prompt: save_to_dirs = (grid and opts.grid_save_to_dirs) or (not grid and opts.save_to_dirs and not no_prompt)
words = re.findall(r'\w+', prompt or "")
if len(words) == 0:
words = ["empty"]
dirname = " ".join(words[0:opts.save_to_dirs_prompt_len]) if save_to_dirs:
dirname = apply_filename_pattern(opts.directories_filename_pattern or "[prompt_words]", p, seed, prompt).strip('\\ /')
path = os.path.join(path, dirname) path = os.path.join(path, dirname)
os.makedirs(path, exist_ok=True) os.makedirs(path, exist_ok=True)
filecount = len([x for x in os.listdir(path) if os.path.splitext(x)[1] == '.' + extension]) if forced_filename is None:
basecount = get_next_sequence_number(path, basename)
fullfn = "a.png" fullfn = "a.png"
fullfn_without_extension = "a" fullfn_without_extension = "a"
for i in range(500): for i in range(500):
fn = f"{filecount+i:05}" if basename == '' else f"{basename}-{filecount+i:04}" fn = f"{basecount + i:05}" if basename == '' else f"{basename}-{basecount + i:04}"
fullfn = os.path.join(path, f"{fn}{file_decoration}.{extension}") fullfn = os.path.join(path, f"{fn}{file_decoration}.{extension}")
fullfn_without_extension = os.path.join(path, f"{fn}{file_decoration}") fullfn_without_extension = os.path.join(path, f"{fn}{file_decoration}")
if not os.path.exists(fullfn): if not os.path.exists(fullfn):
break break
else:
fullfn = os.path.join(path, f"{forced_filename}.{extension}")
fullfn_without_extension = os.path.join(path, forced_filename)
def exif_bytes():
return piexif.dump({
"Exif": {
piexif.ExifIFD.UserComment: piexif.helper.UserComment.dump(info or "", encoding="unicode")
},
})
if extension.lower() in ("jpg", "jpeg", "webp"):
image.save(fullfn, quality=opts.jpeg_quality)
if opts.enable_pnginfo and info is not None:
piexif.insert(exif_bytes(), fullfn)
else:
image.save(fullfn, quality=opts.jpeg_quality, pnginfo=pnginfo) image.save(fullfn, quality=opts.jpeg_quality, pnginfo=pnginfo)
target_side_length = 4000 target_side_length = 4000
@@ -286,38 +423,12 @@ def save_image(image, path, basename, seed=None, prompt=None, extension='png', i
elif oversize: elif oversize:
image = image.resize((image.width * target_side_length // image.height, target_side_length), LANCZOS) image = image.resize((image.width * target_side_length // image.height, target_side_length), LANCZOS)
image.save(f"{fullfn_without_extension}.jpg", quality=opts.jpeg_quality, pnginfo=pnginfo) image.save(fullfn_without_extension + ".jpg", quality=opts.jpeg_quality)
if opts.enable_pnginfo and info is not None:
piexif.insert(exif_bytes(), fullfn_without_extension + ".jpg")
if opts.save_txt and info is not None: if opts.save_txt and info is not None:
with open(f"{fullfn_without_extension}.txt", "w", encoding="utf8") as file: with open(f"{fullfn_without_extension}.txt", "w", encoding="utf8") as file:
file.write(info + "\n") file.write(info + "\n")
class Upscaler:
name = "Lanczos"
def do_upscale(self, img):
return img
def upscale(self, img, w, h):
for i in range(3):
if img.width >= w and img.height >= h:
break
img = self.do_upscale(img)
if img.width != w or img.height != h:
img = img.resize((w, h), resample=LANCZOS)
return img
class UpscalerNone(Upscaler):
name = "None"
def upscale(self, img, w, h):
return img
modules.shared.sd_upscalers.append(UpscalerNone())
modules.shared.sd_upscalers.append(Upscaler())
+79 -89
View File
@@ -1,6 +1,12 @@
import math import math
from PIL import Image import os
import sys
import traceback
import numpy as np
from PIL import Image, ImageOps, ImageChops
from modules import devices
from modules.processing import Processed, StableDiffusionProcessingImg2Img, process_images from modules.processing import Processed, StableDiffusionProcessingImg2Img, process_images
from modules.shared import opts, state from modules.shared import opts, state
import modules.shared as shared import modules.shared as shared
@@ -9,14 +15,59 @@ from modules.ui import plaintext_to_html
import modules.images as images import modules.images as images
import modules.scripts import modules.scripts
def img2img(prompt: str, init_img, init_img_with_mask, steps: int, sampler_index: int, mask_blur: int, inpainting_fill: int, restore_faces: bool, tiling: bool, mode: int, n_iter: int, batch_size: int, cfg_scale: float, denoising_strength: float, seed: int, height: int, width: int, resize_mode: int, upscaler_index: str, upscale_overlap: int, inpaint_full_res: bool, inpainting_mask_invert: int, *args):
def process_batch(p, input_dir, output_dir, args):
processing.fix_seed(p)
images = [file for file in [os.path.join(input_dir, x) for x in os.listdir(input_dir)] if os.path.isfile(file)]
print(f"Will process {len(images)} images, creating {p.n_iter * p.batch_size} new images for each.")
save_normally = output_dir == ''
p.do_not_save_grid = True
p.do_not_save_samples = not save_normally
state.job_count = len(images) * p.n_iter
for i, image in enumerate(images):
state.job = f"{i+1} out of {len(images)}"
if state.interrupted:
break
img = Image.open(image)
p.init_images = [img] * p.batch_size
proc = modules.scripts.scripts_img2img.run(p, *args)
if proc is None:
proc = process_images(p)
for n, processed_image in enumerate(proc.images):
filename = os.path.basename(image)
if n > 0:
left, right = os.path.splitext(filename)
filename = f"{left}-{n}{right}"
if not save_normally:
processed_image.save(os.path.join(output_dir, filename))
def img2img(mode: int, prompt: str, negative_prompt: str, prompt_style: str, prompt_style2: str, init_img, init_img_with_mask, init_img_inpaint, init_mask_inpaint, mask_mode, steps: int, sampler_index: int, mask_blur: int, inpainting_fill: int, restore_faces: bool, tiling: bool, n_iter: int, batch_size: int, cfg_scale: float, denoising_strength: float, seed: int, subseed: int, subseed_strength: float, seed_resize_from_h: int, seed_resize_from_w: int, seed_enable_extras: bool, height: int, width: int, resize_mode: int, inpaint_full_res: bool, inpaint_full_res_padding: int, inpainting_mask_invert: int, img2img_batch_input_dir: str, img2img_batch_output_dir: str, *args):
is_inpaint = mode == 1 is_inpaint = mode == 1
is_loopback = mode == 2 is_batch = mode == 2
is_upscale = mode == 3
if is_inpaint: if is_inpaint:
if mask_mode == 0:
image = init_img_with_mask['image'] image = init_img_with_mask['image']
mask = init_img_with_mask['mask'] mask = init_img_with_mask['mask']
alpha_mask = ImageOps.invert(image.split()[-1]).convert('L').point(lambda x: 255 if x > 0 else 0, mode='1')
mask = ImageChops.lighter(alpha_mask, mask.convert('L')).convert('L')
image = image.convert('RGB')
else:
image = init_img_inpaint
mask = init_mask_inpaint
else: else:
image = init_img image = init_img
mask = None mask = None
@@ -28,7 +79,14 @@ def img2img(prompt: str, init_img, init_img_with_mask, steps: int, sampler_index
outpath_samples=opts.outdir_samples or opts.outdir_img2img_samples, outpath_samples=opts.outdir_samples or opts.outdir_img2img_samples,
outpath_grids=opts.outdir_grids or opts.outdir_img2img_grids, outpath_grids=opts.outdir_grids or opts.outdir_img2img_grids,
prompt=prompt, prompt=prompt,
negative_prompt=negative_prompt,
styles=[prompt_style, prompt_style2],
seed=seed, seed=seed,
subseed=subseed,
subseed_strength=subseed_strength,
seed_resize_from_h=seed_resize_from_h,
seed_resize_from_w=seed_resize_from_w,
seed_enable_extras=seed_enable_extras,
sampler_index=sampler_index, sampler_index=sampler_index,
batch_size=batch_size, batch_size=batch_size,
n_iter=n_iter, n_iter=n_iter,
@@ -45,101 +103,33 @@ def img2img(prompt: str, init_img, init_img_with_mask, steps: int, sampler_index
resize_mode=resize_mode, resize_mode=resize_mode,
denoising_strength=denoising_strength, denoising_strength=denoising_strength,
inpaint_full_res=inpaint_full_res, inpaint_full_res=inpaint_full_res,
inpaint_full_res_padding=inpaint_full_res_padding,
inpainting_mask_invert=inpainting_mask_invert, inpainting_mask_invert=inpainting_mask_invert,
extra_generation_params={"Denoising Strength": denoising_strength}
) )
if is_loopback: if shared.cmd_opts.enable_console_prompts:
output_images, info = None, None print(f"\nimg2img: {prompt}", file=shared.progress_print_out)
history = []
initial_seed = None
initial_info = None
state.job_count = n_iter p.extra_generation_params["Mask blur"] = mask_blur
for i in range(n_iter): if is_batch:
assert not shared.cmd_opts.hide_ui_dir_config, "Launched with --hide-ui-dir-config, batch img2img disabled"
p.n_iter = 1 process_batch(p, img2img_batch_input_dir, img2img_batch_output_dir, args)
p.batch_size = 1
p.do_not_save_grid = True
state.job = f"Batch {i + 1} out of {n_iter}"
processed = process_images(p)
if initial_seed is None:
initial_seed = processed.seed
initial_info = processed.info
p.init_images = [processed.images[0]]
p.seed = processed.seed + 1
p.denoising_strength = max(p.denoising_strength * 0.95, 0.1)
history.append(processed.images[0])
grid = images.image_grid(history, batch_size, rows=1)
images.save_image(grid, p.outpath_grids, "grid", initial_seed, prompt, opts.grid_format, info=info, short_filename=not opts.grid_extended_filename)
processed = Processed(p, history, initial_seed, initial_info)
elif is_upscale:
initial_seed = None
initial_info = None
upscaler = shared.sd_upscalers[upscaler_index]
img = upscaler.upscale(init_img, init_img.width * 2, init_img.height * 2)
processing.torch_gc()
grid = images.split_grid(img, tile_w=width, tile_h=height, overlap=upscale_overlap)
p.n_iter = 1
p.do_not_save_grid = True
p.do_not_save_samples = True
work = []
work_results = []
for y, h, row in grid.tiles:
for tiledata in row:
work.append(tiledata[2])
batch_count = math.ceil(len(work) / p.batch_size)
print(f"SD upscaling will process a total of {len(work)} images tiled as {len(grid.tiles[0][2])}x{len(grid.tiles)} in a total of {batch_count} batches.")
state.job_count = batch_count
for i in range(batch_count):
p.init_images = work[i*p.batch_size:(i+1)*p.batch_size]
state.job = f"Batch {i + 1} out of {batch_count}"
processed = process_images(p)
if initial_seed is None:
initial_seed = processed.seed
initial_info = processed.info
p.seed = processed.seed + 1
work_results += processed.images
image_index = 0
for y, h, row in grid.tiles:
for tiledata in row:
tiledata[2] = work_results[image_index] if image_index < len(work_results) else Image.new("RGB", (p.width, p.height))
image_index += 1
combined_image = images.combine_grid(grid)
if opts.samples_save:
images.save_image(combined_image, p.outpath_samples, "", initial_seed, prompt, opts.grid_format, info=initial_info)
processed = Processed(p, [combined_image], initial_seed, initial_info)
processed = Processed(p, [], p.seed, "")
else: else:
processed = modules.scripts.scripts_img2img.run(p, *args) processed = modules.scripts.scripts_img2img.run(p, *args)
if processed is None: if processed is None:
processed = process_images(p) processed = process_images(p)
shared.total_tqdm.clear()
return processed.images, processed.js(), plaintext_to_html(processed.info) generation_info_js = processed.js()
if opts.samples_log_stdout:
print(generation_info_js)
if opts.do_not_show_images:
processed.images = []
return processed.images, generation_info_js, plaintext_to_html(processed.info)
+168
View File
@@ -0,0 +1,168 @@
import contextlib
import os
import sys
import traceback
from collections import namedtuple
import re
import torch
from torchvision import transforms
from torchvision.transforms.functional import InterpolationMode
import modules.shared as shared
from modules import devices, paths, lowvram
blip_image_eval_size = 384
blip_model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_caption_capfilt_large.pth'
clip_model_name = 'ViT-L/14'
Category = namedtuple("Category", ["name", "topn", "items"])
re_topn = re.compile(r"\.top(\d+)\.")
class InterrogateModels:
blip_model = None
clip_model = None
clip_preprocess = None
categories = None
dtype = None
def __init__(self, content_dir):
self.categories = []
if os.path.exists(content_dir):
for filename in os.listdir(content_dir):
m = re_topn.search(filename)
topn = 1 if m is None else int(m.group(1))
with open(os.path.join(content_dir, filename), "r", encoding="utf8") as file:
lines = [x.strip() for x in file.readlines()]
self.categories.append(Category(name=filename, topn=topn, items=lines))
def load_blip_model(self):
import models.blip
blip_model = models.blip.blip_decoder(pretrained=blip_model_url, image_size=blip_image_eval_size, vit='base', med_config=os.path.join(paths.paths["BLIP"], "configs", "med_config.json"))
blip_model.eval()
return blip_model
def load_clip_model(self):
import clip
model, preprocess = clip.load(clip_model_name)
model.eval()
model = model.to(shared.device)
return model, preprocess
def load(self):
if self.blip_model is None:
self.blip_model = self.load_blip_model()
if not shared.cmd_opts.no_half:
self.blip_model = self.blip_model.half()
self.blip_model = self.blip_model.to(shared.device)
if self.clip_model is None:
self.clip_model, self.clip_preprocess = self.load_clip_model()
if not shared.cmd_opts.no_half:
self.clip_model = self.clip_model.half()
self.clip_model = self.clip_model.to(shared.device)
self.dtype = next(self.clip_model.parameters()).dtype
def send_clip_to_ram(self):
if not shared.opts.interrogate_keep_models_in_memory:
if self.clip_model is not None:
self.clip_model = self.clip_model.to(devices.cpu)
def send_blip_to_ram(self):
if not shared.opts.interrogate_keep_models_in_memory:
if self.blip_model is not None:
self.blip_model = self.blip_model.to(devices.cpu)
def unload(self):
self.send_clip_to_ram()
self.send_blip_to_ram()
devices.torch_gc()
def rank(self, image_features, text_array, top_count=1):
import clip
if shared.opts.interrogate_clip_dict_limit != 0:
text_array = text_array[0:int(shared.opts.interrogate_clip_dict_limit)]
top_count = min(top_count, len(text_array))
text_tokens = clip.tokenize([text for text in text_array], truncate=True).to(shared.device)
text_features = self.clip_model.encode_text(text_tokens).type(self.dtype)
text_features /= text_features.norm(dim=-1, keepdim=True)
similarity = torch.zeros((1, len(text_array))).to(shared.device)
for i in range(image_features.shape[0]):
similarity += (100.0 * image_features[i].unsqueeze(0) @ text_features.T).softmax(dim=-1)
similarity /= image_features.shape[0]
top_probs, top_labels = similarity.cpu().topk(top_count, dim=-1)
return [(text_array[top_labels[0][i].numpy()], (top_probs[0][i].numpy()*100)) for i in range(top_count)]
def generate_caption(self, pil_image):
gpu_image = transforms.Compose([
transforms.Resize((blip_image_eval_size, blip_image_eval_size), interpolation=InterpolationMode.BICUBIC),
transforms.ToTensor(),
transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711))
])(pil_image).unsqueeze(0).type(self.dtype).to(shared.device)
with torch.no_grad():
caption = self.blip_model.generate(gpu_image, sample=False, num_beams=shared.opts.interrogate_clip_num_beams, min_length=shared.opts.interrogate_clip_min_length, max_length=shared.opts.interrogate_clip_max_length)
return caption[0]
def interrogate(self, pil_image):
res = None
try:
if shared.cmd_opts.lowvram or shared.cmd_opts.medvram:
lowvram.send_everything_to_cpu()
devices.torch_gc()
self.load()
caption = self.generate_caption(pil_image)
self.send_blip_to_ram()
devices.torch_gc()
res = caption
cilp_image = self.clip_preprocess(pil_image).unsqueeze(0).type(self.dtype).to(shared.device)
precision_scope = torch.autocast if shared.cmd_opts.precision == "autocast" else contextlib.nullcontext
with torch.no_grad(), precision_scope("cuda"):
image_features = self.clip_model.encode_image(cilp_image).type(self.dtype)
image_features /= image_features.norm(dim=-1, keepdim=True)
if shared.opts.interrogate_use_builtin_artists:
artist = self.rank(image_features, ["by " + artist.name for artist in shared.artist_db.artists])[0]
res += ", " + artist[0]
for name, topn, items in self.categories:
matches = self.rank(image_features, items, top_count=topn)
for match, score in matches:
res += ", " + match
except Exception:
print(f"Error interrogating", file=sys.stderr)
print(traceback.format_exc(), file=sys.stderr)
res += "<error>"
self.unload()
return res
+56
View File
@@ -0,0 +1,56 @@
import os
import sys
import traceback
from basicsr.utils.download_util import load_file_from_url
from modules.upscaler import Upscaler, UpscalerData
from modules.ldsr_model_arch import LDSR
from modules import shared
from modules.paths import models_path
class UpscalerLDSR(Upscaler):
def __init__(self, user_path):
self.name = "LDSR"
self.model_path = os.path.join(models_path, self.name)
self.user_path = user_path
self.model_url = "https://heibox.uni-heidelberg.de/f/578df07c8fc04ffbadf3/?dl=1"
self.yaml_url = "https://heibox.uni-heidelberg.de/f/31a76b13ea27482981b4/?dl=1"
super().__init__()
scaler_data = UpscalerData("LDSR", None, self)
self.scalers = [scaler_data]
def load_model(self, path: str):
# Remove incorrect project.yaml file if too big
yaml_path = os.path.join(self.model_path, "project.yaml")
old_model_path = os.path.join(self.model_path, "model.pth")
new_model_path = os.path.join(self.model_path, "model.ckpt")
if os.path.exists(yaml_path):
statinfo = os.stat(yaml_path)
if statinfo.st_size >= 10485760:
print("Removing invalid LDSR YAML file.")
os.remove(yaml_path)
if os.path.exists(old_model_path):
print("Renaming model from model.pth to model.ckpt")
os.rename(old_model_path, new_model_path)
model = load_file_from_url(url=self.model_url, model_dir=self.model_path,
file_name="model.ckpt", progress=True)
yaml = load_file_from_url(url=self.yaml_url, model_dir=self.model_path,
file_name="project.yaml", progress=True)
try:
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):
ldsr = self.load_model(path)
if ldsr is None:
print("NO LDSR!")
return img
ddim_steps = shared.opts.ldsr_steps
return ldsr.super_resolution(img, ddim_steps, self.scale)
+222
View File
@@ -0,0 +1,222 @@
import gc
import time
import warnings
import numpy as np
import torch
import torchvision
from PIL import Image
from einops import rearrange, repeat
from omegaconf import OmegaConf
from ldm.models.diffusion.ddim import DDIMSampler
from ldm.util import instantiate_from_config, ismap
warnings.filterwarnings("ignore", category=UserWarning)
# Create LDSR Class
class LDSR:
def load_model_from_config(self, half_attention):
print(f"Loading model from {self.modelPath}")
pl_sd = torch.load(self.modelPath, map_location="cpu")
sd = pl_sd["state_dict"]
config = OmegaConf.load(self.yamlPath)
model = instantiate_from_config(config.model)
model.load_state_dict(sd, strict=False)
model.cuda()
if half_attention:
model = model.half()
model.eval()
return {"model": model}
def __init__(self, model_path, yaml_path):
self.modelPath = model_path
self.yamlPath = yaml_path
@staticmethod
def run(model, selected_path, custom_steps, eta):
example = get_cond(selected_path)
n_runs = 1
guider = None
ckwargs = None
ddim_use_x0_pred = False
temperature = 1.
eta = eta
custom_shape = None
height, width = example["image"].shape[1:3]
split_input = height >= 128 and width >= 128
if split_input:
ks = 128
stride = 64
vqf = 4 #
model.split_input_params = {"ks": (ks, ks), "stride": (stride, stride),
"vqf": vqf,
"patch_distributed_vq": True,
"tie_braker": False,
"clip_max_weight": 0.5,
"clip_min_weight": 0.01,
"clip_max_tie_weight": 0.5,
"clip_min_tie_weight": 0.01}
else:
if hasattr(model, "split_input_params"):
delattr(model, "split_input_params")
x_t = None
logs = None
for n in range(n_runs):
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 = repeat(x_t, '1 c h w -> b c h w', b=custom_shape[0])
logs = make_convolutional_sample(example, model,
custom_steps=custom_steps,
eta=eta, quantize_x0=False,
custom_shape=custom_shape,
temperature=temperature, noise_dropout=0.,
corrector=guider, corrector_kwargs=ckwargs, x_T=x_t,
ddim_use_x0_pred=ddim_use_x0_pred
)
return logs
def super_resolution(self, image, steps=100, target_scale=2, half_attention=False):
model = self.load_model_from_config(half_attention)
# Run settings
diffusion_steps = int(steps)
eta = 1.0
down_sample_method = 'Lanczos'
gc.collect()
torch.cuda.empty_cache()
im_og = image
width_og, height_og = im_og.size
# If we can adjust the max upscale size, then the 4 below should be our variable
down_sample_rate = target_scale / 4
wd = width_og * down_sample_rate
hd = height_og * down_sample_rate
width_downsampled_pre = int(wd)
height_downsampled_pre = int(hd)
if down_sample_rate != 1:
print(
f'Downsampling from [{width_og}, {height_og}] to [{width_downsampled_pre}, {height_downsampled_pre}]')
im_og = im_og.resize((width_downsampled_pre, height_downsampled_pre), Image.LANCZOS)
else:
print(f"Down sample rate is 1 from {target_scale} / 4 (Not downsampling)")
logs = self.run(model["model"], im_og, diffusion_steps, eta)
sample = logs["sample"]
sample = sample.detach().cpu()
sample = torch.clamp(sample, -1., 1.)
sample = (sample + 1.) / 2. * 255
sample = sample.numpy().astype(np.uint8)
sample = np.transpose(sample, (0, 2, 3, 1))
a = Image.fromarray(sample[0])
del model
gc.collect()
torch.cuda.empty_cache()
return a
def get_cond(selected_path):
example = dict()
up_f = 4
c = selected_path.convert('RGB')
c = torch.unsqueeze(torchvision.transforms.ToTensor()(c), 0)
c_up = torchvision.transforms.functional.resize(c, size=[up_f * c.shape[2], up_f * c.shape[3]],
antialias=True)
c_up = rearrange(c_up, '1 c h w -> 1 h w c')
c = rearrange(c, '1 c h w -> 1 h w c')
c = 2. * c - 1.
c = c.to(torch.device("cuda"))
example["LR_image"] = c
example["image"] = c_up
return example
@torch.no_grad()
def convsample_ddim(model, cond, steps, shape, eta=1.0, callback=None, normals_sequence=None,
mask=None, x0=None, quantize_x0=False, temperature=1., score_corrector=None,
corrector_kwargs=None, x_t=None
):
ddim = DDIMSampler(model)
bs = shape[0]
shape = shape[1:]
print(f"Sampling with eta = {eta}; steps: {steps}")
samples, intermediates = ddim.sample(steps, batch_size=bs, shape=shape, conditioning=cond, callback=callback,
normals_sequence=normals_sequence, quantize_x0=quantize_x0, eta=eta,
mask=mask, x0=x0, temperature=temperature, verbose=False,
score_corrector=score_corrector,
corrector_kwargs=corrector_kwargs, x_t=x_t)
return samples, intermediates
@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,
corrector_kwargs=None, x_T=None, ddim_use_x0_pred=False):
log = dict()
z, c, x, xrec, xc = model.get_input(batch, model.first_stage_key,
return_first_stage_outputs=True,
force_c_encode=not (hasattr(model, 'split_input_params')
and model.cond_stage_key == 'coordinates_bbox'),
return_original_cond=True)
if custom_shape is not None:
z = torch.randn(custom_shape)
print(f"Generating {custom_shape[0]} samples of shape {custom_shape[1:]}")
z0 = None
log["input"] = x
log["reconstruction"] = xrec
if ismap(xc):
log["original_conditioning"] = model.to_rgb(xc)
if hasattr(model, 'cond_stage_key'):
log[model.cond_stage_key] = model.to_rgb(xc)
else:
log["original_conditioning"] = xc if xc is not None else torch.zeros_like(x)
if model.cond_stage_model:
log[model.cond_stage_key] = xc if xc is not None else torch.zeros_like(x)
if model.cond_stage_key == 'class_label':
log[model.cond_stage_key] = xc[model.cond_stage_key]
with model.ema_scope("Plotting"):
t0 = time.time()
sample, intermediates = convsample_ddim(model, c, steps=custom_steps, shape=z.shape,
eta=eta,
quantize_x0=quantize_x0, mask=None, x0=z0,
temperature=temperature, score_corrector=corrector, corrector_kwargs=corrector_kwargs,
x_t=x_T)
t1 = time.time()
if ddim_use_x0_pred:
sample = intermediates['pred_x0'][-1]
x_sample = model.decode_first_stage(sample)
try:
x_sample_noquant = model.decode_first_stage(sample, force_not_quantize=True)
log["sample_noquant"] = x_sample_noquant
log["sample_diff"] = torch.abs(x_sample_noquant - x_sample)
except:
pass
log["sample"] = x_sample
log["time"] = t1 - t0
return log
+11 -2
View File
@@ -1,9 +1,18 @@
import torch import torch
from modules.devices import get_optimal_device
module_in_gpu = None module_in_gpu = None
cpu = torch.device("cpu") cpu = torch.device("cpu")
gpu = torch.device("cuda") device = gpu = get_optimal_device()
device = gpu if torch.cuda.is_available() else cpu
def send_everything_to_cpu():
global module_in_gpu
if module_in_gpu is not None:
module_in_gpu.to(cpu)
module_in_gpu = None
def setup_for_low_vram(sd_model, use_medvram): def setup_for_low_vram(sd_model, use_medvram):
+99
View File
@@ -0,0 +1,99 @@
from PIL import Image, ImageFilter, ImageOps
def get_crop_region(mask, pad=0):
"""finds a rectangular region that contains all masked ares in an image. Returns (x1, y1, x2, y2) coordinates of the rectangle.
For example, if a user has painted the top-right part of a 512x512 image", the result may be (256, 0, 512, 256)"""
h, w = mask.shape
crop_left = 0
for i in range(w):
if not (mask[:, i] == 0).all():
break
crop_left += 1
crop_right = 0
for i in reversed(range(w)):
if not (mask[:, i] == 0).all():
break
crop_right += 1
crop_top = 0
for i in range(h):
if not (mask[i] == 0).all():
break
crop_top += 1
crop_bottom = 0
for i in reversed(range(h)):
if not (mask[i] == 0).all():
break
crop_bottom += 1
return (
int(max(crop_left-pad, 0)),
int(max(crop_top-pad, 0)),
int(min(w - crop_right + pad, w)),
int(min(h - crop_bottom + pad, h))
)
def expand_crop_region(crop_region, processing_width, processing_height, image_width, image_height):
"""expands crop region get_crop_region() to match the ratio of the image the region will processed in; returns expanded region
for example, if user drew mask in a 128x32 region, and the dimensions for processing are 512x512, the region will be expanded to 128x128."""
x1, y1, x2, y2 = crop_region
ratio_crop_region = (x2 - x1) / (y2 - y1)
ratio_processing = processing_width / processing_height
if ratio_crop_region > ratio_processing:
desired_height = (x2 - x1) * ratio_processing
desired_height_diff = int(desired_height - (y2-y1))
y1 -= desired_height_diff//2
y2 += desired_height_diff - desired_height_diff//2
if y2 >= image_height:
diff = y2 - image_height
y2 -= diff
y1 -= diff
if y1 < 0:
y2 -= y1
y1 -= y1
if y2 >= image_height:
y2 = image_height
else:
desired_width = (y2 - y1) * ratio_processing
desired_width_diff = int(desired_width - (x2-x1))
x1 -= desired_width_diff//2
x2 += desired_width_diff - desired_width_diff//2
if x2 >= image_width:
diff = x2 - image_width
x2 -= diff
x1 -= diff
if x1 < 0:
x2 -= x1
x1 -= x1
if x2 >= image_width:
x2 = image_width
return x1, y1, x2, y2
def fill(image, mask):
"""fills masked regions with colors from image using blur. Not extremely effective."""
image_mod = Image.new('RGBA', (image.width, image.height))
image_masked = Image.new('RGBa', (image.width, image.height))
image_masked.paste(image.convert("RGBA").convert("RGBa"), mask=ImageOps.invert(mask.convert('L')))
image_masked = image_masked.convert('RGBa')
for radius, repeats in [(256, 1), (64, 1), (16, 2), (4, 4), (2, 2), (0, 1)]:
blurred = image_masked.filter(ImageFilter.GaussianBlur(radius)).convert('RGBA')
for _ in range(repeats):
image_mod.alpha_composite(blurred)
return image_mod.convert("RGB")
+85
View File
@@ -0,0 +1,85 @@
import threading
import time
from collections import defaultdict
import torch
class MemUsageMonitor(threading.Thread):
run_flag = None
device = None
disabled = False
opts = None
data = None
def __init__(self, name, device, opts):
threading.Thread.__init__(self)
self.name = name
self.device = device
self.opts = opts
self.daemon = True
self.run_flag = threading.Event()
self.data = defaultdict(int)
try:
torch.cuda.mem_get_info()
torch.cuda.memory_stats(self.device)
except Exception as e: # AMD or whatever
print(f"Warning: caught exception '{e}', memory monitor disabled")
self.disabled = True
def run(self):
if self.disabled:
return
while True:
self.run_flag.wait()
torch.cuda.reset_peak_memory_stats()
self.data.clear()
if self.opts.memmon_poll_rate <= 0:
self.run_flag.clear()
continue
self.data["min_free"] = torch.cuda.mem_get_info()[0]
while self.run_flag.is_set():
free, total = torch.cuda.mem_get_info() # calling with self.device errors, torch bug?
self.data["min_free"] = min(self.data["min_free"], free)
time.sleep(1 / self.opts.memmon_poll_rate)
def dump_debug(self):
print(self, 'recorded data:')
for k, v in self.read().items():
print(k, -(v // -(1024 ** 2)))
print(self, 'raw torch memory stats:')
tm = torch.cuda.memory_stats(self.device)
for k, v in tm.items():
if 'bytes' not in k:
continue
print('\t' if 'peak' in k else '', k, -(v // -(1024 ** 2)))
print(torch.cuda.memory_summary())
def monitor(self):
self.run_flag.set()
def read(self):
if not self.disabled:
free, total = torch.cuda.mem_get_info()
self.data["total"] = total
torch_stats = torch.cuda.memory_stats(self.device)
self.data["active_peak"] = torch_stats["active_bytes.all.peak"]
self.data["reserved_peak"] = torch_stats["reserved_bytes.all.peak"]
self.data["system_peak"] = total - self.data["min_free"]
return self.data
def stop(self):
self.run_flag.clear()
return self.read()
+153
View File
@@ -0,0 +1,153 @@
import glob
import os
import shutil
import importlib
from urllib.parse import urlparse
from basicsr.utils.download_util import load_file_from_url
from modules import shared
from modules.upscaler import Upscaler
from modules.paths import script_path, models_path
def load_models(model_path: str, model_url: str = None, command_path: str = None, ext_filter=None, download_name=None) -> list:
"""
A one-and done loader to try finding the desired models in specified directories.
@param download_name: Specify to download from model_url immediately.
@param model_url: If no other models are found, this will be downloaded on upscale.
@param model_path: The location to store/find models in.
@param command_path: A command-line argument to search for models in first.
@param ext_filter: An optional list of filename extensions to filter by
@return: A list of paths containing the desired model(s)
"""
output = []
if ext_filter is None:
ext_filter = []
try:
places = []
if command_path is not None and command_path != model_path:
pretrained_path = os.path.join(command_path, 'experiments/pretrained_models')
if os.path.exists(pretrained_path):
print(f"Appending path: {pretrained_path}")
places.append(pretrained_path)
elif os.path.exists(command_path):
places.append(command_path)
places.append(model_path)
for place in places:
if os.path.exists(place):
for file in glob.iglob(place + '**/**', recursive=True):
full_path = file
if os.path.isdir(full_path):
continue
if len(ext_filter) != 0:
model_name, extension = os.path.splitext(file)
if extension not in ext_filter:
continue
if file not in output:
output.append(full_path)
if model_url is not None and len(output) == 0:
if download_name is not None:
dl = load_file_from_url(model_url, model_path, True, download_name)
output.append(dl)
else:
output.append(model_url)
except Exception:
pass
return output
def friendly_name(file: str):
if "http" in file:
file = urlparse(file).path
file = os.path.basename(file)
model_name, extension = os.path.splitext(file)
return model_name
def cleanup_models():
# This code could probably be more efficient if we used a tuple list or something to store the src/destinations
# and then enumerate that, but this works for now. In the future, it'd be nice to just have every "model" scaler
# somehow auto-register and just do these things...
root_path = script_path
src_path = models_path
dest_path = os.path.join(models_path, "Stable-diffusion")
move_files(src_path, dest_path, ".ckpt")
src_path = os.path.join(root_path, "ESRGAN")
dest_path = os.path.join(models_path, "ESRGAN")
move_files(src_path, dest_path)
src_path = os.path.join(root_path, "gfpgan")
dest_path = os.path.join(models_path, "GFPGAN")
move_files(src_path, dest_path)
src_path = os.path.join(root_path, "SwinIR")
dest_path = os.path.join(models_path, "SwinIR")
move_files(src_path, dest_path)
src_path = os.path.join(root_path, "repositories/latent-diffusion/experiments/pretrained_models/")
dest_path = os.path.join(models_path, "LDSR")
move_files(src_path, dest_path)
def move_files(src_path: str, dest_path: str, ext_filter: str = None):
try:
if not os.path.exists(dest_path):
os.makedirs(dest_path)
if os.path.exists(src_path):
for file in os.listdir(src_path):
fullpath = os.path.join(src_path, file)
if os.path.isfile(fullpath):
if ext_filter is not None:
if ext_filter not in file:
continue
print(f"Moving {file} from {src_path} to {dest_path}.")
try:
shutil.move(fullpath, dest_path)
except:
pass
if len(os.listdir(src_path)) == 0:
print(f"Removing empty folder: {src_path}")
shutil.rmtree(src_path, True)
except:
pass
def load_upscalers():
sd = shared.script_path
# We can only do this 'magic' method to dynamically load upscalers if they are referenced,
# so we'll try to import any _model.py files before looking in __subclasses__
modules_dir = os.path.join(sd, "modules")
for file in os.listdir(modules_dir):
if "_model.py" in file:
model_name = file.replace("_model.py", "")
full_model = f"modules.{model_name}_model"
try:
importlib.import_module(full_model)
except:
pass
datas = []
c_o = vars(shared.cmd_opts)
for cls in Upscaler.__subclasses__():
name = cls.__name__
module_name = cls.__module__
module = importlib.import_module(module_name)
class_ = getattr(module, name)
cmd_name = f"{name.lower().replace('upscaler', '')}_models_path"
opt_string = None
try:
if cmd_name in c_o:
opt_string = c_o[cmd_name]
except:
pass
scaler = class_(opt_string)
for child in scaler.scalers:
datas.append(child)
shared.sd_upscalers = datas
+13 -7
View File
@@ -3,30 +3,36 @@ import os
import sys import sys
script_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) script_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
models_path = os.path.join(script_path, "models")
sys.path.insert(0, script_path) sys.path.insert(0, script_path)
# search for directory of stable diffsuion in following palces # search for directory of stable diffusion in following places
sd_path = None sd_path = None
possible_sd_paths = ['.', os.path.dirname(script_path), os.path.join(script_path, 'repositories/stable-diffusion')] possible_sd_paths = [os.path.join(script_path, 'repositories/stable-diffusion'), '.', os.path.dirname(script_path)]
for possible_sd_path in possible_sd_paths: for possible_sd_path in possible_sd_paths:
if os.path.exists(os.path.join(possible_sd_path, 'ldm/models/diffusion/ddpm.py')): if os.path.exists(os.path.join(possible_sd_path, 'ldm/models/diffusion/ddpm.py')):
sd_path = os.path.abspath(possible_sd_path) sd_path = os.path.abspath(possible_sd_path)
assert sd_path is not None, "Couldn't find Stable Diffusion in any of: " + possible_sd_paths assert sd_path is not None, "Couldn't find Stable Diffusion in any of: " + str(possible_sd_paths)
path_dirs = [ path_dirs = [
(sd_path, 'ldm', 'Stable Diffusion'), (sd_path, 'ldm', 'Stable Diffusion', []),
(os.path.join(sd_path, '../taming-transformers'), 'taming', 'Taming Transformers'), (os.path.join(sd_path, '../taming-transformers'), 'taming', 'Taming Transformers', []),
(os.path.join(sd_path, '../CodeFormer'), 'inference_codeformer.py', 'CodeFormer'), (os.path.join(sd_path, '../CodeFormer'), 'inference_codeformer.py', 'CodeFormer', []),
(os.path.join(sd_path, '../BLIP'), 'models/blip.py', 'BLIP', []),
(os.path.join(sd_path, '../k-diffusion'), 'k_diffusion/sampling.py', 'k_diffusion', ["atstart"]),
] ]
paths = {} paths = {}
for d, must_exist, what in path_dirs: for d, must_exist, what, options in path_dirs:
must_exist_path = os.path.abspath(os.path.join(script_path, d, must_exist)) must_exist_path = os.path.abspath(os.path.join(script_path, d, must_exist))
if not os.path.exists(must_exist_path): if not os.path.exists(must_exist_path):
print(f"Warning: {what} not found at path {must_exist_path}", file=sys.stderr) print(f"Warning: {what} not found at path {must_exist_path}", file=sys.stderr)
else: else:
d = os.path.abspath(d) d = os.path.abspath(d)
if "atstart" in options:
sys.path.insert(0, d)
else:
sys.path.append(d) sys.path.append(d)
paths[what] = d paths[what] = d
+372 -123
View File
@@ -1,4 +1,3 @@
import contextlib
import json import json
import math import math
import os import os
@@ -8,35 +7,59 @@ import torch
import numpy as np import numpy as np
from PIL import Image, ImageFilter, ImageOps from PIL import Image, ImageFilter, ImageOps
import random import random
import cv2
from skimage import exposure
import modules.sd_hijack import modules.sd_hijack
from modules import devices, prompt_parser, masking, sd_samplers
from modules.sd_hijack import model_hijack from modules.sd_hijack import model_hijack
from modules.sd_samplers import samplers, samplers_for_img2img
from modules.shared import opts, cmd_opts, state from modules.shared import opts, cmd_opts, state
import modules.shared as shared import modules.shared as shared
import modules.face_restoration import modules.face_restoration
import modules.images as images import modules.images as images
import modules.styles
import logging
# some of those options should not be changed at all because they would break the model, so I removed them from options. # some of those options should not be changed at all because they would break the model, so I removed them from options.
opt_C = 4 opt_C = 4
opt_f = 8 opt_f = 8
def torch_gc(): def setup_color_correction(image):
if torch.cuda.is_available(): logging.info("Calibrating color correction.")
torch.cuda.empty_cache() correction_target = cv2.cvtColor(np.asarray(image.copy()), cv2.COLOR_RGB2LAB)
torch.cuda.ipc_collect() return correction_target
def apply_color_correction(correction, image):
logging.info("Applying color correction.")
image = Image.fromarray(cv2.cvtColor(exposure.match_histograms(
cv2.cvtColor(
np.asarray(image),
cv2.COLOR_RGB2LAB
),
correction,
channel_axis=2
), cv2.COLOR_LAB2RGB).astype("uint8"))
return image
class StableDiffusionProcessing: class StableDiffusionProcessing:
def __init__(self, sd_model=None, outpath_samples=None, outpath_grids=None, prompt="", seed=-1, sampler_index=0, batch_size=1, n_iter=1, steps=50, cfg_scale=7.0, width=512, height=512, restore_faces=False, tiling=False, do_not_save_samples=False, do_not_save_grid=False, extra_generation_params=None, overlay_images=None, negative_prompt=None): def __init__(self, sd_model=None, outpath_samples=None, outpath_grids=None, prompt="", styles=None, seed=-1, subseed=-1, subseed_strength=0, seed_resize_from_h=-1, seed_resize_from_w=-1, seed_enable_extras=True, sampler_index=0, batch_size=1, n_iter=1, steps=50, cfg_scale=7.0, width=512, height=512, restore_faces=False, tiling=False, do_not_save_samples=False, do_not_save_grid=False, extra_generation_params=None, overlay_images=None, negative_prompt=None, eta=None):
self.sd_model = sd_model self.sd_model = sd_model
self.outpath_samples: str = outpath_samples self.outpath_samples: str = outpath_samples
self.outpath_grids: str = outpath_grids self.outpath_grids: str = outpath_grids
self.prompt: str = prompt self.prompt: str = prompt
self.prompt_for_display: str = None self.prompt_for_display: str = None
self.negative_prompt: str = (negative_prompt or "") self.negative_prompt: str = (negative_prompt or "")
self.styles: list = styles or []
self.seed: int = seed self.seed: int = seed
self.subseed: int = subseed
self.subseed_strength: float = subseed_strength
self.seed_resize_from_h: int = seed_resize_from_h
self.seed_resize_from_w: int = seed_resize_from_w
self.sampler_index: int = sampler_index self.sampler_index: int = sampler_index
self.batch_size: int = batch_size self.batch_size: int = batch_size
self.n_iter: int = n_iter self.n_iter: int = n_iter
@@ -48,114 +71,275 @@ class StableDiffusionProcessing:
self.tiling: bool = tiling self.tiling: bool = tiling
self.do_not_save_samples: bool = do_not_save_samples self.do_not_save_samples: bool = do_not_save_samples
self.do_not_save_grid: bool = do_not_save_grid self.do_not_save_grid: bool = do_not_save_grid
self.extra_generation_params: dict = extra_generation_params self.extra_generation_params: dict = extra_generation_params or {}
self.overlay_images = overlay_images self.overlay_images = overlay_images
self.eta = eta
self.paste_to = None self.paste_to = None
self.color_corrections = None
self.denoising_strength: float = 0
self.sampler_noise_scheduler_override = None
self.ddim_discretize = opts.ddim_discretize
self.s_churn = opts.s_churn
self.s_tmin = opts.s_tmin
self.s_tmax = float('inf') # not representable as a standard ui option
self.s_noise = opts.s_noise
def init(self): if not seed_enable_extras:
self.subseed = -1
self.subseed_strength = 0
self.seed_resize_from_h = 0
self.seed_resize_from_w = 0
def init(self, all_prompts, all_seeds, all_subseeds):
pass pass
def sample(self, x, conditioning, unconditional_conditioning): def sample(self, conditioning, unconditional_conditioning, seeds, subseeds, subseed_strength):
raise NotImplementedError() raise NotImplementedError()
class Processed: class Processed:
def __init__(self, p: StableDiffusionProcessing, images_list, seed, info): def __init__(self, p: StableDiffusionProcessing, images_list, seed=-1, info="", subseed=None, all_prompts=None, all_seeds=None, all_subseeds=None, index_of_first_image=0, infotexts=None):
self.images = images_list self.images = images_list
self.prompt = p.prompt self.prompt = p.prompt
self.negative_prompt = p.negative_prompt
self.seed = seed self.seed = seed
self.subseed = subseed
self.subseed_strength = p.subseed_strength
self.info = info self.info = info
self.width = p.width self.width = p.width
self.height = p.height self.height = p.height
self.sampler = samplers[p.sampler_index].name self.sampler_index = p.sampler_index
self.sampler = sd_samplers.samplers[p.sampler_index].name
self.cfg_scale = p.cfg_scale self.cfg_scale = p.cfg_scale
self.steps = p.steps self.steps = p.steps
self.batch_size = p.batch_size
self.restore_faces = p.restore_faces
self.face_restoration_model = opts.face_restoration_model if p.restore_faces else None
self.sd_model_hash = shared.sd_model.sd_model_hash
self.seed_resize_from_w = p.seed_resize_from_w
self.seed_resize_from_h = p.seed_resize_from_h
self.denoising_strength = getattr(p, 'denoising_strength', None)
self.extra_generation_params = p.extra_generation_params
self.index_of_first_image = index_of_first_image
self.eta = p.eta
self.ddim_discretize = p.ddim_discretize
self.s_churn = p.s_churn
self.s_tmin = p.s_tmin
self.s_tmax = p.s_tmax
self.s_noise = p.s_noise
self.sampler_noise_scheduler_override = p.sampler_noise_scheduler_override
self.prompt = self.prompt if type(self.prompt) != list else self.prompt[0]
self.negative_prompt = self.negative_prompt if type(self.negative_prompt) != list else self.negative_prompt[0]
self.seed = int(self.seed if type(self.seed) != list else self.seed[0])
self.subseed = int(self.subseed if type(self.subseed) != list else self.subseed[0]) if self.subseed is not None else -1
self.all_prompts = all_prompts or [self.prompt]
self.all_seeds = all_seeds or [self.seed]
self.all_subseeds = all_subseeds or [self.subseed]
self.infotexts = infotexts or [info]
def js(self): def js(self):
obj = { obj = {
"prompt": self.prompt if type(self.prompt) != list else self.prompt[0], "prompt": self.prompt,
"seed": int(self.seed if type(self.seed) != list else self.seed[0]), "all_prompts": self.all_prompts,
"negative_prompt": self.negative_prompt,
"seed": self.seed,
"all_seeds": self.all_seeds,
"subseed": self.subseed,
"all_subseeds": self.all_subseeds,
"subseed_strength": self.subseed_strength,
"width": self.width, "width": self.width,
"height": self.height, "height": self.height,
"sampler_index": self.sampler_index,
"sampler": self.sampler, "sampler": self.sampler,
"cfg_scale": self.cfg_scale, "cfg_scale": self.cfg_scale,
"steps": self.steps, "steps": self.steps,
"batch_size": self.batch_size,
"restore_faces": self.restore_faces,
"face_restoration_model": self.face_restoration_model,
"sd_model_hash": self.sd_model_hash,
"seed_resize_from_w": self.seed_resize_from_w,
"seed_resize_from_h": self.seed_resize_from_h,
"denoising_strength": self.denoising_strength,
"extra_generation_params": self.extra_generation_params,
"index_of_first_image": self.index_of_first_image,
"infotexts": self.infotexts,
} }
return json.dumps(obj) return json.dumps(obj)
def infotext(self, p: StableDiffusionProcessing, index):
return create_infotext(p, self.all_prompts, self.all_seeds, self.all_subseeds, comments=[], position_in_batch=index % self.batch_size, iteration=index // self.batch_size)
def create_random_tensors(shape, seeds):
# from https://discuss.pytorch.org/t/help-regarding-slerp-function-for-generative-model-sampling/32475/3
def slerp(val, low, high):
low_norm = low/torch.norm(low, dim=1, keepdim=True)
high_norm = high/torch.norm(high, dim=1, keepdim=True)
dot = (low_norm*high_norm).sum(1)
if dot.mean() > 0.9995:
return low * val + high * (1 - val)
omega = torch.acos(dot)
so = torch.sin(omega)
res = (torch.sin((1.0-val)*omega)/so).unsqueeze(1)*low + (torch.sin(val*omega)/so).unsqueeze(1) * high
return res
def create_random_tensors(shape, seeds, subseeds=None, subseed_strength=0.0, seed_resize_from_h=0, seed_resize_from_w=0, p=None):
xs = [] xs = []
for seed in seeds:
torch.manual_seed(seed) # if we have multiple seeds, this means we are working with batch size>1; this then
# enables the generation of additional tensors with noise that the sampler will use during its processing.
# Using those pre-generated tensors instead of simple torch.randn allows a batch with seeds [100, 101] to
# produce the same images as with two batches [100], [101].
if p is not None and p.sampler is not None and len(seeds) > 1 and opts.enable_batch_seeds:
sampler_noises = [[] for _ in range(p.sampler.number_of_needed_noises(p))]
else:
sampler_noises = None
for i, seed in enumerate(seeds):
noise_shape = shape if seed_resize_from_h <= 0 or seed_resize_from_w <= 0 else (shape[0], seed_resize_from_h//8, seed_resize_from_w//8)
subnoise = None
if subseeds is not None:
subseed = 0 if i >= len(subseeds) else subseeds[i]
subnoise = devices.randn(subseed, noise_shape)
# randn results depend on device; gpu and cpu get different results for same seed; # randn results depend on device; gpu and cpu get different results for same seed;
# the way I see it, it's better to do this on CPU, so that everyone gets same result; # the way I see it, it's better to do this on CPU, so that everyone gets same result;
# but the original script had it like this so I do not dare change it for now because # but the original script had it like this, so I do not dare change it for now because
# it will break everyone's seeds. # it will break everyone's seeds.
xs.append(torch.randn(shape, device=shared.device)) noise = devices.randn(seed, noise_shape)
x = torch.stack(xs)
if subnoise is not None:
noise = slerp(subseed_strength, noise, subnoise)
if noise_shape != shape:
x = devices.randn(seed, shape)
dx = (shape[2] - noise_shape[2]) // 2
dy = (shape[1] - noise_shape[1]) // 2
w = noise_shape[2] if dx >= 0 else noise_shape[2] + 2 * dx
h = noise_shape[1] if dy >= 0 else noise_shape[1] + 2 * dy
tx = 0 if dx < 0 else dx
ty = 0 if dy < 0 else dy
dx = max(-dx, 0)
dy = max(-dy, 0)
x[:, ty:ty+h, tx:tx+w] = noise[:, dy:dy+h, dx:dx+w]
noise = x
if sampler_noises is not None:
cnt = p.sampler.number_of_needed_noises(p)
for j in range(cnt):
sampler_noises[j].append(devices.randn_without_seed(tuple(noise_shape)))
xs.append(noise)
if sampler_noises is not None:
p.sampler.sampler_noises = [torch.stack(n).to(shared.device) for n in sampler_noises]
x = torch.stack(xs).to(shared.device)
return x return x
def set_seed(seed): def get_fixed_seed(seed):
return int(random.randrange(4294967294)) if seed is None or seed == -1 else seed if seed is None or seed == '' or seed == -1:
return int(random.randrange(4294967294))
return seed
def fix_seed(p):
p.seed = get_fixed_seed(p.seed)
p.subseed = get_fixed_seed(p.subseed)
def create_infotext(p, all_prompts, all_seeds, all_subseeds, comments, iteration=0, position_in_batch=0):
index = position_in_batch + iteration * p.batch_size
generation_params = {
"Steps": p.steps,
"Sampler": sd_samplers.samplers[p.sampler_index].name,
"CFG scale": p.cfg_scale,
"Seed": all_seeds[index],
"Face restoration": (opts.face_restoration_model if p.restore_faces else None),
"Size": f"{p.width}x{p.height}",
"Model hash": getattr(p, 'sd_model_hash', None if not opts.add_model_hash_to_info or not shared.sd_model.sd_model_hash else shared.sd_model.sd_model_hash),
"Batch size": (None if p.batch_size < 2 else p.batch_size),
"Batch pos": (None if p.batch_size < 2 else position_in_batch),
"Variation seed": (None if p.subseed_strength == 0 else all_subseeds[index]),
"Variation seed strength": (None if p.subseed_strength == 0 else p.subseed_strength),
"Seed resize from": (None if p.seed_resize_from_w == 0 or p.seed_resize_from_h == 0 else f"{p.seed_resize_from_w}x{p.seed_resize_from_h}"),
"Denoising strength": getattr(p, 'denoising_strength', None),
"Eta": (None if p.sampler is None or p.sampler.eta == p.sampler.default_eta else p.sampler.eta),
}
generation_params.update(p.extra_generation_params)
generation_params_text = ", ".join([k if k == v else f'{k}: {v}' for k, v in generation_params.items() if v is not None])
negative_prompt_text = "\nNegative prompt: " + p.negative_prompt if p.negative_prompt else ""
return f"{all_prompts[index]}{negative_prompt_text}\n{generation_params_text}".strip()
def process_images(p: StableDiffusionProcessing) -> Processed: def process_images(p: StableDiffusionProcessing) -> Processed:
"""this is the main loop that both txt2img and img2img use; it calls func_init once inside all the scopes and func_sample once per batch""" """this is the main loop that both txt2img and img2img use; it calls func_init once inside all the scopes and func_sample once per batch"""
prompt = p.prompt if type(p.prompt) == list:
assert(len(p.prompt) > 0)
else:
assert p.prompt is not None assert p.prompt is not None
torch_gc()
seed = set_seed(p.seed) devices.torch_gc()
seed = get_fixed_seed(p.seed)
subseed = get_fixed_seed(p.subseed)
if p.outpath_samples is not None:
os.makedirs(p.outpath_samples, exist_ok=True) os.makedirs(p.outpath_samples, exist_ok=True)
if p.outpath_grids is not None:
os.makedirs(p.outpath_grids, exist_ok=True) os.makedirs(p.outpath_grids, exist_ok=True)
modules.sd_hijack.model_hijack.apply_circular(p.tiling) modules.sd_hijack.model_hijack.apply_circular(p.tiling)
comments = [] comments = {}
if type(prompt) == list: shared.prompt_styles.apply_styles(p)
all_prompts = prompt
if type(p.prompt) == list:
all_prompts = p.prompt
else: else:
all_prompts = p.batch_size * p.n_iter * [prompt] all_prompts = p.batch_size * p.n_iter * [p.prompt]
if type(seed) == list: if type(seed) == list:
all_seeds = seed all_seeds = seed
else: else:
all_seeds = [int(seed + x) for x in range(len(all_prompts))] all_seeds = [int(seed) + (x if p.subseed_strength == 0 else 0) for x in range(len(all_prompts))]
if type(subseed) == list:
all_subseeds = subseed
else:
all_subseeds = [int(subseed) + x for x in range(len(all_prompts))]
def infotext(iteration=0, position_in_batch=0): def infotext(iteration=0, position_in_batch=0):
generation_params = { return create_infotext(p, all_prompts, all_seeds, all_subseeds, comments, iteration, position_in_batch)
"Steps": p.steps,
"Sampler": samplers[p.sampler_index].name,
"CFG scale": p.cfg_scale,
"Seed": all_seeds[position_in_batch + iteration * p.batch_size],
"Face restoration": (opts.face_restoration_model if p.restore_faces else None),
"Batch size": (None if p.batch_size < 2 else p.batch_size),
"Batch pos": (None if p.batch_size < 2 else position_in_batch),
}
if p.extra_generation_params is not None:
generation_params.update(p.extra_generation_params)
generation_params_text = ", ".join([k if k == v else f'{k}: {v}' for k, v in generation_params.items() if v is not None])
return f"{p.prompt_for_display or prompt}\n{generation_params_text}".strip() + "".join(["\n\n" + x for x in comments])
if os.path.exists(cmd_opts.embeddings_dir): if os.path.exists(cmd_opts.embeddings_dir):
model_hijack.load_textual_inversion_embeddings(cmd_opts.embeddings_dir, p.sd_model) model_hijack.embedding_db.load_textual_inversion_embeddings()
infotexts = []
output_images = [] output_images = []
precision_scope = torch.autocast if cmd_opts.precision == "autocast" else contextlib.nullcontext
ema_scope = (contextlib.nullcontext if cmd_opts.lowvram else p.sd_model.ema_scope) with torch.no_grad():
with torch.no_grad(), precision_scope("cuda"), ema_scope(): with devices.autocast():
p.init() p.init(all_prompts, all_seeds, all_subseeds)
if state.job_count == -1: if state.job_count == -1:
state.job_count = p.n_iter state.job_count = p.n_iter
@@ -166,40 +350,62 @@ def process_images(p: StableDiffusionProcessing) -> Processed:
prompts = all_prompts[n * p.batch_size:(n + 1) * p.batch_size] prompts = all_prompts[n * p.batch_size:(n + 1) * p.batch_size]
seeds = all_seeds[n * p.batch_size:(n + 1) * p.batch_size] seeds = all_seeds[n * p.batch_size:(n + 1) * p.batch_size]
subseeds = all_subseeds[n * p.batch_size:(n + 1) * p.batch_size]
uc = p.sd_model.get_learned_conditioning(len(prompts) * [p.negative_prompt]) if (len(prompts) == 0):
c = p.sd_model.get_learned_conditioning(prompts) break
#uc = p.sd_model.get_learned_conditioning(len(prompts) * [p.negative_prompt])
#c = p.sd_model.get_learned_conditioning(prompts)
with devices.autocast():
uc = prompt_parser.get_learned_conditioning(shared.sd_model, len(prompts) * [p.negative_prompt], p.steps)
c = prompt_parser.get_multicond_learned_conditioning(shared.sd_model, prompts, p.steps)
if len(model_hijack.comments) > 0: if len(model_hijack.comments) > 0:
comments += model_hijack.comments for comment in model_hijack.comments:
comments[comment] = 1
# we manually generate all input noises because each one should have a specific seed
x = create_random_tensors([opt_C, p.height // opt_f, p.width // opt_f], seeds=seeds)
if p.n_iter > 1: if p.n_iter > 1:
shared.state.job = f"Batch {n+1} out of {p.n_iter}" shared.state.job = f"Batch {n+1} out of {p.n_iter}"
samples_ddim = p.sample(x=x, conditioning=c, unconditional_conditioning=uc) with devices.autocast():
samples_ddim = p.sample(conditioning=c, unconditional_conditioning=uc, seeds=seeds, subseeds=subseeds, subseed_strength=p.subseed_strength)
if state.interrupted: if state.interrupted:
# if we are interruped, sample returns just noise # if we are interruped, sample returns just noise
# use the image collected previously in sampler loop # use the image collected previously in sampler loop
samples_ddim = shared.state.current_latent samples_ddim = shared.state.current_latent
samples_ddim = samples_ddim.to(devices.dtype)
x_samples_ddim = p.sd_model.decode_first_stage(samples_ddim) x_samples_ddim = p.sd_model.decode_first_stage(samples_ddim)
x_samples_ddim = torch.clamp((x_samples_ddim + 1.0) / 2.0, min=0.0, max=1.0) x_samples_ddim = torch.clamp((x_samples_ddim + 1.0) / 2.0, min=0.0, max=1.0)
if opts.filter_nsfw:
import modules.safety as safety
x_samples_ddim = modules.safety.censor_batch(x_samples_ddim)
for i, x_sample in enumerate(x_samples_ddim): for i, x_sample in enumerate(x_samples_ddim):
x_sample = 255. * np.moveaxis(x_sample.cpu().numpy(), 0, 2) x_sample = 255. * np.moveaxis(x_sample.cpu().numpy(), 0, 2)
x_sample = x_sample.astype(np.uint8) x_sample = x_sample.astype(np.uint8)
if p.restore_faces: if p.restore_faces:
torch_gc() if opts.save and not p.do_not_save_samples and opts.save_images_before_face_restoration:
images.save_image(Image.fromarray(x_sample), p.outpath_samples, "", seeds[i], prompts[i], opts.samples_format, info=infotext(n, i), p=p, suffix="-before-face-restoration")
devices.torch_gc()
x_sample = modules.face_restoration.restore_faces(x_sample) x_sample = modules.face_restoration.restore_faces(x_sample)
devices.torch_gc()
image = Image.fromarray(x_sample) image = Image.fromarray(x_sample)
if p.color_corrections is not None and i < len(p.color_corrections):
if opts.save and not p.do_not_save_samples and opts.save_images_before_color_correction:
images.save_image(image, p.outpath_samples, "", seeds[i], prompts[i], opts.samples_format, info=infotext(n, i), p=p, suffix="-before-color-correction")
image = apply_color_correction(p.color_corrections[i], image)
if p.overlay_images is not None and i < len(p.overlay_images): if p.overlay_images is not None and i < len(p.overlay_images):
overlay = p.overlay_images[i] overlay = p.overlay_images[i]
@@ -215,94 +421,122 @@ def process_images(p: StableDiffusionProcessing) -> Processed:
image = image.convert('RGB') image = image.convert('RGB')
if opts.samples_save and not p.do_not_save_samples: if opts.samples_save and not p.do_not_save_samples:
images.save_image(image, p.outpath_samples, "", seeds[i], prompts[i], opts.samples_format, info=infotext(n, i)) images.save_image(image, p.outpath_samples, "", seeds[i], prompts[i], opts.samples_format, info=infotext(n, i), p=p)
infotexts.append(infotext(n, i))
output_images.append(image) output_images.append(image)
state.nextjob() state.nextjob()
unwanted_grid_because_of_img_count = len(output_images) < 2 and opts.grid_only_if_multiple p.color_corrections = None
if not p.do_not_save_grid and not unwanted_grid_because_of_img_count:
return_grid = opts.return_grid
index_of_first_image = 0
unwanted_grid_because_of_img_count = len(output_images) < 2 and opts.grid_only_if_multiple
if (opts.return_grid or opts.grid_save) and not p.do_not_save_grid and not unwanted_grid_because_of_img_count:
grid = images.image_grid(output_images, p.batch_size) grid = images.image_grid(output_images, p.batch_size)
if return_grid: if opts.return_grid:
infotexts.insert(0, infotext())
output_images.insert(0, grid) output_images.insert(0, grid)
index_of_first_image = 1
if opts.grid_save: if opts.grid_save:
images.save_image(grid, p.outpath_grids, "grid", seed, all_prompts[0], opts.grid_format, info=infotext(), short_filename=not opts.grid_extended_filename) images.save_image(grid, p.outpath_grids, "grid", all_seeds[0], all_prompts[0], opts.grid_format, info=infotext(), short_filename=not opts.grid_extended_filename, p=p, grid=True)
torch_gc() devices.torch_gc()
return Processed(p, output_images, seed, infotext()) return Processed(p, output_images, all_seeds[0], infotext() + "".join(["\n\n" + x for x in comments]), subseed=all_subseeds[0], all_prompts=all_prompts, all_seeds=all_seeds, all_subseeds=all_subseeds, index_of_first_image=index_of_first_image, infotexts=infotexts)
class StableDiffusionProcessingTxt2Img(StableDiffusionProcessing): class StableDiffusionProcessingTxt2Img(StableDiffusionProcessing):
sampler = None sampler = None
firstphase_width = 0
firstphase_height = 0
firstphase_width_truncated = 0
firstphase_height_truncated = 0
def init(self): def __init__(self, enable_hr=False, scale_latent=True, denoising_strength=0.75, **kwargs):
self.sampler = samplers[self.sampler_index].constructor(self.sd_model) super().__init__(**kwargs)
self.enable_hr = enable_hr
self.scale_latent = scale_latent
self.denoising_strength = denoising_strength
def sample(self, x, conditioning, unconditional_conditioning): def init(self, all_prompts, all_seeds, all_subseeds):
samples_ddim = self.sampler.sample(self, x, conditioning, unconditional_conditioning) if self.enable_hr:
return samples_ddim if state.job_count == -1:
state.job_count = self.n_iter * 2
else:
state.job_count = state.job_count * 2
desired_pixel_count = 512 * 512
actual_pixel_count = self.width * self.height
scale = math.sqrt(desired_pixel_count / actual_pixel_count)
def get_crop_region(mask, pad=0): self.firstphase_width = math.ceil(scale * self.width / 64) * 64
h, w = mask.shape self.firstphase_height = math.ceil(scale * self.height / 64) * 64
self.firstphase_width_truncated = int(scale * self.width)
self.firstphase_height_truncated = int(scale * self.height)
crop_left = 0 def sample(self, conditioning, unconditional_conditioning, seeds, subseeds, subseed_strength):
for i in range(w): self.sampler = sd_samplers.create_sampler_with_index(sd_samplers.samplers, self.sampler_index, self.sd_model)
if not (mask[:, i] == 0).all():
break
crop_left += 1
crop_right = 0 if not self.enable_hr:
for i in reversed(range(w)): x = create_random_tensors([opt_C, self.height // opt_f, self.width // opt_f], seeds=seeds, subseeds=subseeds, subseed_strength=self.subseed_strength, seed_resize_from_h=self.seed_resize_from_h, seed_resize_from_w=self.seed_resize_from_w, p=self)
if not (mask[:, i] == 0).all(): samples = self.sampler.sample(self, x, conditioning, unconditional_conditioning)
break return samples
crop_right += 1
crop_top = 0 x = create_random_tensors([opt_C, self.firstphase_height // opt_f, self.firstphase_width // opt_f], seeds=seeds, subseeds=subseeds, subseed_strength=self.subseed_strength, seed_resize_from_h=self.seed_resize_from_h, seed_resize_from_w=self.seed_resize_from_w, p=self)
for i in range(h): samples = self.sampler.sample(self, x, conditioning, unconditional_conditioning)
if not (mask[i] == 0).all():
break
crop_top += 1
crop_bottom = 0 truncate_x = (self.firstphase_width - self.firstphase_width_truncated) // opt_f
for i in reversed(range(h)): truncate_y = (self.firstphase_height - self.firstphase_height_truncated) // opt_f
if not (mask[i] == 0).all():
break
crop_bottom += 1
return ( samples = samples[:, :, truncate_y//2:samples.shape[2]-truncate_y//2, truncate_x//2:samples.shape[3]-truncate_x//2]
int(max(crop_left-pad, 0)),
int(max(crop_top-pad, 0)),
int(min(w - crop_right + pad, w)),
int(min(h - crop_bottom + pad, h))
)
if self.scale_latent:
samples = torch.nn.functional.interpolate(samples, size=(self.height // opt_f, self.width // opt_f), mode="bilinear")
else:
decoded_samples = self.sd_model.decode_first_stage(samples)
def fill(image, mask): if opts.upscaler_for_img2img is None or opts.upscaler_for_img2img == "None":
image_mod = Image.new('RGBA', (image.width, image.height)) decoded_samples = torch.nn.functional.interpolate(decoded_samples, size=(self.height, self.width), mode="bilinear")
else:
lowres_samples = torch.clamp((decoded_samples + 1.0) / 2.0, min=0.0, max=1.0)
image_masked = Image.new('RGBa', (image.width, image.height)) batch_images = []
image_masked.paste(image.convert("RGBA").convert("RGBa"), mask=ImageOps.invert(mask.convert('L'))) for i, x_sample in enumerate(lowres_samples):
x_sample = 255. * np.moveaxis(x_sample.cpu().numpy(), 0, 2)
x_sample = x_sample.astype(np.uint8)
image = Image.fromarray(x_sample)
image = images.resize_image(0, image, self.width, self.height)
image = np.array(image).astype(np.float32) / 255.0
image = np.moveaxis(image, 2, 0)
batch_images.append(image)
image_masked = image_masked.convert('RGBa') decoded_samples = torch.from_numpy(np.array(batch_images))
decoded_samples = decoded_samples.to(shared.device)
decoded_samples = 2. * decoded_samples - 1.
for radius, repeats in [(256, 1), (64, 1), (16, 2), (4, 4), (2, 2), (0, 1)]: samples = self.sd_model.get_first_stage_encoding(self.sd_model.encode_first_stage(decoded_samples))
blurred = image_masked.filter(ImageFilter.GaussianBlur(radius)).convert('RGBA')
for _ in range(repeats):
image_mod.alpha_composite(blurred)
return image_mod.convert("RGB") shared.state.nextjob()
self.sampler = sd_samplers.create_sampler_with_index(sd_samplers.samplers, self.sampler_index, self.sd_model)
noise = create_random_tensors(samples.shape[1:], seeds=seeds, subseeds=subseeds, subseed_strength=subseed_strength, seed_resize_from_h=self.seed_resize_from_h, seed_resize_from_w=self.seed_resize_from_w, p=self)
# GC now before running the next img2img to prevent running out of memory
x = None
devices.torch_gc()
samples = self.sampler.sample_img2img(self, samples, noise, conditioning, unconditional_conditioning, steps=self.steps)
return samples
class StableDiffusionProcessingImg2Img(StableDiffusionProcessing): class StableDiffusionProcessingImg2Img(StableDiffusionProcessing):
sampler = None sampler = None
def __init__(self, init_images=None, resize_mode=0, denoising_strength=0.75, mask=None, mask_blur=4, inpainting_fill=0, inpaint_full_res=True, inpainting_mask_invert=0, **kwargs): def __init__(self, init_images=None, resize_mode=0, denoising_strength=0.75, mask=None, mask_blur=4, inpainting_fill=0, inpaint_full_res=True, inpaint_full_res_padding=0, inpainting_mask_invert=0, **kwargs):
super().__init__(**kwargs) super().__init__(**kwargs)
self.init_images = init_images self.init_images = init_images
@@ -316,12 +550,13 @@ class StableDiffusionProcessingImg2Img(StableDiffusionProcessing):
self.mask_blur = mask_blur self.mask_blur = mask_blur
self.inpainting_fill = inpainting_fill self.inpainting_fill = inpainting_fill
self.inpaint_full_res = inpaint_full_res self.inpaint_full_res = inpaint_full_res
self.inpaint_full_res_padding = inpaint_full_res_padding
self.inpainting_mask_invert = inpainting_mask_invert self.inpainting_mask_invert = inpainting_mask_invert
self.mask = None self.mask = None
self.nmask = None self.nmask = None
def init(self): def init(self, all_prompts, all_seeds, all_subseeds):
self.sampler = samplers_for_img2img[self.sampler_index].constructor(self.sd_model) self.sampler = sd_samplers.create_sampler_with_index(sd_samplers.samplers_for_img2img, self.sampler_index, self.sd_model)
crop_region = None crop_region = None
if self.image_mask is not None: if self.image_mask is not None:
@@ -338,7 +573,8 @@ class StableDiffusionProcessingImg2Img(StableDiffusionProcessing):
if self.inpaint_full_res: if self.inpaint_full_res:
self.mask_for_overlay = self.image_mask self.mask_for_overlay = self.image_mask
mask = self.image_mask.convert('L') mask = self.image_mask.convert('L')
crop_region = get_crop_region(np.array(mask), opts.upscale_at_full_resolution_padding) crop_region = masking.get_crop_region(np.array(mask), self.inpaint_full_res_padding)
crop_region = masking.expand_crop_region(crop_region, self.width, self.height, mask.width, mask.height)
x1, y1, x2, y2 = crop_region x1, y1, x2, y2 = crop_region
mask = mask.crop(crop_region) mask = mask.crop(crop_region)
@@ -347,11 +583,16 @@ class StableDiffusionProcessingImg2Img(StableDiffusionProcessing):
else: else:
self.image_mask = images.resize_image(self.resize_mode, self.image_mask, self.width, self.height) self.image_mask = images.resize_image(self.resize_mode, self.image_mask, self.width, self.height)
np_mask = np.array(self.image_mask) np_mask = np.array(self.image_mask)
np_mask = 255 - np.clip((255 - np_mask.astype(np.float)) * 2, 0, 255).astype(np.uint8) np_mask = np.clip((np_mask.astype(np.float32)) * 2, 0, 255).astype(np.uint8)
self.mask_for_overlay = Image.fromarray(np_mask) self.mask_for_overlay = Image.fromarray(np_mask)
self.overlay_images = [] self.overlay_images = []
latent_mask = self.latent_mask if self.latent_mask is not None else self.image_mask
add_color_corrections = opts.img2img_color_correction and self.color_corrections is None
if add_color_corrections:
self.color_corrections = []
imgs = [] imgs = []
for img in self.init_images: for img in self.init_images:
image = img.convert("RGB") image = img.convert("RGB")
@@ -360,9 +601,6 @@ class StableDiffusionProcessingImg2Img(StableDiffusionProcessing):
image = images.resize_image(self.resize_mode, image, self.width, self.height) image = images.resize_image(self.resize_mode, image, self.width, self.height)
if self.image_mask is not None: if self.image_mask is not None:
if self.inpainting_fill != 1:
image = fill(image, self.mask_for_overlay)
image_masked = Image.new('RGBa', (image.width, image.height)) image_masked = Image.new('RGBa', (image.width, image.height))
image_masked.paste(image.convert("RGBA").convert("RGBa"), mask=ImageOps.invert(self.mask_for_overlay.convert('L'))) image_masked.paste(image.convert("RGBA").convert("RGBa"), mask=ImageOps.invert(self.mask_for_overlay.convert('L')))
@@ -372,6 +610,13 @@ class StableDiffusionProcessingImg2Img(StableDiffusionProcessing):
image = image.crop(crop_region) image = image.crop(crop_region)
image = images.resize_image(2, image, self.width, self.height) image = images.resize_image(2, image, self.width, self.height)
if self.image_mask is not None:
if self.inpainting_fill != 1:
image = masking.fill(image, latent_mask)
if add_color_corrections:
self.color_corrections.append(setup_color_correction(image))
image = np.array(image).astype(np.float32) / 255.0 image = np.array(image).astype(np.float32) / 255.0
image = np.moveaxis(image, 2, 0) image = np.moveaxis(image, 2, 0)
@@ -394,21 +639,25 @@ class StableDiffusionProcessingImg2Img(StableDiffusionProcessing):
self.init_latent = self.sd_model.get_first_stage_encoding(self.sd_model.encode_first_stage(image)) self.init_latent = self.sd_model.get_first_stage_encoding(self.sd_model.encode_first_stage(image))
if self.image_mask is not None: if self.image_mask is not None:
init_mask = self.latent_mask if self.latent_mask is not None else self.image_mask init_mask = latent_mask
latmask = init_mask.convert('RGB').resize((self.init_latent.shape[3], self.init_latent.shape[2])) latmask = init_mask.convert('RGB').resize((self.init_latent.shape[3], self.init_latent.shape[2]))
latmask = np.moveaxis(np.array(latmask, dtype=np.float64), 2, 0) / 255 latmask = np.moveaxis(np.array(latmask, dtype=np.float32), 2, 0) / 255
latmask = latmask[0] latmask = latmask[0]
latmask = np.around(latmask)
latmask = np.tile(latmask[None], (4, 1, 1)) latmask = np.tile(latmask[None], (4, 1, 1))
self.mask = torch.asarray(1.0 - latmask).to(shared.device).type(self.sd_model.dtype) self.mask = torch.asarray(1.0 - latmask).to(shared.device).type(self.sd_model.dtype)
self.nmask = torch.asarray(latmask).to(shared.device).type(self.sd_model.dtype) self.nmask = torch.asarray(latmask).to(shared.device).type(self.sd_model.dtype)
# this needs to be fixed to be done in sample() using actual seeds for batches
if self.inpainting_fill == 2: if self.inpainting_fill == 2:
self.init_latent = self.init_latent * self.mask + create_random_tensors(self.init_latent.shape[1:], [self.seed + x + 1 for x in range(self.init_latent.shape[0])]) * self.nmask self.init_latent = self.init_latent * self.mask + create_random_tensors(self.init_latent.shape[1:], all_seeds[0:self.init_latent.shape[0]]) * self.nmask
elif self.inpainting_fill == 3: elif self.inpainting_fill == 3:
self.init_latent = self.init_latent * self.mask self.init_latent = self.init_latent * self.mask
def sample(self, x, conditioning, unconditional_conditioning): def sample(self, conditioning, unconditional_conditioning, seeds, subseeds, subseed_strength):
x = create_random_tensors([opt_C, self.height // opt_f, self.width // opt_f], seeds=seeds, subseeds=subseeds, subseed_strength=self.subseed_strength, seed_resize_from_h=self.seed_resize_from_h, seed_resize_from_w=self.seed_resize_from_w, p=self)
samples = self.sampler.sample_img2img(self, self.init_latent, x, conditioning, unconditional_conditioning) samples = self.sampler.sample_img2img(self, self.init_latent, x, conditioning, unconditional_conditioning)
if self.mask is not None: if self.mask is not None:
+352
View File
@@ -0,0 +1,352 @@
import re
from collections import namedtuple
from typing import List
import lark
# a prompt like this: "fantasy landscape with a [mountain:lake:0.25] and [an oak:a christmas tree:0.75][ in foreground::0.6][ in background:0.25] [shoddy:masterful:0.5]"
# will be represented with prompt_schedule like this (assuming steps=100):
# [25, 'fantasy landscape with a mountain and an oak in foreground shoddy']
# [50, 'fantasy landscape with a lake and an oak in foreground in background shoddy']
# [60, 'fantasy landscape with a lake and an oak in foreground in background masterful']
# [75, 'fantasy landscape with a lake and an oak in background masterful']
# [100, 'fantasy landscape with a lake and a christmas tree in background masterful']
schedule_parser = lark.Lark(r"""
!start: (prompt | /[][():]/+)*
prompt: (emphasized | scheduled | plain | WHITESPACE)*
!emphasized: "(" prompt ")"
| "(" prompt ":" prompt ")"
| "[" prompt "]"
scheduled: "[" [prompt ":"] prompt ":" [WHITESPACE] NUMBER "]"
WHITESPACE: /\s+/
plain: /([^\\\[\]():]|\\.)+/
%import common.SIGNED_NUMBER -> NUMBER
""")
def get_learned_conditioning_prompt_schedules(prompts, steps):
"""
>>> g = lambda p: get_learned_conditioning_prompt_schedules([p], 10)[0]
>>> g("test")
[[10, 'test']]
>>> g("a [b:3]")
[[3, 'a '], [10, 'a b']]
>>> g("a [b: 3]")
[[3, 'a '], [10, 'a b']]
>>> g("a [[[b]]:2]")
[[2, 'a '], [10, 'a [[b]]']]
>>> g("[(a:2):3]")
[[3, ''], [10, '(a:2)']]
>>> g("a [b : c : 1] d")
[[1, 'a b d'], [10, 'a c d']]
>>> g("a[b:[c:d:2]:1]e")
[[1, 'abe'], [2, 'ace'], [10, 'ade']]
>>> g("a [unbalanced")
[[10, 'a [unbalanced']]
>>> g("a [b:.5] c")
[[5, 'a c'], [10, 'a b c']]
>>> g("a [{b|d{:.5] c") # not handling this right now
[[5, 'a c'], [10, 'a {b|d{ c']]
>>> g("((a][:b:c [d:3]")
[[3, '((a][:b:c '], [10, '((a][:b:c d']]
"""
def collect_steps(steps, tree):
l = [steps]
class CollectSteps(lark.Visitor):
def scheduled(self, tree):
tree.children[-1] = float(tree.children[-1])
if tree.children[-1] < 1:
tree.children[-1] *= steps
tree.children[-1] = min(steps, int(tree.children[-1]))
l.append(tree.children[-1])
CollectSteps().visit(tree)
return sorted(set(l))
def at_step(step, tree):
class AtStep(lark.Transformer):
def scheduled(self, args):
before, after, _, when = args
yield before or () if step <= when else after
def start(self, args):
def flatten(x):
if type(x) == str:
yield x
else:
for gen in x:
yield from flatten(gen)
return ''.join(flatten(args))
def plain(self, args):
yield args[0].value
def __default__(self, data, children, meta):
for child in children:
yield from child
return AtStep().transform(tree)
def get_schedule(prompt):
try:
tree = schedule_parser.parse(prompt)
except lark.exceptions.LarkError as e:
if 0:
import traceback
traceback.print_exc()
return [[steps, prompt]]
return [[t, at_step(t, tree)] for t in collect_steps(steps, tree)]
promptdict = {prompt: get_schedule(prompt) for prompt in set(prompts)}
return [promptdict[prompt] for prompt in prompts]
ScheduledPromptConditioning = namedtuple("ScheduledPromptConditioning", ["end_at_step", "cond"])
def get_learned_conditioning(model, prompts, steps):
"""converts a list of prompts into a list of prompt schedules - each schedule is a list of ScheduledPromptConditioning, specifying the comdition (cond),
and the sampling step at which this condition is to be replaced by the next one.
Input:
(model, ['a red crown', 'a [blue:green:5] jeweled crown'], 20)
Output:
[
[
ScheduledPromptConditioning(end_at_step=20, cond=tensor([[-0.3886, 0.0229, -0.0523, ..., -0.4901, -0.3066, 0.0674], ..., [ 0.3317, -0.5102, -0.4066, ..., 0.4119, -0.7647, -1.0160]], device='cuda:0'))
],
[
ScheduledPromptConditioning(end_at_step=5, cond=tensor([[-0.3886, 0.0229, -0.0522, ..., -0.4901, -0.3067, 0.0673], ..., [-0.0192, 0.3867, -0.4644, ..., 0.1135, -0.3696, -0.4625]], device='cuda:0')),
ScheduledPromptConditioning(end_at_step=20, cond=tensor([[-0.3886, 0.0229, -0.0522, ..., -0.4901, -0.3067, 0.0673], ..., [-0.7352, -0.4356, -0.7888, ..., 0.6994, -0.4312, -1.2593]], device='cuda:0'))
]
]
"""
res = []
prompt_schedules = get_learned_conditioning_prompt_schedules(prompts, steps)
cache = {}
for prompt, prompt_schedule in zip(prompts, prompt_schedules):
cached = cache.get(prompt, None)
if cached is not None:
res.append(cached)
continue
texts = [x[1] for x in prompt_schedule]
conds = model.get_learned_conditioning(texts)
cond_schedule = []
for i, (end_at_step, text) in enumerate(prompt_schedule):
cond_schedule.append(ScheduledPromptConditioning(end_at_step, conds[i]))
cache[prompt] = cond_schedule
res.append(cond_schedule)
return res
re_AND = re.compile(r"\bAND\b")
re_weight = re.compile(r"^(.*?)(?:\s*:\s*([-+]?(?:\d+\.?|\d*\.\d+)))?\s*$")
def get_multicond_prompt_list(prompts):
res_indexes = []
prompt_flat_list = []
prompt_indexes = {}
for prompt in prompts:
subprompts = re_AND.split(prompt)
indexes = []
for subprompt in subprompts:
match = re_weight.search(subprompt)
text, weight = match.groups() if match is not None else (subprompt, 1.0)
weight = float(weight) if weight is not None else 1.0
index = prompt_indexes.get(text, None)
if index is None:
index = len(prompt_flat_list)
prompt_flat_list.append(text)
prompt_indexes[text] = index
indexes.append((index, weight))
res_indexes.append(indexes)
return res_indexes, prompt_flat_list, prompt_indexes
class ComposableScheduledPromptConditioning:
def __init__(self, schedules, weight=1.0):
self.schedules: List[ScheduledPromptConditioning] = schedules
self.weight: float = weight
class MulticondLearnedConditioning:
def __init__(self, shape, batch):
self.shape: tuple = shape # the shape field is needed to send this object to DDIM/PLMS
self.batch: List[List[ComposableScheduledPromptConditioning]] = batch
def get_multicond_learned_conditioning(model, prompts, steps) -> MulticondLearnedConditioning:
"""same as get_learned_conditioning, but returns a list of ScheduledPromptConditioning along with the weight objects for each prompt.
For each prompt, the list is obtained by splitting the prompt using the AND separator.
https://energy-based-model.github.io/Compositional-Visual-Generation-with-Composable-Diffusion-Models/
"""
res_indexes, prompt_flat_list, prompt_indexes = get_multicond_prompt_list(prompts)
learned_conditioning = get_learned_conditioning(model, prompt_flat_list, steps)
res = []
for indexes in res_indexes:
res.append([ComposableScheduledPromptConditioning(learned_conditioning[i], weight) for i, weight in indexes])
return MulticondLearnedConditioning(shape=(len(prompts),), batch=res)
def reconstruct_cond_batch(c: List[List[ScheduledPromptConditioning]], current_step):
param = c[0][0].cond
res = torch.zeros((len(c),) + param.shape, device=param.device, dtype=param.dtype)
for i, cond_schedule in enumerate(c):
target_index = 0
for current, (end_at, cond) in enumerate(cond_schedule):
if current_step <= end_at:
target_index = current
break
res[i] = cond_schedule[target_index].cond
return res
def reconstruct_multicond_batch(c: MulticondLearnedConditioning, current_step):
param = c.batch[0][0].schedules[0].cond
tensors = []
conds_list = []
for batch_no, composable_prompts in enumerate(c.batch):
conds_for_batch = []
for cond_index, composable_prompt in enumerate(composable_prompts):
target_index = 0
for current, (end_at, cond) in enumerate(composable_prompt.schedules):
if current_step <= end_at:
target_index = current
break
conds_for_batch.append((len(tensors), composable_prompt.weight))
tensors.append(composable_prompt.schedules[target_index].cond)
conds_list.append(conds_for_batch)
return conds_list, torch.stack(tensors).to(device=param.device, dtype=param.dtype)
re_attention = re.compile(r"""
\\\(|
\\\)|
\\\[|
\\]|
\\\\|
\\|
\(|
\[|
:([+-]?[.\d]+)\)|
\)|
]|
[^\\()\[\]:]+|
:
""", re.X)
def parse_prompt_attention(text):
"""
Parses a string with attention tokens and returns a list of pairs: text and its assoicated weight.
Accepted tokens are:
(abc) - increases attention to abc by a multiplier of 1.1
(abc:3.12) - increases attention to abc by a multiplier of 3.12
[abc] - decreases attention to abc by a multiplier of 1.1
\( - literal character '('
\[ - literal character '['
\) - literal character ')'
\] - literal character ']'
\\ - literal character '\'
anything else - just text
>>> parse_prompt_attention('normal text')
[['normal text', 1.0]]
>>> parse_prompt_attention('an (important) word')
[['an ', 1.0], ['important', 1.1], [' word', 1.0]]
>>> parse_prompt_attention('(unbalanced')
[['unbalanced', 1.1]]
>>> parse_prompt_attention('\(literal\]')
[['(literal]', 1.0]]
>>> parse_prompt_attention('(unnecessary)(parens)')
[['unnecessaryparens', 1.1]]
>>> parse_prompt_attention('a (((house:1.3)) [on] a (hill:0.5), sun, (((sky))).')
[['a ', 1.0],
['house', 1.5730000000000004],
[' ', 1.1],
['on', 1.0],
[' a ', 1.1],
['hill', 0.55],
[', sun, ', 1.1],
['sky', 1.4641000000000006],
['.', 1.1]]
"""
res = []
round_brackets = []
square_brackets = []
round_bracket_multiplier = 1.1
square_bracket_multiplier = 1 / 1.1
def multiply_range(start_position, multiplier):
for p in range(start_position, len(res)):
res[p][1] *= multiplier
for m in re_attention.finditer(text):
text = m.group(0)
weight = m.group(1)
if text.startswith('\\'):
res.append([text[1:], 1.0])
elif text == '(':
round_brackets.append(len(res))
elif text == '[':
square_brackets.append(len(res))
elif weight is not None and len(round_brackets) > 0:
multiply_range(round_brackets.pop(), float(weight))
elif text == ')' and len(round_brackets) > 0:
multiply_range(round_brackets.pop(), round_bracket_multiplier)
elif text == ']' and len(square_brackets) > 0:
multiply_range(square_brackets.pop(), square_bracket_multiplier)
else:
res.append([text, 1.0])
for pos in round_brackets:
multiply_range(pos, round_bracket_multiplier)
for pos in square_brackets:
multiply_range(pos, square_bracket_multiplier)
if len(res) == 0:
res = [["", 1.0]]
# merge runs of identical weights
i = 0
while i + 1 < len(res):
if res[i][1] == res[i + 1][1]:
res[i][0] += res[i + 1][0]
res.pop(i + 1)
else:
i += 1
return res
if __name__ == "__main__":
import doctest
doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
else:
import torch # doctest faster
+112 -62
View File
@@ -1,85 +1,135 @@
import os
import sys import sys
import traceback import traceback
from collections import namedtuple
import numpy as np import numpy as np
from PIL import Image from PIL import Image
from basicsr.utils.download_util import load_file_from_url
from realesrgan import RealESRGANer
import modules.images from modules.upscaler import Upscaler, UpscalerData
from modules.shared import cmd_opts from modules.paths import models_path
from modules.shared import cmd_opts, opts
RealesrganModelInfo = namedtuple("RealesrganModelInfo", ["name", "location", "model", "netscale"])
realesrgan_models = []
have_realesrgan = False
RealESRGANer_constructor = None
class UpscalerRealESRGAN(modules.images.Upscaler): class UpscalerRealESRGAN(Upscaler):
def __init__(self, upscaling, model_index): def __init__(self, path):
self.upscaling = upscaling self.name = "RealESRGAN"
self.model_index = model_index self.model_path = os.path.join(models_path, self.name)
self.name = realesrgan_models[model_index].name self.user_path = path
super().__init__()
def do_upscale(self, img):
return upscale_with_realesrgan(img, self.upscaling, self.model_index)
def setup_realesrgan():
global realesrgan_models
global have_realesrgan
global RealESRGANer_constructor
try: try:
from basicsr.archs.rrdbnet_arch import RRDBNet from basicsr.archs.rrdbnet_arch import RRDBNet
from realesrgan import RealESRGANer from realesrgan import RealESRGANer
from realesrgan.archs.srvgg_arch import SRVGGNetCompact from realesrgan.archs.srvgg_arch import SRVGGNetCompact
self.enable = True
realesrgan_models = [ self.scalers = []
RealesrganModelInfo( scalers = self.load_models(path)
name="Real-ESRGAN 4x plus", for scaler in scalers:
location="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth", if scaler.name in opts.realesrgan_enabled_models:
netscale=4, model=lambda: RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4) self.scalers.append(scaler)
),
RealesrganModelInfo(
name="Real-ESRGAN 4x plus anime 6B",
location="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth",
netscale=4, model=lambda: RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4)
),
RealesrganModelInfo(
name="Real-ESRGAN 2x plus",
location="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth",
netscale=2, model=lambda: RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2)
),
]
have_realesrgan = True
RealESRGANer_constructor = RealESRGANer
for i, model in enumerate(realesrgan_models):
modules.shared.sd_upscalers.append(UpscalerRealESRGAN(model.netscale, i))
except Exception: except Exception:
print("Error importing Real-ESRGAN:", file=sys.stderr) print("Error importing Real-ESRGAN:", file=sys.stderr)
print(traceback.format_exc(), file=sys.stderr) print(traceback.format_exc(), file=sys.stderr)
self.enable = False
self.scalers = []
realesrgan_models = [RealesrganModelInfo('None', '', 0, None)] def do_upscale(self, img, path):
have_realesrgan = False if not self.enable:
return img
info = self.load_model(path)
if not os.path.exists(info.data_path):
print("Unable to load RealESRGAN model: %s" % info.name)
return img
def upscale_with_realesrgan(image, RealESRGAN_upscaling, RealESRGAN_model_index): upsampler = RealESRGANer(
if not have_realesrgan or RealESRGANer_constructor is None: scale=info.scale,
return image model_path=info.data_path,
model=info.model(),
info = realesrgan_models[RealESRGAN_model_index] half=not cmd_opts.no_half,
tile=opts.ESRGAN_tile,
model = info.model() tile_pad=opts.ESRGAN_tile_overlap,
upsampler = RealESRGANer_constructor(
scale=info.netscale,
model_path=info.location,
model=model,
half=not cmd_opts.no_half
) )
upsampled = upsampler.enhance(np.array(image), outscale=RealESRGAN_upscaling)[0] upsampled = upsampler.enhance(np.array(img), outscale=info.scale)[0]
image = Image.fromarray(upsampled) image = Image.fromarray(upsampled)
return image return image
def load_model(self, path):
try:
info = None
for scaler in self.scalers:
if scaler.data_path == path:
info = scaler
if info is None:
print(f"Unable to find model info: {path}")
return None
model_file = load_file_from_url(url=info.data_path, model_dir=self.model_path, progress=True)
info.data_path = model_file
return info
except Exception as e:
print(f"Error making Real-ESRGAN models list: {e}", file=sys.stderr)
print(traceback.format_exc(), file=sys.stderr)
return None
def load_models(self, _):
return get_realesrgan_models(self)
def get_realesrgan_models(scaler):
try:
from basicsr.archs.rrdbnet_arch import RRDBNet
from realesrgan.archs.srvgg_arch import SRVGGNetCompact
models = [
UpscalerData(
name="R-ESRGAN General 4xV3",
path="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth",
scale=4,
upscaler=scaler,
model=lambda: SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=32, upscale=4, act_type='prelu')
),
UpscalerData(
name="R-ESRGAN General WDN 4xV3",
path="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-wdn-x4v3.pth",
scale=4,
upscaler=scaler,
model=lambda: SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=32, upscale=4, act_type='prelu')
),
UpscalerData(
name="R-ESRGAN AnimeVideo",
path="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth",
scale=4,
upscaler=scaler,
model=lambda: SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=4, act_type='prelu')
),
UpscalerData(
name="R-ESRGAN 4x+",
path="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth",
scale=4,
upscaler=scaler,
model=lambda: RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)
),
UpscalerData(
name="R-ESRGAN 4x+ Anime6B",
path="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth",
scale=4,
upscaler=scaler,
model=lambda: RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4)
),
UpscalerData(
name="R-ESRGAN 2x+",
path="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth",
scale=2,
upscaler=scaler,
model=lambda: RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2)
),
]
return models
except Exception as e:
print("Error making Real-ESRGAN models list:", file=sys.stderr)
print(traceback.format_exc(), file=sys.stderr)
+42
View File
@@ -0,0 +1,42 @@
import torch
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from transformers import AutoFeatureExtractor
from PIL import Image
import modules.shared as shared
safety_model_id = "CompVis/stable-diffusion-safety-checker"
safety_feature_extractor = None
safety_checker = None
def numpy_to_pil(images):
"""
Convert a numpy image or a batch of images to a PIL image.
"""
if images.ndim == 3:
images = images[None, ...]
images = (images * 255).round().astype("uint8")
pil_images = [Image.fromarray(image) for image in images]
return pil_images
# check and replace nsfw content
def check_safety(x_image):
global safety_feature_extractor, safety_checker
if safety_feature_extractor is None:
safety_feature_extractor = AutoFeatureExtractor.from_pretrained(safety_model_id)
safety_checker = StableDiffusionSafetyChecker.from_pretrained(safety_model_id)
safety_checker_input = safety_feature_extractor(numpy_to_pil(x_image), return_tensors="pt")
x_checked_image, has_nsfw_concept = safety_checker(images=x_image, clip_input=safety_checker_input.pixel_values)
return x_checked_image, has_nsfw_concept
def censor_batch(x):
x_samples_ddim_numpy = x.cpu().permute(0, 2, 3, 1).numpy()
x_checked_image, has_nsfw_concept = check_safety(x_samples_ddim_numpy)
x = torch.from_numpy(x_checked_image).permute(0, 3, 1, 2)
return x
+60 -3
View File
@@ -6,24 +6,44 @@ import modules.ui as ui
import gradio as gr import gradio as gr
from modules.processing import StableDiffusionProcessing from modules.processing import StableDiffusionProcessing
from modules import shared
class Script: class Script:
filename = None filename = None
args_from = None args_from = None
args_to = None args_to = None
# The title of the script. This is what will be displayed in the dropdown menu.
def title(self): def title(self):
raise NotImplementedError() raise NotImplementedError()
# How the script is displayed in the UI. See https://gradio.app/docs/#components
# for the different UI components you can use and how to create them.
# Most UI components can return a value, such as a boolean for a checkbox.
# The returned values are passed to the run method as parameters.
def ui(self, is_img2img): def ui(self, is_img2img):
pass pass
# Determines when the script should be shown in the dropdown menu via the
# returned value. As an example:
# is_img2img is True if the current tab is img2img, and False if it is txt2img.
# Thus, return is_img2img to only show the script on the img2img tab.
def show(self, is_img2img): def show(self, is_img2img):
return True return True
# This is where the additional processing is implemented. The parameters include
# self, the model object "p" (a StableDiffusionProcessing class, see
# processing.py), and the parameters returned by the ui method.
# Custom functions can be defined here, and additional libraries can be imported
# to be used in processing. The return value should be a Processed object, which is
# what is returned by the process_images method.
def run(self, *args): def run(self, *args):
raise NotImplementedError() raise NotImplementedError()
# The description method is currently unused.
# To add a description that appears when hovering over the title, amend the "titles"
# dict in script.js to include the script title (returned by title) as a key, and
# your description as the value.
def describe(self): def describe(self):
return "" return ""
@@ -35,16 +55,16 @@ def load_scripts(basedir):
if not os.path.exists(basedir): if not os.path.exists(basedir):
return return
for filename in os.listdir(basedir): for filename in sorted(os.listdir(basedir)):
path = os.path.join(basedir, filename) path = os.path.join(basedir, filename)
if not os.path.isfile(path): if not os.path.isfile(path):
continue continue
try:
with open(path, "r", encoding="utf8") as file: with open(path, "r", encoding="utf8") as file:
text = file.read() text = file.read()
try:
from types import ModuleType from types import ModuleType
compiled = compile(text, path, 'exec') compiled = compile(text, path, 'exec')
module = ModuleType(filename) module = ModuleType(filename)
@@ -91,6 +111,7 @@ class ScriptRunner:
for script in self.scripts: for script in self.scripts:
script.args_from = len(inputs) script.args_from = len(inputs)
script.args_to = len(inputs)
controls = wrap_call(script.ui, script.filename, "ui", is_img2img) controls = wrap_call(script.ui, script.filename, "ui", is_img2img)
@@ -98,6 +119,7 @@ class ScriptRunner:
continue continue
for control in controls: for control in controls:
control.custom_script_source = os.path.basename(script.filename)
control.visible = False control.visible = False
inputs += controls inputs += controls
@@ -122,7 +144,6 @@ class ScriptRunner:
return inputs return inputs
def run(self, p: StableDiffusionProcessing, *args): def run(self, p: StableDiffusionProcessing, *args):
script_index = args[0] script_index = args[0]
@@ -137,8 +158,44 @@ class ScriptRunner:
script_args = args[script.args_from:script.args_to] script_args = args[script.args_from:script.args_to]
processed = script.run(p, *script_args) processed = script.run(p, *script_args)
shared.total_tqdm.clear()
return processed return processed
def reload_sources(self):
for si, script in list(enumerate(self.scripts)):
with open(script.filename, "r", encoding="utf8") as file:
args_from = script.args_from
args_to = script.args_to
filename = script.filename
text = file.read()
from types import ModuleType
compiled = compile(text, filename, 'exec')
module = ModuleType(script.filename)
exec(compiled, module.__dict__)
for key, script_class in module.__dict__.items():
if type(script_class) == type and issubclass(script_class, Script):
self.scripts[si] = script_class()
self.scripts[si].filename = filename
self.scripts[si].args_from = args_from
self.scripts[si].args_to = args_to
scripts_txt2img = ScriptRunner() scripts_txt2img = ScriptRunner()
scripts_img2img = ScriptRunner() scripts_img2img = ScriptRunner()
def reload_script_body_only():
scripts_txt2img.reload_sources()
scripts_img2img.reload_sources()
def reload_scripts(basedir):
global scripts_txt2img, scripts_img2img
scripts_data.clear()
load_scripts(basedir)
scripts_txt2img = ScriptRunner()
scripts_img2img = ScriptRunner()
+90
View File
@@ -0,0 +1,90 @@
import os.path
import sys
import traceback
import PIL.Image
import numpy as np
import torch
from basicsr.utils.download_util import load_file_from_url
import modules.upscaler
from modules import devices, modelloader
from modules.paths import models_path
from modules.scunet_model_arch import SCUNet as net
class UpscalerScuNET(modules.upscaler.Upscaler):
def __init__(self, dirname):
self.name = "ScuNET"
self.model_path = os.path.join(models_path, self.name)
self.model_name = "ScuNET GAN"
self.model_name2 = "ScuNET PSNR"
self.model_url = "https://github.com/cszn/KAIR/releases/download/v1.0/scunet_color_real_gan.pth"
self.model_url2 = "https://github.com/cszn/KAIR/releases/download/v1.0/scunet_color_real_psnr.pth"
self.user_path = dirname
super().__init__()
model_paths = self.find_models(ext_filter=[".pth"])
scalers = []
add_model2 = True
for file in model_paths:
if "http" in file:
name = self.model_name
else:
name = modelloader.friendly_name(file)
if name == self.model_name2 or file == self.model_url2:
add_model2 = False
try:
scaler_data = modules.upscaler.UpscalerData(name, file, self, 4)
scalers.append(scaler_data)
except Exception:
print(f"Error loading ScuNET model: {file}", file=sys.stderr)
print(traceback.format_exc(), file=sys.stderr)
if add_model2:
scaler_data2 = modules.upscaler.UpscalerData(self.model_name2, self.model_url2, self)
scalers.append(scaler_data2)
self.scalers = scalers
def do_upscale(self, img: PIL.Image, selected_file):
torch.cuda.empty_cache()
model = self.load_model(selected_file)
if model is None:
return img
device = devices.device_scunet
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)
img = img.to(device)
with torch.no_grad():
output = model(img)
output = output.squeeze().float().cpu().clamp_(0, 1).numpy()
output = 255. * np.moveaxis(output, 0, 2)
output = output.astype(np.uint8)
output = output[:, :, ::-1]
torch.cuda.empty_cache()
return PIL.Image.fromarray(output, 'RGB')
def load_model(self, path: str):
device = devices.device_scunet
if "http" in path:
filename = load_file_from_url(url=self.model_url, model_dir=self.model_path, file_name="%s.pth" % self.name,
progress=True)
else:
filename = path
if not os.path.exists(os.path.join(self.model_path, filename)) or filename is None:
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
+265
View File
@@ -0,0 +1,265 @@
# -*- 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 sqaure.
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)
# sqaure 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)
+156 -114
View File
@@ -1,3 +1,4 @@
import math
import os import os
import sys import sys
import traceback import traceback
@@ -5,98 +6,41 @@ import torch
import numpy as np import numpy as np
from torch import einsum from torch import einsum
import modules.textual_inversion.textual_inversion
from modules import prompt_parser, devices, sd_hijack_optimizations, shared
from modules.shared import opts, device, cmd_opts from modules.shared import opts, device, cmd_opts
from ldm.util import default
from einops import rearrange
import ldm.modules.attention import ldm.modules.attention
import ldm.modules.diffusionmodules.model
attention_CrossAttention_forward = ldm.modules.attention.CrossAttention.forward
diffusionmodules_model_nonlinearity = ldm.modules.diffusionmodules.model.nonlinearity
diffusionmodules_model_AttnBlock_forward = ldm.modules.diffusionmodules.model.AttnBlock.forward
# see https://github.com/basujindal/stable-diffusion/pull/117 for discussion def apply_optimizations():
def split_cross_attention_forward(self, x, context=None, mask=None): if cmd_opts.opt_split_attention_v1:
h = self.heads ldm.modules.attention.CrossAttention.forward = sd_hijack_optimizations.split_cross_attention_forward_v1
elif not cmd_opts.disable_opt_split_attention and (cmd_opts.opt_split_attention or torch.cuda.is_available()):
ldm.modules.attention.CrossAttention.forward = sd_hijack_optimizations.split_cross_attention_forward
ldm.modules.diffusionmodules.model.nonlinearity = sd_hijack_optimizations.nonlinearity_hijack
ldm.modules.diffusionmodules.model.AttnBlock.forward = sd_hijack_optimizations.cross_attention_attnblock_forward
q = self.to_q(x)
context = default(context, x)
k = self.to_k(context)
v = self.to_v(context)
del context, x
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v)) def undo_optimizations():
ldm.modules.attention.CrossAttention.forward = attention_CrossAttention_forward
r1 = torch.zeros(q.shape[0], q.shape[1], v.shape[2], device=q.device) ldm.modules.diffusionmodules.model.nonlinearity = diffusionmodules_model_nonlinearity
for i in range(0, q.shape[0], 2): ldm.modules.diffusionmodules.model.AttnBlock.forward = diffusionmodules_model_AttnBlock_forward
end = i + 2
s1 = einsum('b i d, b j d -> b i j', q[i:end], k[i:end])
s1 *= self.scale
s2 = s1.softmax(dim=-1)
del s1
r1[i:end] = einsum('b i j, b j d -> b i d', s2, v[i:end])
del s2
r2 = rearrange(r1, '(b h) n d -> b n (h d)', h=h)
del r1
return self.to_out(r2)
class StableDiffusionModelHijack: class StableDiffusionModelHijack:
ids_lookup = {}
word_embeddings = {}
word_embeddings_checksums = {}
fixes = None fixes = None
comments = [] comments = []
dir_mtime = None
layers = None layers = None
circular_enabled = False circular_enabled = False
clip = None
def load_textual_inversion_embeddings(self, dirname, model): embedding_db = modules.textual_inversion.textual_inversion.EmbeddingDatabase(cmd_opts.embeddings_dir)
mt = os.path.getmtime(dirname)
if self.dir_mtime is not None and mt <= self.dir_mtime:
return
self.dir_mtime = mt
self.ids_lookup.clear()
self.word_embeddings.clear()
tokenizer = model.cond_stage_model.tokenizer
def const_hash(a):
r = 0
for v in a:
r = (r * 281 ^ int(v) * 997) & 0xFFFFFFFF
return r
def process_file(path, filename):
name = os.path.splitext(filename)[0]
data = torch.load(path)
param_dict = data['string_to_param']
if hasattr(param_dict, '_parameters'):
param_dict = getattr(param_dict, '_parameters') # fix for torch 1.12.1 loading saved file from torch 1.11
assert len(param_dict) == 1, 'embedding file has multiple terms in it'
emb = next(iter(param_dict.items()))[1]
self.word_embeddings[name] = emb.detach()
self.word_embeddings_checksums[name] = f'{const_hash(emb.reshape(-1))&0xffff:04x}'
ids = tokenizer([name], add_special_tokens=False)['input_ids'][0]
first_id = ids[0]
if first_id not in self.ids_lookup:
self.ids_lookup[first_id] = []
self.ids_lookup[first_id].append((ids, name))
for fn in os.listdir(dirname):
try:
process_file(os.path.join(dirname, fn), fn)
except Exception:
print(f"Error loading emedding {fn}:", file=sys.stderr)
print(traceback.format_exc(), file=sys.stderr)
continue
print(f"Loaded a total of {len(self.word_embeddings)} text inversion embeddings.")
def hijack(self, m): def hijack(self, m):
model_embeddings = m.cond_stage_model.transformer.text_model.embeddings model_embeddings = m.cond_stage_model.transformer.text_model.embeddings
@@ -104,8 +48,9 @@ class StableDiffusionModelHijack:
model_embeddings.token_embedding = EmbeddingsWithFixes(model_embeddings.token_embedding, self) model_embeddings.token_embedding = EmbeddingsWithFixes(model_embeddings.token_embedding, self)
m.cond_stage_model = FrozenCLIPEmbedderWithCustomWords(m.cond_stage_model, self) m.cond_stage_model = FrozenCLIPEmbedderWithCustomWords(m.cond_stage_model, self)
if cmd_opts.opt_split_attention: self.clip = m.cond_stage_model
ldm.modules.attention.CrossAttention.forward = split_cross_attention_forward
apply_optimizations()
def flatten(el): def flatten(el):
flattened = [flatten(children) for children in el.children()] flattened = [flatten(children) for children in el.children()]
@@ -116,6 +61,14 @@ class StableDiffusionModelHijack:
self.layers = flatten(m) self.layers = flatten(m)
def undo_hijack(self, m):
if type(m.cond_stage_model) == FrozenCLIPEmbedderWithCustomWords:
m.cond_stage_model = m.cond_stage_model.wrapped
model_embeddings = m.cond_stage_model.transformer.text_model.embeddings
if type(model_embeddings.token_embedding) == EmbeddingsWithFixes:
model_embeddings.token_embedding = model_embeddings.token_embedding.wrapped
def apply_circular(self, enable): def apply_circular(self, enable):
if self.circular_enabled == enable: if self.circular_enabled == enable:
return return
@@ -125,12 +78,17 @@ class StableDiffusionModelHijack:
for layer in [layer for layer in self.layers if type(layer) == torch.nn.Conv2d]: for layer in [layer for layer in self.layers if type(layer) == torch.nn.Conv2d]:
layer.padding_mode = 'circular' if enable else 'zeros' layer.padding_mode = 'circular' if enable else 'zeros'
def tokenize(self, text):
max_length = self.clip.max_length - 2
_, remade_batch_tokens, _, _, _, token_count = self.clip.process_text([text])
return remade_batch_tokens[0], token_count, max_length
class FrozenCLIPEmbedderWithCustomWords(torch.nn.Module): class FrozenCLIPEmbedderWithCustomWords(torch.nn.Module):
def __init__(self, wrapped, hijack): def __init__(self, wrapped, hijack):
super().__init__() super().__init__()
self.wrapped = wrapped self.wrapped = wrapped
self.hijack = hijack self.hijack: StableDiffusionModelHijack = hijack
self.tokenizer = wrapped.tokenizer self.tokenizer = wrapped.tokenizer
self.max_length = wrapped.max_length self.max_length = wrapped.max_length
self.token_mults = {} self.token_mults = {}
@@ -151,14 +109,91 @@ class FrozenCLIPEmbedderWithCustomWords(torch.nn.Module):
if mult != 1.0: if mult != 1.0:
self.token_mults[ident] = mult self.token_mults[ident] = mult
def forward(self, text): def tokenize_line(self, line, used_custom_terms, hijack_comments):
self.hijack.fixes = []
self.hijack.comments = []
remade_batch_tokens = []
id_start = self.wrapped.tokenizer.bos_token_id id_start = self.wrapped.tokenizer.bos_token_id
id_end = self.wrapped.tokenizer.eos_token_id id_end = self.wrapped.tokenizer.eos_token_id
maxlen = self.wrapped.max_length - 2 maxlen = self.wrapped.max_length
if opts.enable_emphasis:
parsed = prompt_parser.parse_prompt_attention(line)
else:
parsed = [[line, 1.0]]
tokenized = self.wrapped.tokenizer([text for text, _ in parsed], truncation=False, add_special_tokens=False)["input_ids"]
fixes = []
remade_tokens = []
multipliers = []
for tokens, (text, weight) in zip(tokenized, parsed):
i = 0
while i < len(tokens):
token = tokens[i]
embedding, embedding_length_in_tokens = self.hijack.embedding_db.find_embedding_at_position(tokens, i)
if embedding is None:
remade_tokens.append(token)
multipliers.append(weight)
i += 1
else:
emb_len = int(embedding.vec.shape[0])
fixes.append((len(remade_tokens), embedding))
remade_tokens += [0] * emb_len
multipliers += [weight] * emb_len
used_custom_terms.append((embedding.name, embedding.checksum()))
i += embedding_length_in_tokens
if len(remade_tokens) > maxlen - 2:
vocab = {v: k for k, v in self.wrapped.tokenizer.get_vocab().items()}
ovf = remade_tokens[maxlen - 2:]
overflowing_words = [vocab.get(int(x), "") for x in ovf]
overflowing_text = self.wrapped.tokenizer.convert_tokens_to_string(''.join(overflowing_words))
hijack_comments.append(f"Warning: too many input tokens; some ({len(overflowing_words)}) have been truncated:\n{overflowing_text}\n")
token_count = len(remade_tokens)
remade_tokens = remade_tokens + [id_end] * (maxlen - 2 - len(remade_tokens))
remade_tokens = [id_start] + remade_tokens[0:maxlen - 2] + [id_end]
multipliers = multipliers + [1.0] * (maxlen - 2 - len(multipliers))
multipliers = [1.0] + multipliers[0:maxlen - 2] + [1.0]
return remade_tokens, fixes, multipliers, token_count
def process_text(self, texts):
used_custom_terms = [] used_custom_terms = []
remade_batch_tokens = []
hijack_comments = []
hijack_fixes = []
token_count = 0
cache = {}
batch_multipliers = []
for line in texts:
if line in cache:
remade_tokens, fixes, multipliers = cache[line]
else:
remade_tokens, fixes, multipliers, token_count = self.tokenize_line(line, used_custom_terms, hijack_comments)
cache[line] = (remade_tokens, fixes, multipliers)
remade_batch_tokens.append(remade_tokens)
hijack_fixes.append(fixes)
batch_multipliers.append(multipliers)
return batch_multipliers, remade_batch_tokens, used_custom_terms, hijack_comments, hijack_fixes, token_count
def process_text_old(self, text):
id_start = self.wrapped.tokenizer.bos_token_id
id_end = self.wrapped.tokenizer.eos_token_id
maxlen = self.wrapped.max_length
used_custom_terms = []
remade_batch_tokens = []
overflowing_words = []
hijack_comments = []
hijack_fixes = []
token_count = 0
cache = {} cache = {}
batch_tokens = self.wrapped.tokenizer(text, truncation=False, add_special_tokens=False)["input_ids"] batch_tokens = self.wrapped.tokenizer(text, truncation=False, add_special_tokens=False)["input_ids"]
@@ -178,41 +213,32 @@ class FrozenCLIPEmbedderWithCustomWords(torch.nn.Module):
while i < len(tokens): while i < len(tokens):
token = tokens[i] token = tokens[i]
possible_matches = self.hijack.ids_lookup.get(token, None) embedding, embedding_length_in_tokens = self.hijack.embedding_db.find_embedding_at_position(tokens, i)
mult_change = self.token_mults.get(token) if opts.enable_emphasis else None mult_change = self.token_mults.get(token) if opts.enable_emphasis else None
if mult_change is not None: if mult_change is not None:
mult *= mult_change mult *= mult_change
elif possible_matches is None: i += 1
elif embedding is None:
remade_tokens.append(token) remade_tokens.append(token)
multipliers.append(mult) multipliers.append(mult)
i += 1
else: else:
found = False emb_len = int(embedding.vec.shape[0])
for ids, word in possible_matches: fixes.append((len(remade_tokens), embedding))
if tokens[i:i+len(ids)] == ids:
emb_len = int(self.hijack.word_embeddings[word].shape[0])
fixes.append((len(remade_tokens), word))
remade_tokens += [0] * emb_len remade_tokens += [0] * emb_len
multipliers += [mult] * emb_len multipliers += [mult] * emb_len
i += len(ids) - 1 used_custom_terms.append((embedding.name, embedding.checksum()))
found = True i += embedding_length_in_tokens
used_custom_terms.append((word, self.hijack.word_embeddings_checksums[word]))
break
if not found:
remade_tokens.append(token)
multipliers.append(mult)
i += 1
if len(remade_tokens) > maxlen - 2: if len(remade_tokens) > maxlen - 2:
vocab = {v: k for k, v in self.wrapped.tokenizer.get_vocab().items()} vocab = {v: k for k, v in self.wrapped.tokenizer.get_vocab().items()}
ovf = remade_tokens[maxlen - 2:] ovf = remade_tokens[maxlen - 2:]
overflowing_words = [vocab.get(int(x), "") for x in ovf] overflowing_words = [vocab.get(int(x), "") for x in ovf]
overflowing_text = self.wrapped.tokenizer.convert_tokens_to_string(''.join(overflowing_words)) overflowing_text = self.wrapped.tokenizer.convert_tokens_to_string(''.join(overflowing_words))
hijack_comments.append(f"Warning: too many input tokens; some ({len(overflowing_words)}) have been truncated:\n{overflowing_text}\n")
self.hijack.comments.append(f"Warning: too many input tokens; some ({len(overflowing_words)}) have been truncated:\n{overflowing_text}\n") token_count = len(remade_tokens)
remade_tokens = remade_tokens + [id_end] * (maxlen - 2 - len(remade_tokens)) remade_tokens = remade_tokens + [id_end] * (maxlen - 2 - len(remade_tokens))
remade_tokens = [id_start] + remade_tokens[0:maxlen-2] + [id_end] remade_tokens = [id_start] + remade_tokens[0:maxlen-2] + [id_end]
cache[tuple_tokens] = (remade_tokens, fixes, multipliers) cache[tuple_tokens] = (remade_tokens, fixes, multipliers)
@@ -221,18 +247,29 @@ class FrozenCLIPEmbedderWithCustomWords(torch.nn.Module):
multipliers = [1.0] + multipliers[0:maxlen - 2] + [1.0] multipliers = [1.0] + multipliers[0:maxlen - 2] + [1.0]
remade_batch_tokens.append(remade_tokens) remade_batch_tokens.append(remade_tokens)
self.hijack.fixes.append(fixes) hijack_fixes.append(fixes)
batch_multipliers.append(multipliers) batch_multipliers.append(multipliers)
return batch_multipliers, remade_batch_tokens, used_custom_terms, hijack_comments, hijack_fixes, token_count
def forward(self, text):
if opts.use_old_emphasis_implementation:
batch_multipliers, remade_batch_tokens, used_custom_terms, hijack_comments, hijack_fixes, token_count = self.process_text_old(text)
else:
batch_multipliers, remade_batch_tokens, used_custom_terms, hijack_comments, hijack_fixes, token_count = self.process_text(text)
self.hijack.fixes = hijack_fixes
self.hijack.comments = hijack_comments
if len(used_custom_terms) > 0: if len(used_custom_terms) > 0:
self.hijack.comments.append("Used custom terms: " + ", ".join([f'{word} [{checksum}]' for word, checksum in used_custom_terms])) self.hijack.comments.append("Used embeddings: " + ", ".join([f'{word} [{checksum}]' for word, checksum in used_custom_terms]))
tokens = torch.asarray(remade_batch_tokens).to(device) tokens = torch.asarray(remade_batch_tokens).to(device)
outputs = self.wrapped.transformer(input_ids=tokens) outputs = self.wrapped.transformer(input_ids=tokens)
z = outputs.last_hidden_state z = outputs.last_hidden_state
# restoring original mean is likely not correct, but it seems to work well to prevent artifacts that happen otherwise # restoring original mean is likely not correct, but it seems to work well to prevent artifacts that happen otherwise
batch_multipliers = torch.asarray(np.array(batch_multipliers)).to(device) batch_multipliers = torch.asarray(batch_multipliers).to(device)
original_mean = z.mean() original_mean = z.mean()
z *= batch_multipliers.reshape(batch_multipliers.shape + (1,)).expand(z.shape) z *= batch_multipliers.reshape(batch_multipliers.shape + (1,)).expand(z.shape)
new_mean = z.mean() new_mean = z.mean()
@@ -253,15 +290,20 @@ class EmbeddingsWithFixes(torch.nn.Module):
inputs_embeds = self.wrapped(input_ids) inputs_embeds = self.wrapped(input_ids)
if batch_fixes is not None: if batch_fixes is None or len(batch_fixes) == 0 or max([len(x) for x in batch_fixes]) == 0:
for fixes, tensor in zip(batch_fixes, inputs_embeds):
for offset, word in fixes:
emb = self.embeddings.word_embeddings[word]
emb_len = min(tensor.shape[0]-offset, emb.shape[0])
tensor[offset:offset+emb_len] = self.embeddings.word_embeddings[word][0:emb_len]
return inputs_embeds return inputs_embeds
vecs = []
for fixes, tensor in zip(batch_fixes, inputs_embeds):
for offset, embedding in fixes:
emb = embedding.vec
emb_len = min(tensor.shape[0]-offset-1, emb.shape[0])
tensor = torch.cat([tensor[0:offset+1], emb[0:emb_len], tensor[offset+1+emb_len:]])
vecs.append(tensor)
return torch.stack(vecs)
def add_circular_option_to_conv_2d(): def add_circular_option_to_conv_2d():
conv2d_constructor = torch.nn.Conv2d.__init__ conv2d_constructor = torch.nn.Conv2d.__init__
+164
View File
@@ -0,0 +1,164 @@
import math
import torch
from torch import einsum
from ldm.util import default
from einops import rearrange
# see https://github.com/basujindal/stable-diffusion/pull/117 for discussion
def split_cross_attention_forward_v1(self, x, context=None, mask=None):
h = self.heads
q = self.to_q(x)
context = default(context, x)
k = self.to_k(context)
v = self.to_v(context)
del context, x
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
r1 = torch.zeros(q.shape[0], q.shape[1], v.shape[2], device=q.device)
for i in range(0, q.shape[0], 2):
end = i + 2
s1 = einsum('b i d, b j d -> b i j', q[i:end], k[i:end])
s1 *= self.scale
s2 = s1.softmax(dim=-1)
del s1
r1[i:end] = einsum('b i j, b j d -> b i d', s2, v[i:end])
del s2
r2 = rearrange(r1, '(b h) n d -> b n (h d)', h=h)
del r1
return self.to_out(r2)
# taken from https://github.com/Doggettx/stable-diffusion
def split_cross_attention_forward(self, x, context=None, mask=None):
h = self.heads
q_in = self.to_q(x)
context = default(context, x)
k_in = self.to_k(context) * self.scale
v_in = self.to_v(context)
del context, x
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q_in, k_in, v_in))
del q_in, k_in, v_in
r1 = torch.zeros(q.shape[0], q.shape[1], v.shape[2], device=q.device, dtype=q.dtype)
stats = torch.cuda.memory_stats(q.device)
mem_active = stats['active_bytes.all.current']
mem_reserved = stats['reserved_bytes.all.current']
mem_free_cuda, _ = torch.cuda.mem_get_info(torch.cuda.current_device())
mem_free_torch = mem_reserved - mem_active
mem_free_total = mem_free_cuda + mem_free_torch
gb = 1024 ** 3
tensor_size = q.shape[0] * q.shape[1] * k.shape[1] * q.element_size()
modifier = 3 if q.element_size() == 2 else 2.5
mem_required = tensor_size * modifier
steps = 1
if mem_required > mem_free_total:
steps = 2 ** (math.ceil(math.log(mem_required / mem_free_total, 2)))
# print(f"Expected tensor size:{tensor_size/gb:0.1f}GB, cuda free:{mem_free_cuda/gb:0.1f}GB "
# f"torch free:{mem_free_torch/gb:0.1f} total:{mem_free_total/gb:0.1f} steps:{steps}")
if steps > 64:
max_res = math.floor(math.sqrt(math.sqrt(mem_free_total / 2.5)) / 8) * 64
raise RuntimeError(f'Not enough memory, use lower resolution (max approx. {max_res}x{max_res}). '
f'Need: {mem_required / 64 / gb:0.1f}GB free, Have:{mem_free_total / gb:0.1f}GB free')
slice_size = q.shape[1] // steps if (q.shape[1] % steps) == 0 else q.shape[1]
for i in range(0, q.shape[1], slice_size):
end = i + slice_size
s1 = einsum('b i d, b j d -> b i j', q[:, i:end], k)
s2 = s1.softmax(dim=-1, dtype=q.dtype)
del s1
r1[:, i:end] = einsum('b i j, b j d -> b i d', s2, v)
del s2
del q, k, v
r2 = rearrange(r1, '(b h) n d -> b n (h d)', h=h)
del r1
return self.to_out(r2)
def nonlinearity_hijack(x):
# swish
t = torch.sigmoid(x)
x *= t
del t
return x
def cross_attention_attnblock_forward(self, x):
h_ = x
h_ = self.norm(h_)
q1 = self.q(h_)
k1 = self.k(h_)
v = self.v(h_)
# compute attention
b, c, h, w = q1.shape
q2 = q1.reshape(b, c, h*w)
del q1
q = q2.permute(0, 2, 1) # b,hw,c
del q2
k = k1.reshape(b, c, h*w) # b,c,hw
del k1
h_ = torch.zeros_like(k, device=q.device)
stats = torch.cuda.memory_stats(q.device)
mem_active = stats['active_bytes.all.current']
mem_reserved = stats['reserved_bytes.all.current']
mem_free_cuda, _ = torch.cuda.mem_get_info(torch.cuda.current_device())
mem_free_torch = mem_reserved - mem_active
mem_free_total = mem_free_cuda + mem_free_torch
tensor_size = q.shape[0] * q.shape[1] * k.shape[2] * q.element_size()
mem_required = tensor_size * 2.5
steps = 1
if mem_required > mem_free_total:
steps = 2**(math.ceil(math.log(mem_required / mem_free_total, 2)))
slice_size = q.shape[1] // steps if (q.shape[1] % steps) == 0 else q.shape[1]
for i in range(0, q.shape[1], slice_size):
end = i + slice_size
w1 = torch.bmm(q[:, i:end], k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j]
w2 = w1 * (int(c)**(-0.5))
del w1
w3 = torch.nn.functional.softmax(w2, dim=2, dtype=q.dtype)
del w2
# attend to values
v1 = v.reshape(b, c, h*w)
w4 = w3.permute(0, 2, 1) # b,hw,hw (first hw of k, second of q)
del w3
h_[:, :, i:end] = torch.bmm(v1, w4) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j]
del v1, w4
h2 = h_.reshape(b, c, h, w)
del h_
h3 = self.proj_out(h2)
del h2
h3 += x
return h3
+184
View File
@@ -0,0 +1,184 @@
import glob
import os.path
import sys
from collections import namedtuple
import torch
from omegaconf import OmegaConf
from ldm.util import instantiate_from_config
from modules import shared, modelloader, devices
from modules.paths import models_path
model_dir = "Stable-diffusion"
model_path = os.path.abspath(os.path.join(models_path, model_dir))
CheckpointInfo = namedtuple("CheckpointInfo", ['filename', 'title', 'hash', 'model_name'])
checkpoints_list = {}
try:
# this silences the annoying "Some weights of the model checkpoint were not used when initializing..." message at start.
from transformers import logging
logging.set_verbosity_error()
except Exception:
pass
def setup_model():
if not os.path.exists(model_path):
os.makedirs(model_path)
list_models()
def checkpoint_tiles():
return sorted([x.title for x in checkpoints_list.values()])
def list_models():
checkpoints_list.clear()
model_list = modelloader.load_models(model_path=model_path, command_path=shared.cmd_opts.ckpt_dir, ext_filter=[".ckpt"])
def modeltitle(path, shorthash):
abspath = os.path.abspath(path)
if shared.cmd_opts.ckpt_dir is not None and abspath.startswith(shared.cmd_opts.ckpt_dir):
name = abspath.replace(shared.cmd_opts.ckpt_dir, '')
elif abspath.startswith(model_path):
name = abspath.replace(model_path, '')
else:
name = os.path.basename(path)
if name.startswith("\\") or name.startswith("/"):
name = name[1:]
shortname = os.path.splitext(name.replace("/", "_").replace("\\", "_"))[0]
return f'{name} [{shorthash}]', shortname
cmd_ckpt = shared.cmd_opts.ckpt
if os.path.exists(cmd_ckpt):
h = model_hash(cmd_ckpt)
title, short_model_name = modeltitle(cmd_ckpt, h)
checkpoints_list[title] = CheckpointInfo(cmd_ckpt, title, h, short_model_name)
shared.opts.data['sd_model_checkpoint'] = title
elif cmd_ckpt is not None and cmd_ckpt != shared.default_sd_model_file:
print(f"Checkpoint in --ckpt argument not found (Possible it was moved to {model_path}: {cmd_ckpt}", file=sys.stderr)
for filename in model_list:
h = model_hash(filename)
title, short_model_name = modeltitle(filename, h)
checkpoints_list[title] = CheckpointInfo(filename, title, h, short_model_name)
def get_closet_checkpoint_match(searchString):
applicable = sorted([info for info in checkpoints_list.values() if searchString in info.title], key = lambda x:len(x.title))
if len(applicable) > 0:
return applicable[0]
return None
def model_hash(filename):
try:
with open(filename, "rb") as file:
import hashlib
m = hashlib.sha256()
file.seek(0x100000)
m.update(file.read(0x10000))
return m.hexdigest()[0:8]
except FileNotFoundError:
return 'NOFILE'
def select_checkpoint():
model_checkpoint = shared.opts.sd_model_checkpoint
checkpoint_info = checkpoints_list.get(model_checkpoint, None)
if checkpoint_info is not None:
return checkpoint_info
if len(checkpoints_list) == 0:
print(f"No checkpoints found. When searching for checkpoints, looked at:", file=sys.stderr)
if shared.cmd_opts.ckpt is not None:
print(f" - file {os.path.abspath(shared.cmd_opts.ckpt)}", file=sys.stderr)
print(f" - directory {model_path}", file=sys.stderr)
if shared.cmd_opts.ckpt_dir is not None:
print(f" - directory {os.path.abspath(shared.cmd_opts.ckpt_dir)}", file=sys.stderr)
print(f"Can't run without a checkpoint. Find and place a .ckpt file into any of those locations. The program will exit.", file=sys.stderr)
exit(1)
checkpoint_info = next(iter(checkpoints_list.values()))
if model_checkpoint is not None:
print(f"Checkpoint {model_checkpoint} not found; loading fallback {checkpoint_info.title}", file=sys.stderr)
return checkpoint_info
def load_model_weights(model, checkpoint_file, sd_model_hash):
print(f"Loading weights [{sd_model_hash}] from {checkpoint_file}")
pl_sd = torch.load(checkpoint_file, map_location="cpu")
if "global_step" in pl_sd:
print(f"Global Step: {pl_sd['global_step']}")
sd = pl_sd["state_dict"]
model.load_state_dict(sd, strict=False)
if shared.cmd_opts.opt_channelslast:
model.to(memory_format=torch.channels_last)
if not shared.cmd_opts.no_half:
model.half()
devices.dtype = torch.float32 if shared.cmd_opts.no_half else torch.float16
model.sd_model_hash = sd_model_hash
model.sd_model_checkpint = checkpoint_file
def load_model():
from modules import lowvram, sd_hijack
checkpoint_info = select_checkpoint()
sd_config = OmegaConf.load(shared.cmd_opts.config)
sd_model = instantiate_from_config(sd_config.model)
load_model_weights(sd_model, checkpoint_info.filename, checkpoint_info.hash)
if shared.cmd_opts.lowvram or shared.cmd_opts.medvram:
lowvram.setup_for_low_vram(sd_model, shared.cmd_opts.medvram)
else:
sd_model.to(shared.device)
sd_hijack.model_hijack.hijack(sd_model)
sd_model.eval()
print(f"Model loaded.")
return sd_model
def reload_model_weights(sd_model, info=None):
from modules import lowvram, devices, sd_hijack
checkpoint_info = info or select_checkpoint()
if sd_model.sd_model_checkpint == checkpoint_info.filename:
return
if shared.cmd_opts.lowvram or shared.cmd_opts.medvram:
lowvram.send_everything_to_cpu()
else:
sd_model.to(devices.cpu)
sd_hijack.model_hijack.undo_hijack(sd_model)
load_model_weights(sd_model, checkpoint_info.filename, checkpoint_info.hash)
sd_hijack.model_hijack.hijack(sd_model)
if not shared.cmd_opts.lowvram and not shared.cmd_opts.medvram:
sd_model.to(devices.device)
print(f"Weights loaded.")
return sd_model
+251 -65
View File
@@ -3,38 +3,83 @@ import numpy as np
import torch import torch
import tqdm import tqdm
from PIL import Image from PIL import Image
import inspect
import k_diffusion.sampling import k_diffusion.sampling
import ldm.models.diffusion.ddim import ldm.models.diffusion.ddim
import ldm.models.diffusion.plms import ldm.models.diffusion.plms
from modules import prompt_parser
from modules.shared import opts, cmd_opts, state from modules.shared import opts, cmd_opts, state
import modules.shared as shared import modules.shared as shared
SamplerData = namedtuple('SamplerData', ['name', 'constructor', 'aliases']) SamplerData = namedtuple('SamplerData', ['name', 'constructor', 'aliases', 'options'])
samplers_k_diffusion = [ samplers_k_diffusion = [
('Euler a', 'sample_euler_ancestral', ['k_euler_a']), ('Euler a', 'sample_euler_ancestral', ['k_euler_a'], {}),
('Euler', 'sample_euler', ['k_euler']), ('Euler', 'sample_euler', ['k_euler'], {}),
('LMS', 'sample_lms', ['k_lms']), ('LMS', 'sample_lms', ['k_lms'], {}),
('Heun', 'sample_heun', ['k_heun']), ('Heun', 'sample_heun', ['k_heun'], {}),
('DPM2', 'sample_dpm_2', ['k_dpm_2']), ('DPM2', 'sample_dpm_2', ['k_dpm_2'], {}),
('DPM2 a', 'sample_dpm_2_ancestral', ['k_dpm_2_a']), ('DPM2 a', 'sample_dpm_2_ancestral', ['k_dpm_2_a'], {}),
('DPM fast', 'sample_dpm_fast', ['k_dpm_fast'], {}),
('DPM adaptive', 'sample_dpm_adaptive', ['k_dpm_ad'], {}),
('LMS Karras', 'sample_lms', ['k_lms_ka'], {'scheduler': 'karras'}),
('DPM2 Karras', 'sample_dpm_2', ['k_dpm_2_ka'], {'scheduler': 'karras'}),
('DPM2 a Karras', 'sample_dpm_2_ancestral', ['k_dpm_2_a_ka'], {'scheduler': 'karras'}),
] ]
samplers_data_k_diffusion = [ samplers_data_k_diffusion = [
SamplerData(label, lambda model, funcname=funcname: KDiffusionSampler(funcname, model), aliases) SamplerData(label, lambda model, funcname=funcname: KDiffusionSampler(funcname, model), aliases, options)
for label, funcname, aliases in samplers_k_diffusion for label, funcname, aliases, options in samplers_k_diffusion
if hasattr(k_diffusion.sampling, funcname) if hasattr(k_diffusion.sampling, funcname)
] ]
samplers = [ all_samplers = [
*samplers_data_k_diffusion, *samplers_data_k_diffusion,
SamplerData('DDIM', lambda model: VanillaStableDiffusionSampler(ldm.models.diffusion.ddim.DDIMSampler, model), []), SamplerData('DDIM', lambda model: VanillaStableDiffusionSampler(ldm.models.diffusion.ddim.DDIMSampler, model), [], {}),
SamplerData('PLMS', lambda model: VanillaStableDiffusionSampler(ldm.models.diffusion.plms.PLMSSampler, model), []), SamplerData('PLMS', lambda model: VanillaStableDiffusionSampler(ldm.models.diffusion.plms.PLMSSampler, model), [], {}),
] ]
samplers_for_img2img = [x for x in samplers if x.name != 'PLMS']
samplers = []
samplers_for_img2img = []
def create_sampler_with_index(list_of_configs, index, model):
config = list_of_configs[index]
sampler = config.constructor(model)
sampler.config = config
return sampler
def set_samplers():
global samplers, samplers_for_img2img
hidden = set(opts.hide_samplers)
hidden_img2img = set(opts.hide_samplers + ['PLMS', 'DPM fast', 'DPM adaptive'])
samplers = [x for x in all_samplers if x.name not in hidden]
samplers_for_img2img = [x for x in all_samplers if x.name not in hidden_img2img]
set_samplers()
sampler_extra_params = {
'sample_euler': ['s_churn', 's_tmin', 's_tmax', 's_noise'],
'sample_heun': ['s_churn', 's_tmin', 's_tmax', 's_noise'],
'sample_dpm_2': ['s_churn', 's_tmin', 's_tmax', 's_noise'],
}
def setup_img2img_steps(p, steps=None):
if opts.img2img_fix_steps or steps is not None:
steps = int((steps or p.steps) / min(p.denoising_strength, 0.999)) if p.denoising_strength > 0 else 0
t_enc = p.steps - 1
else:
steps = p.steps
t_enc = int(min(p.denoising_strength, 0.999) * steps)
return steps, t_enc
def sample_to_image(samples): def sample_to_image(samples):
@@ -53,27 +98,21 @@ def store_latent(decoded):
shared.state.current_image = sample_to_image(decoded) shared.state.current_image = sample_to_image(decoded)
def p_sample_ddim_hook(sampler_wrapper, x_dec, cond, ts, *args, **kwargs):
if sampler_wrapper.mask is not None:
img_orig = sampler_wrapper.sampler.model.q_sample(sampler_wrapper.init_latent, ts)
x_dec = img_orig * sampler_wrapper.mask + sampler_wrapper.nmask * x_dec
store_latent(x_dec)
return sampler_wrapper.orig_p_sample_ddim(x_dec, cond, ts, *args, **kwargs)
def extended_tdqm(sequence, *args, desc=None, **kwargs): def extended_tdqm(sequence, *args, desc=None, **kwargs):
state.sampling_steps = len(sequence) state.sampling_steps = len(sequence)
state.sampling_step = 0 state.sampling_step = 0
for x in tqdm.tqdm(sequence, *args, desc=state.job, **kwargs): seq = sequence if cmd_opts.disable_console_progressbars else tqdm.tqdm(sequence, *args, desc=state.job, file=shared.progress_print_out, **kwargs)
for x in seq:
if state.interrupted: if state.interrupted:
break break
yield x yield x
state.sampling_step += 1 state.sampling_step += 1
shared.total_tqdm.update()
ldm.models.diffusion.ddim.tqdm = lambda *args, desc=None, **kwargs: extended_tdqm(*args, desc=desc, **kwargs) ldm.models.diffusion.ddim.tqdm = lambda *args, desc=None, **kwargs: extended_tdqm(*args, desc=desc, **kwargs)
@@ -83,33 +122,84 @@ ldm.models.diffusion.plms.tqdm = lambda *args, desc=None, **kwargs: extended_tdq
class VanillaStableDiffusionSampler: class VanillaStableDiffusionSampler:
def __init__(self, constructor, sd_model): def __init__(self, constructor, sd_model):
self.sampler = constructor(sd_model) self.sampler = constructor(sd_model)
self.orig_p_sample_ddim = self.sampler.p_sample_ddim if hasattr(self.sampler, 'p_sample_ddim') else None self.orig_p_sample_ddim = self.sampler.p_sample_ddim if hasattr(self.sampler, 'p_sample_ddim') else self.sampler.p_sample_plms
self.mask = None self.mask = None
self.nmask = None self.nmask = None
self.init_latent = None self.init_latent = None
self.sampler_noises = None
self.step = 0
self.eta = None
self.default_eta = 0.0
self.config = None
def sample_img2img(self, p, x, noise, conditioning, unconditional_conditioning): def number_of_needed_noises(self, p):
t_enc = int(min(p.denoising_strength, 0.999) * p.steps) return 0
# existing code fails with cetin step counts, like 9 def p_sample_ddim_hook(self, x_dec, cond, ts, unconditional_conditioning, *args, **kwargs):
conds_list, tensor = prompt_parser.reconstruct_multicond_batch(cond, self.step)
unconditional_conditioning = prompt_parser.reconstruct_cond_batch(unconditional_conditioning, self.step)
assert all([len(conds) == 1 for conds in conds_list]), 'composition via AND is not supported for DDIM/PLMS samplers'
cond = tensor
if self.mask is not None:
img_orig = self.sampler.model.q_sample(self.init_latent, ts)
x_dec = img_orig * self.mask + self.nmask * x_dec
res = self.orig_p_sample_ddim(x_dec, cond, ts, unconditional_conditioning=unconditional_conditioning, *args, **kwargs)
if self.mask is not None:
store_latent(self.init_latent * self.mask + self.nmask * res[1])
else:
store_latent(res[1])
self.step += 1
return res
def initialize(self, p):
self.eta = p.eta if p.eta is not None else opts.eta_ddim
for fieldname in ['p_sample_ddim', 'p_sample_plms']:
if hasattr(self.sampler, fieldname):
setattr(self.sampler, fieldname, self.p_sample_ddim_hook)
self.mask = p.mask if hasattr(p, 'mask') else None
self.nmask = p.nmask if hasattr(p, 'nmask') else None
def sample_img2img(self, p, x, noise, conditioning, unconditional_conditioning, steps=None):
steps, t_enc = setup_img2img_steps(p, steps)
self.initialize(p)
# existing code fails with cetain step counts, like 9
try: try:
self.sampler.make_schedule(ddim_num_steps=p.steps, verbose=False) self.sampler.make_schedule(ddim_num_steps=steps, ddim_eta=self.eta, ddim_discretize=p.ddim_discretize, verbose=False)
except Exception: except Exception:
self.sampler.make_schedule(ddim_num_steps=p.steps+1, verbose=False) self.sampler.make_schedule(ddim_num_steps=steps+1, ddim_eta=self.eta, ddim_discretize=p.ddim_discretize, verbose=False)
x1 = self.sampler.stochastic_encode(x, torch.tensor([t_enc] * int(x.shape[0])).to(shared.device), noise=noise) x1 = self.sampler.stochastic_encode(x, torch.tensor([t_enc] * int(x.shape[0])).to(shared.device), noise=noise)
self.sampler.p_sample_ddim = lambda x_dec, cond, ts, *args, **kwargs: p_sample_ddim_hook(self, x_dec, cond, ts, *args, **kwargs) self.init_latent = x
self.mask = p.mask self.step = 0
self.nmask = p.nmask
self.init_latent = p.init_latent
samples = self.sampler.decode(x1, conditioning, t_enc, unconditional_guidance_scale=p.cfg_scale, unconditional_conditioning=unconditional_conditioning) samples = self.sampler.decode(x1, conditioning, t_enc, unconditional_guidance_scale=p.cfg_scale, unconditional_conditioning=unconditional_conditioning)
return samples return samples
def sample(self, p, x, conditioning, unconditional_conditioning): def sample(self, p, x, conditioning, unconditional_conditioning, steps=None):
samples_ddim, _ = self.sampler.sample(S=p.steps, conditioning=conditioning, batch_size=int(x.shape[0]), shape=x[0].shape, verbose=False, unconditional_guidance_scale=p.cfg_scale, unconditional_conditioning=unconditional_conditioning, x_T=x) self.initialize(p)
self.init_latent = None
self.step = 0
steps = steps or p.steps
# existing code fails with cetin step counts, like 9
try:
samples_ddim, _ = self.sampler.sample(S=steps, conditioning=conditioning, batch_size=int(x.shape[0]), shape=x[0].shape, verbose=False, unconditional_guidance_scale=p.cfg_scale, unconditional_conditioning=unconditional_conditioning, x_T=x, eta=self.eta)
except Exception:
samples_ddim, _ = self.sampler.sample(S=steps+1, conditioning=conditioning, batch_size=int(x.shape[0]), shape=x[0].shape, verbose=False, unconditional_guidance_scale=p.cfg_scale, unconditional_conditioning=unconditional_conditioning, x_T=x, eta=self.eta)
return samples_ddim return samples_ddim
@@ -120,73 +210,169 @@ class CFGDenoiser(torch.nn.Module):
self.mask = None self.mask = None
self.nmask = None self.nmask = None
self.init_latent = None self.init_latent = None
self.step = 0
def forward(self, x, sigma, uncond, cond, cond_scale): def forward(self, x, sigma, uncond, cond, cond_scale):
conds_list, tensor = prompt_parser.reconstruct_multicond_batch(cond, self.step)
uncond = prompt_parser.reconstruct_cond_batch(uncond, self.step)
batch_size = len(conds_list)
repeats = [len(conds_list[i]) for i in range(batch_size)]
x_in = torch.cat([torch.stack([x[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [x])
sigma_in = torch.cat([torch.stack([sigma[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [sigma])
cond_in = torch.cat([tensor, uncond])
if shared.batch_cond_uncond: if shared.batch_cond_uncond:
x_in = torch.cat([x] * 2) x_out = self.inner_model(x_in, sigma_in, cond=cond_in)
sigma_in = torch.cat([sigma] * 2)
cond_in = torch.cat([uncond, cond])
uncond, cond = self.inner_model(x_in, sigma_in, cond=cond_in).chunk(2)
denoised = uncond + (cond - uncond) * cond_scale
else: else:
uncond = self.inner_model(x, sigma, cond=uncond) x_out = torch.zeros_like(x_in)
cond = self.inner_model(x, sigma, cond=cond) for batch_offset in range(0, x_out.shape[0], batch_size):
denoised = uncond + (cond - uncond) * cond_scale a = batch_offset
b = a + batch_size
x_out[a:b] = self.inner_model(x_in[a:b], sigma_in[a:b], cond=cond_in[a:b])
denoised_uncond = x_out[-batch_size:]
denoised = torch.clone(denoised_uncond)
for i, conds in enumerate(conds_list):
for cond_index, weight in conds:
denoised[i] += (x_out[cond_index] - denoised_uncond[i]) * (weight * cond_scale)
if self.mask is not None: if self.mask is not None:
denoised = self.init_latent * self.mask + self.nmask * denoised denoised = self.init_latent * self.mask + self.nmask * denoised
self.step += 1
return denoised return denoised
def extended_trange(count, *args, **kwargs): def extended_trange(sampler, count, *args, **kwargs):
state.sampling_steps = count state.sampling_steps = count
state.sampling_step = 0 state.sampling_step = 0
for x in tqdm.trange(count, *args, desc=state.job, **kwargs): seq = range(count) if cmd_opts.disable_console_progressbars else tqdm.trange(count, *args, desc=state.job, file=shared.progress_print_out, **kwargs)
for x in seq:
if state.interrupted: if state.interrupted:
break break
if sampler.stop_at is not None and x > sampler.stop_at:
break
yield x yield x
state.sampling_step += 1 state.sampling_step += 1
shared.total_tqdm.update()
class TorchHijack:
def __init__(self, kdiff_sampler):
self.kdiff_sampler = kdiff_sampler
def __getattr__(self, item):
if item == 'randn_like':
return self.kdiff_sampler.randn_like
if hasattr(torch, item):
return getattr(torch, item)
raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, item))
class KDiffusionSampler: class KDiffusionSampler:
def __init__(self, funcname, sd_model): def __init__(self, funcname, sd_model):
self.model_wrap = k_diffusion.external.CompVisDenoiser(sd_model) self.model_wrap = k_diffusion.external.CompVisDenoiser(sd_model, quantize=shared.opts.enable_quantization)
self.funcname = funcname self.funcname = funcname
self.func = getattr(k_diffusion.sampling, self.funcname) self.func = getattr(k_diffusion.sampling, self.funcname)
self.extra_params = sampler_extra_params.get(funcname, [])
self.model_wrap_cfg = CFGDenoiser(self.model_wrap) self.model_wrap_cfg = CFGDenoiser(self.model_wrap)
self.sampler_noises = None
self.sampler_noise_index = 0
self.stop_at = None
self.eta = None
self.default_eta = 1.0
self.config = None
def callback_state(self, d): def callback_state(self, d):
store_latent(d["denoised"]) store_latent(d["denoised"])
def sample_img2img(self, p, x, noise, conditioning, unconditional_conditioning): def number_of_needed_noises(self, p):
t_enc = int(min(p.denoising_strength, 0.999) * p.steps) return p.steps
sigmas = self.model_wrap.get_sigmas(p.steps)
noise = noise * sigmas[p.steps - t_enc - 1]
def randn_like(self, x):
noise = self.sampler_noises[self.sampler_noise_index] if self.sampler_noises is not None and self.sampler_noise_index < len(self.sampler_noises) else None
if noise is not None and x.shape == noise.shape:
res = noise
else:
res = torch.randn_like(x)
self.sampler_noise_index += 1
return res
def initialize(self, p):
self.model_wrap_cfg.mask = p.mask if hasattr(p, 'mask') else None
self.model_wrap_cfg.nmask = p.nmask if hasattr(p, 'nmask') else None
self.model_wrap.step = 0
self.sampler_noise_index = 0
self.eta = p.eta or opts.eta_ancestral
if hasattr(k_diffusion.sampling, 'trange'):
k_diffusion.sampling.trange = lambda *args, **kwargs: extended_trange(self, *args, **kwargs)
if self.sampler_noises is not None:
k_diffusion.sampling.torch = TorchHijack(self)
extra_params_kwargs = {}
for param_name in self.extra_params:
if hasattr(p, param_name) and param_name in inspect.signature(self.func).parameters:
extra_params_kwargs[param_name] = getattr(p, param_name)
if 'eta' in inspect.signature(self.func).parameters:
extra_params_kwargs['eta'] = self.eta
return extra_params_kwargs
def sample_img2img(self, p, x, noise, conditioning, unconditional_conditioning, steps=None):
steps, t_enc = setup_img2img_steps(p, steps)
if p.sampler_noise_scheduler_override:
sigmas = p.sampler_noise_scheduler_override(steps)
else:
sigmas = self.model_wrap.get_sigmas(steps)
noise = noise * sigmas[steps - t_enc - 1]
xi = x + noise xi = x + noise
sigma_sched = sigmas[p.steps - t_enc - 1:] extra_params_kwargs = self.initialize(p)
self.model_wrap_cfg.mask = p.mask sigma_sched = sigmas[steps - t_enc - 1:]
self.model_wrap_cfg.nmask = p.nmask
self.model_wrap_cfg.init_latent = p.init_latent
if hasattr(k_diffusion.sampling, 'trange'): self.model_wrap_cfg.init_latent = x
k_diffusion.sampling.trange = lambda *args, **kwargs: extended_trange(*args, **kwargs)
return self.func(self.model_wrap_cfg, xi, sigma_sched, extra_args={'cond': conditioning, 'uncond': unconditional_conditioning, 'cond_scale': p.cfg_scale}, disable=False, callback=self.callback_state) return self.func(self.model_wrap_cfg, xi, sigma_sched, extra_args={'cond': conditioning, 'uncond': unconditional_conditioning, 'cond_scale': p.cfg_scale}, disable=False, callback=self.callback_state, **extra_params_kwargs)
def sample(self, p, x, conditioning, unconditional_conditioning, steps=None):
steps = steps or p.steps
if p.sampler_noise_scheduler_override:
sigmas = p.sampler_noise_scheduler_override(steps)
elif self.config is not None and self.config.options.get('scheduler', None) == 'karras':
sigmas = k_diffusion.sampling.get_sigmas_karras(n=steps, sigma_min=0.1, sigma_max=10, device=shared.device)
else:
sigmas = self.model_wrap.get_sigmas(steps)
def sample(self, p, x, conditioning, unconditional_conditioning):
sigmas = self.model_wrap.get_sigmas(p.steps)
x = x * sigmas[0] x = x * sigmas[0]
if hasattr(k_diffusion.sampling, 'trange'): extra_params_kwargs = self.initialize(p)
k_diffusion.sampling.trange = lambda *args, **kwargs: extended_trange(*args, **kwargs) if 'sigma_min' in inspect.signature(self.func).parameters:
extra_params_kwargs['sigma_min'] = self.model_wrap.sigmas[0].item()
samples_ddim = self.func(self.model_wrap_cfg, x, sigmas, extra_args={'cond': conditioning, 'uncond': unconditional_conditioning, 'cond_scale': p.cfg_scale}, disable=False, callback=self.callback_state) extra_params_kwargs['sigma_max'] = self.model_wrap.sigmas[-1].item()
return samples_ddim if 'n' in inspect.signature(self.func).parameters:
extra_params_kwargs['n'] = steps
else:
extra_params_kwargs['sigmas'] = sigmas
samples = self.func(self.model_wrap_cfg, x, extra_args={'cond': conditioning, 'uncond': unconditional_conditioning, 'cond_scale': p.cfg_scale}, disable=False, callback=self.callback_state, **extra_params_kwargs)
return samples
+255 -60
View File
@@ -1,59 +1,95 @@
import argparse import argparse
import datetime
import json import json
import os import os
import sys
import gradio as gr import gradio as gr
import torch import tqdm
import modules.artists import modules.artists
import modules.interrogate
import modules.memmon
import modules.sd_models
import modules.styles
import modules.devices as devices
from modules import sd_samplers
from modules.paths import script_path, sd_path from modules.paths import script_path, sd_path
import modules.codeformer_model
config_filename = "config.json"
sd_model_file = os.path.join(script_path, 'model.ckpt') sd_model_file = os.path.join(script_path, 'model.ckpt')
if not os.path.exists(sd_model_file): default_sd_model_file = sd_model_file
sd_model_file = "models/ldm/stable-diffusion-v1/model.ckpt" model_path = os.path.join(script_path, 'models')
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument("--config", type=str, default=os.path.join(sd_path, "configs/stable-diffusion/v1-inference.yaml"), help="path to config which constructs model",) parser.add_argument("--config", type=str, default=os.path.join(sd_path, "configs/stable-diffusion/v1-inference.yaml"), help="path to config which constructs model",)
parser.add_argument("--ckpt", type=str, default=os.path.join(sd_path, sd_model_file), help="path to checkpoint of model",) parser.add_argument("--ckpt", type=str, default=sd_model_file, help="path to checkpoint of stable diffusion model; if specified, this checkpoint will be added to the list of checkpoints and loaded",)
parser.add_argument("--ckpt-dir", type=str, default=None, help="Path to directory with stable diffusion checkpoints")
parser.add_argument("--gfpgan-dir", type=str, help="GFPGAN directory", default=('./src/gfpgan' if os.path.exists('./src/gfpgan') else './GFPGAN')) parser.add_argument("--gfpgan-dir", type=str, help="GFPGAN directory", default=('./src/gfpgan' if os.path.exists('./src/gfpgan') else './GFPGAN'))
parser.add_argument("--gfpgan-model", type=str, help="GFPGAN model file name", default='GFPGANv1.3.pth') parser.add_argument("--gfpgan-model", type=str, help="GFPGAN model file name", default=None)
parser.add_argument("--no-half", action='store_true', help="do not switch the model to 16-bit floats") parser.add_argument("--no-half", action='store_true', help="do not switch the model to 16-bit floats")
parser.add_argument("--no-progressbar-hiding", action='store_true', help="do not hide progressbar in gradio UI (we hide it because it slows down ML if you have hardware accleration in browser)") parser.add_argument("--no-progressbar-hiding", action='store_true', help="do not hide progressbar in gradio UI (we hide it because it slows down ML if you have hardware acceleration in browser)")
parser.add_argument("--max-batch-count", type=int, default=16, help="maximum batch count value for the UI") parser.add_argument("--max-batch-count", type=int, default=16, help="maximum batch count value for the UI")
parser.add_argument("--embeddings-dir", type=str, default='embeddings', help="embeddings dirtectory for textual inversion (default: embeddings)") parser.add_argument("--embeddings-dir", type=str, default=os.path.join(script_path, 'embeddings'), help="embeddings directory for textual inversion (default: embeddings)")
parser.add_argument("--allow-code", action='store_true', help="allow custom script execution from webui") parser.add_argument("--allow-code", action='store_true', help="allow custom script execution from webui")
parser.add_argument("--medvram", action='store_true', help="enable stable diffusion model optimizations for sacrficing a little speed for low VRM usage") parser.add_argument("--medvram", action='store_true', help="enable stable diffusion model optimizations for sacrificing a little speed for low VRM usage")
parser.add_argument("--lowvram", action='store_true', help="enable stable diffusion model optimizations for sacrficing a lot of speed for very low VRM usage") parser.add_argument("--lowvram", action='store_true', help="enable stable diffusion model optimizations for sacrificing a lot of speed for very low VRM usage")
parser.add_argument("--always-batch-cond-uncond", action='store_true', help="a workaround test; may help with speed in you use --lowvram") parser.add_argument("--always-batch-cond-uncond", action='store_true', help="disables cond/uncond batching that is enabled to save memory with --medvram or --lowvram")
parser.add_argument("--unload-gfpgan", action='store_true', help="unload GFPGAN every time after processing images. Warning: seems to cause memory leaks") parser.add_argument("--unload-gfpgan", action='store_true', help="does not do anything.")
parser.add_argument("--precision", type=str, help="evaluate at this precision", choices=["full", "autocast"], default="autocast") parser.add_argument("--precision", type=str, help="evaluate at this precision", choices=["full", "autocast"], default="autocast")
parser.add_argument("--share", action='store_true', help="use share=True for gradio and make the UI accessible through their site (doesn't work for me but you might have better luck)") parser.add_argument("--share", action='store_true', help="use share=True for gradio and make the UI accessible through their site (doesn't work for me but you might have better luck)")
parser.add_argument("--esrgan-models-path", type=str, help="path to directory with ESRGAN models", default=os.path.join(script_path, 'ESRGAN')) parser.add_argument("--codeformer-models-path", type=str, help="Path to directory with codeformer model file(s).", default=os.path.join(model_path, 'Codeformer'))
parser.add_argument("--opt-split-attention", action='store_true', help="enable optimization that reduced vram usage by a lot for about 10%% decrease in performance") parser.add_argument("--gfpgan-models-path", type=str, help="Path to directory with GFPGAN model file(s).", default=os.path.join(model_path, 'GFPGAN'))
parser.add_argument("--esrgan-models-path", type=str, help="Path to directory with ESRGAN model file(s).", default=os.path.join(model_path, 'ESRGAN'))
parser.add_argument("--bsrgan-models-path", type=str, help="Path to directory with BSRGAN model file(s).", default=os.path.join(model_path, 'BSRGAN'))
parser.add_argument("--realesrgan-models-path", type=str, help="Path to directory with RealESRGAN model file(s).", default=os.path.join(model_path, 'RealESRGAN'))
parser.add_argument("--scunet-models-path", type=str, help="Path to directory with ScuNET model file(s).", default=os.path.join(model_path, 'ScuNET'))
parser.add_argument("--swinir-models-path", type=str, help="Path to directory with SwinIR model file(s).", default=os.path.join(model_path, 'SwinIR'))
parser.add_argument("--ldsr-models-path", type=str, help="Path to directory with LDSR model file(s).", default=os.path.join(model_path, 'LDSR'))
parser.add_argument("--opt-split-attention", action='store_true', help="force-enables cross-attention layer optimization. By default, it's on for torch.cuda and off for other torch devices.")
parser.add_argument("--disable-opt-split-attention", action='store_true', help="force-disables cross-attention layer optimization")
parser.add_argument("--opt-split-attention-v1", action='store_true', help="enable older version of split attention optimization that does not consume all the VRAM it can find")
parser.add_argument("--use-cpu", nargs='+',choices=['SD', 'GFPGAN', 'BSRGAN', 'ESRGAN', 'SCUNet', 'CodeFormer'], help="use CPU as torch device for specified modules", default=[])
parser.add_argument("--listen", action='store_true', help="launch gradio with 0.0.0.0 as server name, allowing to respond to network requests") parser.add_argument("--listen", action='store_true', help="launch gradio with 0.0.0.0 as server name, allowing to respond to network requests")
parser.add_argument("--port", type=int, help="launch gradio with given server port, you need root/admin rights for ports < 1024, defaults to 7860 if available", default=None)
parser.add_argument("--show-negative-prompt", action='store_true', help="does not do anything", default=False)
parser.add_argument("--ui-config-file", type=str, help="filename to use for ui configuration", default=os.path.join(script_path, 'ui-config.json'))
parser.add_argument("--hide-ui-dir-config", action='store_true', help="hide directory configuration from webui", default=False)
parser.add_argument("--ui-settings-file", type=str, help="filename to use for ui settings", default=os.path.join(script_path, 'config.json'))
parser.add_argument("--gradio-debug", action='store_true', help="launch gradio with --debug option")
parser.add_argument("--gradio-auth", type=str, help='set gradio authentication like "username:password"; or comma-delimit multiple like "u1:p1,u2:p2,u3:p3"', default=None)
parser.add_argument("--gradio-img2img-tool", type=str, help='gradio image uploader tool: can be either editor for ctopping, or color-sketch for drawing', choices=["color-sketch", "editor"], default="editor")
parser.add_argument("--opt-channelslast", action='store_true', help="change memory type for stable diffusion to channels last")
parser.add_argument("--styles-file", type=str, help="filename to use for styles", default=os.path.join(script_path, 'styles.csv'))
parser.add_argument("--autolaunch", action='store_true', help="open the webui URL in the system's default browser upon launch", default=False)
parser.add_argument("--use-textbox-seed", action='store_true', help="use textbox for seeds in UI (no up/down, but possible to input long seeds)", default=False)
parser.add_argument("--disable-console-progressbars", action='store_true', help="do not output progressbars to console", default=False)
parser.add_argument("--enable-console-prompts", action='store_true', help="print prompts to console when generating with txt2img and img2img", default=False)
cmd_opts = parser.parse_args() cmd_opts = parser.parse_args()
cpu = torch.device("cpu") devices.device, devices.device_gfpgan, devices.device_bsrgan, devices.device_esrgan, devices.device_scunet, devices.device_codeformer = \
gpu = torch.device("cuda") (devices.cpu if x in cmd_opts.use_cpu else devices.get_optimal_device() for x in ['SD', 'GFPGAN', 'BSRGAN', 'ESRGAN', 'SCUNet', 'CodeFormer'])
device = gpu if torch.cuda.is_available() else cpu
device = devices.device
batch_cond_uncond = cmd_opts.always_batch_cond_uncond or not (cmd_opts.lowvram or cmd_opts.medvram) batch_cond_uncond = cmd_opts.always_batch_cond_uncond or not (cmd_opts.lowvram or cmd_opts.medvram)
parallel_processing_allowed = not cmd_opts.lowvram and not cmd_opts.medvram parallel_processing_allowed = not cmd_opts.lowvram and not cmd_opts.medvram
config_filename = cmd_opts.ui_settings_file
class State: class State:
interrupted = False interrupted = False
job = "" job = ""
job_no = 0 job_no = 0
job_count = 0 job_count = 0
job_timestamp = '0'
sampling_step = 0 sampling_step = 0
sampling_steps = 0 sampling_steps = 0
current_latent = None current_latent = None
current_image = None current_image = None
current_image_sampling_step = 0 current_image_sampling_step = 0
textinfo = None
def interrupt(self): def interrupt(self):
self.interrupted = True self.interrupted = True
@@ -63,66 +99,160 @@ class State:
self.sampling_step = 0 self.sampling_step = 0
self.current_image_sampling_step = 0 self.current_image_sampling_step = 0
def get_job_timestamp(self):
return datetime.datetime.now().strftime("%Y%m%d%H%M%S") # shouldn't this return job_timestamp?
state = State() state = State()
artist_db = modules.artists.ArtistsDatabase(os.path.join(script_path, 'artists.csv')) artist_db = modules.artists.ArtistsDatabase(os.path.join(script_path, 'artists.csv'))
styles_filename = cmd_opts.styles_file
prompt_styles = modules.styles.StyleDatabase(styles_filename)
interrogator = modules.interrogate.InterrogateModels("interrogate")
face_restorers = [] face_restorers = []
# This was moved to webui.py with the other model "setup" calls.
def find_any_font(): # modules.sd_models.list_models()
fonts = ['/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf']
for font in fonts:
if os.path.exists(font):
return font
return "arial.ttf"
class Options: def realesrgan_models_names():
class OptionInfo: import modules.realesrgan_model
def __init__(self, default=None, label="", component=None, component_args=None): return [x.name for x in modules.realesrgan_model.get_realesrgan_models(None)]
class OptionInfo:
def __init__(self, default=None, label="", component=None, component_args=None, onchange=None):
self.default = default self.default = default
self.label = label self.label = label
self.component = component self.component = component
self.component_args = component_args self.component_args = component_args
self.onchange = onchange
self.section = None
data = None
data_labels = { def options_section(section_identifer, options_dict):
"outdir_samples": OptionInfo("", "Output dictectory for images; if empty, defaults to two directories below"), for k, v in options_dict.items():
"outdir_txt2img_samples": OptionInfo("outputs/txt2img-images", 'Output dictectory for txt2img images'), v.section = section_identifer
"outdir_img2img_samples": OptionInfo("outputs/img2img-images", 'Output dictectory for img2img images'),
"outdir_extras_samples": OptionInfo("outputs/extras-images", 'Output dictectory for images from extras tab'), return options_dict
"outdir_grids": OptionInfo("", "Output dictectory for grids; if empty, defaults to two directories below"),
"outdir_txt2img_grids": OptionInfo("outputs/txt2img-grids", 'Output dictectory for txt2img grids'),
"outdir_img2img_grids": OptionInfo("outputs/img2img-grids", 'Output dictectory for img2img grids'), hide_dirs = {"visible": not cmd_opts.hide_ui_dir_config}
"save_to_dirs": OptionInfo(False, "When writing images/grids, create a directory with name derived from the prompt"),
"save_to_dirs_prompt_len": OptionInfo(10, "When using above, how many words from prompt to put into directory name", gr.Slider, {"minimum": 1, "maximum": 32, "step": 1}), options_templates = {}
"outdir_save": OptionInfo("log/images", "Directory for saving images using the Save button"),
"samples_save": OptionInfo(True, "Save indiviual samples"), options_templates.update(options_section(('saving-images', "Saving images/grids"), {
"samples_format": OptionInfo('png', 'File format for indiviual samples'), "samples_save": OptionInfo(True, "Always save all generated images"),
"grid_save": OptionInfo(True, "Save image grids"), "samples_format": OptionInfo('png', 'File format for images'),
"return_grid": OptionInfo(True, "Show grid in results for web"), "samples_filename_pattern": OptionInfo("", "Images filename pattern"),
"grid_save": OptionInfo(True, "Always save all generated image grids"),
"grid_format": OptionInfo('png', 'File format for grids'), "grid_format": OptionInfo('png', 'File format for grids'),
"grid_extended_filename": OptionInfo(False, "Add extended info (seed, prompt) to filename when saving grid"), "grid_extended_filename": OptionInfo(False, "Add extended info (seed, prompt) to filename when saving grid"),
"grid_only_if_multiple": OptionInfo(True, "Do not save grids consisting of one picture"), "grid_only_if_multiple": OptionInfo(True, "Do not save grids consisting of one picture"),
"n_rows": OptionInfo(-1, "Grid row count; use -1 for autodetect and 0 for it to be same as batch size", gr.Slider, {"minimum": -1, "maximum": 16, "step": 1}), "n_rows": OptionInfo(-1, "Grid row count; use -1 for autodetect and 0 for it to be same as batch size", gr.Slider, {"minimum": -1, "maximum": 16, "step": 1}),
"enable_pnginfo": OptionInfo(True, "Save text information about generation parameters as chunks to png files"),
"save_txt": OptionInfo(False, "Create a text file next to every image with generation parameters."),
"save_images_before_face_restoration": OptionInfo(False, "Save a copy of image before doing face restoration."),
"jpeg_quality": OptionInfo(80, "Quality for saved jpeg images", gr.Slider, {"minimum": 1, "maximum": 100, "step": 1}), "jpeg_quality": OptionInfo(80, "Quality for saved jpeg images", gr.Slider, {"minimum": 1, "maximum": 100, "step": 1}),
"export_for_4chan": OptionInfo(True, "If PNG image is larger than 4MB or any dimension is larger than 4000, downscale and save copy as JPG"), "export_for_4chan": OptionInfo(True, "If PNG image is larger than 4MB or any dimension is larger than 4000, downscale and save copy as JPG"),
"enable_pnginfo": OptionInfo(True, "Save text information about generation parameters as chunks to png files"),
"font": OptionInfo(find_any_font(), "Font for image grids that have text"), "use_original_name_batch": OptionInfo(False, "Use original name for output filename during batch process in extras tab"),
"enable_emphasis": OptionInfo(True, "Use (text) to make model pay more attention to text text and [text] to make it pay less attention"), "save_selected_only": OptionInfo(True, "When using 'Save' button, only save a single selected image"),
"save_txt": OptionInfo(False, "Create a text file next to every image with generation parameters."), }))
"ESRGAN_tile": OptionInfo(192, "Tile size for ESRGAN upscaling. 0 = no tiling.", gr.Slider, {"minimum": 0, "maximum": 512, "step": 16}),
"ESRGAN_tile_overlap": OptionInfo(8, "Tile overlap, in pixels for ESRGAN upscaling. Low values = visible seam.", gr.Slider, {"minimum": 0, "maximum": 48, "step": 1}), options_templates.update(options_section(('saving-paths', "Paths for saving"), {
"random_artist_categories": OptionInfo([], "Allowed categories for random artists selection when using the Roll button", gr.CheckboxGroup, {"choices": artist_db.categories()}), "outdir_samples": OptionInfo("", "Output directory for images; if empty, defaults to three directories below", component_args=hide_dirs),
"upscale_at_full_resolution_padding": OptionInfo(16, "Inpainting at full resolution: padding, in pixels, for the masked region.", gr.Slider, {"minimum": 0, "maximum": 128, "step": 4}), "outdir_txt2img_samples": OptionInfo("outputs/txt2img-images", 'Output directory for txt2img images', component_args=hide_dirs),
"show_progressbar": OptionInfo(True, "Show progressbar"), "outdir_img2img_samples": OptionInfo("outputs/img2img-images", 'Output directory for img2img images', component_args=hide_dirs),
"show_progress_every_n_steps": OptionInfo(0, "Show show image creation progress every N sampling steps. Set 0 to disable.", gr.Slider, {"minimum": 0, "maximum": 32, "step": 1}), "outdir_extras_samples": OptionInfo("outputs/extras-images", 'Output directory for images from extras tab', component_args=hide_dirs),
"outdir_grids": OptionInfo("", "Output directory for grids; if empty, defaults to two directories below", component_args=hide_dirs),
"outdir_txt2img_grids": OptionInfo("outputs/txt2img-grids", 'Output directory for txt2img grids', component_args=hide_dirs),
"outdir_img2img_grids": OptionInfo("outputs/img2img-grids", 'Output directory for img2img grids', component_args=hide_dirs),
"outdir_save": OptionInfo("log/images", "Directory for saving images using the Save button", component_args=hide_dirs),
}))
options_templates.update(options_section(('saving-to-dirs', "Saving to a directory"), {
"save_to_dirs": OptionInfo(False, "Save images to a subdirectory"),
"grid_save_to_dirs": OptionInfo(False, "Save grids to a subdirectory"),
"use_save_to_dirs_for_ui": OptionInfo(False, "When using \"Save\" button, save images to a subdirectory"),
"directories_filename_pattern": OptionInfo("", "Directory name pattern"),
"directories_max_prompt_words": OptionInfo(8, "Max prompt words for [prompt_words] pattern", gr.Slider, {"minimum": 1, "maximum": 20, "step": 1}),
}))
options_templates.update(options_section(('upscaling', "Upscaling"), {
"ESRGAN_tile": OptionInfo(192, "Tile size for ESRGAN upscalers. 0 = no tiling.", gr.Slider, {"minimum": 0, "maximum": 512, "step": 16}),
"ESRGAN_tile_overlap": OptionInfo(8, "Tile overlap, in pixels for ESRGAN upscalers. Low values = visible seam.", gr.Slider, {"minimum": 0, "maximum": 48, "step": 1}),
"realesrgan_enabled_models": OptionInfo(["R-ESRGAN x4+", "R-ESRGAN x4+ Anime6B"], "Select which Real-ESRGAN models to show in the web UI. (Requires restart)", gr.CheckboxGroup, lambda: {"choices": realesrgan_models_names()}),
"SWIN_tile": OptionInfo(192, "Tile size for all SwinIR.", gr.Slider, {"minimum": 16, "maximum": 512, "step": 16}),
"SWIN_tile_overlap": OptionInfo(8, "Tile overlap, in pixels for SwinIR. Low values = visible seam.", gr.Slider, {"minimum": 0, "maximum": 48, "step": 1}),
"ldsr_steps": OptionInfo(100, "LDSR processing steps. Lower = faster", gr.Slider, {"minimum": 1, "maximum": 200, "step": 1}),
"upscaler_for_img2img": OptionInfo(None, "Upscaler for img2img", gr.Dropdown, lambda: {"choices": [x.name for x in sd_upscalers]}),
}))
options_templates.update(options_section(('face-restoration', "Face restoration"), {
"face_restoration_model": OptionInfo(None, "Face restoration model", gr.Radio, lambda: {"choices": [x.name() for x in face_restorers]}), "face_restoration_model": OptionInfo(None, "Face restoration model", gr.Radio, lambda: {"choices": [x.name() for x in face_restorers]}),
"code_former_weight": OptionInfo(0.5, "CodeFormer weight parameter; 0 = maximum effect; 1 = minimum effect", gr.Slider, {"minimum": 0, "maximum": 1, "step": 0.01}), "code_former_weight": OptionInfo(0.5, "CodeFormer weight parameter; 0 = maximum effect; 1 = minimum effect", gr.Slider, {"minimum": 0, "maximum": 1, "step": 0.01}),
} "face_restoration_unload": OptionInfo(False, "Move face restoration model from VRAM into RAM after processing"),
}))
options_templates.update(options_section(('system', "System"), {
"memmon_poll_rate": OptionInfo(8, "VRAM usage polls per second during generation. Set to 0 to disable.", gr.Slider, {"minimum": 0, "maximum": 40, "step": 1}),
"samples_log_stdout": OptionInfo(False, "Always print all generation info to standard output"),
"multiple_tqdm": OptionInfo(True, "Add a second progress bar to the console that shows progress for an entire job."),
}))
options_templates.update(options_section(('sd', "Stable Diffusion"), {
"sd_model_checkpoint": OptionInfo(None, "Stable Diffusion checkpoint", gr.Dropdown, lambda: {"choices": modules.sd_models.checkpoint_tiles()}),
"img2img_color_correction": OptionInfo(False, "Apply color correction to img2img results to match original colors."),
"save_images_before_color_correction": OptionInfo(False, "Save a copy of image before applying color correction to img2img results"),
"img2img_fix_steps": OptionInfo(False, "With img2img, do exactly the amount of steps the slider specifies (normally you'd do less with less denoising)."),
"enable_quantization": OptionInfo(False, "Enable quantization in K samplers for sharper and cleaner results. This may change existing seeds. Requires restart to apply."),
"enable_emphasis": OptionInfo(True, "Emphasis: use (text) to make model pay more attention to text and [text] to make it pay less attention"),
"use_old_emphasis_implementation": OptionInfo(False, "Use old emphasis implementation. Can be useful to reproduce old seeds."),
"enable_batch_seeds": OptionInfo(True, "Make K-diffusion samplers produce same images in a batch as when making a single image"),
"filter_nsfw": OptionInfo(False, "Filter NSFW content"),
"random_artist_categories": OptionInfo([], "Allowed categories for random artists selection when using the Roll button", gr.CheckboxGroup, {"choices": artist_db.categories()}),
}))
options_templates.update(options_section(('interrogate', "Interrogate Options"), {
"interrogate_keep_models_in_memory": OptionInfo(False, "Interrogate: keep models in VRAM"),
"interrogate_use_builtin_artists": OptionInfo(True, "Interrogate: use artists from artists.csv"),
"interrogate_clip_num_beams": OptionInfo(1, "Interrogate: num_beams for BLIP", gr.Slider, {"minimum": 1, "maximum": 16, "step": 1}),
"interrogate_clip_min_length": OptionInfo(24, "Interrogate: minimum description length (excluding artists, etc..)", gr.Slider, {"minimum": 1, "maximum": 128, "step": 1}),
"interrogate_clip_max_length": OptionInfo(48, "Interrogate: maximum description length", gr.Slider, {"minimum": 1, "maximum": 256, "step": 1}),
"interrogate_clip_dict_limit": OptionInfo(1500, "Interrogate: maximum number of lines in text file (0 = No limit)"),
}))
options_templates.update(options_section(('ui', "User interface"), {
"show_progressbar": OptionInfo(True, "Show progressbar"),
"show_progress_every_n_steps": OptionInfo(0, "Show show image creation progress every N sampling steps. Set 0 to disable.", gr.Slider, {"minimum": 0, "maximum": 32, "step": 1}),
"return_grid": OptionInfo(True, "Show grid in results for web"),
"do_not_show_images": OptionInfo(False, "Do not show any images in results for web"),
"add_model_hash_to_info": OptionInfo(True, "Add model hash to generation information"),
"font": OptionInfo("", "Font for image grids that have text"),
"js_modal_lightbox": OptionInfo(True, "Enable full page image viewer"),
"js_modal_lightbox_initialy_zoomed": OptionInfo(True, "Show images zoomed in by default in full page image viewer"),
}))
options_templates.update(options_section(('sampler-params', "Sampler parameters"), {
"hide_samplers": OptionInfo([], "Hide samplers in user interface (requires restart)", gr.CheckboxGroup, lambda: {"choices": [x.name for x in sd_samplers.all_samplers]}),
"eta_ddim": OptionInfo(0.0, "eta (noise multiplier) for DDIM", gr.Slider, {"minimum": 0.0, "maximum": 1.0, "step": 0.01}),
"eta_ancestral": OptionInfo(1.0, "eta (noise multiplier) for ancestral samplers", gr.Slider, {"minimum": 0.0, "maximum": 1.0, "step": 0.01}),
"ddim_discretize": OptionInfo('uniform', "img2img DDIM discretize", gr.Radio, {"choices": ['uniform', 'quad']}),
's_churn': OptionInfo(0.0, "sigma churn", gr.Slider, {"minimum": 0.0, "maximum": 1.0, "step": 0.01}),
's_tmin': OptionInfo(0.0, "sigma tmin", gr.Slider, {"minimum": 0.0, "maximum": 1.0, "step": 0.01}),
's_noise': OptionInfo(1.0, "sigma noise", gr.Slider, {"minimum": 0.0, "maximum": 1.0, "step": 0.01}),
}))
class Options:
data = None
data_labels = options_templates
typemap = {int: float}
def __init__(self): def __init__(self):
self.data = {k: v.default for k, v in self.data_labels.items()} self.data = {k: v.default for k, v in self.data_labels.items()}
@@ -148,10 +278,37 @@ class Options:
with open(filename, "w", encoding="utf8") as file: with open(filename, "w", encoding="utf8") as file:
json.dump(self.data, file) json.dump(self.data, file)
def same_type(self, x, y):
if x is None or y is None:
return True
type_x = self.typemap.get(type(x), type(x))
type_y = self.typemap.get(type(y), type(y))
return type_x == type_y
def load(self, filename): def load(self, filename):
with open(filename, "r", encoding="utf8") as file: with open(filename, "r", encoding="utf8") as file:
self.data = json.load(file) self.data = json.load(file)
bad_settings = 0
for k, v in self.data.items():
info = self.data_labels.get(k, None)
if info is not None and not self.same_type(info.default, v):
print(f"Warning: bad setting value: {k}: {v} ({type(v).__name__}; expected {type(info.default).__name__})", file=sys.stderr)
bad_settings += 1
if bad_settings > 0:
print(f"The program is likely to not work with bad settings.\nSettings file: {filename}\nEither fix the file, or delete it and restart.", file=sys.stderr)
def onchange(self, key, func):
item = self.data_labels.get(key)
item.onchange = func
def dumpjson(self):
d = {k: self.data.get(k, self.data_labels.get(k).default) for k in self.data_labels.keys()}
return json.dumps(d)
opts = Options() opts = Options()
if os.path.exists(config_filename): if os.path.exists(config_filename):
@@ -161,4 +318,42 @@ sd_upscalers = []
sd_model = None sd_model = None
progress_print_out = sys.stdout
class TotalTQDM:
def __init__(self):
self._tqdm = None
def reset(self):
self._tqdm = tqdm.tqdm(
desc="Total progress",
total=state.job_count * state.sampling_steps,
position=1,
file=progress_print_out
)
def update(self):
if not opts.multiple_tqdm or cmd_opts.disable_console_progressbars:
return
if self._tqdm is None:
self.reset()
self._tqdm.update()
def updateTotal(self, new_total):
if not opts.multiple_tqdm or cmd_opts.disable_console_progressbars:
return
if self._tqdm is None:
self.reset()
self._tqdm.total=new_total
def clear(self):
if self._tqdm is not None:
self._tqdm.close()
self._tqdm = None
total_tqdm = TotalTQDM()
mem_mon = modules.memmon.MemUsageMonitor("MemMon", device, opts)
mem_mon.start()
+92
View File
@@ -0,0 +1,92 @@
# We need this so Python doesn't complain about the unknown StableDiffusionProcessing-typehint at runtime
from __future__ import annotations
import csv
import os
import os.path
import typing
import collections.abc as abc
import tempfile
import shutil
if typing.TYPE_CHECKING:
# Only import this when code is being type-checked, it doesn't have any effect at runtime
from .processing import StableDiffusionProcessing
class PromptStyle(typing.NamedTuple):
name: str
prompt: str
negative_prompt: str
def merge_prompts(style_prompt: str, prompt: str) -> str:
if "{prompt}" in style_prompt:
res = style_prompt.replace("{prompt}", prompt)
else:
parts = filter(None, (prompt.strip(), style_prompt.strip()))
res = ", ".join(parts)
return res
def apply_styles_to_prompt(prompt, styles):
for style in styles:
prompt = merge_prompts(style, prompt)
return prompt
class StyleDatabase:
def __init__(self, path: str):
self.no_style = PromptStyle("None", "", "")
self.styles = {"None": self.no_style}
if not os.path.exists(path):
return
with open(path, "r", encoding="utf8", newline='') as file:
reader = csv.DictReader(file)
for row in reader:
# Support loading old CSV format with "name, text"-columns
prompt = row["prompt"] if "prompt" in row else row["text"]
negative_prompt = row.get("negative_prompt", "")
self.styles[row["name"]] = PromptStyle(row["name"], prompt, negative_prompt)
def get_style_prompts(self, styles):
return [self.styles.get(x, self.no_style).prompt for x in styles]
def get_negative_style_prompts(self, styles):
return [self.styles.get(x, self.no_style).negative_prompt for x in styles]
def apply_styles_to_prompt(self, prompt, styles):
return apply_styles_to_prompt(prompt, [self.styles.get(x, self.no_style).prompt for x in styles])
def apply_negative_styles_to_prompt(self, prompt, styles):
return apply_styles_to_prompt(prompt, [self.styles.get(x, self.no_style).negative_prompt for x in styles])
def apply_styles(self, p: StableDiffusionProcessing) -> None:
if isinstance(p.prompt, list):
p.prompt = [self.apply_styles_to_prompt(prompt, p.styles) for prompt in p.prompt]
else:
p.prompt = self.apply_styles_to_prompt(p.prompt, p.styles)
if isinstance(p.negative_prompt, list):
p.negative_prompt = [self.apply_negative_styles_to_prompt(prompt, p.styles) for prompt in p.negative_prompt]
else:
p.negative_prompt = self.apply_negative_styles_to_prompt(p.negative_prompt, p.styles)
def save_styles(self, path: str) -> None:
# Write to temporary file first, so we don't nuke the file if something goes wrong
fd, temp_path = tempfile.mkstemp(".csv")
with os.fdopen(fd, "w", encoding="utf8", newline='') as file:
# _fields is actually part of the public API: typing.NamedTuple is a replacement for collections.NamedTuple,
# and collections.NamedTuple has explicit documentation for accessing _fields. Same goes for _asdict()
writer = csv.DictWriter(file, fieldnames=PromptStyle._fields)
writer.writeheader()
writer.writerows(style._asdict() for k, style in self.styles.items())
# Always keep a backup file around
if os.path.exists(path):
shutil.move(path, path + ".bak")
shutil.move(temp_path, path)
+142
View File
@@ -0,0 +1,142 @@
import contextlib
import os
import numpy as np
import torch
from PIL import Image
from basicsr.utils.download_util import load_file_from_url
from tqdm import tqdm
from modules import modelloader
from modules.paths import models_path
from modules.shared import cmd_opts, opts, device
from modules.swinir_model_arch import SwinIR as net
from modules.upscaler import Upscaler, UpscalerData
precision_scope = (
torch.autocast if cmd_opts.precision == "autocast" else contextlib.nullcontext
)
class UpscalerSwinIR(Upscaler):
def __init__(self, dirname):
self.name = "SwinIR"
self.model_url = "https://github.com/JingyunLiang/SwinIR/releases/download/v0.0" \
"/003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR" \
"-L_x4_GAN.pth "
self.model_name = "SwinIR 4x"
self.model_path = os.path.join(models_path, self.name)
self.user_path = dirname
super().__init__()
scalers = []
model_files = self.find_models(ext_filter=[".pt", ".pth"])
for model in model_files:
if "http" in model:
name = self.model_name
else:
name = modelloader.friendly_name(model)
model_data = UpscalerData(name, model, self)
scalers.append(model_data)
self.scalers = scalers
def do_upscale(self, img, model_file):
model = self.load_model(model_file)
if model is None:
return img
model = model.to(device)
img = upscale(img, model)
try:
torch.cuda.empty_cache()
except:
pass
return img
def load_model(self, path, scale=4):
if "http" in path:
dl_name = "%s%s" % (self.model_name.replace(" ", "_"), ".pth")
filename = load_file_from_url(url=path, model_dir=self.model_path, file_name=dl_name, progress=True)
else:
filename = path
if filename is None or not os.path.exists(filename):
return None
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",
)
pretrained_model = torch.load(filename)
model.load_state_dict(pretrained_model["params_ema"], strict=True)
if not cmd_opts.no_half:
model = model.half()
return model
def upscale(
img,
model,
tile=opts.SWIN_tile,
tile_overlap=opts.SWIN_tile_overlap,
window_size=8,
scale=4,
):
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)
with torch.no_grad(), precision_scope("cuda"):
_, _, 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=torch.half, device=device).type_as(img)
W = torch.zeros_like(E, dtype=torch.half, device=device)
with tqdm(total=len(h_idx_list) * len(w_idx_list), desc="SwinIR 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
+867
View File
@@ -0,0 +1,867 @@
# -----------------------------------------------------------------------------------
# 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 resulotion.
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)
+81
View File
@@ -0,0 +1,81 @@
import os
import numpy as np
import PIL
import torch
from PIL import Image
from torch.utils.data import Dataset
from torchvision import transforms
import random
import tqdm
from modules import devices
import re
re_tag = re.compile(r"[a-zA-Z][_\w\d()]+")
class PersonalizedBase(Dataset):
def __init__(self, data_root, size=None, repeats=100, flip_p=0.5, placeholder_token="*", width=512, height=512, model=None, device=None, template_file=None):
self.placeholder_token = placeholder_token
self.size = size
self.width = width
self.height = height
self.flip = transforms.RandomHorizontalFlip(p=flip_p)
self.dataset = []
with open(template_file, "r") as file:
lines = [x.strip() for x in file.readlines()]
self.lines = lines
assert data_root, 'dataset directory not specified'
self.image_paths = [os.path.join(data_root, file_path) for file_path in os.listdir(data_root)]
print("Preparing dataset...")
for path in tqdm.tqdm(self.image_paths):
image = Image.open(path)
image = image.convert('RGB')
image = image.resize((self.width, self.height), PIL.Image.BICUBIC)
filename = os.path.basename(path)
filename_tokens = os.path.splitext(filename)[0]
filename_tokens = re_tag.findall(filename_tokens)
npimage = np.array(image).astype(np.uint8)
npimage = (npimage / 127.5 - 1.0).astype(np.float32)
torchdata = torch.from_numpy(npimage).to(device=device, dtype=torch.float32)
torchdata = torch.moveaxis(torchdata, 2, 0)
init_latent = model.get_first_stage_encoding(model.encode_first_stage(torchdata.unsqueeze(dim=0))).squeeze()
init_latent = init_latent.to(devices.cpu)
self.dataset.append((init_latent, filename_tokens))
self.length = len(self.dataset) * repeats
self.initial_indexes = np.arange(self.length) % len(self.dataset)
self.indexes = None
self.shuffle()
def shuffle(self):
self.indexes = self.initial_indexes[torch.randperm(self.initial_indexes.shape[0])]
def __len__(self):
return self.length
def __getitem__(self, i):
if i % len(self.dataset) == 0:
self.shuffle()
index = self.indexes[i % len(self.indexes)]
x, filename_tokens = self.dataset[index]
text = random.choice(self.lines)
text = text.replace("[name]", self.placeholder_token)
text = text.replace("[filewords]", ' '.join(filename_tokens))
return x, text
+104
View File
@@ -0,0 +1,104 @@
import os
from PIL import Image, ImageOps
import platform
import sys
import tqdm
from modules import shared, images
def preprocess(process_src, process_dst, process_flip, process_split, process_caption):
size = 512
src = os.path.abspath(process_src)
dst = os.path.abspath(process_dst)
assert src != dst, 'same directory specified as source and destination'
os.makedirs(dst, exist_ok=True)
files = os.listdir(src)
shared.state.textinfo = "Preprocessing..."
shared.state.job_count = len(files)
if process_caption:
shared.interrogator.load()
def save_pic_with_caption(image, index):
if process_caption:
caption = "-" + shared.interrogator.generate_caption(image)
caption = sanitize_caption(os.path.join(dst, f"{index:05}-{subindex[0]}"), caption, ".png")
else:
caption = filename
caption = os.path.splitext(caption)[0]
caption = os.path.basename(caption)
image.save(os.path.join(dst, f"{index:05}-{subindex[0]}{caption}.png"))
subindex[0] += 1
def save_pic(image, index):
save_pic_with_caption(image, index)
if process_flip:
save_pic_with_caption(ImageOps.mirror(image), index)
for index, imagefile in enumerate(tqdm.tqdm(files)):
subindex = [0]
filename = os.path.join(src, imagefile)
img = Image.open(filename).convert("RGB")
if shared.state.interrupted:
break
ratio = img.height / img.width
is_tall = ratio > 1.35
is_wide = ratio < 1 / 1.35
if process_split and is_tall:
img = img.resize((size, size * img.height // img.width))
top = img.crop((0, 0, size, size))
save_pic(top, index)
bot = img.crop((0, img.height - size, size, img.height))
save_pic(bot, index)
elif process_split and is_wide:
img = img.resize((size * img.width // img.height, size))
left = img.crop((0, 0, size, size))
save_pic(left, index)
right = img.crop((img.width - size, 0, img.width, size))
save_pic(right, index)
else:
img = images.resize_image(1, img, size, size)
save_pic(img, index)
shared.state.nextjob()
if process_caption:
shared.interrogator.send_blip_to_ram()
def sanitize_caption(base_path, original_caption, suffix):
operating_system = platform.system().lower()
if (operating_system == "windows"):
invalid_path_characters = "\\/:*?\"<>|"
max_path_length = 259
else:
invalid_path_characters = "/" #linux/macos
max_path_length = 1023
caption = original_caption
for invalid_character in invalid_path_characters:
caption = caption.replace(invalid_character, "")
fixed_path_length = len(base_path) + len(suffix)
if fixed_path_length + len(caption) <= max_path_length:
return caption
caption_tokens = caption.split()
new_caption = ""
for token in caption_tokens:
last_caption = new_caption
new_caption = new_caption + token + " "
if (len(new_caption) + fixed_path_length - 1 > max_path_length):
break
print(f"\nPath will be too long. Truncated caption: {original_caption}\nto: {last_caption}", file=sys.stderr)
return last_caption.strip()
@@ -0,0 +1,271 @@
import os
import sys
import traceback
import torch
import tqdm
import html
import datetime
from modules import shared, devices, sd_hijack, processing, sd_models
import modules.textual_inversion.dataset
class Embedding:
def __init__(self, vec, name, step=None):
self.vec = vec
self.name = name
self.step = step
self.cached_checksum = None
self.sd_checkpoint = None
self.sd_checkpoint_name = None
def save(self, filename):
embedding_data = {
"string_to_token": {"*": 265},
"string_to_param": {"*": self.vec},
"name": self.name,
"step": self.step,
"sd_checkpoint": self.sd_checkpoint,
"sd_checkpoint_name": self.sd_checkpoint_name,
}
torch.save(embedding_data, filename)
def checksum(self):
if self.cached_checksum is not None:
return self.cached_checksum
def const_hash(a):
r = 0
for v in a:
r = (r * 281 ^ int(v) * 997) & 0xFFFFFFFF
return r
self.cached_checksum = f'{const_hash(self.vec.reshape(-1) * 100) & 0xffff:04x}'
return self.cached_checksum
class EmbeddingDatabase:
def __init__(self, embeddings_dir):
self.ids_lookup = {}
self.word_embeddings = {}
self.dir_mtime = None
self.embeddings_dir = embeddings_dir
def register_embedding(self, embedding, model):
self.word_embeddings[embedding.name] = embedding
ids = model.cond_stage_model.tokenizer([embedding.name], add_special_tokens=False)['input_ids'][0]
first_id = ids[0]
if first_id not in self.ids_lookup:
self.ids_lookup[first_id] = []
self.ids_lookup[first_id] = sorted(self.ids_lookup[first_id] + [(ids, embedding)], key=lambda x: len(x[0]), reverse=True)
return embedding
def load_textual_inversion_embeddings(self):
mt = os.path.getmtime(self.embeddings_dir)
if self.dir_mtime is not None and mt <= self.dir_mtime:
return
self.dir_mtime = mt
self.ids_lookup.clear()
self.word_embeddings.clear()
def process_file(path, filename):
name = os.path.splitext(filename)[0]
data = torch.load(path, map_location="cpu")
# textual inversion embeddings
if 'string_to_param' in data:
param_dict = data['string_to_param']
if hasattr(param_dict, '_parameters'):
param_dict = getattr(param_dict, '_parameters') # fix for torch 1.12.1 loading saved file from torch 1.11
assert len(param_dict) == 1, 'embedding file has multiple terms in it'
emb = next(iter(param_dict.items()))[1]
# diffuser concepts
elif type(data) == dict and type(next(iter(data.values()))) == torch.Tensor:
assert len(data.keys()) == 1, 'embedding file has multiple terms in it'
emb = next(iter(data.values()))
if len(emb.shape) == 1:
emb = emb.unsqueeze(0)
else:
raise Exception(f"Couldn't identify {filename} as neither textual inversion embedding nor diffuser concept.")
vec = emb.detach().to(devices.device, dtype=torch.float32)
embedding = Embedding(vec, name)
embedding.step = data.get('step', None)
embedding.sd_checkpoint = data.get('hash', None)
embedding.sd_checkpoint_name = data.get('sd_checkpoint_name', None)
self.register_embedding(embedding, shared.sd_model)
for fn in os.listdir(self.embeddings_dir):
try:
fullfn = os.path.join(self.embeddings_dir, fn)
if os.stat(fullfn).st_size == 0:
continue
process_file(fullfn, fn)
except Exception:
print(f"Error loading emedding {fn}:", file=sys.stderr)
print(traceback.format_exc(), file=sys.stderr)
continue
print(f"Loaded a total of {len(self.word_embeddings)} textual inversion embeddings.")
def find_embedding_at_position(self, tokens, offset):
token = tokens[offset]
possible_matches = self.ids_lookup.get(token, None)
if possible_matches is None:
return None, None
for ids, embedding in possible_matches:
if tokens[offset:offset + len(ids)] == ids:
return embedding, len(ids)
return None, None
def create_embedding(name, num_vectors_per_token, init_text='*'):
cond_model = shared.sd_model.cond_stage_model
embedding_layer = cond_model.wrapped.transformer.text_model.embeddings
ids = cond_model.tokenizer(init_text, max_length=num_vectors_per_token, return_tensors="pt", add_special_tokens=False)["input_ids"]
embedded = embedding_layer.token_embedding.wrapped(ids.to(devices.device)).squeeze(0)
vec = torch.zeros((num_vectors_per_token, embedded.shape[1]), device=devices.device)
for i in range(num_vectors_per_token):
vec[i] = embedded[i * int(embedded.shape[0]) // num_vectors_per_token]
fn = os.path.join(shared.cmd_opts.embeddings_dir, f"{name}.pt")
assert not os.path.exists(fn), f"file {fn} already exists"
embedding = Embedding(vec, name)
embedding.step = 0
embedding.save(fn)
return fn
def train_embedding(embedding_name, learn_rate, data_root, log_directory, steps, create_image_every, save_embedding_every, template_file):
assert embedding_name, 'embedding not selected'
shared.state.textinfo = "Initializing textual inversion training..."
shared.state.job_count = steps
filename = os.path.join(shared.cmd_opts.embeddings_dir, f'{embedding_name}.pt')
log_directory = os.path.join(log_directory, datetime.datetime.now().strftime("%Y-%m-%d"), embedding_name)
if save_embedding_every > 0:
embedding_dir = os.path.join(log_directory, "embeddings")
os.makedirs(embedding_dir, exist_ok=True)
else:
embedding_dir = None
if create_image_every > 0:
images_dir = os.path.join(log_directory, "images")
os.makedirs(images_dir, exist_ok=True)
else:
images_dir = None
cond_model = shared.sd_model.cond_stage_model
shared.state.textinfo = f"Preparing dataset from {html.escape(data_root)}..."
with torch.autocast("cuda"):
ds = modules.textual_inversion.dataset.PersonalizedBase(data_root=data_root, size=512, placeholder_token=embedding_name, model=shared.sd_model, device=devices.device, template_file=template_file)
hijack = sd_hijack.model_hijack
embedding = hijack.embedding_db.word_embeddings[embedding_name]
embedding.vec.requires_grad = True
optimizer = torch.optim.AdamW([embedding.vec], lr=learn_rate)
losses = torch.zeros((32,))
last_saved_file = "<none>"
last_saved_image = "<none>"
ititial_step = embedding.step or 0
if ititial_step > steps:
return embedding, filename
pbar = tqdm.tqdm(enumerate(ds), total=steps-ititial_step)
for i, (x, text) in pbar:
embedding.step = i + ititial_step
if embedding.step > steps:
break
if shared.state.interrupted:
break
with torch.autocast("cuda"):
c = cond_model([text])
x = x.to(devices.device)
loss = shared.sd_model(x.unsqueeze(0), c)[0]
del x
losses[embedding.step % losses.shape[0]] = loss.item()
optimizer.zero_grad()
loss.backward()
optimizer.step()
pbar.set_description(f"loss: {losses.mean():.7f}")
if embedding.step > 0 and embedding_dir is not None and embedding.step % save_embedding_every == 0:
last_saved_file = os.path.join(embedding_dir, f'{embedding_name}-{embedding.step}.pt')
embedding.save(last_saved_file)
if embedding.step > 0 and images_dir is not None and embedding.step % create_image_every == 0:
last_saved_image = os.path.join(images_dir, f'{embedding_name}-{embedding.step}.png')
p = processing.StableDiffusionProcessingTxt2Img(
sd_model=shared.sd_model,
prompt=text,
steps=20,
do_not_save_grid=True,
do_not_save_samples=True,
)
processed = processing.process_images(p)
image = processed.images[0]
shared.state.current_image = image
image.save(last_saved_image)
last_saved_image += f", prompt: {text}"
shared.state.job_no = embedding.step
shared.state.textinfo = f"""
<p>
Loss: {losses.mean():.7f}<br/>
Step: {embedding.step}<br/>
Last prompt: {html.escape(text)}<br/>
Last saved embedding: {html.escape(last_saved_file)}<br/>
Last saved image: {html.escape(last_saved_image)}<br/>
</p>
"""
checkpoint = sd_models.select_checkpoint()
embedding.sd_checkpoint = checkpoint.hash
embedding.sd_checkpoint_name = checkpoint.model_name
embedding.cached_checksum = None
embedding.save(filename)
return embedding, filename
+40
View File
@@ -0,0 +1,40 @@
import html
import gradio as gr
import modules.textual_inversion.textual_inversion
import modules.textual_inversion.preprocess
from modules import sd_hijack, shared
def create_embedding(name, initialization_text, nvpt):
filename = modules.textual_inversion.textual_inversion.create_embedding(name, nvpt, init_text=initialization_text)
sd_hijack.model_hijack.embedding_db.load_textual_inversion_embeddings()
return gr.Dropdown.update(choices=sorted(sd_hijack.model_hijack.embedding_db.word_embeddings.keys())), f"Created: {filename}", ""
def preprocess(*args):
modules.textual_inversion.preprocess.preprocess(*args)
return "Preprocessing finished.", ""
def train_embedding(*args):
try:
sd_hijack.undo_optimizations()
embedding, filename = modules.textual_inversion.textual_inversion.train_embedding(*args)
res = f"""
Training {'interrupted' if shared.state.interrupted else 'finished'} at {embedding.step} steps.
Embedding saved to {html.escape(filename)}
"""
return res, ""
except Exception:
raise
finally:
sd_hijack.apply_optimizations()
+24 -5
View File
@@ -6,14 +6,20 @@ import modules.processing as processing
from modules.ui import plaintext_to_html from modules.ui import plaintext_to_html
def txt2img(prompt: str, negative_prompt: str, steps: int, sampler_index: int, restore_faces: bool, tiling: bool, n_iter: int, batch_size: int, cfg_scale: float, seed: int, height: int, width: int, *args): def txt2img(prompt: str, negative_prompt: str, prompt_style: str, prompt_style2: str, steps: int, sampler_index: int, restore_faces: bool, tiling: bool, n_iter: int, batch_size: int, cfg_scale: float, seed: int, subseed: int, subseed_strength: float, seed_resize_from_h: int, seed_resize_from_w: int, seed_enable_extras: bool, height: int, width: int, enable_hr: bool, scale_latent: bool, denoising_strength: float, *args):
p = StableDiffusionProcessingTxt2Img( p = StableDiffusionProcessingTxt2Img(
sd_model=shared.sd_model, sd_model=shared.sd_model,
outpath_samples=opts.outdir_samples or opts.outdir_txt2img_samples, outpath_samples=opts.outdir_samples or opts.outdir_txt2img_samples,
outpath_grids=opts.outdir_grids or opts.outdir_txt2img_grids, outpath_grids=opts.outdir_grids or opts.outdir_txt2img_grids,
prompt=prompt, prompt=prompt,
styles=[prompt_style, prompt_style2],
negative_prompt=negative_prompt, negative_prompt=negative_prompt,
seed=seed, seed=seed,
subseed=subseed,
subseed_strength=subseed_strength,
seed_resize_from_h=seed_resize_from_h,
seed_resize_from_w=seed_resize_from_w,
seed_enable_extras=seed_enable_extras,
sampler_index=sampler_index, sampler_index=sampler_index,
batch_size=batch_size, batch_size=batch_size,
n_iter=n_iter, n_iter=n_iter,
@@ -23,14 +29,27 @@ def txt2img(prompt: str, negative_prompt: str, steps: int, sampler_index: int, r
height=height, height=height,
restore_faces=restore_faces, restore_faces=restore_faces,
tiling=tiling, tiling=tiling,
enable_hr=enable_hr,
scale_latent=scale_latent if enable_hr else None,
denoising_strength=denoising_strength if enable_hr else None,
) )
if cmd_opts.enable_console_prompts:
print(f"\ntxt2img: {prompt}", file=shared.progress_print_out)
processed = modules.scripts.scripts_txt2img.run(p, *args) processed = modules.scripts.scripts_txt2img.run(p, *args)
if processed is not None: if processed is None:
pass
else:
processed = process_images(p) processed = process_images(p)
return processed.images, processed.js(), plaintext_to_html(processed.info) shared.total_tqdm.clear()
generation_info_js = processed.js()
if opts.samples_log_stdout:
print(generation_info_js)
if opts.do_not_show_images:
processed.images = []
return processed.images, generation_info_js, plaintext_to_html(processed.info)
+956 -225
View File
File diff suppressed because it is too large. Load diff
+121
View File
@@ -0,0 +1,121 @@
import os
from abc import abstractmethod
import PIL
import numpy as np
import torch
from PIL import Image
import modules.shared
from modules import modelloader, shared
LANCZOS = (Image.Resampling.LANCZOS if hasattr(Image, 'Resampling') else Image.LANCZOS)
from modules.paths import models_path
class Upscaler:
name = None
model_path = None
model_name = None
model_url = None
enable = True
filter = None
model = None
user_path = None
scalers: []
tile = True
def __init__(self, create_dirs=False):
self.mod_pad_h = None
self.tile_size = modules.shared.opts.ESRGAN_tile
self.tile_pad = modules.shared.opts.ESRGAN_tile_overlap
self.device = modules.shared.device
self.img = None
self.output = None
self.scale = 1
self.half = not modules.shared.cmd_opts.no_half
self.pre_pad = 0
self.mod_scale = None
if self.name is not None and create_dirs:
self.model_path = os.path.join(models_path, self.name)
if not os.path.exists(self.model_path):
os.makedirs(self.model_path)
try:
import cv2
self.can_tile = True
except:
pass
@abstractmethod
def do_upscale(self, img: PIL.Image, selected_model: str):
return img
def upscale(self, img: PIL.Image, scale: int, selected_model: str = None):
self.scale = scale
dest_w = img.width * scale
dest_h = img.height * scale
for i in range(3):
if img.width >= dest_w and img.height >= dest_h:
break
img = self.do_upscale(img, selected_model)
if img.width != dest_w or img.height != dest_h:
img = img.resize((int(dest_w), int(dest_h)), resample=LANCZOS)
return img
@abstractmethod
def load_model(self, path: str):
pass
def find_models(self, ext_filter=None) -> list:
return modelloader.load_models(model_path=self.model_path, model_url=self.model_url, command_path=self.user_path)
def update_status(self, prompt):
print(f"\nextras: {prompt}", file=shared.progress_print_out)
class UpscalerData:
name = None
data_path = None
scale: int = 4
scaler: Upscaler = None
model: None
def __init__(self, name: str, path: str, upscaler: Upscaler = None, scale: int = 4, model=None):
self.name = name
self.data_path = path
self.scaler = upscaler
self.scale = scale
self.model = model
class UpscalerNone(Upscaler):
name = "None"
scalers = []
def load_model(self, path):
pass
def do_upscale(self, img, selected_model=None):
return img
def __init__(self, dirname=None):
super().__init__(False)
self.scalers = [UpscalerData("None", None, self)]
class UpscalerLanczos(Upscaler):
scalers = []
def do_upscale(self, img, selected_model=None):
return img.resize((int(img.width * self.scale), int(img.height * self.scale)), resample=LANCZOS)
def load_model(self, _):
pass
def __init__(self, dirname=None):
super().__init__(False)
self.name = "Lanczos"
self.scalers = [UpscalerData("Lanczos", None, self)]
+22 -11
View File
@@ -1,14 +1,25 @@
basicsr basicsr
gfpgan
gradio
numpy
Pillow
realesrgan
torch
transformers
omegaconf
pytorch_lightning
diffusers diffusers
fairscale==0.4.4
fonts
font-roboto
gfpgan
gradio==3.4b3
invisible-watermark invisible-watermark
git+https://github.com/crowsonkb/k-diffusion.git numpy
git+https://github.com/TencentARC/GFPGAN.git omegaconf
piexif
Pillow
pytorch_lightning
realesrgan
scikit-image>=0.19
timm==0.4.12
transformers==4.19.2
torch
einops
jsonmerge
clean-fid
resize-right
torchdiffeq
kornia
lark
+23 -9
View File
@@ -1,10 +1,24 @@
basicsr==1.3.5
gfpgan
gradio==3.2
numpy==1.22.0
Pillow==9.2.0
realesrgan==0.2.5.0
torch
transformers==4.19.2 transformers==4.19.2
omegaconf==2.1.1 diffusers==0.3.0
pytorch_lightning==1.7.2 basicsr==1.4.2
gfpgan==1.3.8
gradio==3.4b3
numpy==1.23.3
Pillow==9.2.0
realesrgan==0.3.0
torch
omegaconf==2.2.3
pytorch_lightning==1.7.6
scikit-image==0.19.2
fonts
font-roboto
timm==0.6.7
fairscale==0.4.9
piexif==1.1.3
einops==0.4.1
jsonmerge==1.8.0
clean-fid==0.1.29
resize-right==0.0.2
torchdiffeq==0.2.3
kornia==0.6.7
lark==1.1.2
+42 -135
View File
@@ -1,155 +1,62 @@
titles = {
"Sampling steps": "How many times to imptove the generated image itratively; higher values take longer; very low values can produce bad results",
"Sampling method": "Which algorithm to use to produce the image",
"GFPGAN": "Restore low quality faces using GFPGAN neural network",
"Euler a": "Euler Ancestral - very creative, each can get acompletely different pictures depending on step count, setting seps tohigher than 30-40 does not help",
"DDIM": "Denoising Diffusion Implicit Models - best at inpainting",
"Batch count": "How many batches of images to create",
"Batch size": "How many image to create in a single batch",
"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",
"Inpaint a part of image": "Draw a mask over an image, and the script will regenerate the masked area with content according to prompt",
"Loopback": "Process an image, use it as an input, repeat. Batch count determings number of iterations.",
"SD upscale": "Upscale image normally, split result into tiles, improve each tile using img2img, merge whole image back",
"Just resize": "Resize image to target resolution. Unless height and width match, you will get incorrect aspect ratio.",
"Crop and resize": "Resize the image so that entirety of target resolution is filled with the image. Crop parts that stick out.",
"Resize and fill": "Resize the image so that entirety of image is inside target resolution. Fill empty space with image's colors.",
"Mask blur": "How much to blur the mask before processing, in pixels.",
"Masked content": "What to put inside the masked area before processing it with Stable Diffusion.",
"fill": "fill it with colors of the image",
"original": "keep whatever was there originally",
"latent noise": "fill it with latent space noise",
"latent nothing": "fill it with latent space zeroes",
"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.",
"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.",
"X values": "Separate values for X axis using commas.",
"Y values": "Separate values for Y axis using commas.",
"None": "Do not do anything special",
"Prompt matrix": "Separate prompts into parts using vertical pipe character (|) and the script will create a picture for every combination of them (except for the first part, which will be present in all combinations)",
"X/Y plot": "Create a grid where images will have different parameters. Use inputs below to specify which parameterswill be shared by columns and rows",
"Custom code": "Run python code. Advanced user only. Must run program with --allow-code for this to work",
"Prompt S/R": "Separate a list of words with commas, and the first word will be used as a keyword: script will search for this word in the prompt, and replace it with others",
"Tiling": "Produce an image that can be tiled.",
"Tile overlap": "For SD upscale, how much overlap in pixels should there be between tiles. Tils overlap so that when they are merged back into one oicture, there is no clearly visible seam.",
"Roll": "Add a random artist to the prompt.",
}
function gradioApp(){ function gradioApp(){
return document.getElementsByTagName('gradio-app')[0].shadowRoot; return document.getElementsByTagName('gradio-app')[0].shadowRoot;
} }
global_progressbar = null function get_uiCurrentTab() {
return gradioApp().querySelector('.tabs button:not(.border-transparent)')
}
function addTitles(root){ uiUpdateCallbacks = []
root.querySelectorAll('span, button, select').forEach(function(span){ uiTabChangeCallbacks = []
tooltip = titles[span.textContent]; let uiCurrentTab = null
if(!tooltip){ function onUiUpdate(callback){
tooltip = titles[span.value]; uiUpdateCallbacks.push(callback)
}
function onUiTabChange(callback){
uiTabChangeCallbacks.push(callback)
}
function runCallback(x){
try {
x()
} catch (e) {
(console.error || console.log).call(console, e.message, e);
} }
}
if(tooltip){ function executeCallbacks(queue) {
span.title = tooltip; queue.forEach(runCallback)
}
})
root.querySelectorAll('select').forEach(function(select){
if (select.onchange != null) return;
select.onchange = function(){
select.title = titles[select.value] || "";
}
})
progressbar = root.getElementById('progressbar')
if(progressbar!= null && progressbar != global_progressbar){
global_progressbar = progressbar
var mutationObserver = new MutationObserver(function(m){
txt2img_preview = gradioApp().getElementById('txt2img_preview')
txt2img_gallery = gradioApp().getElementById('txt2img_gallery')
img2img_preview = gradioApp().getElementById('img2img_preview')
img2img_gallery = gradioApp().getElementById('img2img_gallery')
if(txt2img_preview != null && txt2img_gallery != null){
txt2img_preview.style.width = txt2img_gallery.clientWidth + "px"
txt2img_preview.style.height = txt2img_gallery.clientHeight + "px"
}
if(img2img_preview != null && img2img_gallery != null){
img2img_preview.style.width = img2img_gallery.clientWidth + "px"
img2img_preview.style.height = img2img_gallery.clientHeight + "px"
}
window.setTimeout(requestProgress, 500)
});
mutationObserver.observe( progressbar, { childList:true, subtree:true })
}
} }
document.addEventListener("DOMContentLoaded", function() { document.addEventListener("DOMContentLoaded", function() {
var mutationObserver = new MutationObserver(function(m){ var mutationObserver = new MutationObserver(function(m){
addTitles(gradioApp()); executeCallbacks(uiUpdateCallbacks);
const newTab = get_uiCurrentTab();
if ( newTab && ( newTab !== uiCurrentTab ) ) {
uiCurrentTab = newTab;
executeCallbacks(uiTabChangeCallbacks);
}
}); });
mutationObserver.observe( gradioApp(), { childList:true, subtree:true }) mutationObserver.observe( gradioApp(), { childList:true, subtree:true })
}); });
function selected_gallery_index(){ /**
var gr = gradioApp() * checks that a UI element is not in another hidden element or tab content
var buttons = gradioApp().querySelectorAll(".gallery-item") */
var button = gr.querySelector(".gallery-item.\\!ring-2") function uiElementIsVisible(el) {
let isVisible = !el.closest('.\\!hidden');
var result = -1 if ( ! isVisible ) {
buttons.forEach(function(v, i){ if(v==button) { result = i } }) return false;
return result
}
function extract_image_from_gallery(gallery){
if(gallery.length == 1){
return gallery[0]
} }
index = selected_gallery_index() while( isVisible = el.closest('.tabitem')?.style.display !== 'none' ) {
if ( ! isVisible ) {
if (index < 0 || index >= gallery.length){ return false;
return [] } else if ( el.parentElement ) {
el = el.parentElement
} else {
break;
} }
return gallery[index];
}
function requestProgress(){
btn = gradioApp().getElementById("check_progress");
if(btn==null) return;
btn.click();
}
function submit(){
window.setTimeout(requestProgress, 500)
res = []
for(var i=0;i<arguments.length;i++){
res.push(arguments[i])
} }
console.log(res) return isVisible;
return res
} }
+3 -1
View File
@@ -4,8 +4,8 @@ import gradio as gr
from modules.processing import Processed from modules.processing import Processed
from modules.shared import opts, cmd_opts, state from modules.shared import opts, cmd_opts, state
class Script(scripts.Script): class Script(scripts.Script):
def title(self): def title(self):
return "Custom code" return "Custom code"
@@ -18,6 +18,7 @@ class Script(scripts.Script):
return [code] return [code]
def run(self, p, code): def run(self, p, code):
assert cmd_opts.allow_code, '--allow-code option must be enabled' assert cmd_opts.allow_code, '--allow-code option must be enabled'
@@ -38,3 +39,4 @@ class Script(scripts.Script):
return Processed(p, *display_result_data) return Processed(p, *display_result_data)
+183
View File
@@ -0,0 +1,183 @@
from collections import namedtuple
import numpy as np
from tqdm import trange
import modules.scripts as scripts
import gradio as gr
from modules import processing, shared, sd_samplers, prompt_parser
from modules.processing import Processed
from modules.shared import opts, cmd_opts, state
import torch
import k_diffusion as K
from PIL import Image
from torch import autocast
from einops import rearrange, repeat
def find_noise_for_image(p, cond, uncond, cfg_scale, steps):
x = p.init_latent
s_in = x.new_ones([x.shape[0]])
dnw = K.external.CompVisDenoiser(shared.sd_model)
sigmas = dnw.get_sigmas(steps).flip(0)
shared.state.sampling_steps = steps
for i in trange(1, len(sigmas)):
shared.state.sampling_step += 1
x_in = torch.cat([x] * 2)
sigma_in = torch.cat([sigmas[i] * s_in] * 2)
cond_in = torch.cat([uncond, cond])
c_out, c_in = [K.utils.append_dims(k, x_in.ndim) for k in dnw.get_scalings(sigma_in)]
t = dnw.sigma_to_t(sigma_in)
eps = shared.sd_model.apply_model(x_in * c_in, t, cond=cond_in)
denoised_uncond, denoised_cond = (x_in + eps * c_out).chunk(2)
denoised = denoised_uncond + (denoised_cond - denoised_uncond) * cfg_scale
d = (x - denoised) / sigmas[i]
dt = sigmas[i] - sigmas[i - 1]
x = x + d * dt
sd_samplers.store_latent(x)
# This shouldn't be necessary, but solved some VRAM issues
del x_in, sigma_in, cond_in, c_out, c_in, t,
del eps, denoised_uncond, denoised_cond, denoised, d, dt
shared.state.nextjob()
return x / x.std()
Cached = namedtuple("Cached", ["noise", "cfg_scale", "steps", "latent", "original_prompt", "original_negative_prompt", "sigma_adjustment"])
# Based on changes suggested by briansemrau in https://github.com/AUTOMATIC1111/stable-diffusion-webui/issues/736
def find_noise_for_image_sigma_adjustment(p, cond, uncond, cfg_scale, steps):
x = p.init_latent
s_in = x.new_ones([x.shape[0]])
dnw = K.external.CompVisDenoiser(shared.sd_model)
sigmas = dnw.get_sigmas(steps).flip(0)
shared.state.sampling_steps = steps
for i in trange(1, len(sigmas)):
shared.state.sampling_step += 1
x_in = torch.cat([x] * 2)
sigma_in = torch.cat([sigmas[i - 1] * s_in] * 2)
cond_in = torch.cat([uncond, cond])
c_out, c_in = [K.utils.append_dims(k, x_in.ndim) for k in dnw.get_scalings(sigma_in)]
if i == 1:
t = dnw.sigma_to_t(torch.cat([sigmas[i] * s_in] * 2))
else:
t = dnw.sigma_to_t(sigma_in)
eps = shared.sd_model.apply_model(x_in * c_in, t, cond=cond_in)
denoised_uncond, denoised_cond = (x_in + eps * c_out).chunk(2)
denoised = denoised_uncond + (denoised_cond - denoised_uncond) * cfg_scale
if i == 1:
d = (x - denoised) / (2 * sigmas[i])
else:
d = (x - denoised) / sigmas[i - 1]
dt = sigmas[i] - sigmas[i - 1]
x = x + d * dt
sd_samplers.store_latent(x)
# This shouldn't be necessary, but solved some VRAM issues
del x_in, sigma_in, cond_in, c_out, c_in, t,
del eps, denoised_uncond, denoised_cond, denoised, d, dt
shared.state.nextjob()
return x / sigmas[-1]
class Script(scripts.Script):
def __init__(self):
self.cache = None
def title(self):
return "img2img alternative test"
def show(self, is_img2img):
return is_img2img
def ui(self, is_img2img):
original_prompt = gr.Textbox(label="Original prompt", lines=1)
original_negative_prompt = gr.Textbox(label="Original negative prompt", lines=1)
cfg = gr.Slider(label="Decode CFG scale", minimum=0.0, maximum=15.0, step=0.1, value=1.0)
st = gr.Slider(label="Decode steps", minimum=1, maximum=150, step=1, value=50)
randomness = gr.Slider(label="Randomness", minimum=0.0, maximum=1.0, step=0.01, value=0.0)
sigma_adjustment = gr.Checkbox(label="Sigma adjustment for finding noise for image", value=False)
return [original_prompt, original_negative_prompt, cfg, st, randomness, sigma_adjustment]
def run(self, p, original_prompt, original_negative_prompt, cfg, st, randomness, sigma_adjustment):
p.batch_size = 1
p.batch_count = 1
def sample_extra(conditioning, unconditional_conditioning, seeds, subseeds, subseed_strength):
lat = (p.init_latent.cpu().numpy() * 10).astype(int)
same_params = self.cache is not None and self.cache.cfg_scale == cfg and self.cache.steps == st \
and self.cache.original_prompt == original_prompt \
and self.cache.original_negative_prompt == original_negative_prompt \
and self.cache.sigma_adjustment == sigma_adjustment
same_everything = same_params and self.cache.latent.shape == lat.shape and np.abs(self.cache.latent-lat).sum() < 100
if same_everything:
rec_noise = self.cache.noise
else:
shared.state.job_count += 1
cond = p.sd_model.get_learned_conditioning(p.batch_size * [original_prompt])
uncond = p.sd_model.get_learned_conditioning(p.batch_size * [original_negative_prompt])
if sigma_adjustment:
rec_noise = find_noise_for_image_sigma_adjustment(p, cond, uncond, cfg, st)
else:
rec_noise = find_noise_for_image(p, cond, uncond, cfg, st)
self.cache = Cached(rec_noise, cfg, st, lat, original_prompt, original_negative_prompt, sigma_adjustment)
rand_noise = processing.create_random_tensors(p.init_latent.shape[1:], [p.seed + x + 1 for x in range(p.init_latent.shape[0])])
combined_noise = ((1 - randomness) * rec_noise + randomness * rand_noise) / ((randomness**2 + (1-randomness)**2) ** 0.5)
sampler = sd_samplers.create_sampler_with_index(sd_samplers.samplers, p.sampler_index, p.sd_model)
sigmas = sampler.model_wrap.get_sigmas(p.steps)
noise_dt = combined_noise - (p.init_latent / sigmas[0])
p.seed = p.seed + 1
return sampler.sample_img2img(p, p.init_latent, noise_dt, conditioning, unconditional_conditioning)
p.sample = sample_extra
p.extra_generation_params["Decode prompt"] = original_prompt
p.extra_generation_params["Decode negative prompt"] = original_negative_prompt
p.extra_generation_params["Decode CFG scale"] = cfg
p.extra_generation_params["Decode steps"] = st
p.extra_generation_params["Randomness"] = randomness
p.extra_generation_params["Sigma Adjustment"] = sigma_adjustment
processed = processing.process_images(p)
return processed
+83
View File
@@ -0,0 +1,83 @@
import numpy as np
from tqdm import trange
import modules.scripts as scripts
import gradio as gr
from modules import processing, shared, sd_samplers, images
from modules.processing import Processed
from modules.sd_samplers import samplers
from modules.shared import opts, cmd_opts, state
class Script(scripts.Script):
def title(self):
return "Loopback"
def show(self, is_img2img):
return is_img2img
def ui(self, is_img2img):
loops = gr.Slider(minimum=1, maximum=32, step=1, label='Loops', value=4)
denoising_strength_change_factor = gr.Slider(minimum=0.9, maximum=1.1, step=0.01, label='Denoising strength change factor', value=1)
return [loops, denoising_strength_change_factor]
def run(self, p, loops, denoising_strength_change_factor):
processing.fix_seed(p)
batch_count = p.n_iter
p.extra_generation_params = {
"Denoising strength change factor": denoising_strength_change_factor,
}
p.batch_size = 1
p.n_iter = 1
output_images, info = None, None
initial_seed = None
initial_info = None
grids = []
all_images = []
state.job_count = loops * batch_count
initial_color_corrections = [processing.setup_color_correction(p.init_images[0])]
for n in range(batch_count):
history = []
for i in range(loops):
p.n_iter = 1
p.batch_size = 1
p.do_not_save_grid = True
if opts.img2img_color_correction:
p.color_corrections = initial_color_corrections
state.job = f"Iteration {i + 1}/{loops}, batch {n + 1}/{batch_count}"
processed = processing.process_images(p)
if initial_seed is None:
initial_seed = processed.seed
initial_info = processed.info
init_img = processed.images[0]
p.init_images = [init_img]
p.seed = processed.seed + 1
p.denoising_strength = min(max(p.denoising_strength * denoising_strength_change_factor, 0.1), 1)
history.append(processed.images[0])
grid = images.image_grid(history, rows=1)
if opts.grid_save:
images.save_image(grid, p.outpath_grids, "grid", initial_seed, p.prompt, opts.grid_format, info=info, short_filename=not opts.grid_extended_filename, grid=True, p=p)
grids.append(grid)
all_images += history
if opts.return_grid:
all_images = grids + all_images
processed = Processed(p, all_images, initial_seed, initial_info)
return processed
+262
View File
@@ -0,0 +1,262 @@
import math
import numpy as np
import skimage
import modules.scripts as scripts
import gradio as gr
from PIL import Image, ImageDraw
from modules import images, processing, devices
from modules.processing import Processed, process_images
from modules.shared import opts, cmd_opts, state
# this function is taken from https://github.com/parlance-zz/g-diffuser-bot
def get_matched_noise(_np_src_image, np_mask_rgb, noise_q=1, color_variation=0.05):
# helper fft routines that keep ortho normalization and auto-shift before and after fft
def _fft2(data):
if data.ndim > 2: # has channels
out_fft = np.zeros((data.shape[0], data.shape[1], data.shape[2]), dtype=np.complex128)
for c in range(data.shape[2]):
c_data = data[:, :, c]
out_fft[:, :, c] = np.fft.fft2(np.fft.fftshift(c_data), norm="ortho")
out_fft[:, :, c] = np.fft.ifftshift(out_fft[:, :, c])
else: # one channel
out_fft = np.zeros((data.shape[0], data.shape[1]), dtype=np.complex128)
out_fft[:, :] = np.fft.fft2(np.fft.fftshift(data), norm="ortho")
out_fft[:, :] = np.fft.ifftshift(out_fft[:, :])
return out_fft
def _ifft2(data):
if data.ndim > 2: # has channels
out_ifft = np.zeros((data.shape[0], data.shape[1], data.shape[2]), dtype=np.complex128)
for c in range(data.shape[2]):
c_data = data[:, :, c]
out_ifft[:, :, c] = np.fft.ifft2(np.fft.fftshift(c_data), norm="ortho")
out_ifft[:, :, c] = np.fft.ifftshift(out_ifft[:, :, c])
else: # one channel
out_ifft = np.zeros((data.shape[0], data.shape[1]), dtype=np.complex128)
out_ifft[:, :] = np.fft.ifft2(np.fft.fftshift(data), norm="ortho")
out_ifft[:, :] = np.fft.ifftshift(out_ifft[:, :])
return out_ifft
def _get_gaussian_window(width, height, std=3.14, mode=0):
window_scale_x = float(width / min(width, height))
window_scale_y = float(height / min(width, height))
window = np.zeros((width, height))
x = (np.arange(width) / width * 2. - 1.) * window_scale_x
for y in range(height):
fy = (y / height * 2. - 1.) * window_scale_y
if mode == 0:
window[:, y] = np.exp(-(x ** 2 + fy ** 2) * std)
else:
window[:, y] = (1 / ((x ** 2 + 1.) * (fy ** 2 + 1.))) ** (std / 3.14) # hey wait a minute that's not gaussian
return window
def _get_masked_window_rgb(np_mask_grey, hardness=1.):
np_mask_rgb = np.zeros((np_mask_grey.shape[0], np_mask_grey.shape[1], 3))
if hardness != 1.:
hardened = np_mask_grey[:] ** hardness
else:
hardened = np_mask_grey[:]
for c in range(3):
np_mask_rgb[:, :, c] = hardened[:]
return np_mask_rgb
width = _np_src_image.shape[0]
height = _np_src_image.shape[1]
num_channels = _np_src_image.shape[2]
np_src_image = _np_src_image[:] * (1. - np_mask_rgb)
np_mask_grey = (np.sum(np_mask_rgb, axis=2) / 3.)
img_mask = np_mask_grey > 1e-6
ref_mask = np_mask_grey < 1e-3
windowed_image = _np_src_image * (1. - _get_masked_window_rgb(np_mask_grey))
windowed_image /= np.max(windowed_image)
windowed_image += np.average(_np_src_image) * np_mask_rgb # / (1.-np.average(np_mask_rgb)) # rather than leave the masked area black, we get better results from fft by filling the average unmasked color
src_fft = _fft2(windowed_image) # get feature statistics from masked src img
src_dist = np.absolute(src_fft)
src_phase = src_fft / src_dist
# create a generator with a static seed to make outpainting deterministic / only follow global seed
rng = np.random.default_rng(0)
noise_window = _get_gaussian_window(width, height, mode=1) # start with simple gaussian noise
noise_rgb = rng.random((width, height, num_channels))
noise_grey = (np.sum(noise_rgb, axis=2) / 3.)
noise_rgb *= color_variation # the colorfulness of the starting noise is blended to greyscale with a parameter
for c in range(num_channels):
noise_rgb[:, :, c] += (1. - color_variation) * noise_grey
noise_fft = _fft2(noise_rgb)
for c in range(num_channels):
noise_fft[:, :, c] *= noise_window
noise_rgb = np.real(_ifft2(noise_fft))
shaped_noise_fft = _fft2(noise_rgb)
shaped_noise_fft[:, :, :] = np.absolute(shaped_noise_fft[:, :, :]) ** 2 * (src_dist ** noise_q) * src_phase # perform the actual shaping
brightness_variation = 0. # color_variation # todo: temporarily tieing brightness variation to color variation for now
contrast_adjusted_np_src = _np_src_image[:] * (brightness_variation + 1.) - brightness_variation * 2.
# scikit-image is used for histogram matching, very convenient!
shaped_noise = np.real(_ifft2(shaped_noise_fft))
shaped_noise -= np.min(shaped_noise)
shaped_noise /= np.max(shaped_noise)
shaped_noise[img_mask, :] = skimage.exposure.match_histograms(shaped_noise[img_mask, :] ** 1., contrast_adjusted_np_src[ref_mask, :], channel_axis=1)
shaped_noise = _np_src_image[:] * (1. - np_mask_rgb) + shaped_noise * np_mask_rgb
matched_noise = shaped_noise[:]
return np.clip(matched_noise, 0., 1.)
class Script(scripts.Script):
def title(self):
return "Outpainting mk2"
def show(self, is_img2img):
return is_img2img
def ui(self, is_img2img):
if not is_img2img:
return None
info = gr.HTML("<p style=\"margin-bottom:0.75em\">Recommended settings: Sampling Steps: 80-100, Sampler: Euler a, Denoising strength: 0.8</p>")
pixels = gr.Slider(label="Pixels to expand", minimum=8, maximum=256, step=8, value=128)
mask_blur = gr.Slider(label='Mask blur', minimum=0, maximum=64, step=1, value=8, visible=False)
direction = gr.CheckboxGroup(label="Outpainting direction", choices=['left', 'right', 'up', 'down'], value=['left', 'right', 'up', 'down'])
noise_q = gr.Slider(label="Fall-off exponent (lower=higher detail)", minimum=0.0, maximum=4.0, step=0.01, value=1.0)
color_variation = gr.Slider(label="Color variation", minimum=0.0, maximum=1.0, step=0.01, value=0.05)
return [info, pixels, mask_blur, direction, noise_q, color_variation]
def run(self, p, _, pixels, mask_blur, direction, noise_q, color_variation):
initial_seed_and_info = [None, None]
process_width = p.width
process_height = p.height
p.mask_blur = mask_blur*4
p.inpaint_full_res = False
p.inpainting_fill = 1
p.do_not_save_samples = True
p.do_not_save_grid = True
left = pixels if "left" in direction else 0
right = pixels if "right" in direction else 0
up = pixels if "up" in direction else 0
down = pixels if "down" in direction else 0
init_img = p.init_images[0]
target_w = math.ceil((init_img.width + left + right) / 64) * 64
target_h = math.ceil((init_img.height + up + down) / 64) * 64
if left > 0:
left = left * (target_w - init_img.width) // (left + right)
if right > 0:
right = target_w - init_img.width - left
if up > 0:
up = up * (target_h - init_img.height) // (up + down)
if down > 0:
down = target_h - init_img.height - up
init_image = p.init_images[0]
state.job_count = (1 if left > 0 else 0) + (1 if right > 0 else 0) + (1 if up > 0 else 0) + (1 if down > 0 else 0)
def expand(init, expand_pixels, is_left=False, is_right=False, is_top=False, is_bottom=False):
is_horiz = is_left or is_right
is_vert = is_top or is_bottom
pixels_horiz = expand_pixels if is_horiz else 0
pixels_vert = expand_pixels if is_vert else 0
res_w = init.width + pixels_horiz
res_h = init.height + pixels_vert
process_res_w = math.ceil(res_w / 64) * 64
process_res_h = math.ceil(res_h / 64) * 64
img = Image.new("RGB", (process_res_w, process_res_h))
img.paste(init, (pixels_horiz if is_left else 0, pixels_vert if is_top else 0))
mask = Image.new("RGB", (process_res_w, process_res_h), "white")
draw = ImageDraw.Draw(mask)
draw.rectangle((
expand_pixels + mask_blur if is_left else 0,
expand_pixels + mask_blur if is_top else 0,
mask.width - expand_pixels - mask_blur if is_right else res_w,
mask.height - expand_pixels - mask_blur if is_bottom else res_h,
), fill="black")
np_image = (np.asarray(img) / 255.0).astype(np.float64)
np_mask = (np.asarray(mask) / 255.0).astype(np.float64)
noised = get_matched_noise(np_image, np_mask, noise_q, color_variation)
out = Image.fromarray(np.clip(noised * 255., 0., 255.).astype(np.uint8), mode="RGB")
target_width = min(process_width, init.width + pixels_horiz) if is_horiz else img.width
target_height = min(process_height, init.height + pixels_vert) if is_vert else img.height
crop_region = (
0 if is_left else out.width - target_width,
0 if is_top else out.height - target_height,
target_width if is_left else out.width,
target_height if is_top else out.height,
)
image_to_process = out.crop(crop_region)
mask = mask.crop(crop_region)
p.width = target_width if is_horiz else img.width
p.height = target_height if is_vert else img.height
p.init_images = [image_to_process]
p.image_mask = mask
latent_mask = Image.new("RGB", (p.width, p.height), "white")
draw = ImageDraw.Draw(latent_mask)
draw.rectangle((
expand_pixels + mask_blur * 2 if is_left else 0,
expand_pixels + mask_blur * 2 if is_top else 0,
mask.width - expand_pixels - mask_blur * 2 if is_right else res_w,
mask.height - expand_pixels - mask_blur * 2 if is_bottom else res_h,
), fill="black")
p.latent_mask = latent_mask
proc = process_images(p)
proc_img = proc.images[0]
if initial_seed_and_info[0] is None:
initial_seed_and_info[0] = proc.seed
initial_seed_and_info[1] = proc.info
out.paste(proc_img, (0 if is_left else out.width - proc_img.width, 0 if is_top else out.height - proc_img.height))
out = out.crop((0, 0, res_w, res_h))
return out
img = init_image
if left > 0:
img = expand(img, left, is_left=True)
if right > 0:
img = expand(img, right, is_right=True)
if up > 0:
img = expand(img, up, is_top=True)
if down > 0:
img = expand(img, down, is_bottom=True)
res = Processed(p, [img], initial_seed_and_info[0], initial_seed_and_info[1])
if opts.samples_save:
images.save_image(img, p.outpath_samples, "", res.seed, p.prompt, opts.grid_format, info=res.info, p=p)
return res
+26 -8
View File
@@ -4,7 +4,7 @@ import modules.scripts as scripts
import gradio as gr import gradio as gr
from PIL import Image, ImageDraw from PIL import Image, ImageDraw
from modules import images, processing from modules import images, processing, devices
from modules.processing import Processed, process_images from modules.processing import Processed, process_images
from modules.shared import opts, cmd_opts, state from modules.shared import opts, cmd_opts, state
@@ -21,7 +21,7 @@ class Script(scripts.Script):
if not is_img2img: if not is_img2img:
return None return None
pixels = gr.Slider(label="Pixels to expand", minimum=8, maximum=128, step=8) pixels = gr.Slider(label="Pixels to expand", minimum=8, maximum=256, step=8, value=128)
mask_blur = gr.Slider(label='Mask blur', minimum=0, maximum=64, step=1, value=4, visible=False) mask_blur = gr.Slider(label='Mask blur', minimum=0, maximum=64, step=1, value=4, visible=False)
inpainting_fill = gr.Radio(label='Masked content', choices=['fill', 'original', 'latent noise', 'latent nothing'], value='fill', type="index", visible=False) inpainting_fill = gr.Radio(label='Masked content', choices=['fill', 'original', 'latent noise', 'latent nothing'], value='fill', type="index", visible=False)
direction = gr.CheckboxGroup(label="Outpainting direction", choices=['left', 'right', 'up', 'down'], value=['left', 'right', 'up', 'down']) direction = gr.CheckboxGroup(label="Outpainting direction", choices=['left', 'right', 'up', 'down'], value=['left', 'right', 'up', 'down'])
@@ -32,7 +32,7 @@ class Script(scripts.Script):
initial_seed = None initial_seed = None
initial_info = None initial_info = None
p.mask_blur = mask_blur p.mask_blur = mask_blur * 2
p.inpainting_fill = inpainting_fill p.inpainting_fill = inpainting_fill
p.inpaint_full_res = False p.inpaint_full_res = False
@@ -47,10 +47,13 @@ class Script(scripts.Script):
if left > 0: if left > 0:
left = left * (target_w - init_img.width) // (left + right) left = left * (target_w - init_img.width) // (left + right)
if right > 0:
right = target_w - init_img.width - left right = target_w - init_img.width - left
if up > 0: if up > 0:
up = up * (target_h - init_img.height) // (up + down) up = up * (target_h - init_img.height) // (up + down)
if down > 0:
down = target_h - init_img.height - up down = target_h - init_img.height - up
img = Image.new("RGB", (target_w, target_h)) img = Image.new("RGB", (target_w, target_h))
@@ -67,13 +70,18 @@ class Script(scripts.Script):
latent_mask = Image.new("L", (img.width, img.height), "white") latent_mask = Image.new("L", (img.width, img.height), "white")
latent_draw = ImageDraw.Draw(latent_mask) latent_draw = ImageDraw.Draw(latent_mask)
latent_draw.rectangle((left + left//2, up + up//2, mask.width - right - right//2, mask.height - down - down//2), fill="black") latent_draw.rectangle((
left + (mask_blur//2 if left > 0 else 0),
up + (mask_blur//2 if up > 0 else 0),
mask.width - right - (mask_blur//2 if right > 0 else 0),
mask.height - down - (mask_blur//2 if down > 0 else 0)
), fill="black")
processing.torch_gc() devices.torch_gc()
grid = images.split_grid(img, tile_w=p.width, tile_h=p.height, overlap=pixels) grid = images.split_grid(img, tile_w=p.width, tile_h=p.height, overlap=pixels)
grid_mask = images.split_grid(mask, tile_w=p.width, tile_h=p.height, overlap=pixels) grid_mask = images.split_grid(mask, tile_w=p.width, tile_h=p.height, overlap=pixels)
grid_latent_mask = images.split_grid(mask, tile_w=p.width, tile_h=p.height, overlap=pixels) grid_latent_mask = images.split_grid(latent_mask, tile_w=p.width, tile_h=p.height, overlap=pixels)
p.n_iter = 1 p.n_iter = 1
p.batch_size = 1 p.batch_size = 1
@@ -85,8 +93,13 @@ class Script(scripts.Script):
work_latent_mask = [] work_latent_mask = []
work_results = [] work_results = []
for (_, _, row), (_, _, row_mask), (_, _, row_latent_mask) in zip(grid.tiles, grid_mask.tiles, grid_latent_mask.tiles): for (y, h, row), (_, _, row_mask), (_, _, row_latent_mask) in zip(grid.tiles, grid_mask.tiles, grid_latent_mask.tiles):
for tiledata, tiledata_mask, tiledata_latent_mask in zip(row, row_mask, row_latent_mask): for tiledata, tiledata_mask, tiledata_latent_mask in zip(row, row_mask, row_latent_mask):
x, w = tiledata[0:2]
if x >= left and x+w <= img.width - right and y >= up and y+h <= img.height - down:
continue
work.append(tiledata[2]) work.append(tiledata[2])
work_mask.append(tiledata_mask[2]) work_mask.append(tiledata_mask[2])
work_latent_mask.append(tiledata_latent_mask[2]) work_latent_mask.append(tiledata_latent_mask[2])
@@ -115,13 +128,18 @@ class Script(scripts.Script):
image_index = 0 image_index = 0
for y, h, row in grid.tiles: for y, h, row in grid.tiles:
for tiledata in row: for tiledata in row:
x, w = tiledata[0:2]
if x >= left and x+w <= img.width - right and y >= up and y+h <= img.height - down:
continue
tiledata[2] = work_results[image_index] if image_index < len(work_results) else Image.new("RGB", (p.width, p.height)) tiledata[2] = work_results[image_index] if image_index < len(work_results) else Image.new("RGB", (p.width, p.height))
image_index += 1 image_index += 1
combined_image = images.combine_grid(grid) combined_image = images.combine_grid(grid)
if opts.samples_save: if opts.samples_save:
images.save_image(combined_image, p.outpath_samples, "", initial_seed, p.prompt, opts.grid_format, info=initial_info) images.save_image(combined_image, p.outpath_samples, "", initial_seed, p.prompt, opts.grid_format, info=initial_info, p=p)
processed = Processed(p, [combined_image], initial_seed, initial_info) processed = Processed(p, [combined_image], initial_seed, initial_info)
+3 -3
View File
@@ -50,7 +50,7 @@ class Script(scripts.Script):
return [put_at_start] return [put_at_start]
def run(self, p, put_at_start): def run(self, p, put_at_start):
seed = modules.processing.set_seed(p.seed) modules.processing.fix_seed(p)
original_prompt = p.prompt[0] if type(p.prompt) == list else p.prompt original_prompt = p.prompt[0] if type(p.prompt) == list else p.prompt
@@ -73,8 +73,8 @@ class Script(scripts.Script):
print(f"Prompt matrix will create {len(all_prompts)} images using a total of {p.n_iter} batches.") print(f"Prompt matrix will create {len(all_prompts)} images using a total of {p.n_iter} batches.")
p.prompt = all_prompts p.prompt = all_prompts
p.seed = [p.seed for _ in all_prompts]
p.prompt_for_display = original_prompt p.prompt_for_display = original_prompt
p.seed = len(all_prompts) * [seed]
processed = process_images(p) processed = process_images(p)
grid = images.image_grid(processed.images, p.batch_size, rows=1 << ((len(prompt_matrix_parts) - 1) // 2)) grid = images.image_grid(processed.images, p.batch_size, rows=1 << ((len(prompt_matrix_parts) - 1) // 2))
@@ -82,6 +82,6 @@ class Script(scripts.Script):
processed.images.insert(0, grid) processed.images.insert(0, grid)
if opts.grid_save: if opts.grid_save:
images.save_image(processed.images[0], p.outpath_grids, "prompt_matrix", prompt=original_prompt, seed=seed) images.save_image(processed.images[0], p.outpath_grids, "prompt_matrix", prompt=original_prompt, seed=processed.seed, grid=True, p=p)
return processed return processed
+55
View File
@@ -0,0 +1,55 @@
import math
import os
import sys
import traceback
import modules.scripts as scripts
import gradio as gr
from modules.processing import Processed, process_images
from PIL import Image
from modules.shared import opts, cmd_opts, state
class Script(scripts.Script):
def title(self):
return "Prompts from file or textbox"
def ui(self, is_img2img):
# This checkbox would look nicer as two tabs, but there are two problems:
# 1) There is a bug in Gradio 3.3 that prevents visibility from working on Tabs
# 2) Even with Gradio 3.3.1, returning a control (like Tabs) that can't be used as input
# causes a AttributeError: 'Tabs' object has no attribute 'preprocess' assert,
# due to the way Script assumes all controls returned can be used as inputs.
# Therefore, there's no good way to use grouping components right now,
# so we will use a checkbox! :)
checkbox_txt = gr.Checkbox(label="Show Textbox", value=False)
file = gr.File(label="File with inputs", type='bytes')
prompt_txt = gr.TextArea(label="Prompts")
checkbox_txt.change(fn=lambda x: [gr.File.update(visible = not x), gr.TextArea.update(visible = x)], inputs=[checkbox_txt], outputs=[file, prompt_txt])
return [checkbox_txt, file, prompt_txt]
def run(self, p, checkbox_txt, data: bytes, prompt_txt: str):
if (checkbox_txt):
lines = [x.strip() for x in prompt_txt.splitlines()]
else:
lines = [x.strip() for x in data.decode('utf8', errors='ignore').split("\n")]
lines = [x for x in lines if len(x) > 0]
img_count = len(lines) * p.n_iter
batch_count = math.ceil(img_count / p.batch_size)
loop_count = math.ceil(batch_count / p.n_iter)
print(f"Will process {img_count} images in {batch_count} batches.")
p.do_not_save_grid = True
state.job_count = batch_count
images = []
for loop_no in range(loop_count):
state.job = f"{loop_no + 1} out of {loop_count}"
p.prompt = lines[loop_no*p.batch_size:(loop_no+1)*p.batch_size] * p.n_iter
proc = process_images(p)
images += proc.images
return Processed(p, images, p.seed, "")
+97
View File
@@ -0,0 +1,97 @@
import math
import modules.scripts as scripts
import gradio as gr
from PIL import Image
from modules import processing, shared, sd_samplers, images, devices
from modules.processing import Processed
from modules.shared import opts, cmd_opts, state
class Script(scripts.Script):
def title(self):
return "SD upscale"
def show(self, is_img2img):
return is_img2img
def ui(self, is_img2img):
info = gr.HTML("<p style=\"margin-bottom:0.75em\">Will upscale the image to twice the dimensions; use width and height sliders to set tile size</p>")
overlap = gr.Slider(minimum=0, maximum=256, step=16, label='Tile overlap', value=64, visible=False)
upscaler_index = gr.Radio(label='Upscaler', choices=[x.name for x in shared.sd_upscalers], value=shared.sd_upscalers[0].name, type="index", visible=False)
return [info, overlap, upscaler_index]
def run(self, p, _, overlap, upscaler_index):
processing.fix_seed(p)
upscaler = shared.sd_upscalers[upscaler_index]
p.extra_generation_params["SD upscale overlap"] = overlap
p.extra_generation_params["SD upscale upscaler"] = upscaler.name
initial_info = None
seed = p.seed
init_img = p.init_images[0]
if(upscaler.name != "None"):
img = upscaler.scaler.upscale(init_img, 2, upscaler.data_path)
else:
img = init_img
devices.torch_gc()
grid = images.split_grid(img, tile_w=p.width, tile_h=p.height, overlap=overlap)
batch_size = p.batch_size
upscale_count = p.n_iter
p.n_iter = 1
p.do_not_save_grid = True
p.do_not_save_samples = True
work = []
for y, h, row in grid.tiles:
for tiledata in row:
work.append(tiledata[2])
batch_count = math.ceil(len(work) / batch_size)
state.job_count = batch_count * upscale_count
print(f"SD upscaling will process a total of {len(work)} images tiled as {len(grid.tiles[0][2])}x{len(grid.tiles)} per upscale in a total of {state.job_count} batches.")
result_images = []
for n in range(upscale_count):
start_seed = seed + n
p.seed = start_seed
work_results = []
for i in range(batch_count):
p.batch_size = batch_size
p.init_images = work[i*batch_size:(i+1)*batch_size]
state.job = f"Batch {i + 1 + n * batch_count} out of {state.job_count}"
processed = processing.process_images(p)
if initial_info is None:
initial_info = processed.info
p.seed = processed.seed + 1
work_results += processed.images
image_index = 0
for y, h, row in grid.tiles:
for tiledata in row:
tiledata[2] = work_results[image_index] if image_index < len(work_results) else Image.new("RGB", (p.width, p.height))
image_index += 1
combined_image = images.combine_grid(grid)
result_images.append(combined_image)
if opts.samples_save:
images.save_image(combined_image, p.outpath_samples, "", start_seed, p.prompt, opts.samples_format, info=initial_info, p=p)
processed = Processed(p, result_images, seed, initial_info)
return processed
+155 -15
View File
@@ -1,14 +1,20 @@
from collections import namedtuple from collections import namedtuple
from copy import copy from copy import copy
from itertools import permutations
import random import random
from PIL import Image
import numpy as np
import modules.scripts as scripts import modules.scripts as scripts
import gradio as gr import gradio as gr
from modules import images from modules import images
from modules.processing import process_images, Processed from modules.processing import process_images, Processed
from modules.shared import opts, cmd_opts, state from modules.shared import opts, cmd_opts, state
import modules.shared as shared
import modules.sd_samplers import modules.sd_samplers
import modules.sd_models
import re import re
@@ -21,6 +27,32 @@ def apply_field(field):
def apply_prompt(p, x, xs): def apply_prompt(p, x, xs):
p.prompt = p.prompt.replace(xs[0], x) p.prompt = p.prompt.replace(xs[0], x)
p.negative_prompt = p.negative_prompt.replace(xs[0], x)
def apply_order(p, x, xs):
token_order = []
# Initally grab the tokens from the prompt, so they can be replaced in order of earliest seen
for token in x:
token_order.append((p.prompt.find(token), token))
token_order.sort(key=lambda t: t[0])
prompt_parts = []
# Split the prompt up, taking out the tokens
for _, token in token_order:
n = p.prompt.find(token)
prompt_parts.append(p.prompt[0:n])
p.prompt = p.prompt[n + len(token):]
# Rebuild the prompt with the tokens in the order we want
prompt_tmp = ""
for idx, part in enumerate(prompt_parts):
prompt_tmp += part
prompt_tmp += x[idx]
p.prompt = prompt_tmp + p.prompt
samplers_dict = {} samplers_dict = {}
@@ -38,11 +70,39 @@ def apply_sampler(p, x, xs):
p.sampler_index = sampler_index p.sampler_index = sampler_index
def apply_checkpoint(p, x, xs):
info = modules.sd_models.get_closet_checkpoint_match(x)
assert info is not None, f'Checkpoint for {x} not found'
modules.sd_models.reload_model_weights(shared.sd_model, info)
def format_value_add_label(p, opt, x): def format_value_add_label(p, opt, x):
if type(x) == float:
x = round(x, 8)
return f"{opt.label}: {x}" return f"{opt.label}: {x}"
def format_value(p, opt, x): def format_value(p, opt, x):
if type(x) == float:
x = round(x, 8)
return x
def format_value_join_list(p, opt, x):
return ", ".join(x)
def do_nothing(p, x, xs):
pass
def format_nothing(p, opt, x):
return ""
def str_permutations(x):
"""dummy function for specifying it in AxisOption's type when you want to get a list of permutations"""
return x return x
@@ -51,24 +111,34 @@ AxisOptionImg2Img = namedtuple("AxisOptionImg2Img", ["label", "type", "apply", "
axis_options = [ axis_options = [
AxisOption("Nothing", str, do_nothing, format_nothing),
AxisOption("Seed", int, apply_field("seed"), format_value_add_label), AxisOption("Seed", int, apply_field("seed"), format_value_add_label),
AxisOption("Var. seed", int, apply_field("subseed"), format_value_add_label),
AxisOption("Var. strength", float, apply_field("subseed_strength"), format_value_add_label),
AxisOption("Steps", int, apply_field("steps"), format_value_add_label), AxisOption("Steps", int, apply_field("steps"), format_value_add_label),
AxisOption("CFG Scale", float, apply_field("cfg_scale"), format_value_add_label), AxisOption("CFG Scale", float, apply_field("cfg_scale"), format_value_add_label),
AxisOption("Prompt S/R", str, apply_prompt, format_value), AxisOption("Prompt S/R", str, apply_prompt, format_value),
AxisOption("Prompt order", str_permutations, apply_order, format_value_join_list),
AxisOption("Sampler", str, apply_sampler, format_value), AxisOption("Sampler", str, apply_sampler, format_value),
AxisOptionImg2Img("Denoising", float, apply_field("denoising_strength"), format_value_add_label) # as it is now all AxisOptionImg2Img items must go after AxisOption ones AxisOption("Checkpoint name", str, apply_checkpoint, format_value),
AxisOption("Sigma Churn", float, apply_field("s_churn"), format_value_add_label),
AxisOption("Sigma min", float, apply_field("s_tmin"), format_value_add_label),
AxisOption("Sigma max", float, apply_field("s_tmax"), format_value_add_label),
AxisOption("Sigma noise", float, apply_field("s_noise"), format_value_add_label),
AxisOption("Eta", float, apply_field("eta"), format_value_add_label),
AxisOptionImg2Img("Denoising", float, apply_field("denoising_strength"), format_value_add_label), # as it is now all AxisOptionImg2Img items must go after AxisOption ones
] ]
def draw_xy_grid(xs, ys, x_label, y_label, cell): def draw_xy_grid(p, xs, ys, x_labels, y_labels, cell, draw_legend):
res = [] res = []
ver_texts = [[images.GridAnnotation(y_label(y))] for y in ys] ver_texts = [[images.GridAnnotation(y)] for y in y_labels]
hor_texts = [[images.GridAnnotation(x_label(x))] for x in xs] hor_texts = [[images.GridAnnotation(x)] for x in x_labels]
first_pocessed = None first_pocessed = None
state.job_count = len(xs) * len(ys) state.job_count = len(xs) * len(ys) * p.n_iter
for iy, y in enumerate(ys): for iy, y in enumerate(ys):
for ix, x in enumerate(xs): for ix, x in enumerate(xs):
@@ -78,9 +148,13 @@ def draw_xy_grid(xs, ys, x_label, y_label, cell):
if first_pocessed is None: if first_pocessed is None:
first_pocessed = processed first_pocessed = processed
try:
res.append(processed.images[0]) res.append(processed.images[0])
except:
res.append(Image.new(res[0].mode, res[0].size))
grid = images.image_grid(res, rows=len(ys)) grid = images.image_grid(res, rows=len(ys))
if draw_legend:
grid = images.draw_grid_annotations(grid, res[0].width, res[0].height, hor_texts, ver_texts) grid = images.draw_grid_annotations(grid, res[0].width, res[0].height, hor_texts, ver_texts)
first_pocessed.images = [grid] first_pocessed.images = [grid]
@@ -89,6 +163,11 @@ def draw_xy_grid(xs, ys, x_label, y_label, cell):
re_range = re.compile(r"\s*([+-]?\s*\d+)\s*-\s*([+-]?\s*\d+)(?:\s*\(([+-]\d+)\s*\))?\s*") re_range = re.compile(r"\s*([+-]?\s*\d+)\s*-\s*([+-]?\s*\d+)(?:\s*\(([+-]\d+)\s*\))?\s*")
re_range_float = re.compile(r"\s*([+-]?\s*\d+(?:.\d*)?)\s*-\s*([+-]?\s*\d+(?:.\d*)?)(?:\s*\(([+-]\d+(?:.\d*)?)\s*\))?\s*")
re_range_count = re.compile(r"\s*([+-]?\s*\d+)\s*-\s*([+-]?\s*\d+)(?:\s*\[(\d+)\s*\])?\s*")
re_range_count_float = re.compile(r"\s*([+-]?\s*\d+(?:.\d*)?)\s*-\s*([+-]?\s*\d+(?:.\d*)?)(?:\s*\[(\d+(?:.\d*)?)\s*\])?\s*")
class Script(scripts.Script): class Script(scripts.Script):
def title(self): def title(self):
@@ -98,21 +177,26 @@ class Script(scripts.Script):
current_axis_options = [x for x in axis_options if type(x) == AxisOption or type(x) == AxisOptionImg2Img and is_img2img] current_axis_options = [x for x in axis_options if type(x) == AxisOption or type(x) == AxisOptionImg2Img and is_img2img]
with gr.Row(): with gr.Row():
x_type = gr.Dropdown(label="X type", choices=[x.label for x in current_axis_options], value=current_axis_options[0].label, visible=False, type="index", elem_id="x_type") x_type = gr.Dropdown(label="X type", choices=[x.label for x in current_axis_options], value=current_axis_options[1].label, visible=False, type="index", elem_id="x_type")
x_values = gr.Textbox(label="X values", visible=False, lines=1) x_values = gr.Textbox(label="X values", visible=False, lines=1)
with gr.Row(): with gr.Row():
y_type = gr.Dropdown(label="Y type", choices=[x.label for x in current_axis_options], value=current_axis_options[1].label, visible=False, type="index", elem_id="y_type") y_type = gr.Dropdown(label="Y type", choices=[x.label for x in current_axis_options], value=current_axis_options[4].label, visible=False, type="index", elem_id="y_type")
y_values = gr.Textbox(label="Y values", visible=False, lines=1) y_values = gr.Textbox(label="Y values", visible=False, lines=1)
return [x_type, x_values, y_type, y_values] draw_legend = gr.Checkbox(label='Draw legend', value=True)
no_fixed_seeds = gr.Checkbox(label='Keep -1 for seeds', value=False)
def run(self, p, x_type, x_values, y_type, y_values): return [x_type, x_values, y_type, y_values, draw_legend, no_fixed_seeds]
p.seed = modules.processing.set_seed(p.seed)
def run(self, p, x_type, x_values, y_type, y_values, draw_legend, no_fixed_seeds):
modules.processing.fix_seed(p)
p.batch_size = 1 p.batch_size = 1
p.batch_count = 1
def process_axis(opt, vals): def process_axis(opt, vals):
if opt.label == 'Nothing':
return [0]
valslist = [x.strip() for x in vals.split(",")] valslist = [x.strip() for x in vals.split(",")]
if opt.type == int: if opt.type == int:
@@ -120,6 +204,7 @@ class Script(scripts.Script):
for val in valslist: for val in valslist:
m = re_range.fullmatch(val) m = re_range.fullmatch(val)
mc = re_range_count.fullmatch(val)
if m is not None: if m is not None:
start = int(m.group(1)) start = int(m.group(1))
@@ -127,10 +212,40 @@ class Script(scripts.Script):
step = int(m.group(3)) if m.group(3) is not None else 1 step = int(m.group(3)) if m.group(3) is not None else 1
valslist_ext += list(range(start, end, step)) valslist_ext += list(range(start, end, step))
elif mc is not None:
start = int(mc.group(1))
end = int(mc.group(2))
num = int(mc.group(3)) if mc.group(3) is not None else 1
valslist_ext += [int(x) for x in np.linspace(start=start, stop=end, num=num).tolist()]
else: else:
valslist_ext.append(val) valslist_ext.append(val)
valslist = valslist_ext valslist = valslist_ext
elif opt.type == float:
valslist_ext = []
for val in valslist:
m = re_range_float.fullmatch(val)
mc = re_range_count_float.fullmatch(val)
if m is not None:
start = float(m.group(1))
end = float(m.group(2))
step = float(m.group(3)) if m.group(3) is not None else 1
valslist_ext += np.arange(start, end + step, step).tolist()
elif mc is not None:
start = float(mc.group(1))
end = float(mc.group(2))
num = int(mc.group(3)) if mc.group(3) is not None else 1
valslist_ext += np.linspace(start=start, stop=end, num=num).tolist()
else:
valslist_ext.append(val)
valslist = valslist_ext
elif opt.type == str_permutations:
valslist = list(permutations(valslist))
valslist = [opt.type(x) for x in valslist] valslist = [opt.type(x) for x in valslist]
@@ -142,6 +257,26 @@ class Script(scripts.Script):
y_opt = axis_options[y_type] y_opt = axis_options[y_type]
ys = process_axis(y_opt, y_values) ys = process_axis(y_opt, y_values)
def fix_axis_seeds(axis_opt, axis_list):
if axis_opt.label == 'Seed':
return [int(random.randrange(4294967294)) if val is None or val == '' or val == -1 else val for val in axis_list]
else:
return axis_list
if not no_fixed_seeds:
xs = fix_axis_seeds(x_opt, xs)
ys = fix_axis_seeds(y_opt, ys)
if x_opt.label == 'Steps':
total_steps = sum(xs) * len(ys)
elif y_opt.label == 'Steps':
total_steps = sum(ys) * len(xs)
else:
total_steps = p.steps * len(xs) * len(ys)
print(f"X/Y plot will create {len(xs) * len(ys) * p.n_iter} images on a {len(xs)}x{len(ys)} grid. (Total steps to process: {total_steps * p.n_iter})")
shared.total_tqdm.updateTotal(total_steps * p.n_iter)
def cell(x, y): def cell(x, y):
pc = copy(p) pc = copy(p)
x_opt.apply(pc, x, xs) x_opt.apply(pc, x, xs)
@@ -150,14 +285,19 @@ class Script(scripts.Script):
return process_images(pc) return process_images(pc)
processed = draw_xy_grid( processed = draw_xy_grid(
p,
xs=xs, xs=xs,
ys=ys, ys=ys,
x_label=lambda x: x_opt.format_value(p, x_opt, x), x_labels=[x_opt.format_value(p, x_opt, x) for x in xs],
y_label=lambda y: y_opt.format_value(p, y_opt, y), y_labels=[y_opt.format_value(p, y_opt, y) for y in ys],
cell=cell cell=cell,
draw_legend=draw_legend
) )
if opts.grid_save: if opts.grid_save:
images.save_image(processed.images[0], p.outpath_grids, "xy_grid", prompt=p.prompt, seed=processed.seed) images.save_image(processed.images[0], p.outpath_grids, "xy_grid", prompt=p.prompt, seed=processed.seed, grid=True, p=p)
# restore checkpoint in case it was changed by axes
modules.sd_models.reload_model_weights(shared.sd_model)
return processed return processed
+309 -13
View File
@@ -1,23 +1,149 @@
.output-html p {margin: 0 0.5em;} .output-html p {margin: 0 0.5em;}
.performance { font-size: 0.85em; color: #444; }
#txt2img_generate, #img2img_generate{ .row > *,
max-width: 13em; .row > .gr-form > * {
min-width: min(120px, 100%);
flex: 1 1 0%;
} }
#txt2img_roll{ .performance {
min-width: 1em; font-size: 0.85em;
max-width: 4em; color: #444;
display: flex;
justify-content: space-between;
white-space: nowrap;
}
.performance .time {
margin-right: 0;
}
.performance .vram {
margin-left: 0;
text-align: right;
}
#txt2img_generate, #img2img_generate {
min-height: 4.5em;
}
@media screen and (min-width: 2500px) {
#txt2img_gallery, #img2img_gallery {
min-height: 768px;
}
}
#txt2img_gallery img, #img2img_gallery img{
object-fit: scale-down;
}
.justify-center.overflow-x-scroll {
justify-content: left;
}
.justify-center.overflow-x-scroll button:first-of-type {
margin-left: auto;
}
.justify-center.overflow-x-scroll button:last-of-type {
margin-right: auto;
}
#random_seed, #random_subseed, #reuse_seed, #reuse_subseed, #open_folder{
min-width: auto;
flex-grow: 0;
padding-left: 0.25em;
padding-right: 0.25em;
}
#hidden_element{
display: none;
}
#seed_row, #subseed_row{
gap: 0.5rem;
}
#subseed_show_box{
min-width: auto;
flex-grow: 0;
}
#subseed_show_box > div{
border: 0;
height: 100%;
}
#subseed_show{
min-width: auto;
flex-grow: 0;
padding: 0;
}
#subseed_show label{
height: 100%;
}
#roll_col{
min-width: unset !important;
flex-grow: 0 !important;
padding: 0.4em 0;
}
#roll, #paste{
min-width: 2em;
min-height: 2em;
max-width: 2em;
max-height: 2em;
flex-grow: 0;
padding-left: 0.25em;
padding-right: 0.25em;
margin: 0.1em 0;
}
#style_apply, #style_create, #interrogate{
margin: 0.75em 0.25em 0.25em 0.25em;
min-width: 3em;
}
#style_pos_col, #style_neg_col{
min-width: 8em !important;
}
#txt2img_style_index, #txt2img_style2_index, #img2img_style_index, #img2img_style2_index{
margin-top: 1em;
}
.gr-form{
background: transparent;
}
.my-4{
margin-top: 0;
margin-bottom: 0;
}
#toprow div{
border: none;
gap: 0;
background: transparent;
}
#resize_mode{
flex: 1.5;
} }
button{ button{
align-self: stretch !important; align-self: stretch !important;
} }
#img2img_prompt, #txt2img_prompt{ #prompt, #negative_prompt{
padding: 0;
border: none !important; border: none !important;
} }
#prompt textarea, #negative_prompt textarea{
border: none !important;
}
#img2maskimg .h-60{ #img2maskimg .h-60{
height: 30rem; height: 30rem;
@@ -31,17 +157,33 @@ button{
max-width: 10em; max-width: 10em;
} }
#txt2img_preview, #img2img_preview{ #txt2img_preview, #img2img_preview, #ti_preview{
position: absolute; position: absolute;
width: 320px; width: 320px;
left: 0; left: 0;
right: 0; right: 0;
margin-left: auto; margin-left: auto;
margin-right: auto; margin-right: auto;
margin-top: 34px;
z-index: 100; z-index: 100;
border: none;
border-top-left-radius: 0;
border-top-right-radius: 0;
} }
#txt2img_preview div.left-0.top-0, #img2img_preview div.left-0.top-0{ @media screen and (min-width: 768px) {
#txt2img_preview, #img2img_preview, #ti_preview {
position: absolute;
}
}
@media screen and (max-width: 767px) {
#txt2img_preview, #img2img_preview, #ti_preview {
position: relative;
}
}
#txt2img_preview div.left-0.top-0, #img2img_preview div.left-0.top-0, #ti_preview div.left-0.top-0{
display: none; display: none;
} }
@@ -65,6 +207,10 @@ fieldset span.text-gray-500, .gr-block.gr-box span.text-gray-500, label.block s
border-right: 1px solid rgb(55 65 81); border-right: 1px solid rgb(55 65 81);
} }
#settings fieldset span.text-gray-500, #settings .gr-block.gr-box span.text-gray-500, #settings label.block span{
position: relative;
border: none;
}
.gr-panel div.flex-col div.justify-between label span{ .gr-panel div.flex-col div.justify-between label span{
margin: 0; margin: 0;
@@ -77,6 +223,11 @@ fieldset span.text-gray-500, .gr-block.gr-box span.text-gray-500, label.block s
padding: 0 0.5em; padding: 0 0.5em;
} }
#settings .gr-panel div.flex-col div.justify-between div{
position: relative;
z-index: 200;
}
input[type="range"]{ input[type="range"]{
margin: 0.5em 0 -0.3em 0; margin: 0.5em 0 -0.3em 0;
} }
@@ -86,11 +237,33 @@ input[type="range"]{
padding-right: 0.6em; padding-right: 0.6em;
} }
#mask_bug_info {
text-align: center;
display: block;
margin-top: -0.75em;
margin-bottom: -0.75em;
}
#txt2img_negative_prompt, #img2img_negative_prompt{
}
#txt2img_progressbar, #img2img_progressbar, #ti_progressbar{
position: absolute;
z-index: 1000;
right: 0;
padding-left: 5px;
padding-right: 5px;
display: block;
}
#txt2img_progress_row, #img2img_progress_row{
margin-bottom: 10px;
margin-top: -18px;
}
.progressDiv{ .progressDiv{
width: 100%; width: 100%;
height: 30px; height: 20px;
background: #b4c0cc; background: #b4c0cc;
border-radius: 8px; border-radius: 8px;
} }
@@ -101,13 +274,136 @@ input[type="range"]{
.progressDiv .progress{ .progressDiv .progress{
width: 0%; width: 0%;
height: 30px; height: 20px;
background: #0060df; background: #0060df;
color: white; color: white;
font-weight: bold; font-weight: bold;
line-height: 30px; line-height: 20px;
padding: 0 8px 0 0; padding: 0 8px 0 0;
text-align: right; text-align: right;
border-radius: 8px; border-radius: 8px;
} }
#lightboxModal{
display: none;
position: fixed;
z-index: 1001;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(20, 20, 20, 0.95);
}
.modalControls {
display: grid;
grid-template-columns: 32px auto 1fr 32px;
grid-template-areas: "zoom tile space close";
position: absolute;
top: 0;
left: 0;
right: 0;
padding: 16px;
gap: 16px;
background-color: rgba(0,0,0,0.2);
}
.modalClose {
grid-area: close;
}
.modalZoom {
grid-area: zoom;
}
.modalTileImage {
grid-area: tile;
}
.modalClose,
.modalZoom,
.modalTileImage {
color: white;
font-size: 35px;
font-weight: bold;
cursor: pointer;
}
.modalClose:hover,
.modalClose:focus,
.modalZoom:hover,
.modalZoom:focus {
color: #999;
text-decoration: none;
cursor: pointer;
}
#modalImage {
display: block;
margin-left: auto;
margin-right: auto;
margin-top: auto;
width: auto;
}
.modalImageFullscreen {
object-fit: contain;
height: 90%;
}
.modalPrev,
.modalNext {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
padding: 16px;
margin-top: -50px;
color: white;
font-weight: bold;
font-size: 20px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
user-select: none;
-webkit-user-select: none;
}
.modalNext {
right: 0;
border-radius: 3px 0 0 3px;
}
.modalPrev:hover,
.modalNext:hover {
background-color: rgba(0, 0, 0, 0.8);
}
#imageARPreview{
position:absolute;
top:0px;
left:0px;
border:2px solid red;
background:rgba(255, 0, 0, 0.3);
z-index: 900;
pointer-events:none;
display:none
}
#txt2img_interrupt, #img2img_interrupt{
position: absolute;
width: 100%;
height: 72px;
background: #b4c0cc;
border-radius: 8px;
display: none;
}
.red {
color: red;
}
#img2img_image div.h-60{
height: 480px;
}
+19
View File
@@ -0,0 +1,19 @@
a painting, art by [name]
a rendering, art by [name]
a cropped painting, art by [name]
the painting, art by [name]
a clean painting, art by [name]
a dirty painting, art by [name]
a dark painting, art by [name]
a picture, art by [name]
a cool painting, art by [name]
a close-up painting, art by [name]
a bright painting, art by [name]
a cropped painting, art by [name]
a good painting, art by [name]
a close-up painting, art by [name]
a rendition, art by [name]
a nice painting, art by [name]
a small painting, art by [name]
a weird painting, art by [name]
a large painting, art by [name]
@@ -0,0 +1,19 @@
a painting of [filewords], art by [name]
a rendering of [filewords], art by [name]
a cropped painting of [filewords], art by [name]
the painting of [filewords], art by [name]
a clean painting of [filewords], art by [name]
a dirty painting of [filewords], art by [name]
a dark painting of [filewords], art by [name]
a picture of [filewords], art by [name]
a cool painting of [filewords], art by [name]
a close-up painting of [filewords], art by [name]
a bright painting of [filewords], art by [name]
a cropped painting of [filewords], art by [name]
a good painting of [filewords], art by [name]
a close-up painting of [filewords], art by [name]
a rendition of [filewords], art by [name]
a nice painting of [filewords], art by [name]
a small painting of [filewords], art by [name]
a weird painting of [filewords], art by [name]
a large painting of [filewords], art by [name]
+27
View File
@@ -0,0 +1,27 @@
a photo of a [name]
a rendering of a [name]
a cropped photo of the [name]
the photo of a [name]
a photo of a clean [name]
a photo of a dirty [name]
a dark photo of the [name]
a photo of my [name]
a photo of the cool [name]
a close-up photo of a [name]
a bright photo of the [name]
a cropped photo of a [name]
a photo of the [name]
a good photo of the [name]
a photo of one [name]
a close-up photo of the [name]
a rendition of the [name]
a photo of the clean [name]
a rendition of a [name]
a photo of a nice [name]
a good photo of a [name]
a photo of the nice [name]
a photo of the small [name]
a photo of the weird [name]
a photo of the large [name]
a photo of a cool [name]
a photo of a small [name]
@@ -0,0 +1,27 @@
a photo of a [name], [filewords]
a rendering of a [name], [filewords]
a cropped photo of the [name], [filewords]
the photo of a [name], [filewords]
a photo of a clean [name], [filewords]
a photo of a dirty [name], [filewords]
a dark photo of the [name], [filewords]
a photo of my [name], [filewords]
a photo of the cool [name], [filewords]
a close-up photo of a [name], [filewords]
a bright photo of the [name], [filewords]
a cropped photo of a [name], [filewords]
a photo of the [name], [filewords]
a good photo of the [name], [filewords]
a photo of one [name], [filewords]
a close-up photo of the [name], [filewords]
a rendition of the [name], [filewords]
a photo of the clean [name], [filewords]
a rendition of a [name], [filewords]
a photo of a nice [name], [filewords]
a good photo of a [name], [filewords]
a photo of the nice [name], [filewords]
a photo of the small [name], [filewords]
a photo of the weird [name], [filewords]
a photo of the large [name], [filewords]
a photo of a cool [name], [filewords]
a photo of a small [name], [filewords]
Binary file not shown.

After

Width:  |  Height:  |  Size: 526 KiB

+8
View File
@@ -0,0 +1,8 @@
@echo off
set PYTHON=
set GIT=
set VENV_DIR=
set COMMANDLINE_ARGS=
call webui.bat
+43
View File
@@ -0,0 +1,43 @@
#!/bin/bash
#########################################################
# Uncomment and change the variables below to your need:#
#########################################################
# Install directory without trailing slash
#install_dir="/home/$(whoami)"
# Name of the subdirectory
#clone_dir="stable-diffusion-webui"
# Commandline arguments for webui.py, for example: export COMMANDLINE_ARGS="--medvram --opt-split-attention"
export COMMANDLINE_ARGS=""
# python3 executable
#python_cmd="python3"
# git executable
#export GIT="git"
# python3 venv without trailing slash (defaults to ${install_dir}/${clone_dir}/venv)
#venv_dir="venv"
# script to launch to start the app
#export LAUNCH_SCRIPT="launch.py"
# install command for torch
#export TORCH_COMMAND="pip install torch==1.12.1+cu113 --extra-index-url https://download.pytorch.org/whl/cu113"
# Requirements file to use for stable-diffusion-webui
#export REQS_FILE="requirements_versions.txt"
# Fixed git repos
#export K_DIFFUSION_PACKAGE=""
#export GFPGAN_PACKAGE=""
# Fixed git commits
#export STABLE_DIFFUSION_COMMIT_HASH=""
#export TAMING_TRANSFORMERS_COMMIT_HASH=""
#export CODEFORMER_COMMIT_HASH=""
#export BLIP_COMMIT_HASH=""
###########################################
+10 -119
View File
@@ -1,28 +1,19 @@
@echo off @echo off
set PYTHON=python if not defined PYTHON (set PYTHON=python)
set GIT=git if not defined VENV_DIR (set VENV_DIR=venv)
set COMMANDLINE_ARGS=
set VENV_DIR=venv set ERROR_REPORTING=FALSE
mkdir tmp 2>NUL mkdir tmp 2>NUL
set TORCH_COMMAND=pip install torch==1.12.1+cu113 --extra-index-url https://download.pytorch.org/whl/cu113
set REQS_FILE=requirements_versions.txt
%PYTHON% -c "" >tmp/stdout.txt 2>tmp/stderr.txt %PYTHON% -c "" >tmp/stdout.txt 2>tmp/stderr.txt
if %ERRORLEVEL% == 0 goto :check_git if %ERRORLEVEL% == 0 goto :start_venv
echo Couldn't launch python echo Couldn't launch python
goto :show_stdout_stderr goto :show_stdout_stderr
:check_git :start_venv
%GIT% --help >tmp/stdout.txt 2>tmp/stderr.txt if [%VENV_DIR%] == [-] goto :skip_venv
if %ERRORLEVEL% == 0 goto :setup_venv
echo Couldn't launch git
goto :show_stdout_stderr
:setup_venv
if [%VENV_DIR%] == [] goto :skip_venv
dir %VENV_DIR%\Scripts\Python.exe >tmp/stdout.txt 2>tmp/stderr.txt dir %VENV_DIR%\Scripts\Python.exe >tmp/stdout.txt 2>tmp/stderr.txt
if %ERRORLEVEL% == 0 goto :activate_venv if %ERRORLEVEL% == 0 goto :activate_venv
@@ -35,114 +26,14 @@ echo Unable to create venv in directory %VENV_DIR%
goto :show_stdout_stderr goto :show_stdout_stderr
:activate_venv :activate_venv
set PYTHON=%~dp0%VENV_DIR%\Scripts\Python.exe set PYTHON="%~dp0%VENV_DIR%\Scripts\Python.exe"
%PYTHON% --version
echo venv %PYTHON% echo venv %PYTHON%
goto :install_torch goto :launch
:skip_venv :skip_venv
%PYTHON% --version
:install_torch
%PYTHON% -c "import torch" >tmp/stdout.txt 2>tmp/stderr.txt
if %ERRORLEVEL% == 0 goto :check_gpu
echo Installing torch...
%PYTHON% -m %TORCH_COMMAND% >tmp/stdout.txt 2>tmp/stderr.txt
if %ERRORLEVEL% == 0 goto :check_gpu
echo Failed to install torch
goto :show_stdout_stderr
:check_gpu
%PYTHON% -c "import torch; assert torch.cuda.is_available(), 'CUDA is not available'" >tmp/stdout.txt 2>tmp/stderr.txt
if %ERRORLEVEL% == 0 goto :install_sd_reqs
echo Torch is not able to use GPU
goto :show_stdout_stderr
:install_sd_reqs
%PYTHON% -c "import transformers; import wheel" >tmp/stdout.txt 2>tmp/stderr.txt
if %ERRORLEVEL% == 0 goto :install_k_diff
echo Installing SD requirements...
%PYTHON% -m pip install wheel transformers==4.19.2 diffusers invisible-watermark --prefer-binary >tmp/stdout.txt 2>tmp/stderr.txt
if %ERRORLEVEL% == 0 goto :install_k_diff
goto :show_stdout_stderr
:install_k_diff
%PYTHON% -c "import k_diffusion.sampling" >tmp/stdout.txt 2>tmp/stderr.txt
if %ERRORLEVEL% == 0 goto :install_GFPGAN
echo Installing K-Diffusion...
%PYTHON% -m pip install git+https://github.com/crowsonkb/k-diffusion.git --prefer-binary --only-binary=psutil >tmp/stdout.txt 2>tmp/stderr.txt
if %ERRORLEVEL% == 0 goto :install_GFPGAN
goto :show_stdout_stderr
:install_GFPGAN
%PYTHON% -c "import gfpgan" >tmp/stdout.txt 2>tmp/stderr.txt
if %ERRORLEVEL% == 0 goto :install_reqs
echo Installing GFPGAN
%PYTHON% -m pip install git+https://github.com/TencentARC/GFPGAN.git --prefer-binary >tmp/stdout.txt 2>tmp/stderr.txt
if %ERRORLEVEL% == 0 goto :install_reqs
goto :show_stdout_stderr
:install_reqs
%PYTHON% -c "import omegaconf" >tmp/stdout.txt 2>tmp/stderr.txt
if %ERRORLEVEL% == 0 goto :make_dirs
echo Installing requirements...
%PYTHON% -m pip install -r %REQS_FILE% --prefer-binary >tmp/stdout.txt 2>tmp/stderr.txt
if %ERRORLEVEL% == 0 goto :update_numpy
goto :show_stdout_stderr
:update_numpy
%PYTHON% -m pip install -U numpy --prefer-binary >tmp/stdout.txt 2>tmp/stderr.txt
:make_dirs
mkdir repositories 2>NUL
if exist repositories\stable-diffusion goto :clone_transformers
echo Cloning Stable Difusion repository...
%GIT% clone https://github.com/CompVis/stable-diffusion.git repositories\stable-diffusion >tmp/stdout.txt 2>tmp/stderr.txt
if %ERRORLEVEL% == 0 goto :clone_transformers
goto :show_stdout_stderr
:clone_transformers
if exist repositories\taming-transformers goto :clone_codeformer
echo Cloning Taming Transforming repository...
%GIT% clone https://github.com/CompVis/taming-transformers.git repositories\taming-transformers >tmp/stdout.txt 2>tmp/stderr.txt
if %ERRORLEVEL% == 0 goto :clone_codeformer
goto :show_stdout_stderr
:clone_codeformer
if exist repositories\CodeFormer goto :install_codeformer_reqs
echo Cloning CodeFormer repository...
%GIT% clone https://github.com/sczhou/CodeFormer.git repositories\CodeFormer >tmp/stdout.txt 2>tmp/stderr.txt
if %ERRORLEVEL% == 0 goto :install_codeformer_reqs
goto :show_stdout_stderr
:install_codeformer_reqs
%PYTHON% -c "import lpips" >tmp/stdout.txt 2>tmp/stderr.txt
if %ERRORLEVEL% == 0 goto :check_model
echo Installing requirements for CodeFormer...
%PYTHON% -m pip install -r repositories\CodeFormer\requirements.txt --prefer-binary >tmp/stdout.txt 2>tmp/stderr.txt
if %ERRORLEVEL% == 0 goto :check_model
goto :show_stdout_stderr
:check_model
dir model.ckpt >tmp/stdout.txt 2>tmp/stderr.txt
if %ERRORLEVEL% == 0 goto :check_gfpgan
echo Stable Diffusion model not found: you need to place model.ckpt file into same directory as this file.
goto :show_stdout_stderr
:check_gfpgan
dir GFPGANv1.3.pth >tmp/stdout.txt 2>tmp/stderr.txt
if %ERRORLEVEL% == 0 goto :launch
echo GFPGAN not found: you need to place GFPGANv1.3.pth file into same directory as this file.
echo Face fixing feature will not work.
:launch :launch
echo Launching webui.py... %PYTHON% launch.py
%PYTHON% webui.py %COMMANDLINE_ARGS%
pause pause
exit /b exit /b
+82 -152
View File
@@ -1,146 +1,65 @@
import os import os
import threading import threading
import time
import importlib
import signal
import threading
from modules.paths import script_path from modules.paths import script_path
import torch from modules import devices, sd_samplers
import numpy as np import modules.codeformer_model as codeformer
from omegaconf import OmegaConf import modules.extras
from PIL import Image
import signal
from ldm.util import instantiate_from_config
from modules.shared import opts, cmd_opts, state
import modules.shared as shared
import modules.ui
from modules.ui import plaintext_to_html
import modules.scripts
import modules.processing as processing
import modules.sd_hijack
import modules.codeformer_model
import modules.gfpgan_model
import modules.face_restoration import modules.face_restoration
import modules.realesrgan_model as realesrgan import modules.gfpgan_model as gfpgan
import modules.esrgan_model as esrgan
import modules.images as images
import modules.lowvram
import modules.txt2img
import modules.img2img import modules.img2img
import modules.lowvram
import modules.paths
import modules.scripts
import modules.sd_hijack
import modules.sd_models
import modules.shared as shared
import modules.txt2img
modules.codeformer_model.setup_codeformer() import modules.ui
modules.gfpgan_model.setup_gfpgan() from modules import devices
from modules import modelloader
from modules.paths import script_path
from modules.shared import cmd_opts
modelloader.cleanup_models()
modules.sd_models.setup_model()
codeformer.setup_model(cmd_opts.codeformer_models_path)
gfpgan.setup_model(cmd_opts.gfpgan_models_path)
shared.face_restorers.append(modules.face_restoration.FaceRestoration()) shared.face_restorers.append(modules.face_restoration.FaceRestoration())
modelloader.load_upscalers()
esrgan.load_models(cmd_opts.esrgan_models_path)
realesrgan.setup_realesrgan()
def load_model_from_config(config, ckpt, verbose=False):
print(f"Loading model from {ckpt}")
pl_sd = torch.load(ckpt, map_location="cpu")
if "global_step" in pl_sd:
print(f"Global Step: {pl_sd['global_step']}")
sd = pl_sd["state_dict"]
model = instantiate_from_config(config.model)
m, u = model.load_state_dict(sd, strict=False)
if len(m) > 0 and verbose:
print("missing keys:")
print(m)
if len(u) > 0 and verbose:
print("unexpected keys:")
print(u)
model.eval()
return model
cached_images = {}
def run_extras(image, gfpgan_visibility, codeformer_visibility, codeformer_weight, upscaling_resize, extras_upscaler_1, extras_upscaler_2, extras_upscaler_2_visibility):
processing.torch_gc()
image = image.convert("RGB")
outpath = opts.outdir_samples or opts.outdir_extras_samples
if gfpgan_visibility > 0:
restored_img = modules.gfpgan_model.gfpgan_fix_faces(np.array(image, dtype=np.uint8))
res = Image.fromarray(restored_img)
if gfpgan_visibility < 1.0:
res = Image.blend(image, res, gfpgan_visibility)
image = res
if codeformer_visibility > 0:
restored_img = modules.codeformer_model.codeformer.restore(np.array(image, dtype=np.uint8), w=codeformer_weight)
res = Image.fromarray(restored_img)
if codeformer_visibility < 1.0:
res = Image.blend(image, res, codeformer_visibility)
image = res
if upscaling_resize != 1.0:
def upscale(image, scaler_index, resize):
small = image.crop((image.width // 2, image.height // 2, image.width // 2 + 10, image.height // 2 + 10))
pixels = tuple(np.array(small).flatten().tolist())
key = (resize, scaler_index, image.width, image.height) + pixels
c = cached_images.get(key)
if c is None:
upscaler = shared.sd_upscalers[scaler_index]
c = upscaler.upscale(image, image.width * resize, image.height * resize)
cached_images[key] = c
return c
res = upscale(image, extras_upscaler_1, upscaling_resize)
if extras_upscaler_2 != 0 and extras_upscaler_2_visibility>0:
res2 = upscale(image, extras_upscaler_2, upscaling_resize)
res = Image.blend(res, res2, extras_upscaler_2_visibility)
image = res
while len(cached_images) > 2:
del cached_images[next(iter(cached_images.keys()))]
images.save_image(image, outpath, "", None, '', opts.samples_format, short_filename=True, no_prompt=True)
return image, '', ''
def run_pnginfo(image):
info = ''
for key, text in image.info.items():
info += f"""
<div>
<p><b>{plaintext_to_html(str(key))}</b></p>
<p>{plaintext_to_html(str(text))}</p>
</div>
""".strip()+"\n"
if len(info) == 0:
message = "Nothing found in the image."
info = f"<div><p>{message}<p></div>"
return '', '', info
queue_lock = threading.Lock() queue_lock = threading.Lock()
def wrap_gradio_gpu_call(func): def wrap_queued_call(func):
def f(*args, **kwargs): def f(*args, **kwargs):
with queue_lock:
res = func(*args, **kwargs)
return res
return f
def wrap_gradio_gpu_call(func, extra_outputs=None):
def f(*args, **kwargs):
devices.torch_gc()
shared.state.sampling_step = 0 shared.state.sampling_step = 0
shared.state.job_count = -1 shared.state.job_count = -1
shared.state.job_no = 0 shared.state.job_no = 0
shared.state.job_timestamp = shared.state.get_job_timestamp()
shared.state.current_latent = None shared.state.current_latent = None
shared.state.current_image = None shared.state.current_image = None
shared.state.current_image_sampling_step = 0 shared.state.current_image_sampling_step = 0
shared.state.interrupted = False
shared.state.textinfo = None
with queue_lock: with queue_lock:
res = func(*args, **kwargs) res = func(*args, **kwargs)
@@ -148,47 +67,58 @@ def wrap_gradio_gpu_call(func):
shared.state.job = "" shared.state.job = ""
shared.state.job_count = 0 shared.state.job_count = 0
devices.torch_gc()
return res return res
return modules.ui.wrap_gradio_call(f) return modules.ui.wrap_gradio_call(f, extra_outputs=extra_outputs)
try:
# this silences the annoying "Some weights of the model checkpoint were not used when initializing..." message at start.
from transformers import logging
logging.set_verbosity_error()
except Exception:
pass
sd_config = OmegaConf.load(cmd_opts.config)
shared.sd_model = load_model_from_config(sd_config, cmd_opts.ckpt)
shared.sd_model = (shared.sd_model if cmd_opts.no_half else shared.sd_model.half())
if cmd_opts.lowvram or cmd_opts.medvram:
modules.lowvram.setup_for_low_vram(shared.sd_model, cmd_opts.medvram)
else:
shared.sd_model = shared.sd_model.to(shared.device)
modules.sd_hijack.model_hijack.hijack(shared.sd_model)
modules.scripts.load_scripts(os.path.join(script_path, "scripts")) modules.scripts.load_scripts(os.path.join(script_path, "scripts"))
if __name__ == "__main__": shared.sd_model = modules.sd_models.load_model()
shared.opts.onchange("sd_model_checkpoint", wrap_queued_call(lambda: modules.sd_models.reload_model_weights(shared.sd_model)))
def webui():
# make the program just exit at ctrl+c without waiting for anything # make the program just exit at ctrl+c without waiting for anything
def sigint_handler(sig, frame): def sigint_handler(sig, frame):
print(f'Interrupted with signal {sig} in {frame}') print(f'Interrupted with signal {sig} in {frame}')
os._exit(0) os._exit(0)
signal.signal(signal.SIGINT, sigint_handler) signal.signal(signal.SIGINT, sigint_handler)
demo = modules.ui.create_ui( while 1:
txt2img=wrap_gradio_gpu_call(modules.txt2img.txt2img),
img2img=wrap_gradio_gpu_call(modules.img2img.img2img), demo = modules.ui.create_ui(wrap_gradio_gpu_call=wrap_gradio_gpu_call)
run_extras=wrap_gradio_gpu_call(run_extras),
run_pnginfo=run_pnginfo demo.launch(
share=cmd_opts.share,
server_name="0.0.0.0" if cmd_opts.listen else None,
server_port=cmd_opts.port,
debug=cmd_opts.gradio_debug,
auth=[tuple(cred.split(':')) for cred in cmd_opts.gradio_auth.strip('"').split(',')] if cmd_opts.gradio_auth else None,
inbrowser=cmd_opts.autolaunch,
prevent_thread_lock=True
) )
demo.launch(share=cmd_opts.share, server_name="0.0.0.0" if cmd_opts.listen else None) while 1:
time.sleep(0.5)
if getattr(demo, 'do_restart', False):
time.sleep(0.5)
demo.close()
time.sleep(0.5)
break
sd_samplers.set_samplers()
print('Reloading Custom Scripts')
modules.scripts.reload_scripts(os.path.join(script_path, "scripts"))
print('Reloading modules: modules.ui')
importlib.reload(modules.ui)
print('Restarting Gradio')
if __name__ == "__main__":
webui()
Executable
+141
View File
@@ -0,0 +1,141 @@
#!/bin/bash
#################################################
# Please do not make any changes to this file, #
# change the variables in webui-user.sh instead #
#################################################
# Read variables from webui-user.sh
# shellcheck source=/dev/null
if [[ -f webui-user.sh ]]
then
source ./webui-user.sh
fi
# Set defaults
# Install directory without trailing slash
if [[ -z "${install_dir}" ]]
then
install_dir="/home/$(whoami)"
fi
# Name of the subdirectory (defaults to stable-diffusion-webui)
if [[ -z "${clone_dir}" ]]
then
clone_dir="stable-diffusion-webui"
fi
# python3 executable
if [[ -z "${python_cmd}" ]]
then
python_cmd="python3"
fi
# git executable
if [[ -z "${GIT}" ]]
then
export GIT="git"
fi
# python3 venv without trailing slash (defaults to ${install_dir}/${clone_dir}/venv)
if [[ -z "${venv_dir}" ]]
then
venv_dir="venv"
fi
if [[ -z "${LAUNCH_SCRIPT}" ]]
then
LAUNCH_SCRIPT="launch.py"
fi
# Disable sentry logging
export ERROR_REPORTING=FALSE
# Do not reinstall existing pip packages on Debian/Ubuntu
export PIP_IGNORE_INSTALLED=0
# Pretty print
delimiter="################################################################"
printf "\n%s\n" "${delimiter}"
printf "\e[1m\e[32mInstall script for stable-diffusion + Web UI\n"
printf "\e[1m\e[34mTested on Debian 11 (Bullseye)\e[0m"
printf "\n%s\n" "${delimiter}"
# Do not run as root
if [[ $(id -u) -eq 0 ]]
then
printf "\n%s\n" "${delimiter}"
printf "\e[1m\e[31mERROR: This script must not be launched as root, aborting...\e[0m"
printf "\n%s\n" "${delimiter}"
exit 1
else
printf "\n%s\n" "${delimiter}"
printf "Running on \e[1m\e[32m%s\e[0m user" "$(whoami)"
printf "\n%s\n" "${delimiter}"
fi
if [[ -d .git ]]
then
printf "\n%s\n" "${delimiter}"
printf "Repo already cloned, using it as install directory"
printf "\n%s\n" "${delimiter}"
install_dir="${PWD}/../"
clone_dir="${PWD##*/}"
fi
# Check prequisites
for preq in git python3
do
if ! hash "${preq}" &>/dev/null
then
printf "\n%s\n" "${delimiter}"
printf "\e[1m\e[31mERROR: %s is not installed, aborting...\e[0m" "${preq}"
printf "\n%s\n" "${delimiter}"
exit 1
fi
done
if ! "${python_cmd}" -c "import venv" &>/dev/null
then
printf "\n%s\n" "${delimiter}"
printf "\e[1m\e[31mERROR: python3-venv is not installed, aborting...\e[0m"
printf "\n%s\n" "${delimiter}"
exit 1
fi
printf "\n%s\n" "${delimiter}"
printf "Clone or update stable-diffusion-webui"
printf "\n%s\n" "${delimiter}"
cd "${install_dir}"/ || { printf "\e[1m\e[31mERROR: Can't cd to %s/, aborting...\e[0m" "${install_dir}"; exit 1; }
if [[ -d "${clone_dir}" ]]
then
cd "${clone_dir}"/ || { printf "\e[1m\e[31mERROR: Can't cd to %s/%s/, aborting...\e[0m" "${install_dir}" "${clone_dir}"; exit 1; }
"${GIT}" pull
else
"${GIT}" clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git "${clone_dir}"
cd "${clone_dir}"/ || { printf "\e[1m\e[31mERROR: Can't cd to %s/%s/, aborting...\e[0m" "${install_dir}" "${clone_dir}"; exit 1; }
fi
printf "\n%s\n" "${delimiter}"
printf "Create and activate python venv"
printf "\n%s\n" "${delimiter}"
cd "${install_dir}"/"${clone_dir}"/ || { printf "\e[1m\e[31mERROR: Can't cd to %s/%s/, aborting...\e[0m" "${install_dir}" "${clone_dir}"; exit 1; }
if [[ ! -d "${venv_dir}" ]]
then
"${python_cmd}" -m venv "${venv_dir}"
first_launch=1
fi
# shellcheck source=/dev/null
if [[ -f "${venv_dir}"/bin/activate ]]
then
source "${venv_dir}"/bin/activate
else
printf "\n%s\n" "${delimiter}"
printf "\e[1m\e[31mERROR: Cannot activate python venv, aborting...\e[0m"
printf "\n%s\n" "${delimiter}"
exit 1
fi
printf "\n%s\n" "${delimiter}"
printf "Launching launch.py..."
printf "\n%s\n" "${delimiter}"
"${python_cmd}" "${LAUNCH_SCRIPT}"