Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1495a7460b |
No files matched your search
@@ -2,7 +2,7 @@
|
|||||||
name: Feature request
|
name: Feature request
|
||||||
about: Suggest an idea for this project
|
about: Suggest an idea for this project
|
||||||
title: ''
|
title: ''
|
||||||
labels: 'suggestion'
|
labels: ''
|
||||||
assignees: ''
|
assignees: ''
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -1,28 +0,0 @@
|
|||||||
# 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.
|
|
||||||
+2
-8
@@ -1,13 +1,10 @@
|
|||||||
__pycache__
|
__pycache__
|
||||||
*.ckpt
|
/ESRGAN
|
||||||
*.pth
|
|
||||||
/ESRGAN/*
|
|
||||||
/SwinIR/*
|
|
||||||
/repositories
|
/repositories
|
||||||
/venv
|
/venv
|
||||||
/tmp
|
/tmp
|
||||||
/model.ckpt
|
/model.ckpt
|
||||||
/models/**/*
|
/models/*.ckpt
|
||||||
/GFPGANv1.3.pth
|
/GFPGANv1.3.pth
|
||||||
/gfpgan/weights/*.pth
|
/gfpgan/weights/*.pth
|
||||||
/ui-config.json
|
/ui-config.json
|
||||||
@@ -23,6 +20,3 @@ __pycache__
|
|||||||
/interrogate
|
/interrogate
|
||||||
/user.css
|
/user.css
|
||||||
/.idea
|
/.idea
|
||||||
notification.mp3
|
|
||||||
/SwinIR
|
|
||||||
/textual_inversion
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
* @AUTOMATIC1111
|
|
||||||
*.js @AUTOMATIC1111
|
|
||||||
File renamed without changes.
@@ -3,73 +3,50 @@ A browser interface based on Gradio library for Stable Diffusion.
|
|||||||
|
|
||||||

|

|
||||||
|
|
||||||
Check the [custom scripts](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Custom-Scripts) wiki page for extra scripts developed by users.
|
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
[Detailed feature showcase with images](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/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 and git)
|
- 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, specify parts of text that the model should pay more attention to
|
- Attention
|
||||||
- a man in a ((tuxedo)) - will pay more attention to tuxedo
|
- Loopback
|
||||||
- a man in a (tuxedo:1.21) - alternative syntax
|
- X/Y plot
|
||||||
- select text and press ctrl+up or ctrl+down to automatically adjust attention to selected text (code contributed by anonymous user)
|
|
||||||
- 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
|
- CodeFormer, face restoration tool as an alternative to GFPGAN
|
||||||
- RealESRGAN, neural network upscaler
|
- RealESRGAN, neural network upscaler
|
||||||
- ESRGAN, neural network upscaler with a lot of third party models
|
- ESRGAN, neural network with a lot of third party models
|
||||||
- SwinIR and Swin2SR([see here](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/2092)), neural network upscalers
|
- SwinIR, neural network upscaler
|
||||||
- LDSR, Latent diffusion super resolution upscaling
|
- LDSR, Latent diffusion super resolution upscaling
|
||||||
- Resizing aspect ratio options
|
- Resizing aspect ratio options
|
||||||
- Sampling method selection
|
- Sampling method selection
|
||||||
- Adjust sampler eta values (noise multiplier)
|
|
||||||
- More advanced noise setting options
|
|
||||||
- Interrupt processing at any time
|
- Interrupt processing at any time
|
||||||
- 4GB video card support (also reports of 2GB working)
|
- 4GB video card support
|
||||||
- Correct seeds for batches
|
- Correct seeds for batches
|
||||||
- Prompt length validation
|
- Prompt length validation
|
||||||
- get length of prompt in tokens as you type
|
- Generation parameters added as text to PNG
|
||||||
- get a warning after generation if some text was truncated
|
- Tab to view an existing picture's generation parameters
|
||||||
- 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 arbitrary python code from UI (must run with --allow-code to enable)
|
- Running custom code from UI
|
||||||
- Mouseover hints for 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, a checkbox to create images that can be tiled like textures
|
- Tiling support: UI 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
|
- Negative prompt
|
||||||
- Styles, a way to save part of prompt and easily apply them via dropdown later
|
- Styles
|
||||||
- Variations, a way to generate same image but with tiny differences
|
- Variations
|
||||||
- Seed resizing, a way to generate same image but at slightly different resolution
|
- Seed resizing
|
||||||
- CLIP interrogator, a button that tries to guess prompt from an image
|
- CLIP interrogator
|
||||||
- Prompt Editing, a way to change prompt mid-generation, say to start making a watermelon and switch to anime girl midway
|
- Prompt Editing
|
||||||
- Batch Processing, process a group of files using img2img
|
- Batch Processing
|
||||||
- Img2img Alternative
|
- Img2img Alternative
|
||||||
- Highres Fix, a convenience option to produce high resolution pictures in one click without usual distortions
|
- Highres Fix
|
||||||
- Reloading checkpoints on the fly
|
- LDSR Upscaling
|
||||||
- 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
|
|
||||||
- [Composable-Diffusion](https://energy-based-model.github.io/Compositional-Visual-Generation-with-Composable-Diffusion-Models/), a way to use multiple prompts at once
|
|
||||||
- separate prompts using uppercase `AND`
|
|
||||||
- also supports weights for prompts: `a cat :1.2 AND a dog AND a penguin :2.2`
|
|
||||||
- No token limit for prompts (original stable diffusion lets you use up to 75 tokens)
|
|
||||||
- DeepDanbooru integration, creates danbooru style tags for anime prompts (add --deepdanbooru to commandline args)
|
|
||||||
- [xformers](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Xformers), major speed increase for select cards: (add --xformers to commandline args)
|
|
||||||
|
|
||||||
## Installation and Running
|
## Installation and Running
|
||||||
Make sure the required [dependencies](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Dependencies) are met and follow the instructions available for both [NVidia](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Install-and-Run-on-NVidia-GPUs) (recommended) and [AMD](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Install-and-Run-on-AMD-GPUs) GPUs.
|
Make sure the required [dependencies](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Dependencies) are met and follow the instructions available for 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.
|
||||||
@@ -106,9 +83,6 @@ bash <(wget -qO- https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusio
|
|||||||
|
|
||||||
Find the instructions [here](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Installation-on-Apple-Silicon).
|
Find the instructions [here](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Installation-on-Apple-Silicon).
|
||||||
|
|
||||||
## Contributing
|
|
||||||
Here's how to add code to this repo: [Contributing](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Contributing)
|
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
The documentation was moved from this README over to the project's [wiki](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki).
|
The documentation was moved from this README over to the project's [wiki](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki).
|
||||||
|
|
||||||
@@ -119,16 +93,11 @@ The documentation was moved from this README over to the project's [wiki](https:
|
|||||||
- CodeFormer - https://github.com/sczhou/CodeFormer
|
- CodeFormer - https://github.com/sczhou/CodeFormer
|
||||||
- ESRGAN - https://github.com/xinntao/ESRGAN
|
- ESRGAN - https://github.com/xinntao/ESRGAN
|
||||||
- SwinIR - https://github.com/JingyunLiang/SwinIR
|
- SwinIR - https://github.com/JingyunLiang/SwinIR
|
||||||
- Swin2SR - https://github.com/mv-lab/swin2sr
|
|
||||||
- LDSR - https://github.com/Hafiidz/latent-diffusion
|
- LDSR - https://github.com/Hafiidz/latent-diffusion
|
||||||
- Ideas for optimizations - https://github.com/basujindal/stable-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.
|
- 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
|
- 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
|
- CLIP interrogator idea and borrowing some code - https://github.com/pharmapsychotic/clip-interrogator
|
||||||
- Idea for Composable Diffusion - https://github.com/energy-based-model/Compositional-Visual-Generation-with-Composable-Diffusion-Models-PyTorch
|
|
||||||
- xformers - https://github.com/facebookresearch/xformers
|
|
||||||
- DeepDanbooru - interrogator for anime diffusers https://github.com/KichangKim/DeepDanbooru
|
|
||||||
- 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)
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
|
||||||
@@ -359,6 +359,7 @@ 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
|
||||||
@@ -1906,6 +1907,7 @@ 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,177 +0,0 @@
|
|||||||
|
|
||||||
contextMenuInit = function(){
|
|
||||||
let eventListenerApplied=false;
|
|
||||||
let menuSpecs = new Map();
|
|
||||||
|
|
||||||
const uid = function(){
|
|
||||||
return Date.now().toString(36) + Math.random().toString(36).substr(2);
|
|
||||||
}
|
|
||||||
|
|
||||||
function showContextMenu(event,element,menuEntries){
|
|
||||||
let posx = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
|
|
||||||
let posy = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
|
|
||||||
|
|
||||||
let oldMenu = gradioApp().querySelector('#context-menu')
|
|
||||||
if(oldMenu){
|
|
||||||
oldMenu.remove()
|
|
||||||
}
|
|
||||||
|
|
||||||
let tabButton = uiCurrentTab
|
|
||||||
let baseStyle = window.getComputedStyle(tabButton)
|
|
||||||
|
|
||||||
const contextMenu = document.createElement('nav')
|
|
||||||
contextMenu.id = "context-menu"
|
|
||||||
contextMenu.style.background = baseStyle.background
|
|
||||||
contextMenu.style.color = baseStyle.color
|
|
||||||
contextMenu.style.fontFamily = baseStyle.fontFamily
|
|
||||||
contextMenu.style.top = posy+'px'
|
|
||||||
contextMenu.style.left = posx+'px'
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const contextMenuList = document.createElement('ul')
|
|
||||||
contextMenuList.className = 'context-menu-items';
|
|
||||||
contextMenu.append(contextMenuList);
|
|
||||||
|
|
||||||
menuEntries.forEach(function(entry){
|
|
||||||
let contextMenuEntry = document.createElement('a')
|
|
||||||
contextMenuEntry.innerHTML = entry['name']
|
|
||||||
contextMenuEntry.addEventListener("click", function(e) {
|
|
||||||
entry['func']();
|
|
||||||
})
|
|
||||||
contextMenuList.append(contextMenuEntry);
|
|
||||||
|
|
||||||
})
|
|
||||||
|
|
||||||
gradioApp().getRootNode().appendChild(contextMenu)
|
|
||||||
|
|
||||||
let menuWidth = contextMenu.offsetWidth + 4;
|
|
||||||
let menuHeight = contextMenu.offsetHeight + 4;
|
|
||||||
|
|
||||||
let windowWidth = window.innerWidth;
|
|
||||||
let windowHeight = window.innerHeight;
|
|
||||||
|
|
||||||
if ( (windowWidth - posx) < menuWidth ) {
|
|
||||||
contextMenu.style.left = windowWidth - menuWidth + "px";
|
|
||||||
}
|
|
||||||
|
|
||||||
if ( (windowHeight - posy) < menuHeight ) {
|
|
||||||
contextMenu.style.top = windowHeight - menuHeight + "px";
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
function appendContextMenuOption(targetEmementSelector,entryName,entryFunction){
|
|
||||||
|
|
||||||
currentItems = menuSpecs.get(targetEmementSelector)
|
|
||||||
|
|
||||||
if(!currentItems){
|
|
||||||
currentItems = []
|
|
||||||
menuSpecs.set(targetEmementSelector,currentItems);
|
|
||||||
}
|
|
||||||
let newItem = {'id':targetEmementSelector+'_'+uid(),
|
|
||||||
'name':entryName,
|
|
||||||
'func':entryFunction,
|
|
||||||
'isNew':true}
|
|
||||||
|
|
||||||
currentItems.push(newItem)
|
|
||||||
return newItem['id']
|
|
||||||
}
|
|
||||||
|
|
||||||
function removeContextMenuOption(uid){
|
|
||||||
menuSpecs.forEach(function(v,k) {
|
|
||||||
let index = -1
|
|
||||||
v.forEach(function(e,ei){if(e['id']==uid){index=ei}})
|
|
||||||
if(index>=0){
|
|
||||||
v.splice(index, 1);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
function addContextMenuEventListener(){
|
|
||||||
if(eventListenerApplied){
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
gradioApp().addEventListener("click", function(e) {
|
|
||||||
let source = e.composedPath()[0]
|
|
||||||
if(source.id && source.indexOf('check_progress')>-1){
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
let oldMenu = gradioApp().querySelector('#context-menu')
|
|
||||||
if(oldMenu){
|
|
||||||
oldMenu.remove()
|
|
||||||
}
|
|
||||||
});
|
|
||||||
gradioApp().addEventListener("contextmenu", function(e) {
|
|
||||||
let oldMenu = gradioApp().querySelector('#context-menu')
|
|
||||||
if(oldMenu){
|
|
||||||
oldMenu.remove()
|
|
||||||
}
|
|
||||||
menuSpecs.forEach(function(v,k) {
|
|
||||||
if(e.composedPath()[0].matches(k)){
|
|
||||||
showContextMenu(e,e.composedPath()[0],v)
|
|
||||||
e.preventDefault()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
})
|
|
||||||
});
|
|
||||||
eventListenerApplied=true
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
return [appendContextMenuOption, removeContextMenuOption, addContextMenuEventListener]
|
|
||||||
}
|
|
||||||
|
|
||||||
initResponse = contextMenuInit();
|
|
||||||
appendContextMenuOption = initResponse[0];
|
|
||||||
removeContextMenuOption = initResponse[1];
|
|
||||||
addContextMenuEventListener = initResponse[2];
|
|
||||||
|
|
||||||
(function(){
|
|
||||||
//Start example Context Menu Items
|
|
||||||
let generateOnRepeat = function(genbuttonid,interruptbuttonid){
|
|
||||||
let genbutton = gradioApp().querySelector(genbuttonid);
|
|
||||||
let interruptbutton = gradioApp().querySelector(interruptbuttonid);
|
|
||||||
if(!interruptbutton.offsetParent){
|
|
||||||
genbutton.click();
|
|
||||||
}
|
|
||||||
clearInterval(window.generateOnRepeatInterval)
|
|
||||||
window.generateOnRepeatInterval = setInterval(function(){
|
|
||||||
if(!interruptbutton.offsetParent){
|
|
||||||
genbutton.click();
|
|
||||||
}
|
|
||||||
},
|
|
||||||
500)
|
|
||||||
}
|
|
||||||
|
|
||||||
appendContextMenuOption('#txt2img_generate','Generate forever',function(){
|
|
||||||
generateOnRepeat('#txt2img_generate','#txt2img_interrupt');
|
|
||||||
})
|
|
||||||
appendContextMenuOption('#img2img_generate','Generate forever',function(){
|
|
||||||
generateOnRepeat('#img2img_generate','#img2img_interrupt');
|
|
||||||
})
|
|
||||||
|
|
||||||
let cancelGenerateForever = function(){
|
|
||||||
clearInterval(window.generateOnRepeatInterval)
|
|
||||||
}
|
|
||||||
|
|
||||||
appendContextMenuOption('#txt2img_interrupt','Cancel generate forever',cancelGenerateForever)
|
|
||||||
appendContextMenuOption('#txt2img_generate', 'Cancel generate forever',cancelGenerateForever)
|
|
||||||
appendContextMenuOption('#img2img_interrupt','Cancel generate forever',cancelGenerateForever)
|
|
||||||
appendContextMenuOption('#img2img_generate', 'Cancel generate forever',cancelGenerateForever)
|
|
||||||
|
|
||||||
appendContextMenuOption('#roll','Roll three',
|
|
||||||
function(){
|
|
||||||
let rollbutton = get_uiCurrentTabContent().querySelector('#roll');
|
|
||||||
setTimeout(function(){rollbutton.click()},100)
|
|
||||||
setTimeout(function(){rollbutton.click()},200)
|
|
||||||
setTimeout(function(){rollbutton.click()},300)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
})();
|
|
||||||
//End example Context Menu Items
|
|
||||||
|
|
||||||
onUiUpdate(function(){
|
|
||||||
addContextMenuEventListener()
|
|
||||||
});
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
addEventListener('keydown', (event) => {
|
|
||||||
let target = event.originalTarget || event.composedPath()[0];
|
|
||||||
if (!target.hasAttribute("placeholder")) return;
|
|
||||||
if (!target.placeholder.toLowerCase().includes("prompt")) return;
|
|
||||||
|
|
||||||
let plus = "ArrowUp"
|
|
||||||
let minus = "ArrowDown"
|
|
||||||
if (event.key != plus && event.key != minus) return;
|
|
||||||
|
|
||||||
selectionStart = target.selectionStart;
|
|
||||||
selectionEnd = target.selectionEnd;
|
|
||||||
if(selectionStart == selectionEnd) return;
|
|
||||||
|
|
||||||
event.preventDefault();
|
|
||||||
|
|
||||||
if (selectionStart == 0 || target.value[selectionStart - 1] != "(") {
|
|
||||||
target.value = target.value.slice(0, selectionStart) +
|
|
||||||
"(" + target.value.slice(selectionStart, selectionEnd) + ":1.0)" +
|
|
||||||
target.value.slice(selectionEnd);
|
|
||||||
|
|
||||||
target.focus();
|
|
||||||
target.selectionStart = selectionStart + 1;
|
|
||||||
target.selectionEnd = selectionEnd + 1;
|
|
||||||
|
|
||||||
} else {
|
|
||||||
end = target.value.slice(selectionEnd + 1).indexOf(")") + 1;
|
|
||||||
weight = parseFloat(target.value.slice(selectionEnd + 1, selectionEnd + 1 + end));
|
|
||||||
if (event.key == minus) weight -= 0.1;
|
|
||||||
if (event.key == plus) weight += 0.1;
|
|
||||||
|
|
||||||
weight = parseFloat(weight.toPrecision(12));
|
|
||||||
|
|
||||||
target.value = target.value.slice(0, selectionEnd + 1) +
|
|
||||||
weight +
|
|
||||||
target.value.slice(selectionEnd + 1 + end - 1);
|
|
||||||
|
|
||||||
target.focus();
|
|
||||||
target.selectionStart = selectionStart;
|
|
||||||
target.selectionEnd = selectionEnd;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
+2
-7
@@ -15,7 +15,6 @@ titles = {
|
|||||||
"\u267b\ufe0f": "Reuse seed from last generation, mostly useful if it was randomed",
|
"\u267b\ufe0f": "Reuse seed from last generation, mostly useful if it was randomed",
|
||||||
"\u{1f3a8}": "Add a random artist to the prompt.",
|
"\u{1f3a8}": "Add a random artist to the prompt.",
|
||||||
"\u2199\ufe0f": "Read generation parameters from prompt into user interface.",
|
"\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",
|
"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",
|
"SD upscale": "Upscale image normally, split result into tiles, improve each tile using img2img, merge whole image back",
|
||||||
@@ -35,7 +34,6 @@ titles = {
|
|||||||
"Denoising strength": "Determines how little respect the algorithm should have for image's content. At 0, nothing will change, and at 1 you'll get an unrelated image. With values below 1.0, processing will take less steps than the Sampling Steps slider specifies.",
|
"Denoising strength": "Determines how little respect the algorithm should have for image's content. At 0, nothing will change, and at 1 you'll get an unrelated image. With values below 1.0, processing will take less steps than the Sampling Steps slider specifies.",
|
||||||
"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.",
|
"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.",
|
||||||
|
|
||||||
"Skip": "Stop processing current image and continue processing.",
|
|
||||||
"Interrupt": "Stop processing images and return any results accumulated so far.",
|
"Interrupt": "Stop processing images and return any results accumulated so far.",
|
||||||
"Save": "Write image to a directory (default - log/images) and generation parameters into csv file.",
|
"Save": "Write image to a directory (default - log/images) and generation parameters into csv file.",
|
||||||
|
|
||||||
@@ -48,7 +46,6 @@ titles = {
|
|||||||
"Custom code": "Run Python code. Advanced user only. Must run program with --allow-code for this to work",
|
"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 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.",
|
"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.",
|
"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.",
|
||||||
@@ -60,8 +57,8 @@ titles = {
|
|||||||
|
|
||||||
"Interrogate": "Reconstruct prompt from existing image and put it into the prompt field.",
|
"Interrogate": "Reconstruct prompt from existing image and put it into the prompt field.",
|
||||||
|
|
||||||
"Images filename pattern": "Use following tags to define how filenames for images are chosen: [steps], [cfg], [prompt], [prompt_no_styles], [prompt_spaces], [width], [height], [styles], [sampler], [seed], [model_hash], [prompt_words], [date], [datetime], [job_timestamp]; leave empty for default.",
|
"Images filename pattern": "Use following tags to define how filenames for images are chosen: [steps], [cfg], [prompt], [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.",
|
"Directory name pattern": "Use following tags to define how subdirectories for images and grids are chosen: [steps], [cfg], [prompt], [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",
|
"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.",
|
"Loopback": "Process an image, use it as an input, repeat.",
|
||||||
@@ -79,8 +76,6 @@ titles = {
|
|||||||
"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",
|
"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.",
|
"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.",
|
||||||
|
|
||||||
"Eta noise seed delta": "If this values is non-zero, it will be added to seed and used to initialize RNG for noises when using samplers with Eta. You can use this to produce even more variation of images, or you can use this to match images of other software if you know what you are doing.",
|
|
||||||
"Do not add watermark to images": "If this option is enabled, watermark will not be added to created images. Warning: if you do not add watermark, you may be bevaing in an unethical manner.",
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+69
-96
@@ -1,97 +1,72 @@
|
|||||||
// A full size 'lightbox' preview modal shown when left clicking on gallery previews
|
// A full size 'lightbox' preview modal shown when left clicking on gallery previews
|
||||||
|
|
||||||
function closeModal() {
|
function closeModal() {
|
||||||
gradioApp().getElementById("lightboxModal").style.display = "none";
|
gradioApp().getElementById("lightboxModal").style.display = "none";
|
||||||
}
|
}
|
||||||
|
|
||||||
function showModal(event) {
|
function showModal(event) {
|
||||||
const source = event.target || event.srcElement;
|
const source = event.target || event.srcElement;
|
||||||
const modalImage = gradioApp().getElementById("modalImage")
|
const modalImage = gradioApp().getElementById("modalImage")
|
||||||
const lb = gradioApp().getElementById("lightboxModal")
|
const lb = gradioApp().getElementById("lightboxModal")
|
||||||
modalImage.src = source.src
|
modalImage.src = source.src
|
||||||
if (modalImage.style.display === 'none') {
|
if (modalImage.style.display === 'none') {
|
||||||
lb.style.setProperty('background-image', 'url(' + source.src + ')');
|
lb.style.setProperty('background-image', 'url(' + source.src + ')');
|
||||||
}
|
}
|
||||||
lb.style.display = "block";
|
lb.style.display = "block";
|
||||||
lb.focus()
|
lb.focus()
|
||||||
event.stopPropagation()
|
event.stopPropagation()
|
||||||
}
|
}
|
||||||
|
|
||||||
function negmod(n, m) {
|
function negmod(n, m) {
|
||||||
return ((n % m) + m) % m;
|
return ((n % m) + m) % m;
|
||||||
}
|
}
|
||||||
|
|
||||||
function updateOnBackgroundChange() {
|
function modalImageSwitch(offset){
|
||||||
const modalImage = gradioApp().getElementById("modalImage")
|
var allgalleryButtons = gradioApp().querySelectorAll(".gallery-item.transition-all")
|
||||||
if (modalImage && modalImage.offsetParent) {
|
var galleryButtons = []
|
||||||
let allcurrentButtons = gradioApp().querySelectorAll(".gallery-item.transition-all.\\!ring-2")
|
allgalleryButtons.forEach(function(elem){
|
||||||
let currentButton = null
|
if(elem.parentElement.offsetParent){
|
||||||
allcurrentButtons.forEach(function(elem) {
|
galleryButtons.push(elem);
|
||||||
if (elem.parentElement.offsetParent) {
|
|
||||||
currentButton = elem;
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
if (modalImage.src != currentButton.children[0].src) {
|
|
||||||
modalImage.src = currentButton.children[0].src;
|
|
||||||
if (modalImage.style.display === 'none') {
|
|
||||||
modal.style.setProperty('background-image', `url(${modalImage.src})`)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
|
|
||||||
function modalImageSwitch(offset) {
|
if(galleryButtons.length>1){
|
||||||
var allgalleryButtons = gradioApp().querySelectorAll(".gallery-item.transition-all")
|
var allcurrentButtons = gradioApp().querySelectorAll(".gallery-item.transition-all.\\!ring-2")
|
||||||
var galleryButtons = []
|
var currentButton = null
|
||||||
allgalleryButtons.forEach(function(elem) {
|
allcurrentButtons.forEach(function(elem){
|
||||||
if (elem.parentElement.offsetParent) {
|
if(elem.parentElement.offsetParent){
|
||||||
galleryButtons.push(elem);
|
currentButton = elem;
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
if (galleryButtons.length > 1) {
|
var result = -1
|
||||||
var allcurrentButtons = gradioApp().querySelectorAll(".gallery-item.transition-all.\\!ring-2")
|
galleryButtons.forEach(function(v, i){ if(v==currentButton) { result = i } })
|
||||||
var currentButton = null
|
|
||||||
allcurrentButtons.forEach(function(elem) {
|
|
||||||
if (elem.parentElement.offsetParent) {
|
|
||||||
currentButton = elem;
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
var result = -1
|
if(result != -1){
|
||||||
galleryButtons.forEach(function(v, i) {
|
nextButton = galleryButtons[negmod((result+offset),galleryButtons.length)]
|
||||||
if (v == currentButton) {
|
nextButton.click()
|
||||||
result = i
|
const modalImage = gradioApp().getElementById("modalImage");
|
||||||
}
|
const modal = gradioApp().getElementById("lightboxModal");
|
||||||
})
|
modalImage.src = nextButton.children[0].src;
|
||||||
|
if (modalImage.style.display === 'none') {
|
||||||
if (result != -1) {
|
modal.style.setProperty('background-image', `url(${modalImage.src})`)
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
}
|
setTimeout( function(){modal.focus()},10)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function modalNextImage(event) {
|
function modalNextImage(event){
|
||||||
modalImageSwitch(1)
|
modalImageSwitch(1)
|
||||||
event.stopPropagation()
|
event.stopPropagation()
|
||||||
}
|
}
|
||||||
|
|
||||||
function modalPrevImage(event) {
|
function modalPrevImage(event){
|
||||||
modalImageSwitch(-1)
|
modalImageSwitch(-1)
|
||||||
event.stopPropagation()
|
event.stopPropagation()
|
||||||
}
|
}
|
||||||
|
|
||||||
function modalKeyHandler(event) {
|
function modalKeyHandler(event){
|
||||||
switch (event.key) {
|
switch (event.key) {
|
||||||
case "ArrowLeft":
|
case "ArrowLeft":
|
||||||
modalPrevImage(event)
|
modalPrevImage(event)
|
||||||
@@ -105,22 +80,21 @@ function modalKeyHandler(event) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function showGalleryImage() {
|
function showGalleryImage(){
|
||||||
setTimeout(function() {
|
setTimeout(function() {
|
||||||
fullImg_preview = gradioApp().querySelectorAll('img.w-full.object-contain')
|
fullImg_preview = gradioApp().querySelectorAll('img.w-full.object-contain')
|
||||||
|
|
||||||
if (fullImg_preview != null) {
|
if(fullImg_preview != null){
|
||||||
fullImg_preview.forEach(function function_name(e) {
|
fullImg_preview.forEach(function function_name(e) {
|
||||||
if (e.dataset.modded)
|
|
||||||
return;
|
|
||||||
e.dataset.modded = true;
|
|
||||||
if(e && e.parentElement.tagName == 'DIV'){
|
if(e && e.parentElement.tagName == 'DIV'){
|
||||||
|
|
||||||
e.style.cursor='pointer'
|
e.style.cursor='pointer'
|
||||||
|
|
||||||
e.addEventListener('click', function (evt) {
|
e.addEventListener('click', function (evt) {
|
||||||
if(!opts.js_modal_lightbox) return;
|
if(!opts.js_modal_lightbox) return;
|
||||||
modalZoomSet(gradioApp().getElementById('modalImage'), opts.js_modal_lightbox_initially_zoomed)
|
modalZoomSet(gradioApp().getElementById('modalImage'), opts.js_modal_lightbox_initialy_zoomed)
|
||||||
showModal(evt)
|
showModal(evt)
|
||||||
}, true);
|
},true);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -128,21 +102,21 @@ function showGalleryImage() {
|
|||||||
}, 100);
|
}, 100);
|
||||||
}
|
}
|
||||||
|
|
||||||
function modalZoomSet(modalImage, enable) {
|
function modalZoomSet(modalImage, enable){
|
||||||
if (enable) {
|
if( enable ){
|
||||||
modalImage.classList.add('modalImageFullscreen');
|
modalImage.classList.add('modalImageFullscreen');
|
||||||
} else {
|
} else{
|
||||||
modalImage.classList.remove('modalImageFullscreen');
|
modalImage.classList.remove('modalImageFullscreen');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function modalZoomToggle(event) {
|
function modalZoomToggle(event){
|
||||||
modalImage = gradioApp().getElementById("modalImage");
|
modalImage = gradioApp().getElementById("modalImage");
|
||||||
modalZoomSet(modalImage, !modalImage.classList.contains('modalImageFullscreen'))
|
modalZoomSet(modalImage, !modalImage.classList.contains('modalImageFullscreen'))
|
||||||
event.stopPropagation()
|
event.stopPropagation()
|
||||||
}
|
}
|
||||||
|
|
||||||
function modalTileImageToggle(event) {
|
function modalTileImageToggle(event){
|
||||||
const modalImage = gradioApp().getElementById("modalImage");
|
const modalImage = gradioApp().getElementById("modalImage");
|
||||||
const modal = gradioApp().getElementById("lightboxModal");
|
const modal = gradioApp().getElementById("lightboxModal");
|
||||||
const isTiling = modalImage.style.display === 'none';
|
const isTiling = modalImage.style.display === 'none';
|
||||||
@@ -157,18 +131,17 @@ function modalTileImageToggle(event) {
|
|||||||
event.stopPropagation()
|
event.stopPropagation()
|
||||||
}
|
}
|
||||||
|
|
||||||
function galleryImageHandler(e) {
|
function galleryImageHandler(e){
|
||||||
if (e && e.parentElement.tagName == 'BUTTON') {
|
if(e && e.parentElement.tagName == 'BUTTON'){
|
||||||
e.onclick = showGalleryImage;
|
e.onclick = showGalleryImage;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
onUiUpdate(function() {
|
onUiUpdate(function(){
|
||||||
fullImg_preview = gradioApp().querySelectorAll('img.w-full')
|
fullImg_preview = gradioApp().querySelectorAll('img.w-full')
|
||||||
if (fullImg_preview != null) {
|
if(fullImg_preview != null){
|
||||||
fullImg_preview.forEach(galleryImageHandler);
|
fullImg_preview.forEach(galleryImageHandler);
|
||||||
}
|
}
|
||||||
updateOnBackgroundChange();
|
|
||||||
})
|
})
|
||||||
|
|
||||||
document.addEventListener("DOMContentLoaded", function() {
|
document.addEventListener("DOMContentLoaded", function() {
|
||||||
@@ -176,7 +149,7 @@ document.addEventListener("DOMContentLoaded", function() {
|
|||||||
const modal = document.createElement('div')
|
const modal = document.createElement('div')
|
||||||
modal.onclick = closeModal;
|
modal.onclick = closeModal;
|
||||||
modal.id = "lightboxModal";
|
modal.id = "lightboxModal";
|
||||||
modal.tabIndex = 0
|
modal.tabIndex=0
|
||||||
modal.addEventListener('keydown', modalKeyHandler, true)
|
modal.addEventListener('keydown', modalKeyHandler, true)
|
||||||
|
|
||||||
const modalControls = document.createElement('div')
|
const modalControls = document.createElement('div')
|
||||||
@@ -207,23 +180,23 @@ document.addEventListener("DOMContentLoaded", function() {
|
|||||||
const modalImage = document.createElement('img')
|
const modalImage = document.createElement('img')
|
||||||
modalImage.id = 'modalImage';
|
modalImage.id = 'modalImage';
|
||||||
modalImage.onclick = closeModal;
|
modalImage.onclick = closeModal;
|
||||||
modalImage.tabIndex = 0
|
modalImage.tabIndex=0
|
||||||
modalImage.addEventListener('keydown', modalKeyHandler, true)
|
modalImage.addEventListener('keydown', modalKeyHandler, true)
|
||||||
modal.appendChild(modalImage)
|
modal.appendChild(modalImage)
|
||||||
|
|
||||||
const modalPrev = document.createElement('a')
|
const modalPrev = document.createElement('a')
|
||||||
modalPrev.className = 'modalPrev';
|
modalPrev.className = 'modalPrev';
|
||||||
modalPrev.innerHTML = '❮'
|
modalPrev.innerHTML = '❮'
|
||||||
modalPrev.tabIndex = 0
|
modalPrev.tabIndex=0
|
||||||
modalPrev.addEventListener('click', modalPrevImage, true);
|
modalPrev.addEventListener('click',modalPrevImage,true);
|
||||||
modalPrev.addEventListener('keydown', modalKeyHandler, true)
|
modalPrev.addEventListener('keydown', modalKeyHandler, true)
|
||||||
modal.appendChild(modalPrev)
|
modal.appendChild(modalPrev)
|
||||||
|
|
||||||
const modalNext = document.createElement('a')
|
const modalNext = document.createElement('a')
|
||||||
modalNext.className = 'modalNext';
|
modalNext.className = 'modalNext';
|
||||||
modalNext.innerHTML = '❯'
|
modalNext.innerHTML = '❯'
|
||||||
modalNext.tabIndex = 0
|
modalNext.tabIndex=0
|
||||||
modalNext.addEventListener('click', modalNextImage, true);
|
modalNext.addEventListener('click',modalNextImage,true);
|
||||||
modalNext.addEventListener('keydown', modalKeyHandler, true)
|
modalNext.addEventListener('keydown', modalKeyHandler, true)
|
||||||
|
|
||||||
modal.appendChild(modalNext)
|
modal.appendChild(modalNext)
|
||||||
|
|||||||
@@ -25,9 +25,6 @@ onUiUpdate(function(){
|
|||||||
|
|
||||||
lastHeadImg = headImg;
|
lastHeadImg = headImg;
|
||||||
|
|
||||||
// play notification sound if available
|
|
||||||
gradioApp().querySelector('#audio_notification audio')?.play();
|
|
||||||
|
|
||||||
if (document.hasFocus()) return;
|
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.
|
// Multiple copies of the images are in the DOM when one is selected. Dedup with a Set to get the real number generated.
|
||||||
|
|||||||
@@ -1,25 +1,9 @@
|
|||||||
// code related to showing and updating progressbar shown as the image is being made
|
// code related to showing and updating progressbar shown as the image is being made
|
||||||
global_progressbars = {}
|
global_progressbars = {}
|
||||||
|
|
||||||
function check_progressbar(id_part, id_progressbar, id_progressbar_span, id_skip, id_interrupt, id_preview, id_gallery){
|
function check_progressbar(id_part, id_progressbar, id_progressbar_span, id_interrupt, id_preview, id_gallery){
|
||||||
var progressbar = gradioApp().getElementById(id_progressbar)
|
var progressbar = gradioApp().getElementById(id_progressbar)
|
||||||
var skip = id_skip ? gradioApp().getElementById(id_skip) : null
|
|
||||||
var interrupt = gradioApp().getElementById(id_interrupt)
|
var interrupt = gradioApp().getElementById(id_interrupt)
|
||||||
|
|
||||||
if(opts.show_progress_in_title && 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]){
|
if(progressbar!= null && progressbar != global_progressbars[id_progressbar]){
|
||||||
global_progressbars[id_progressbar] = progressbar
|
global_progressbars[id_progressbar] = progressbar
|
||||||
|
|
||||||
@@ -33,37 +17,29 @@ function check_progressbar(id_part, id_progressbar, id_progressbar_span, id_skip
|
|||||||
|
|
||||||
var progressDiv = gradioApp().querySelectorAll('#' + id_progressbar_span).length > 0;
|
var progressDiv = gradioApp().querySelectorAll('#' + id_progressbar_span).length > 0;
|
||||||
if(!progressDiv){
|
if(!progressDiv){
|
||||||
if (skip) {
|
|
||||||
skip.style.display = "none"
|
|
||||||
}
|
|
||||||
interrupt.style.display = "none"
|
interrupt.style.display = "none"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
window.setTimeout(function() { requestMoreProgress(id_part, id_progressbar_span, id_skip, id_interrupt) }, 500)
|
window.setTimeout(function(){ requestMoreProgress(id_part, id_progressbar_span, id_interrupt) }, 500)
|
||||||
});
|
});
|
||||||
mutationObserver.observe( progressbar, { childList:true, subtree:true })
|
mutationObserver.observe( progressbar, { childList:true, subtree:true })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
onUiUpdate(function(){
|
onUiUpdate(function(){
|
||||||
check_progressbar('txt2img', 'txt2img_progressbar', 'txt2img_progress_span', 'txt2img_skip', 'txt2img_interrupt', 'txt2img_preview', 'txt2img_gallery')
|
check_progressbar('txt2img', 'txt2img_progressbar', 'txt2img_progress_span', 'txt2img_interrupt', 'txt2img_preview', 'txt2img_gallery')
|
||||||
check_progressbar('img2img', 'img2img_progressbar', 'img2img_progress_span', 'img2img_skip', 'img2img_interrupt', 'img2img_preview', 'img2img_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_skip, id_interrupt){
|
function requestMoreProgress(id_part, id_progressbar_span, id_interrupt){
|
||||||
btn = gradioApp().getElementById(id_part+"_check_progress");
|
btn = gradioApp().getElementById(id_part+"_check_progress");
|
||||||
if(btn==null) return;
|
if(btn==null) return;
|
||||||
|
|
||||||
btn.click();
|
btn.click();
|
||||||
var progressDiv = gradioApp().querySelectorAll('#' + id_progressbar_span).length > 0;
|
var progressDiv = gradioApp().querySelectorAll('#' + id_progressbar_span).length > 0;
|
||||||
var skip = id_skip ? gradioApp().getElementById(id_skip) : null
|
|
||||||
var interrupt = gradioApp().getElementById(id_interrupt)
|
var interrupt = gradioApp().getElementById(id_interrupt)
|
||||||
if(progressDiv && interrupt){
|
if(progressDiv && interrupt){
|
||||||
if (skip) {
|
|
||||||
skip.style.display = "block"
|
|
||||||
}
|
|
||||||
interrupt.style.display = "block"
|
interrupt.style.display = "block"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
|
|
||||||
|
|
||||||
function start_training_textual_inversion(){
|
|
||||||
requestProgress('ti')
|
|
||||||
gradioApp().querySelector('#ti_error').innerHTML=''
|
|
||||||
|
|
||||||
return args_to_array(arguments)
|
|
||||||
}
|
|
||||||
+3
-50
@@ -1,8 +1,9 @@
|
|||||||
// various functions for interation with ui.py not large enough to warrant putting them in separate files
|
// various functions for interation with ui.py not large enough to warrant putting them in separate files
|
||||||
|
|
||||||
function selected_gallery_index(){
|
function selected_gallery_index(){
|
||||||
var buttons = gradioApp().querySelectorAll('[style="display: block;"].tabitem .gallery-item')
|
var gr = gradioApp()
|
||||||
var button = gradioApp().querySelector('[style="display: block;"].tabitem .gallery-item.\\!ring-2')
|
var buttons = gradioApp().querySelectorAll(".gallery-item")
|
||||||
|
var button = gr.querySelector(".gallery-item.\\!ring-2")
|
||||||
|
|
||||||
var result = -1
|
var result = -1
|
||||||
buttons.forEach(function(v, i){ if(v==button) { result = i } })
|
buttons.forEach(function(v, i){ if(v==button) { result = i } })
|
||||||
@@ -182,52 +183,4 @@ onUiUpdate(function(){
|
|||||||
});
|
});
|
||||||
|
|
||||||
json_elem.parentElement.style.display="none"
|
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)
|
|
||||||
}
|
|
||||||
@@ -1,20 +1,43 @@
|
|||||||
# this scripts installs necessary requirements and launches main program in webui.py
|
# this scripts installs necessary requirements and launches main program in webui.py
|
||||||
|
|
||||||
import subprocess
|
import subprocess
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
import importlib.util
|
import importlib.util
|
||||||
import shlex
|
import shlex
|
||||||
import platform
|
|
||||||
|
|
||||||
dir_repos = "repositories"
|
dir_repos = "repositories"
|
||||||
|
dir_tmp = "tmp"
|
||||||
|
|
||||||
python = sys.executable
|
python = sys.executable
|
||||||
git = os.environ.get('GIT', "git")
|
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', "")
|
||||||
|
|
||||||
|
k_diffusion_package = os.environ.get('K_DIFFUSION_PACKAGE', "git+https://github.com/crowsonkb/k-diffusion.git@1a0703dfb7d24d8806267c3e7ccc4caf67fd1331")
|
||||||
|
gfpgan_package = os.environ.get('GFPGAN_PACKAGE', "git+https://github.com/TencentARC/GFPGAN.git@8d2447a2d918f8eba5a4a01463fd48e45126a379")
|
||||||
|
|
||||||
|
stable_diffusion_commit_hash = os.environ.get('STABLE_DIFFUSION_COMMIT_HASH', "69ae4b35e0a0f6ee1af8bb9a5d0016ccb27e36dc")
|
||||||
|
taming_transformers_commit_hash = os.environ.get('TAMING_TRANSFORMERS_COMMIT_HASH', "24268930bf1dce879235a7fddd0b2355b84d7ea6")
|
||||||
|
codeformer_commit_hash = os.environ.get('CODEFORMER_COMMIT_HASH', "c5b4593074ba6214284d6acd5f1719b6c5d739af")
|
||||||
|
blip_commit_hash = os.environ.get('BLIP_COMMIT_HASH', "48211a1594f1321b00f14c9f7a5b4813144b2fb9")
|
||||||
|
ldsr_commit_hash = os.environ.get('LDSR_COMMIT_HASH',"abf33e7002d59d9085081bce93ec798dcabd49af")
|
||||||
|
|
||||||
|
args = shlex.split(commandline_args)
|
||||||
|
|
||||||
|
|
||||||
def extract_arg(args, name):
|
def extract_arg(args, name):
|
||||||
return [x for x in args if x != name], name in args
|
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):
|
def run(command, desc=None, errdesc=None):
|
||||||
if desc is not None:
|
if desc is not None:
|
||||||
print(desc)
|
print(desc)
|
||||||
@@ -34,11 +57,23 @@ stderr: {result.stderr.decode(encoding="utf8", errors="ignore") if len(result.st
|
|||||||
return result.stdout.decode(encoding="utf8", errors="ignore")
|
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):
|
def check_run(command):
|
||||||
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
|
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
|
||||||
return result.returncode == 0
|
return result.returncode == 0
|
||||||
|
|
||||||
|
|
||||||
|
def check_run_python(code):
|
||||||
|
return check_run(f'"{python}" -c "{code}"')
|
||||||
|
|
||||||
|
|
||||||
def is_installed(package):
|
def is_installed(package):
|
||||||
try:
|
try:
|
||||||
spec = importlib.util.find_spec(package)
|
spec = importlib.util.find_spec(package)
|
||||||
@@ -48,35 +83,10 @@ def is_installed(package):
|
|||||||
return spec is not None
|
return spec is not None
|
||||||
|
|
||||||
|
|
||||||
def repo_dir(name):
|
|
||||||
return os.path.join(dir_repos, name)
|
|
||||||
|
|
||||||
|
|
||||||
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_python(code):
|
|
||||||
return check_run(f'"{python}" -c "{code}"')
|
|
||||||
|
|
||||||
|
|
||||||
def git_clone(url, dir, name, commithash=None):
|
def git_clone(url, dir, name, commithash=None):
|
||||||
# TODO clone into temporary dir and move if successful
|
# TODO clone into temporary dir and move if successful
|
||||||
|
|
||||||
if os.path.exists(dir):
|
if os.path.exists(dir):
|
||||||
if commithash is None:
|
|
||||||
return
|
|
||||||
|
|
||||||
current_hash = run(f'"{git}" -C {dir} rev-parse HEAD', None, f"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
|
return
|
||||||
|
|
||||||
run(f'"{git}" clone "{url}" "{dir}"', f"Cloning {name} into {dir}...", f"Couldn't clone {name}")
|
run(f'"{git}" clone "{url}" "{dir}"', f"Cloning {name} into {dir}...", f"Couldn't clone {name}")
|
||||||
@@ -85,77 +95,42 @@ def git_clone(url, dir, name, commithash=None):
|
|||||||
run(f'"{git}" -C {dir} checkout {commithash}', None, "Couldn't checkout {name}'s hash: {commithash}")
|
run(f'"{git}" -C {dir} checkout {commithash}', None, "Couldn't checkout {name}'s hash: {commithash}")
|
||||||
|
|
||||||
|
|
||||||
def prepare_enviroment():
|
try:
|
||||||
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")
|
commit = run(f"{git} rev-parse HEAD").strip()
|
||||||
requirements_file = os.environ.get('REQS_FILE', "requirements_versions.txt")
|
except Exception:
|
||||||
commandline_args = os.environ.get('COMMANDLINE_ARGS', "")
|
commit = "<none>"
|
||||||
|
|
||||||
gfpgan_package = os.environ.get('GFPGAN_PACKAGE', "git+https://github.com/TencentARC/GFPGAN.git@8d2447a2d918f8eba5a4a01463fd48e45126a379")
|
print(f"Python {sys.version}")
|
||||||
clip_package = os.environ.get('CLIP_PACKAGE', "git+https://github.com/openai/CLIP.git@d50d76daa670286dd6cacf3bcd80b5e4823fc8e1")
|
print(f"Commit hash: {commit}")
|
||||||
|
|
||||||
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)
|
if not is_installed("torch") or not is_installed("torchvision"):
|
||||||
|
run(f'"{python}" -m {torch_command}', "Installing torch and torchvision", "Couldn't install torch")
|
||||||
|
|
||||||
args, skip_torch_cuda_test = extract_arg(args, '--skip-torch-cuda-test')
|
if not skip_torch_cuda_test:
|
||||||
xformers = '--xformers' in args
|
run_python("import torch; assert torch.cuda.is_available(), 'Torch is not able to use GPU; add --skip-torch-cuda-test to COMMANDINE_ARGS variable to disable this check'")
|
||||||
deepdanbooru = '--deepdanbooru' in args
|
|
||||||
ngrok = '--ngrok' in args
|
|
||||||
|
|
||||||
try:
|
if not is_installed("k_diffusion.sampling"):
|
||||||
commit = run(f"{git} rev-parse HEAD").strip()
|
run_pip(f"install {k_diffusion_package}", "k-diffusion")
|
||||||
except Exception:
|
|
||||||
commit = "<none>"
|
|
||||||
|
|
||||||
print(f"Python {sys.version}")
|
if not is_installed("gfpgan"):
|
||||||
print(f"Commit hash: {commit}")
|
run_pip(f"install {gfpgan_package}", "gfpgan")
|
||||||
|
|
||||||
if not is_installed("torch") or not is_installed("torchvision"):
|
os.makedirs(dir_repos, exist_ok=True)
|
||||||
run(f'"{python}" -m {torch_command}', "Installing torch and torchvision", "Couldn't install torch")
|
|
||||||
|
|
||||||
if not skip_torch_cuda_test:
|
git_clone("https://github.com/CompVis/stable-diffusion.git", repo_dir('stable-diffusion'), "Stable Diffusion", stable_diffusion_commit_hash)
|
||||||
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'")
|
git_clone("https://github.com/CompVis/taming-transformers.git", repo_dir('taming-transformers'), "Taming Transformers", taming_transformers_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)
|
||||||
|
# Using my repo until my changes are merged, as this makes interfacing with our version of SD-web a lot easier
|
||||||
|
git_clone("https://github.com/Hafiidz/latent-diffusion", repo_dir('latent-diffusion'), "LDSR", ldsr_commit_hash)
|
||||||
|
|
||||||
if not is_installed("gfpgan"):
|
if not is_installed("lpips"):
|
||||||
run_pip(f"install {gfpgan_package}", "gfpgan")
|
run_pip(f"install -r {os.path.join(repo_dir('CodeFormer'), 'requirements.txt')}", "requirements for CodeFormer")
|
||||||
|
|
||||||
if not is_installed("clip"):
|
run_pip(f"install -r {requirements_file}", "requirements for Web UI")
|
||||||
run_pip(f"install {clip_package}", "clip")
|
|
||||||
|
|
||||||
if not is_installed("xformers") and xformers and platform.python_version().startswith("3.10"):
|
sys.argv += args
|
||||||
if platform.system() == "Windows":
|
|
||||||
run_pip("install https://github.com/C43H66N12O12S2/stable-diffusion-webui/releases/download/c/xformers-0.0.14.dev0-cp310-cp310-win_amd64.whl", "xformers")
|
|
||||||
elif platform.system() == "Linux":
|
|
||||||
run_pip("install xformers", "xformers")
|
|
||||||
|
|
||||||
if not is_installed("deepdanbooru") and deepdanbooru:
|
|
||||||
run_pip("install git+https://github.com/KichangKim/DeepDanbooru.git@edf73df4cdaeea2cf00e9ac08bd8a9026b7a7b26#egg=deepdanbooru[tensorflow] tensorflow==2.10.0 tensorflow-io==0.27.0", "deepdanbooru")
|
|
||||||
|
|
||||||
if not is_installed("pyngrok") and ngrok:
|
|
||||||
run_pip("install pyngrok", "ngrok")
|
|
||||||
|
|
||||||
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():
|
def start_webui():
|
||||||
@@ -163,7 +138,5 @@ def start_webui():
|
|||||||
import webui
|
import webui
|
||||||
webui.webui()
|
webui.webui()
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
prepare_enviroment()
|
|
||||||
start_webui()
|
start_webui()
|
||||||
File renamed without changes.
Whitespace-only changes.
@@ -1,76 +0,0 @@
|
|||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
class UpscalerBSRGAN(modules.upscaler.Upscaler):
|
|
||||||
def __init__(self, dirname):
|
|
||||||
self.name = "BSRGAN"
|
|
||||||
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
|
|
||||||
|
|
||||||
@@ -1,102 +0,0 @@
|
|||||||
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
|
|
||||||
+20
-36
@@ -5,31 +5,31 @@ import traceback
|
|||||||
import cv2
|
import cv2
|
||||||
import torch
|
import torch
|
||||||
|
|
||||||
import modules.face_restoration
|
from modules import shared, devices
|
||||||
|
from modules.paths import script_path
|
||||||
import modules.shared
|
import modules.shared
|
||||||
from modules import shared, devices, modelloader
|
import modules.face_restoration
|
||||||
from modules.paths import script_path, models_path
|
from importlib import reload
|
||||||
|
|
||||||
# codeformer people made a choice to include modified basicsr library to their project which makes
|
# codeformer people made a choice to include modified basicsr librry to their projectwhich makes
|
||||||
# it utterly impossible to use it alongside with other libraries that also use basicsr, like GFPGAN.
|
# it utterly impossiblr 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"
|
|
||||||
model_path = os.path.join(models_path, model_dir)
|
pretrain_model_url = 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth'
|
||||||
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
|
||||||
@@ -44,23 +44,18 @@ def setup_model(dirname):
|
|||||||
def name(self):
|
def name(self):
|
||||||
return "CodeFormer"
|
return "CodeFormer"
|
||||||
|
|
||||||
def __init__(self, dirname):
|
def __init__(self):
|
||||||
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)
|
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')
|
|
||||||
if len(model_paths) != 0:
|
|
||||||
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)
|
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)
|
||||||
|
ckpt_path = load_file_from_url(url=pretrain_model_url, model_dir=os.path.join(path, 'weights/CodeFormer'), progress=True)
|
||||||
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()
|
||||||
@@ -69,25 +64,16 @@ def setup_model(dirname):
|
|||||||
|
|
||||||
self.net = net
|
self.net = net
|
||||||
self.face_helper = face_helper
|
self.face_helper = face_helper
|
||||||
|
self.net.to(devices.device_codeformer)
|
||||||
|
|
||||||
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]
|
||||||
|
|
||||||
original_resolution = np_image.shape[0:2]
|
original_resolution = np_image.shape[0:2]
|
||||||
|
|
||||||
self.create_models()
|
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.clean_all()
|
||||||
self.face_helper.read_image(np_image)
|
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.get_face_landmarks_5(only_center_face=False, resize=640, eye_dist_threshold=5)
|
||||||
@@ -119,10 +105,8 @@ def setup_model(dirname):
|
|||||||
if original_resolution != restored_img.shape[0:2]:
|
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)
|
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:
|
if shared.opts.face_restoration_unload:
|
||||||
self.send_model_to(devices.cpu)
|
self.net.to(devices.cpu)
|
||||||
|
|
||||||
return restored_img
|
return restored_img
|
||||||
|
|
||||||
@@ -130,7 +114,7 @@ def setup_model(dirname):
|
|||||||
have_codeformer = True
|
have_codeformer = True
|
||||||
|
|
||||||
global codeformer
|
global codeformer
|
||||||
codeformer = FaceRestorerCodeFormer(dirname)
|
codeformer = FaceRestorerCodeFormer()
|
||||||
shared.face_restorers.append(codeformer)
|
shared.face_restorers.append(codeformer)
|
||||||
|
|
||||||
except Exception:
|
except Exception:
|
||||||
|
|||||||
@@ -1,73 +0,0 @@
|
|||||||
import os.path
|
|
||||||
from concurrent.futures import ProcessPoolExecutor
|
|
||||||
from multiprocessing import get_context
|
|
||||||
|
|
||||||
|
|
||||||
def _load_tf_and_return_tags(pil_image, threshold):
|
|
||||||
import deepdanbooru as dd
|
|
||||||
import tensorflow as tf
|
|
||||||
import numpy as np
|
|
||||||
|
|
||||||
this_folder = os.path.dirname(__file__)
|
|
||||||
model_path = os.path.abspath(os.path.join(this_folder, '..', 'models', 'deepbooru'))
|
|
||||||
if not os.path.exists(os.path.join(model_path, 'project.json')):
|
|
||||||
# there is no point importing these every time
|
|
||||||
import zipfile
|
|
||||||
from basicsr.utils.download_util import load_file_from_url
|
|
||||||
load_file_from_url(r"https://github.com/KichangKim/DeepDanbooru/releases/download/v3-20211112-sgd-e28/deepdanbooru-v3-20211112-sgd-e28.zip",
|
|
||||||
model_path)
|
|
||||||
with zipfile.ZipFile(os.path.join(model_path, "deepdanbooru-v3-20211112-sgd-e28.zip"), "r") as zip_ref:
|
|
||||||
zip_ref.extractall(model_path)
|
|
||||||
os.remove(os.path.join(model_path, "deepdanbooru-v3-20211112-sgd-e28.zip"))
|
|
||||||
|
|
||||||
tags = dd.project.load_tags_from_project(model_path)
|
|
||||||
model = dd.project.load_model_from_project(
|
|
||||||
model_path, compile_model=True
|
|
||||||
)
|
|
||||||
|
|
||||||
width = model.input_shape[2]
|
|
||||||
height = model.input_shape[1]
|
|
||||||
image = np.array(pil_image)
|
|
||||||
image = tf.image.resize(
|
|
||||||
image,
|
|
||||||
size=(height, width),
|
|
||||||
method=tf.image.ResizeMethod.AREA,
|
|
||||||
preserve_aspect_ratio=True,
|
|
||||||
)
|
|
||||||
image = image.numpy() # EagerTensor to np.array
|
|
||||||
image = dd.image.transform_and_pad_image(image, width, height)
|
|
||||||
image = image / 255.0
|
|
||||||
image_shape = image.shape
|
|
||||||
image = image.reshape((1, image_shape[0], image_shape[1], image_shape[2]))
|
|
||||||
|
|
||||||
y = model.predict(image)[0]
|
|
||||||
|
|
||||||
result_dict = {}
|
|
||||||
|
|
||||||
for i, tag in enumerate(tags):
|
|
||||||
result_dict[tag] = y[i]
|
|
||||||
result_tags_out = []
|
|
||||||
result_tags_print = []
|
|
||||||
for tag in tags:
|
|
||||||
if result_dict[tag] >= threshold:
|
|
||||||
if tag.startswith("rating:"):
|
|
||||||
continue
|
|
||||||
result_tags_out.append(tag)
|
|
||||||
result_tags_print.append(f'{result_dict[tag]} {tag}')
|
|
||||||
|
|
||||||
print('\n'.join(sorted(result_tags_print, reverse=True)))
|
|
||||||
|
|
||||||
return ', '.join(result_tags_out).replace('_', ' ').replace(':', ' ')
|
|
||||||
|
|
||||||
|
|
||||||
def subprocess_init_no_cuda():
|
|
||||||
import os
|
|
||||||
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
|
|
||||||
|
|
||||||
|
|
||||||
def get_deepbooru_tags(pil_image, threshold=0.5):
|
|
||||||
context = get_context('spawn')
|
|
||||||
with ProcessPoolExecutor(initializer=subprocess_init_no_cuda, mp_context=context) as executor:
|
|
||||||
f = executor.submit(_load_tf_and_return_tags, pil_image, threshold, )
|
|
||||||
ret = f.result() # will rethrow any exceptions
|
|
||||||
return ret
|
|
||||||
+5
-17
@@ -1,10 +1,8 @@
|
|||||||
import contextlib
|
|
||||||
|
|
||||||
import torch
|
import torch
|
||||||
|
|
||||||
|
# has_mps is only available in nightly pytorch (for now), `getattr` for compatibility
|
||||||
from modules import errors
|
from modules import errors
|
||||||
|
|
||||||
# has_mps is only available in nightly pytorch (for now), `getattr` for compatibility
|
|
||||||
has_mps = getattr(torch, 'has_mps', False)
|
has_mps = getattr(torch, 'has_mps', False)
|
||||||
|
|
||||||
cpu = torch.device("cpu")
|
cpu = torch.device("cpu")
|
||||||
@@ -34,9 +32,10 @@ def enable_tf32():
|
|||||||
|
|
||||||
errors.run(enable_tf32, "Enabling TF32")
|
errors.run(enable_tf32, "Enabling TF32")
|
||||||
|
|
||||||
device = device_gfpgan = device_bsrgan = device_esrgan = device_scunet = device_codeformer = get_optimal_device()
|
|
||||||
dtype = torch.float16
|
device = get_optimal_device()
|
||||||
dtype_vae = torch.float16
|
device_codeformer = cpu if has_mps else device
|
||||||
|
|
||||||
|
|
||||||
def randn(seed, shape):
|
def randn(seed, shape):
|
||||||
# Pytorch currently doesn't handle setting randomness correctly when the metal backend is used.
|
# Pytorch currently doesn't handle setting randomness correctly when the metal backend is used.
|
||||||
@@ -59,14 +58,3 @@ def randn_without_seed(shape):
|
|||||||
|
|
||||||
return torch.randn(shape, device=device)
|
return torch.randn(shape, device=device)
|
||||||
|
|
||||||
|
|
||||||
def autocast(disable=False):
|
|
||||||
from modules import shared
|
|
||||||
|
|
||||||
if disable:
|
|
||||||
return contextlib.nullcontext()
|
|
||||||
|
|
||||||
if dtype == torch.float32 or shared.cmd_opts.precision == "full":
|
|
||||||
return contextlib.nullcontext()
|
|
||||||
|
|
||||||
return torch.autocast("cuda")
|
|
||||||
File renamed without changes.
+45
-62
@@ -1,20 +1,26 @@
|
|||||||
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.esrgan_model_arch as arch
|
import modules.esrgam_model_arch as arch
|
||||||
from modules import shared, modelloader, images, devices
|
from modules import shared
|
||||||
from modules.upscaler import Upscaler, UpscalerData
|
|
||||||
from modules.shared import opts
|
from modules.shared import opts
|
||||||
|
from modules.devices import has_mps
|
||||||
|
import modules.images
|
||||||
|
|
||||||
|
|
||||||
def fix_model_layers(crt_model, pretrained_net):
|
def load_model(filename):
|
||||||
# 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, map_location='cpu' if has_mps else None)
|
||||||
|
crt_model = arch.RRDBNet(3, 3, 64, 23, gc=32)
|
||||||
|
|
||||||
if 'conv_first.weight' in pretrained_net:
|
if 'conv_first.weight' in pretrained_net:
|
||||||
return pretrained_net
|
crt_model.load_state_dict(pretrained_net)
|
||||||
|
return crt_model
|
||||||
|
|
||||||
if 'model.0.weight' not in pretrained_net:
|
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"]
|
is_realesrgan = "params_ema" in pretrained_net and 'body.0.rdb1.conv1.weight' in pretrained_net["params_ema"]
|
||||||
@@ -66,65 +72,16 @@ def fix_model_layers(crt_model, pretrained_net):
|
|||||||
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']
|
||||||
|
|
||||||
return crt_net
|
crt_model.load_state_dict(crt_net)
|
||||||
|
crt_model.eval()
|
||||||
class UpscalerESRGAN(Upscaler):
|
return crt_model
|
||||||
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
|
|
||||||
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 devices.device_esrgan.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()
|
|
||||||
|
|
||||||
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(devices.device_esrgan)
|
img = img.unsqueeze(0).to(shared.device)
|
||||||
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()
|
||||||
@@ -138,7 +95,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 = images.split_grid(img, opts.ESRGAN_tile, opts.ESRGAN_tile, opts.ESRGAN_tile_overlap)
|
grid = modules.images.split_grid(img, opts.ESRGAN_tile, opts.ESRGAN_tile, opts.ESRGAN_tile_overlap)
|
||||||
newtiles = []
|
newtiles = []
|
||||||
scale_factor = 1
|
scale_factor = 1
|
||||||
|
|
||||||
@@ -153,6 +110,32 @@ 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 = 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 = 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)
|
||||||
output = images.combine_grid(newgrid)
|
output = modules.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)
|
||||||
+3
-78
@@ -3,17 +3,13 @@ import os
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
|
|
||||||
import torch
|
from modules import processing, shared, images, devices
|
||||||
import tqdm
|
|
||||||
|
|
||||||
from modules import processing, shared, images, devices, sd_models
|
|
||||||
from modules.shared import opts
|
from modules.shared import opts
|
||||||
import modules.gfpgan_model
|
import modules.gfpgan_model
|
||||||
from modules.ui import plaintext_to_html
|
from modules.ui import plaintext_to_html
|
||||||
import modules.codeformer_model
|
import modules.codeformer_model
|
||||||
import piexif
|
import piexif
|
||||||
import piexif.helper
|
import piexif.helper
|
||||||
import gradio as gr
|
|
||||||
|
|
||||||
|
|
||||||
cached_images = {}
|
cached_images = {}
|
||||||
@@ -29,7 +25,7 @@ def run_extras(extras_mode, image, image_folder, gfpgan_visibility, codeformer_v
|
|||||||
if extras_mode == 1:
|
if extras_mode == 1:
|
||||||
#convert file to pillow image
|
#convert file to pillow image
|
||||||
for img in image_folder:
|
for img in image_folder:
|
||||||
image = Image.open(img)
|
image = Image.fromarray(np.array(Image.open(img)))
|
||||||
imageArr.append(image)
|
imageArr.append(image)
|
||||||
imageNameArr.append(os.path.splitext(img.orig_name)[0])
|
imageNameArr.append(os.path.splitext(img.orig_name)[0])
|
||||||
else:
|
else:
|
||||||
@@ -40,8 +36,6 @@ def run_extras(extras_mode, image, image_folder, gfpgan_visibility, codeformer_v
|
|||||||
|
|
||||||
outputs = []
|
outputs = []
|
||||||
for image, image_name in zip(imageArr, imageNameArr):
|
for image, image_name in zip(imageArr, imageNameArr):
|
||||||
if image is None:
|
|
||||||
return outputs, "Please select an input image.", ''
|
|
||||||
existing_pnginfo = image.info or {}
|
existing_pnginfo = image.info or {}
|
||||||
|
|
||||||
image = image.convert("RGB")
|
image = image.convert("RGB")
|
||||||
@@ -76,7 +70,7 @@ def run_extras(extras_mode, image, image_folder, gfpgan_visibility, codeformer_v
|
|||||||
c = cached_images.get(key)
|
c = cached_images.get(key)
|
||||||
if c is None:
|
if c is None:
|
||||||
upscaler = shared.sd_upscalers[scaler_index]
|
upscaler = shared.sd_upscalers[scaler_index]
|
||||||
c = upscaler.scaler.upscale(image, resize, upscaler.data_path)
|
c = upscaler.upscale(image, image.width * resize, image.height * resize)
|
||||||
cached_images[key] = c
|
cached_images[key] = c
|
||||||
|
|
||||||
return c
|
return c
|
||||||
@@ -98,14 +92,8 @@ def run_extras(extras_mode, image, image_folder, gfpgan_visibility, codeformer_v
|
|||||||
no_prompt=True, grid=False, pnginfo_section_name="extras", existing_info=existing_pnginfo,
|
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)
|
forced_filename=image_name if opts.use_original_name_batch else None)
|
||||||
|
|
||||||
if opts.enable_pnginfo:
|
|
||||||
image.info = existing_pnginfo
|
|
||||||
image.info["extras"] = info
|
|
||||||
|
|
||||||
outputs.append(image)
|
outputs.append(image)
|
||||||
|
|
||||||
devices.torch_gc()
|
|
||||||
|
|
||||||
return outputs, plaintext_to_html(info), ''
|
return outputs, plaintext_to_html(info), ''
|
||||||
|
|
||||||
|
|
||||||
@@ -147,66 +135,3 @@ def run_pnginfo(image):
|
|||||||
info = f"<div><p>{message}<p></div>"
|
info = f"<div><p>{message}<p></div>"
|
||||||
|
|
||||||
return '', geninfo, info
|
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 = sd_models.get_state_dict_from_checkpoint(primary_model)
|
|
||||||
theta_1 = sd_models.get_state_dict_from_checkpoint(secondary_model)
|
|
||||||
|
|
||||||
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)]
|
|
||||||
+45
-65
@@ -1,105 +1,81 @@
|
|||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
import traceback
|
import traceback
|
||||||
|
from glob import glob
|
||||||
|
|
||||||
import facexlib
|
from modules import shared, devices
|
||||||
import gfpgan
|
from modules.shared import cmd_opts
|
||||||
|
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"
|
|
||||||
user_path = None
|
def gfpgan_model_path():
|
||||||
model_path = os.path.join(models_path, model_dir)
|
from modules.shared import cmd_opts
|
||||||
model_url = "https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth"
|
|
||||||
have_gfpgan = False
|
filemask = 'GFPGAN*.pth'
|
||||||
|
|
||||||
|
if cmd_opts.gfpgan_model is not None:
|
||||||
|
return cmd_opts.gfpgan_model
|
||||||
|
|
||||||
|
places = [script_path, '.', os.path.join(cmd_opts.gfpgan_dir, 'experiments/pretrained_models')]
|
||||||
|
|
||||||
|
filename = None
|
||||||
|
for place in places:
|
||||||
|
filename = next(iter(glob(os.path.join(place, filemask))), None)
|
||||||
|
if filename is not None:
|
||||||
|
break
|
||||||
|
|
||||||
|
return filename
|
||||||
|
|
||||||
|
|
||||||
loaded_gfpgan_model = None
|
loaded_gfpgan_model = None
|
||||||
|
|
||||||
|
|
||||||
def gfpgann():
|
def gfpgan():
|
||||||
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)
|
loaded_gfpgan_model.gfpgan.to(shared.device)
|
||||||
return loaded_gfpgan_model
|
return loaded_gfpgan_model
|
||||||
|
|
||||||
if gfpgan_constructor is None:
|
if gfpgan_constructor is None:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
models = modelloader.load_models(model_path, model_url, user_path, ext_filter="GFPGAN")
|
model = gfpgan_constructor(model_path=gfpgan_model_path() or 'https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth', upscale=1, arch='clean', channel_multiplier=2, bg_upsampler=None)
|
||||||
if len(models) == 1 and "http" in models[0]:
|
model.gfpgan.to(shared.device)
|
||||||
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()
|
model = gfpgan()
|
||||||
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 = model.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:
|
if shared.opts.face_restoration_unload:
|
||||||
send_model_to(model, devices.cpu)
|
model.gfpgan.to(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
|
||||||
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
|
have_gfpgan = True
|
||||||
|
|
||||||
|
global gfpgan_constructor
|
||||||
gfpgan_constructor = GFPGANer
|
gfpgan_constructor = GFPGANer
|
||||||
|
|
||||||
class FaceRestorerGFPGAN(modules.face_restoration.FaceRestoration):
|
class FaceRestorerGFPGAN(modules.face_restoration.FaceRestoration):
|
||||||
@@ -107,7 +83,11 @@ def setup_model(dirname):
|
|||||||
return "GFPGAN"
|
return "GFPGAN"
|
||||||
|
|
||||||
def restore(self, np_image):
|
def restore(self, np_image):
|
||||||
return gfpgan_fix_faces(np_image)
|
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)
|
||||||
|
np_image = gfpgan_output_bgr[:, :, ::-1]
|
||||||
|
|
||||||
|
return np_image
|
||||||
|
|
||||||
shared.face_restorers.append(FaceRestorerGFPGAN())
|
shared.face_restorers.append(FaceRestorerGFPGAN())
|
||||||
except Exception:
|
except Exception:
|
||||||
|
|||||||
@@ -1,283 +0,0 @@
|
|||||||
import datetime
|
|
||||||
import glob
|
|
||||||
import html
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import traceback
|
|
||||||
import tqdm
|
|
||||||
|
|
||||||
import torch
|
|
||||||
|
|
||||||
from ldm.util import default
|
|
||||||
from modules import devices, shared, processing, sd_models
|
|
||||||
import torch
|
|
||||||
from torch import einsum
|
|
||||||
from einops import rearrange, repeat
|
|
||||||
import modules.textual_inversion.dataset
|
|
||||||
|
|
||||||
|
|
||||||
class HypernetworkModule(torch.nn.Module):
|
|
||||||
def __init__(self, dim, state_dict=None):
|
|
||||||
super().__init__()
|
|
||||||
|
|
||||||
self.linear1 = torch.nn.Linear(dim, dim * 2)
|
|
||||||
self.linear2 = torch.nn.Linear(dim * 2, dim)
|
|
||||||
|
|
||||||
if state_dict is not None:
|
|
||||||
self.load_state_dict(state_dict, strict=True)
|
|
||||||
else:
|
|
||||||
|
|
||||||
self.linear1.weight.data.normal_(mean=0.0, std=0.01)
|
|
||||||
self.linear1.bias.data.zero_()
|
|
||||||
self.linear2.weight.data.normal_(mean=0.0, std=0.01)
|
|
||||||
self.linear2.bias.data.zero_()
|
|
||||||
|
|
||||||
self.to(devices.device)
|
|
||||||
|
|
||||||
def forward(self, x):
|
|
||||||
return x + (self.linear2(self.linear1(x)))
|
|
||||||
|
|
||||||
|
|
||||||
class Hypernetwork:
|
|
||||||
filename = None
|
|
||||||
name = None
|
|
||||||
|
|
||||||
def __init__(self, name=None):
|
|
||||||
self.filename = None
|
|
||||||
self.name = name
|
|
||||||
self.layers = {}
|
|
||||||
self.step = 0
|
|
||||||
self.sd_checkpoint = None
|
|
||||||
self.sd_checkpoint_name = None
|
|
||||||
|
|
||||||
for size in [320, 640, 768, 1280]:
|
|
||||||
self.layers[size] = (HypernetworkModule(size), HypernetworkModule(size))
|
|
||||||
|
|
||||||
def weights(self):
|
|
||||||
res = []
|
|
||||||
|
|
||||||
for k, layers in self.layers.items():
|
|
||||||
for layer in layers:
|
|
||||||
layer.train()
|
|
||||||
res += [layer.linear1.weight, layer.linear1.bias, layer.linear2.weight, layer.linear2.bias]
|
|
||||||
|
|
||||||
return res
|
|
||||||
|
|
||||||
def save(self, filename):
|
|
||||||
state_dict = {}
|
|
||||||
|
|
||||||
for k, v in self.layers.items():
|
|
||||||
state_dict[k] = (v[0].state_dict(), v[1].state_dict())
|
|
||||||
|
|
||||||
state_dict['step'] = self.step
|
|
||||||
state_dict['name'] = self.name
|
|
||||||
state_dict['sd_checkpoint'] = self.sd_checkpoint
|
|
||||||
state_dict['sd_checkpoint_name'] = self.sd_checkpoint_name
|
|
||||||
|
|
||||||
torch.save(state_dict, filename)
|
|
||||||
|
|
||||||
def load(self, filename):
|
|
||||||
self.filename = filename
|
|
||||||
if self.name is None:
|
|
||||||
self.name = os.path.splitext(os.path.basename(filename))[0]
|
|
||||||
|
|
||||||
state_dict = torch.load(filename, map_location='cpu')
|
|
||||||
|
|
||||||
for size, sd in state_dict.items():
|
|
||||||
if type(size) == int:
|
|
||||||
self.layers[size] = (HypernetworkModule(size, sd[0]), HypernetworkModule(size, sd[1]))
|
|
||||||
|
|
||||||
self.name = state_dict.get('name', self.name)
|
|
||||||
self.step = state_dict.get('step', 0)
|
|
||||||
self.sd_checkpoint = state_dict.get('sd_checkpoint', None)
|
|
||||||
self.sd_checkpoint_name = state_dict.get('sd_checkpoint_name', None)
|
|
||||||
|
|
||||||
|
|
||||||
def list_hypernetworks(path):
|
|
||||||
res = {}
|
|
||||||
for filename in glob.iglob(os.path.join(path, '**/*.pt'), recursive=True):
|
|
||||||
name = os.path.splitext(os.path.basename(filename))[0]
|
|
||||||
res[name] = filename
|
|
||||||
return res
|
|
||||||
|
|
||||||
|
|
||||||
def load_hypernetwork(filename):
|
|
||||||
path = shared.hypernetworks.get(filename, None)
|
|
||||||
if path is not None:
|
|
||||||
print(f"Loading hypernetwork {filename}")
|
|
||||||
try:
|
|
||||||
shared.loaded_hypernetwork = Hypernetwork()
|
|
||||||
shared.loaded_hypernetwork.load(path)
|
|
||||||
|
|
||||||
except Exception:
|
|
||||||
print(f"Error loading hypernetwork {path}", file=sys.stderr)
|
|
||||||
print(traceback.format_exc(), file=sys.stderr)
|
|
||||||
else:
|
|
||||||
if shared.loaded_hypernetwork is not None:
|
|
||||||
print(f"Unloading hypernetwork")
|
|
||||||
|
|
||||||
shared.loaded_hypernetwork = None
|
|
||||||
|
|
||||||
|
|
||||||
def apply_hypernetwork(hypernetwork, context, layer=None):
|
|
||||||
hypernetwork_layers = (hypernetwork.layers if hypernetwork is not None else {}).get(context.shape[2], None)
|
|
||||||
|
|
||||||
if hypernetwork_layers is None:
|
|
||||||
return context, context
|
|
||||||
|
|
||||||
if layer is not None:
|
|
||||||
layer.hyper_k = hypernetwork_layers[0]
|
|
||||||
layer.hyper_v = hypernetwork_layers[1]
|
|
||||||
|
|
||||||
context_k = hypernetwork_layers[0](context)
|
|
||||||
context_v = hypernetwork_layers[1](context)
|
|
||||||
return context_k, context_v
|
|
||||||
|
|
||||||
|
|
||||||
def attention_CrossAttention_forward(self, x, context=None, mask=None):
|
|
||||||
h = self.heads
|
|
||||||
|
|
||||||
q = self.to_q(x)
|
|
||||||
context = default(context, x)
|
|
||||||
|
|
||||||
context_k, context_v = apply_hypernetwork(shared.loaded_hypernetwork, context, self)
|
|
||||||
k = self.to_k(context_k)
|
|
||||||
v = self.to_v(context_v)
|
|
||||||
|
|
||||||
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
|
|
||||||
|
|
||||||
sim = einsum('b i d, b j d -> b i j', q, k) * self.scale
|
|
||||||
|
|
||||||
if mask is not None:
|
|
||||||
mask = rearrange(mask, 'b ... -> b (...)')
|
|
||||||
max_neg_value = -torch.finfo(sim.dtype).max
|
|
||||||
mask = repeat(mask, 'b j -> (b h) () j', h=h)
|
|
||||||
sim.masked_fill_(~mask, max_neg_value)
|
|
||||||
|
|
||||||
# attention, what we cannot get enough of
|
|
||||||
attn = sim.softmax(dim=-1)
|
|
||||||
|
|
||||||
out = einsum('b i j, b j d -> b i d', attn, v)
|
|
||||||
out = rearrange(out, '(b h) n d -> b n (h d)', h=h)
|
|
||||||
return self.to_out(out)
|
|
||||||
|
|
||||||
|
|
||||||
def train_hypernetwork(hypernetwork_name, learn_rate, data_root, log_directory, steps, create_image_every, save_hypernetwork_every, template_file, preview_image_prompt):
|
|
||||||
assert hypernetwork_name, 'embedding not selected'
|
|
||||||
|
|
||||||
path = shared.hypernetworks.get(hypernetwork_name, None)
|
|
||||||
shared.loaded_hypernetwork = Hypernetwork()
|
|
||||||
shared.loaded_hypernetwork.load(path)
|
|
||||||
|
|
||||||
shared.state.textinfo = "Initializing hypernetwork training..."
|
|
||||||
shared.state.job_count = steps
|
|
||||||
|
|
||||||
filename = os.path.join(shared.cmd_opts.hypernetwork_dir, f'{hypernetwork_name}.pt')
|
|
||||||
|
|
||||||
log_directory = os.path.join(log_directory, datetime.datetime.now().strftime("%Y-%m-%d"), hypernetwork_name)
|
|
||||||
|
|
||||||
if save_hypernetwork_every > 0:
|
|
||||||
hypernetwork_dir = os.path.join(log_directory, "hypernetworks")
|
|
||||||
os.makedirs(hypernetwork_dir, exist_ok=True)
|
|
||||||
else:
|
|
||||||
hypernetwork_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, width=512, height=512, repeats=1, placeholder_token=hypernetwork_name, model=shared.sd_model, device=devices.device, template_file=template_file)
|
|
||||||
|
|
||||||
hypernetwork = shared.loaded_hypernetwork
|
|
||||||
weights = hypernetwork.weights()
|
|
||||||
for weight in weights:
|
|
||||||
weight.requires_grad = True
|
|
||||||
|
|
||||||
optimizer = torch.optim.AdamW(weights, lr=learn_rate)
|
|
||||||
|
|
||||||
losses = torch.zeros((32,))
|
|
||||||
|
|
||||||
last_saved_file = "<none>"
|
|
||||||
last_saved_image = "<none>"
|
|
||||||
|
|
||||||
ititial_step = hypernetwork.step or 0
|
|
||||||
if ititial_step > steps:
|
|
||||||
return hypernetwork, filename
|
|
||||||
|
|
||||||
pbar = tqdm.tqdm(enumerate(ds), total=steps - ititial_step)
|
|
||||||
for i, (x, text) in pbar:
|
|
||||||
hypernetwork.step = i + ititial_step
|
|
||||||
|
|
||||||
if hypernetwork.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[hypernetwork.step % losses.shape[0]] = loss.item()
|
|
||||||
|
|
||||||
optimizer.zero_grad()
|
|
||||||
loss.backward()
|
|
||||||
optimizer.step()
|
|
||||||
|
|
||||||
pbar.set_description(f"loss: {losses.mean():.7f}")
|
|
||||||
|
|
||||||
if hypernetwork.step > 0 and hypernetwork_dir is not None and hypernetwork.step % save_hypernetwork_every == 0:
|
|
||||||
last_saved_file = os.path.join(hypernetwork_dir, f'{hypernetwork_name}-{hypernetwork.step}.pt')
|
|
||||||
hypernetwork.save(last_saved_file)
|
|
||||||
|
|
||||||
if hypernetwork.step > 0 and images_dir is not None and hypernetwork.step % create_image_every == 0:
|
|
||||||
last_saved_image = os.path.join(images_dir, f'{hypernetwork_name}-{hypernetwork.step}.png')
|
|
||||||
|
|
||||||
preview_text = text if preview_image_prompt == "" else preview_image_prompt
|
|
||||||
|
|
||||||
p = processing.StableDiffusionProcessingTxt2Img(
|
|
||||||
sd_model=shared.sd_model,
|
|
||||||
prompt=preview_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: {preview_text}"
|
|
||||||
|
|
||||||
shared.state.job_no = hypernetwork.step
|
|
||||||
|
|
||||||
shared.state.textinfo = f"""
|
|
||||||
<p>
|
|
||||||
Loss: {losses.mean():.7f}<br/>
|
|
||||||
Step: {hypernetwork.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()
|
|
||||||
|
|
||||||
hypernetwork.sd_checkpoint = checkpoint.hash
|
|
||||||
hypernetwork.sd_checkpoint_name = checkpoint.model_name
|
|
||||||
hypernetwork.save(filename)
|
|
||||||
|
|
||||||
return hypernetwork, filename
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
import html
|
|
||||||
import os
|
|
||||||
|
|
||||||
import gradio as gr
|
|
||||||
|
|
||||||
import modules.textual_inversion.textual_inversion
|
|
||||||
import modules.textual_inversion.preprocess
|
|
||||||
from modules import sd_hijack, shared
|
|
||||||
from modules.hypernetworks import hypernetwork
|
|
||||||
|
|
||||||
|
|
||||||
def create_hypernetwork(name):
|
|
||||||
fn = os.path.join(shared.cmd_opts.hypernetwork_dir, f"{name}.pt")
|
|
||||||
assert not os.path.exists(fn), f"file {fn} already exists"
|
|
||||||
|
|
||||||
hypernet = modules.hypernetworks.hypernetwork.Hypernetwork(name=name)
|
|
||||||
hypernet.save(fn)
|
|
||||||
|
|
||||||
shared.reload_hypernetworks()
|
|
||||||
|
|
||||||
return gr.Dropdown.update(choices=sorted([x for x in shared.hypernetworks.keys()])), f"Created: {fn}", ""
|
|
||||||
|
|
||||||
|
|
||||||
def train_hypernetwork(*args):
|
|
||||||
|
|
||||||
initial_hypernetwork = shared.loaded_hypernetwork
|
|
||||||
|
|
||||||
try:
|
|
||||||
sd_hijack.undo_optimizations()
|
|
||||||
|
|
||||||
hypernetwork, filename = modules.hypernetworks.hypernetwork.train_hypernetwork(*args)
|
|
||||||
|
|
||||||
res = f"""
|
|
||||||
Training {'interrupted' if shared.state.interrupted else 'finished'} at {hypernetwork.step} steps.
|
|
||||||
Hypernetwork saved to {html.escape(filename)}
|
|
||||||
"""
|
|
||||||
return res, ""
|
|
||||||
except Exception:
|
|
||||||
raise
|
|
||||||
finally:
|
|
||||||
shared.loaded_hypernetwork = initial_hypernetwork
|
|
||||||
sd_hijack.apply_optimizations()
|
|
||||||
|
|
||||||
+57
-89
@@ -11,6 +11,7 @@ from PIL import Image, ImageFont, ImageDraw, PngImagePlugin
|
|||||||
from fonts.ttf import Roboto
|
from fonts.ttf import Roboto
|
||||||
import string
|
import string
|
||||||
|
|
||||||
|
import modules.shared
|
||||||
from modules import sd_samplers, shared
|
from modules import sd_samplers, shared
|
||||||
from modules.shared import opts, cmd_opts
|
from modules.shared import opts, cmd_opts
|
||||||
|
|
||||||
@@ -51,8 +52,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):
|
||||||
@@ -66,7 +67,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))
|
||||||
@@ -131,7 +132,7 @@ 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
|
||||||
|
|
||||||
@@ -170,8 +171,7 @@ 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_text_heights = [sum([line.size[1] + line_spacing for line in lines]) - line_spacing * len(lines) for lines in ver_texts]
|
||||||
ver_texts]
|
|
||||||
|
|
||||||
pad_top = max(hor_text_heights) + line_spacing * 2
|
pad_top = max(hor_text_heights) + line_spacing * 2
|
||||||
|
|
||||||
@@ -213,19 +213,8 @@ def resize_image(resize_mode, im, width, height):
|
|||||||
if opts.upscaler_for_img2img is None or opts.upscaler_for_img2img == "None" or im.mode == 'L':
|
if opts.upscaler_for_img2img is None or opts.upscaler_for_img2img == "None" or im.mode == 'L':
|
||||||
return im.resize((w, h), resample=LANCZOS)
|
return im.resize((w, h), resample=LANCZOS)
|
||||||
|
|
||||||
scale = max(w / im.width, h / im.height)
|
upscaler = [x for x in shared.sd_upscalers if x.name == opts.upscaler_for_img2img][0]
|
||||||
|
return upscaler.upscale(im, w, h)
|
||||||
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 = resize(im, width, height)
|
res = resize(im, width, height)
|
||||||
@@ -267,7 +256,7 @@ def resize_image(resize_mode, im, width, height):
|
|||||||
invalid_filename_chars = '<>:"/\\|?*\n'
|
invalid_filename_chars = '<>:"/\\|?*\n'
|
||||||
invalid_filename_prefix = ' '
|
invalid_filename_prefix = ' '
|
||||||
invalid_filename_postfix = ' .'
|
invalid_filename_postfix = ' .'
|
||||||
re_nonletters = re.compile(r'[\s' + string.punctuation + ']+')
|
re_nonletters = re.compile(r'[\s'+string.punctuation+']+')
|
||||||
max_filename_part_length = 128
|
max_filename_part_length = 128
|
||||||
|
|
||||||
|
|
||||||
@@ -287,32 +276,8 @@ def apply_filename_pattern(x, p, seed, prompt):
|
|||||||
if seed is not None:
|
if seed is not None:
|
||||||
x = x.replace("[seed]", str(seed))
|
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))
|
|
||||||
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]", getattr(p, "sd_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]", getattr(p, "job_timestamp", shared.state.job_timestamp))
|
|
||||||
|
|
||||||
# Apply [prompt] at last. Because it may contain any replacement word.^M
|
|
||||||
if prompt is not None:
|
if prompt is not None:
|
||||||
x = x.replace("[prompt]", sanitize_filename_part(prompt))
|
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))
|
x = x.replace("[prompt_spaces]", sanitize_filename_part(prompt, replace_spaces=False))
|
||||||
if "[prompt_words]" in x:
|
if "[prompt_words]" in x:
|
||||||
words = [x for x in re_nonletters.split(prompt or "") if len(x) > 0]
|
words = [x for x in re_nonletters.split(prompt or "") if len(x) > 0]
|
||||||
@@ -320,12 +285,24 @@ def apply_filename_pattern(x, p, seed, prompt):
|
|||||||
words = ["empty"]
|
words = ["empty"]
|
||||||
x = x.replace("[prompt_words]", sanitize_filename_part(" ".join(words[0:max_prompt_words]), replace_spaces=False))
|
x = x.replace("[prompt_words]", sanitize_filename_part(" ".join(words[0:max_prompt_words]), replace_spaces=False))
|
||||||
|
|
||||||
|
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))
|
||||||
|
x = x.replace("[styles]", sanitize_filename_part(", ".join(p.styles), 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)
|
||||||
|
|
||||||
if cmd_opts.hide_ui_dir_config:
|
if cmd_opts.hide_ui_dir_config:
|
||||||
x = re.sub(r'^[\\/]+|\.{2,}[\\/]+|[\\/]+\.{2,}', '', x)
|
x = re.sub(r'^[\\/]+|\.{2,}[\\/]+|[\\/]+\.{2,}', '', x)
|
||||||
|
|
||||||
return x
|
return x
|
||||||
|
|
||||||
|
|
||||||
def get_next_sequence_number(path, basename):
|
def get_next_sequence_number(path, basename):
|
||||||
"""
|
"""
|
||||||
Determines and returns the next sequence number to use when saving an image in the specified directory.
|
Determines and returns the next sequence number to use when saving an image in the specified directory.
|
||||||
@@ -339,7 +316,7 @@ def get_next_sequence_number(path, basename):
|
|||||||
prefix_length = len(basename)
|
prefix_length = len(basename)
|
||||||
for p in os.listdir(path):
|
for p in os.listdir(path):
|
||||||
if p.startswith(basename):
|
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)
|
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:
|
try:
|
||||||
result = max(int(l[0]), result)
|
result = max(int(l[0]), result)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
@@ -347,40 +324,7 @@ def get_next_sequence_number(path, basename):
|
|||||||
|
|
||||||
return result + 1
|
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=""):
|
||||||
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="", save_to_dirs=None):
|
|
||||||
'''Save an image.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
image (`PIL.Image`):
|
|
||||||
The image to be saved.
|
|
||||||
path (`str`):
|
|
||||||
The directory to save the image. Note, the option `save_to_dirs` will make the image to be saved into a sub directory.
|
|
||||||
basename (`str`):
|
|
||||||
The base filename which will be applied to `filename pattern`.
|
|
||||||
seed, prompt, short_filename,
|
|
||||||
extension (`str`):
|
|
||||||
Image file extension, default is `png`.
|
|
||||||
pngsectionname (`str`):
|
|
||||||
Specify the name of the section which `info` will be saved in.
|
|
||||||
info (`str` or `PngImagePlugin.iTXt`):
|
|
||||||
PNG info chunks.
|
|
||||||
existing_info (`dict`):
|
|
||||||
Additional PNG info. `existing_info == {pngsectionname: info, ...}`
|
|
||||||
no_prompt:
|
|
||||||
TODO I don't know its meaning.
|
|
||||||
p (`StableDiffusionProcessing`)
|
|
||||||
forced_filename (`str`):
|
|
||||||
If specified, `basename` and filename pattern will be ignored.
|
|
||||||
save_to_dirs (bool):
|
|
||||||
If true, the image will be saved into a subdirectory of `path`.
|
|
||||||
|
|
||||||
Returns: (fullfn, txt_fullfn)
|
|
||||||
fullfn (`str`):
|
|
||||||
The full path of the saved imaged.
|
|
||||||
txt_fullfn (`str` or None):
|
|
||||||
If a text file is saved for this image, this will be its full path. Otherwise None.
|
|
||||||
'''
|
|
||||||
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:
|
||||||
@@ -404,11 +348,10 @@ def save_image(image, path, basename, seed=None, prompt=None, extension='png', i
|
|||||||
else:
|
else:
|
||||||
pnginfo = None
|
pnginfo = None
|
||||||
|
|
||||||
if save_to_dirs is None:
|
save_to_dirs = (grid and opts.grid_save_to_dirs) or (not grid and 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)
|
|
||||||
|
|
||||||
if save_to_dirs:
|
if save_to_dirs:
|
||||||
dirname = apply_filename_pattern(opts.directories_filename_pattern or "[prompt_words]", p, seed, prompt).strip('\\ /')
|
dirname = apply_filename_pattern(opts.directories_filename_pattern or "[prompt_words]", p, seed, prompt)
|
||||||
path = os.path.join(path, dirname)
|
path = os.path.join(path, dirname)
|
||||||
|
|
||||||
os.makedirs(path, exist_ok=True)
|
os.makedirs(path, exist_ok=True)
|
||||||
@@ -418,7 +361,7 @@ def save_image(image, path, basename, seed=None, prompt=None, extension='png', i
|
|||||||
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"{basecount + i:05}" if basename == '' else f"{basename}-{basecount + 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):
|
||||||
@@ -456,10 +399,35 @@ def save_image(image, path, basename, seed=None, prompt=None, extension='png', i
|
|||||||
piexif.insert(exif_bytes(), fullfn_without_extension + ".jpg")
|
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:
|
||||||
txt_fullfn = f"{fullfn_without_extension}.txt"
|
with open(f"{fullfn_without_extension}.txt", "w", encoding="utf8") as file:
|
||||||
with open(txt_fullfn, "w", encoding="utf8") as file:
|
|
||||||
file.write(info + "\n")
|
file.write(info + "\n")
|
||||||
else:
|
|
||||||
txt_fullfn = None
|
|
||||||
|
|
||||||
return fullfn, txt_fullfn
|
|
||||||
|
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((int(w), int(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())
|
||||||
+3
-13
@@ -23,17 +23,13 @@ def process_batch(p, input_dir, output_dir, args):
|
|||||||
|
|
||||||
print(f"Will process {len(images)} images, creating {p.n_iter * p.batch_size} new images for each.")
|
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_grid = True
|
||||||
p.do_not_save_samples = not save_normally
|
p.do_not_save_samples = True
|
||||||
|
|
||||||
state.job_count = len(images) * p.n_iter
|
state.job_count = len(images) * p.n_iter
|
||||||
|
|
||||||
for i, image in enumerate(images):
|
for i, image in enumerate(images):
|
||||||
state.job = f"{i+1} out of {len(images)}"
|
state.job = f"{i+1} out of {len(images)}"
|
||||||
if state.skipped:
|
|
||||||
state.skipped = False
|
|
||||||
|
|
||||||
if state.interrupted:
|
if state.interrupted:
|
||||||
break
|
break
|
||||||
@@ -52,8 +48,7 @@ def process_batch(p, input_dir, output_dir, args):
|
|||||||
left, right = os.path.splitext(filename)
|
left, right = os.path.splitext(filename)
|
||||||
filename = f"{left}-{n}{right}"
|
filename = f"{left}-{n}{right}"
|
||||||
|
|
||||||
if not save_normally:
|
processed_image.save(os.path.join(output_dir, filename))
|
||||||
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):
|
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):
|
||||||
@@ -108,9 +103,7 @@ def img2img(mode: int, prompt: str, negative_prompt: str, prompt_style: str, pro
|
|||||||
inpaint_full_res_padding=inpaint_full_res_padding,
|
inpaint_full_res_padding=inpaint_full_res_padding,
|
||||||
inpainting_mask_invert=inpainting_mask_invert,
|
inpainting_mask_invert=inpainting_mask_invert,
|
||||||
)
|
)
|
||||||
|
print(f"\nimg2img: {prompt}", file=shared.progress_print_out)
|
||||||
if shared.cmd_opts.enable_console_prompts:
|
|
||||||
print(f"\nimg2img: {prompt}", file=shared.progress_print_out)
|
|
||||||
|
|
||||||
p.extra_generation_params["Mask blur"] = mask_blur
|
p.extra_generation_params["Mask blur"] = mask_blur
|
||||||
|
|
||||||
@@ -131,7 +124,4 @@ def img2img(mode: int, prompt: str, negative_prompt: str, prompt_style: str, pro
|
|||||||
if opts.samples_log_stdout:
|
if opts.samples_log_stdout:
|
||||||
print(generation_info_js)
|
print(generation_info_js)
|
||||||
|
|
||||||
if opts.do_not_show_images:
|
|
||||||
processed.images = []
|
|
||||||
|
|
||||||
return processed.images, generation_info_js, plaintext_to_html(processed.info)
|
return processed.images, generation_info_js, plaintext_to_html(processed.info)
|
||||||
@@ -21,7 +21,6 @@ Category = namedtuple("Category", ["name", "topn", "items"])
|
|||||||
|
|
||||||
re_topn = re.compile(r"\.top(\d+)\.")
|
re_topn = re.compile(r"\.top(\d+)\.")
|
||||||
|
|
||||||
|
|
||||||
class InterrogateModels:
|
class InterrogateModels:
|
||||||
blip_model = None
|
blip_model = None
|
||||||
clip_model = None
|
clip_model = None
|
||||||
@@ -140,11 +139,11 @@ class InterrogateModels:
|
|||||||
|
|
||||||
res = caption
|
res = caption
|
||||||
|
|
||||||
clip_image = self.clip_preprocess(pil_image).unsqueeze(0).type(self.dtype).to(shared.device)
|
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
|
precision_scope = torch.autocast if shared.cmd_opts.precision == "autocast" else contextlib.nullcontext
|
||||||
with torch.no_grad(), precision_scope("cuda"):
|
with torch.no_grad(), precision_scope("cuda"):
|
||||||
image_features = self.clip_model.encode_image(clip_image).type(self.dtype)
|
image_features = self.clip_model.encode_image(cilp_image).type(self.dtype)
|
||||||
|
|
||||||
image_features /= image_features.norm(dim=-1, keepdim=True)
|
image_features /= image_features.norm(dim=-1, keepdim=True)
|
||||||
|
|
||||||
|
|||||||
+53
-40
@@ -1,54 +1,67 @@
|
|||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
import traceback
|
import traceback
|
||||||
|
from collections import namedtuple
|
||||||
|
|
||||||
from basicsr.utils.download_util import load_file_from_url
|
from basicsr.utils.download_util import load_file_from_url
|
||||||
|
|
||||||
from modules.upscaler import Upscaler, UpscalerData
|
import modules.images
|
||||||
from modules.ldsr_model_arch import LDSR
|
|
||||||
from modules import shared
|
from modules import shared
|
||||||
|
from modules.paths import script_path
|
||||||
|
|
||||||
|
LDSRModelInfo = namedtuple("LDSRModelInfo", ["name", "location", "model", "netscale"])
|
||||||
|
|
||||||
|
ldsr_models = []
|
||||||
|
have_ldsr = False
|
||||||
|
LDSR_obj = None
|
||||||
|
|
||||||
|
|
||||||
class UpscalerLDSR(Upscaler):
|
class UpscalerLDSR(modules.images.Upscaler):
|
||||||
def __init__(self, user_path):
|
def __init__(self, steps):
|
||||||
|
self.steps = steps
|
||||||
self.name = "LDSR"
|
self.name = "LDSR"
|
||||||
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):
|
def do_upscale(self, img):
|
||||||
# Remove incorrect project.yaml file if too big
|
return upscale_with_ldsr(img)
|
||||||
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:
|
def add_lsdr():
|
||||||
print("Error importing LDSR:", file=sys.stderr)
|
modules.shared.sd_upscalers.append(UpscalerLDSR(100))
|
||||||
print(traceback.format_exc(), file=sys.stderr)
|
|
||||||
return None
|
|
||||||
|
|
||||||
def do_upscale(self, img, path):
|
|
||||||
ldsr = self.load_model(path)
|
def setup_ldsr():
|
||||||
if ldsr is None:
|
path = modules.paths.paths.get("LDSR", None)
|
||||||
print("NO LDSR!")
|
if path is None:
|
||||||
return img
|
return
|
||||||
ddim_steps = shared.opts.ldsr_steps
|
global have_ldsr
|
||||||
return ldsr.super_resolution(img, ddim_steps, self.scale)
|
global LDSR_obj
|
||||||
|
try:
|
||||||
|
from LDSR import LDSR
|
||||||
|
model_url = "https://heibox.uni-heidelberg.de/f/578df07c8fc04ffbadf3/?dl=1"
|
||||||
|
yaml_url = "https://heibox.uni-heidelberg.de/f/31a76b13ea27482981b4/?dl=1"
|
||||||
|
repo_path = 'latent-diffusion/experiments/pretrained_models/'
|
||||||
|
model_path = load_file_from_url(url=model_url, model_dir=os.path.join("repositories", repo_path),
|
||||||
|
progress=True, file_name="model.chkpt")
|
||||||
|
yaml_path = load_file_from_url(url=yaml_url, model_dir=os.path.join("repositories", repo_path),
|
||||||
|
progress=True, file_name="project.yaml")
|
||||||
|
have_ldsr = True
|
||||||
|
LDSR_obj = LDSR(model_path, yaml_path)
|
||||||
|
|
||||||
|
|
||||||
|
except Exception:
|
||||||
|
print("Error importing LDSR:", file=sys.stderr)
|
||||||
|
print(traceback.format_exc(), file=sys.stderr)
|
||||||
|
have_ldsr = False
|
||||||
|
|
||||||
|
|
||||||
|
def upscale_with_ldsr(image):
|
||||||
|
setup_ldsr()
|
||||||
|
if not have_ldsr or LDSR_obj is None:
|
||||||
|
return image
|
||||||
|
|
||||||
|
ddim_steps = shared.opts.ldsr_steps
|
||||||
|
pre_scale = shared.opts.ldsr_pre_down
|
||||||
|
post_scale = shared.opts.ldsr_post_down
|
||||||
|
|
||||||
|
image = LDSR_obj.super_resolution(image, ddim_steps, pre_scale, post_scale)
|
||||||
|
return image
|
||||||
@@ -1,222 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -1,153 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
from pyngrok import ngrok, conf, exception
|
|
||||||
|
|
||||||
|
|
||||||
def connect(token, port):
|
|
||||||
if token == None:
|
|
||||||
token = 'None'
|
|
||||||
conf.get_default().auth_token = token
|
|
||||||
try:
|
|
||||||
public_url = ngrok.connect(port).public_url
|
|
||||||
except exception.PyngrokNgrokError:
|
|
||||||
print(f'Invalid ngrok authtoken, ngrok connection aborted.\n'
|
|
||||||
f'Your token: {token}, get the right one on https://dashboard.ngrok.com/get-started/your-authtoken')
|
|
||||||
else:
|
|
||||||
print(f'ngrok connected to localhost:{port}! URL: {public_url}\n'
|
|
||||||
'You can use this link after the launch is complete.')
|
|
||||||
+8
-14
@@ -1,40 +1,34 @@
|
|||||||
import argparse
|
import argparse
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
import modules.safe
|
|
||||||
|
|
||||||
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 diffusion in following places
|
# search for directory of stable diffsuion in following palces
|
||||||
sd_path = None
|
sd_path = None
|
||||||
possible_sd_paths = [os.path.join(script_path, 'repositories/stable-diffusion'), '.', os.path.dirname(script_path)]
|
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)
|
||||||
break
|
|
||||||
|
|
||||||
assert sd_path is not None, "Couldn't find Stable Diffusion in any of: " + str(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, '../BLIP'), 'models/blip.py', 'BLIP'),
|
||||||
(os.path.join(sd_path, '../k-diffusion'), 'k_diffusion/sampling.py', 'k_diffusion', ["atstart"]),
|
(os.path.join(sd_path, '../latent-diffusion'), 'LDSR.py', 'LDSR'),
|
||||||
]
|
]
|
||||||
|
|
||||||
paths = {}
|
paths = {}
|
||||||
|
|
||||||
for d, must_exist, what, options in path_dirs:
|
for d, must_exist, what 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.append(d)
|
||||||
sys.path.insert(0, d)
|
|
||||||
else:
|
|
||||||
sys.path.append(d)
|
|
||||||
paths[what] = d
|
paths[what] = d
|
||||||
+40
-126
@@ -1,3 +1,4 @@
|
|||||||
|
import contextlib
|
||||||
import json
|
import json
|
||||||
import math
|
import math
|
||||||
import os
|
import os
|
||||||
@@ -11,8 +12,9 @@ import cv2
|
|||||||
from skimage import exposure
|
from skimage import exposure
|
||||||
|
|
||||||
import modules.sd_hijack
|
import modules.sd_hijack
|
||||||
from modules import devices, prompt_parser, masking, sd_samplers, lowvram
|
from modules import devices, prompt_parser, masking
|
||||||
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
|
||||||
@@ -46,21 +48,15 @@ def apply_color_correction(correction, image):
|
|||||||
return image
|
return image
|
||||||
|
|
||||||
|
|
||||||
def get_correct_sampler(p):
|
|
||||||
if isinstance(p, modules.processing.StableDiffusionProcessingTxt2Img):
|
|
||||||
return sd_samplers.samplers
|
|
||||||
elif isinstance(p, modules.processing.StableDiffusionProcessingImg2Img):
|
|
||||||
return sd_samplers.samplers_for_img2img
|
|
||||||
|
|
||||||
class StableDiffusionProcessing:
|
class StableDiffusionProcessing:
|
||||||
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):
|
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):
|
||||||
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.styles: str = styles
|
||||||
self.seed: int = seed
|
self.seed: int = seed
|
||||||
self.subseed: int = subseed
|
self.subseed: int = subseed
|
||||||
self.subseed_strength: float = subseed_strength
|
self.subseed_strength: float = subseed_strength
|
||||||
@@ -79,16 +75,9 @@ class StableDiffusionProcessing:
|
|||||||
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 or {}
|
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.color_corrections = None
|
||||||
self.denoising_strength: float = 0
|
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
|
|
||||||
|
|
||||||
if not seed_enable_extras:
|
if not seed_enable_extras:
|
||||||
self.subseed = -1
|
self.subseed = -1
|
||||||
@@ -104,7 +93,7 @@ class StableDiffusionProcessing:
|
|||||||
|
|
||||||
|
|
||||||
class Processed:
|
class Processed:
|
||||||
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):
|
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):
|
||||||
self.images = images_list
|
self.images = images_list
|
||||||
self.prompt = p.prompt
|
self.prompt = p.prompt
|
||||||
self.negative_prompt = p.negative_prompt
|
self.negative_prompt = p.negative_prompt
|
||||||
@@ -115,7 +104,7 @@ class Processed:
|
|||||||
self.width = p.width
|
self.width = p.width
|
||||||
self.height = p.height
|
self.height = p.height
|
||||||
self.sampler_index = p.sampler_index
|
self.sampler_index = p.sampler_index
|
||||||
self.sampler = sd_samplers.samplers[p.sampler_index].name
|
self.sampler = 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.batch_size = p.batch_size
|
||||||
@@ -127,17 +116,7 @@ class Processed:
|
|||||||
self.denoising_strength = getattr(p, 'denoising_strength', None)
|
self.denoising_strength = getattr(p, 'denoising_strength', None)
|
||||||
self.extra_generation_params = p.extra_generation_params
|
self.extra_generation_params = p.extra_generation_params
|
||||||
self.index_of_first_image = index_of_first_image
|
self.index_of_first_image = index_of_first_image
|
||||||
self.styles = p.styles
|
|
||||||
self.job_timestamp = state.job_timestamp
|
|
||||||
self.clip_skip = opts.CLIP_stop_at_last_layers
|
|
||||||
|
|
||||||
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.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.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.seed = int(self.seed if type(self.seed) != list else self.seed[0])
|
||||||
@@ -146,7 +125,6 @@ class Processed:
|
|||||||
self.all_prompts = all_prompts or [self.prompt]
|
self.all_prompts = all_prompts or [self.prompt]
|
||||||
self.all_seeds = all_seeds or [self.seed]
|
self.all_seeds = all_seeds or [self.seed]
|
||||||
self.all_subseeds = all_subseeds or [self.subseed]
|
self.all_subseeds = all_subseeds or [self.subseed]
|
||||||
self.infotexts = infotexts or [info]
|
|
||||||
|
|
||||||
def js(self):
|
def js(self):
|
||||||
obj = {
|
obj = {
|
||||||
@@ -173,10 +151,6 @@ class Processed:
|
|||||||
"denoising_strength": self.denoising_strength,
|
"denoising_strength": self.denoising_strength,
|
||||||
"extra_generation_params": self.extra_generation_params,
|
"extra_generation_params": self.extra_generation_params,
|
||||||
"index_of_first_image": self.index_of_first_image,
|
"index_of_first_image": self.index_of_first_image,
|
||||||
"infotexts": self.infotexts,
|
|
||||||
"styles": self.styles,
|
|
||||||
"job_timestamp": self.job_timestamp,
|
|
||||||
"clip_skip": self.clip_skip,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return json.dumps(obj)
|
return json.dumps(obj)
|
||||||
@@ -207,7 +181,7 @@ def create_random_tensors(shape, seeds, subseeds=None, subseed_strength=0.0, see
|
|||||||
# enables the generation of additional tensors with noise that the sampler will use during its processing.
|
# 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
|
# 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].
|
# 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 or opts.eta_noise_seed_delta > 0):
|
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))]
|
sampler_noises = [[] for _ in range(p.sampler.number_of_needed_noises(p))]
|
||||||
else:
|
else:
|
||||||
sampler_noises = None
|
sampler_noises = None
|
||||||
@@ -247,9 +221,6 @@ def create_random_tensors(shape, seeds, subseeds=None, subseed_strength=0.0, see
|
|||||||
if sampler_noises is not None:
|
if sampler_noises is not None:
|
||||||
cnt = p.sampler.number_of_needed_noises(p)
|
cnt = p.sampler.number_of_needed_noises(p)
|
||||||
|
|
||||||
if opts.eta_noise_seed_delta > 0:
|
|
||||||
torch.manual_seed(seed + opts.eta_noise_seed_delta)
|
|
||||||
|
|
||||||
for j in range(cnt):
|
for j in range(cnt):
|
||||||
sampler_noises[j].append(devices.randn_without_seed(tuple(noise_shape)))
|
sampler_noises[j].append(devices.randn_without_seed(tuple(noise_shape)))
|
||||||
|
|
||||||
@@ -262,49 +233,28 @@ def create_random_tensors(shape, seeds, subseeds=None, subseed_strength=0.0, see
|
|||||||
return x
|
return x
|
||||||
|
|
||||||
|
|
||||||
def decode_first_stage(model, x):
|
|
||||||
with devices.autocast(disable=x.dtype == devices.dtype_vae):
|
|
||||||
x = model.decode_first_stage(x)
|
|
||||||
|
|
||||||
return x
|
|
||||||
|
|
||||||
|
|
||||||
def get_fixed_seed(seed):
|
|
||||||
if seed is None or seed == '' or seed == -1:
|
|
||||||
return int(random.randrange(4294967294))
|
|
||||||
|
|
||||||
return seed
|
|
||||||
|
|
||||||
|
|
||||||
def fix_seed(p):
|
def fix_seed(p):
|
||||||
p.seed = get_fixed_seed(p.seed)
|
p.seed = int(random.randrange(4294967294)) if p.seed is None or p.seed == '' or p.seed == -1 else p.seed
|
||||||
p.subseed = get_fixed_seed(p.subseed)
|
p.subseed = int(random.randrange(4294967294)) if p.subseed is None or p.subseed == '' or p.subseed == -1 else p.subseed
|
||||||
|
|
||||||
|
|
||||||
def create_infotext(p, all_prompts, all_seeds, all_subseeds, comments, iteration=0, position_in_batch=0):
|
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
|
index = position_in_batch + iteration * p.batch_size
|
||||||
|
|
||||||
clip_skip = getattr(p, 'clip_skip', opts.CLIP_stop_at_last_layers)
|
|
||||||
|
|
||||||
generation_params = {
|
generation_params = {
|
||||||
"Steps": p.steps,
|
"Steps": p.steps,
|
||||||
"Sampler": get_correct_sampler(p)[p.sampler_index].name,
|
"Sampler": samplers[p.sampler_index].name,
|
||||||
"CFG scale": p.cfg_scale,
|
"CFG scale": p.cfg_scale,
|
||||||
"Seed": all_seeds[index],
|
"Seed": all_seeds[index],
|
||||||
"Face restoration": (opts.face_restoration_model if p.restore_faces else None),
|
"Face restoration": (opts.face_restoration_model if p.restore_faces else None),
|
||||||
"Size": f"{p.width}x{p.height}",
|
"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),
|
"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),
|
||||||
"Model": (None if not opts.add_model_name_to_info or not shared.sd_model.sd_checkpoint_info.model_name else shared.sd_model.sd_checkpoint_info.model_name.replace(',', '').replace(':', '')),
|
|
||||||
"Hypernet": (None if shared.loaded_hypernetwork is None else shared.loaded_hypernetwork.name.replace(',', '').replace(':', '')),
|
|
||||||
"Batch size": (None if p.batch_size < 2 else p.batch_size),
|
"Batch size": (None if p.batch_size < 2 else p.batch_size),
|
||||||
"Batch pos": (None if p.batch_size < 2 else position_in_batch),
|
"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": (None if p.subseed_strength == 0 else all_subseeds[index]),
|
||||||
"Variation seed strength": (None if p.subseed_strength == 0 else p.subseed_strength),
|
"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}"),
|
"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),
|
"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),
|
|
||||||
"Clip skip": None if clip_skip <= 1 else clip_skip,
|
|
||||||
"ENSD": None if opts.eta_noise_seed_delta == 0 else opts.eta_noise_seed_delta,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
generation_params.update(p.extra_generation_params)
|
generation_params.update(p.extra_generation_params)
|
||||||
@@ -313,7 +263,7 @@ def create_infotext(p, all_prompts, all_seeds, all_subseeds, comments, iteration
|
|||||||
|
|
||||||
negative_prompt_text = "\nNegative prompt: " + p.negative_prompt if p.negative_prompt else ""
|
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()
|
return f"{all_prompts[index]}{negative_prompt_text}\n{generation_params_text}".strip() + "".join(["\n\n" + x for x in comments])
|
||||||
|
|
||||||
|
|
||||||
def process_images(p: StableDiffusionProcessing) -> Processed:
|
def process_images(p: StableDiffusionProcessing) -> Processed:
|
||||||
@@ -326,17 +276,12 @@ def process_images(p: StableDiffusionProcessing) -> Processed:
|
|||||||
|
|
||||||
devices.torch_gc()
|
devices.torch_gc()
|
||||||
|
|
||||||
seed = get_fixed_seed(p.seed)
|
fix_seed(p)
|
||||||
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)
|
os.makedirs(p.outpath_grids, exist_ok=True)
|
||||||
|
|
||||||
if p.outpath_grids is not None:
|
|
||||||
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)
|
||||||
modules.sd_hijack.model_hijack.clear_comments()
|
|
||||||
|
|
||||||
comments = {}
|
comments = {}
|
||||||
|
|
||||||
@@ -347,36 +292,32 @@ def process_images(p: StableDiffusionProcessing) -> Processed:
|
|||||||
else:
|
else:
|
||||||
all_prompts = p.batch_size * p.n_iter * [p.prompt]
|
all_prompts = p.batch_size * p.n_iter * [p.prompt]
|
||||||
|
|
||||||
if type(seed) == list:
|
if type(p.seed) == list:
|
||||||
all_seeds = seed
|
all_seeds = p.seed
|
||||||
else:
|
else:
|
||||||
all_seeds = [int(seed) + (x if p.subseed_strength == 0 else 0) for x in range(len(all_prompts))]
|
all_seeds = [int(p.seed) + (x if p.subseed_strength == 0 else 0) for x in range(len(all_prompts))]
|
||||||
|
|
||||||
if type(subseed) == list:
|
if type(p.subseed) == list:
|
||||||
all_subseeds = subseed
|
all_subseeds = p.subseed
|
||||||
else:
|
else:
|
||||||
all_subseeds = [int(subseed) + x for x in range(len(all_prompts))]
|
all_subseeds = [int(p.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):
|
||||||
return create_infotext(p, all_prompts, all_seeds, all_subseeds, comments, iteration, position_in_batch)
|
return create_infotext(p, all_prompts, all_seeds, all_subseeds, comments, iteration, position_in_batch)
|
||||||
|
|
||||||
if os.path.exists(cmd_opts.embeddings_dir):
|
if os.path.exists(cmd_opts.embeddings_dir):
|
||||||
model_hijack.embedding_db.load_textual_inversion_embeddings()
|
model_hijack.load_textual_inversion_embeddings(cmd_opts.embeddings_dir, p.sd_model)
|
||||||
|
|
||||||
infotexts = []
|
|
||||||
output_images = []
|
output_images = []
|
||||||
|
precision_scope = torch.autocast if cmd_opts.precision == "autocast" else contextlib.nullcontext
|
||||||
with torch.no_grad(), p.sd_model.ema_scope():
|
ema_scope = (contextlib.nullcontext if cmd_opts.lowvram else p.sd_model.ema_scope)
|
||||||
with devices.autocast():
|
with torch.no_grad(), precision_scope("cuda"), ema_scope():
|
||||||
p.init(all_prompts, all_seeds, all_subseeds)
|
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
|
||||||
|
|
||||||
for n in range(p.n_iter):
|
for n in range(p.n_iter):
|
||||||
if state.skipped:
|
|
||||||
state.skipped = False
|
|
||||||
|
|
||||||
if state.interrupted:
|
if state.interrupted:
|
||||||
break
|
break
|
||||||
|
|
||||||
@@ -389,9 +330,8 @@ def process_images(p: StableDiffusionProcessing) -> Processed:
|
|||||||
|
|
||||||
#uc = p.sd_model.get_learned_conditioning(len(prompts) * [p.negative_prompt])
|
#uc = p.sd_model.get_learned_conditioning(len(prompts) * [p.negative_prompt])
|
||||||
#c = p.sd_model.get_learned_conditioning(prompts)
|
#c = p.sd_model.get_learned_conditioning(prompts)
|
||||||
with devices.autocast():
|
uc = prompt_parser.get_learned_conditioning(len(prompts) * [p.negative_prompt], p.steps)
|
||||||
uc = prompt_parser.get_learned_conditioning(shared.sd_model, len(prompts) * [p.negative_prompt], p.steps)
|
c = prompt_parser.get_learned_conditioning(prompts, 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:
|
||||||
for comment in model_hijack.comments:
|
for comment in model_hijack.comments:
|
||||||
@@ -400,26 +340,16 @@ def process_images(p: StableDiffusionProcessing) -> Processed:
|
|||||||
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}"
|
||||||
|
|
||||||
with devices.autocast():
|
samples_ddim = p.sample(conditioning=c, unconditional_conditioning=uc, seeds=seeds, subseeds=subseeds, subseed_strength=p.subseed_strength)
|
||||||
samples_ddim = p.sample(conditioning=c, unconditional_conditioning=uc, seeds=seeds, subseeds=subseeds, subseed_strength=p.subseed_strength)
|
if state.interrupted:
|
||||||
|
|
||||||
if state.interrupted or state.skipped:
|
# if we are interruped, sample returns just noise
|
||||||
|
|
||||||
# if we are interrupted, 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_vae)
|
x_samples_ddim = p.sd_model.decode_first_stage(samples_ddim)
|
||||||
x_samples_ddim = decode_first_stage(p.sd_model, 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)
|
||||||
|
|
||||||
del samples_ddim
|
|
||||||
|
|
||||||
if shared.cmd_opts.lowvram or shared.cmd_opts.medvram:
|
|
||||||
lowvram.send_everything_to_cpu()
|
|
||||||
|
|
||||||
devices.torch_gc()
|
|
||||||
|
|
||||||
if opts.filter_nsfw:
|
if opts.filter_nsfw:
|
||||||
import modules.safety as safety
|
import modules.safety as safety
|
||||||
x_samples_ddim = modules.safety.censor_batch(x_samples_ddim)
|
x_samples_ddim = modules.safety.censor_batch(x_samples_ddim)
|
||||||
@@ -435,7 +365,6 @@ def process_images(p: StableDiffusionProcessing) -> Processed:
|
|||||||
devices.torch_gc()
|
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)
|
||||||
|
|
||||||
@@ -461,16 +390,8 @@ def process_images(p: StableDiffusionProcessing) -> Processed:
|
|||||||
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), p=p)
|
images.save_image(image, p.outpath_samples, "", seeds[i], prompts[i], opts.samples_format, info=infotext(n, i), p=p)
|
||||||
|
|
||||||
text = infotext(n, i)
|
|
||||||
infotexts.append(text)
|
|
||||||
if opts.enable_pnginfo:
|
|
||||||
image.info["parameters"] = text
|
|
||||||
output_images.append(image)
|
output_images.append(image)
|
||||||
|
|
||||||
del x_samples_ddim
|
|
||||||
|
|
||||||
devices.torch_gc()
|
|
||||||
|
|
||||||
state.nextjob()
|
state.nextjob()
|
||||||
|
|
||||||
p.color_corrections = None
|
p.color_corrections = None
|
||||||
@@ -481,18 +402,14 @@ def process_images(p: StableDiffusionProcessing) -> Processed:
|
|||||||
grid = images.image_grid(output_images, p.batch_size)
|
grid = images.image_grid(output_images, p.batch_size)
|
||||||
|
|
||||||
if opts.return_grid:
|
if opts.return_grid:
|
||||||
text = infotext()
|
|
||||||
infotexts.insert(0, text)
|
|
||||||
if opts.enable_pnginfo:
|
|
||||||
grid.info["parameters"] = text
|
|
||||||
output_images.insert(0, grid)
|
output_images.insert(0, grid)
|
||||||
index_of_first_image = 1
|
index_of_first_image = 1
|
||||||
|
|
||||||
if opts.grid_save:
|
if opts.grid_save:
|
||||||
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)
|
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)
|
||||||
|
|
||||||
devices.torch_gc()
|
devices.torch_gc()
|
||||||
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)
|
return Processed(p, output_images, all_seeds[0], infotext(), subseed=all_subseeds[0], all_prompts=all_prompts, all_seeds=all_seeds, all_subseeds=all_subseeds, index_of_first_image=index_of_first_image)
|
||||||
|
|
||||||
|
|
||||||
class StableDiffusionProcessingTxt2Img(StableDiffusionProcessing):
|
class StableDiffusionProcessingTxt2Img(StableDiffusionProcessing):
|
||||||
@@ -525,7 +442,7 @@ class StableDiffusionProcessingTxt2Img(StableDiffusionProcessing):
|
|||||||
self.firstphase_height_truncated = int(scale * self.height)
|
self.firstphase_height_truncated = int(scale * self.height)
|
||||||
|
|
||||||
def sample(self, conditioning, unconditional_conditioning, seeds, subseeds, subseed_strength):
|
def sample(self, conditioning, unconditional_conditioning, seeds, subseeds, subseed_strength):
|
||||||
self.sampler = sd_samplers.create_sampler_with_index(sd_samplers.samplers, self.sampler_index, self.sd_model)
|
self.sampler = samplers[self.sampler_index].constructor(self.sd_model)
|
||||||
|
|
||||||
if not self.enable_hr:
|
if not self.enable_hr:
|
||||||
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)
|
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)
|
||||||
@@ -543,7 +460,7 @@ class StableDiffusionProcessingTxt2Img(StableDiffusionProcessing):
|
|||||||
if self.scale_latent:
|
if self.scale_latent:
|
||||||
samples = torch.nn.functional.interpolate(samples, size=(self.height // opt_f, self.width // opt_f), mode="bilinear")
|
samples = torch.nn.functional.interpolate(samples, size=(self.height // opt_f, self.width // opt_f), mode="bilinear")
|
||||||
else:
|
else:
|
||||||
decoded_samples = decode_first_stage(self.sd_model, samples)
|
decoded_samples = self.sd_model.decode_first_stage(samples)
|
||||||
|
|
||||||
if opts.upscaler_for_img2img is None or opts.upscaler_for_img2img == "None":
|
if opts.upscaler_for_img2img is None or opts.upscaler_for_img2img == "None":
|
||||||
decoded_samples = torch.nn.functional.interpolate(decoded_samples, size=(self.height, self.width), mode="bilinear")
|
decoded_samples = torch.nn.functional.interpolate(decoded_samples, size=(self.height, self.width), mode="bilinear")
|
||||||
@@ -555,7 +472,8 @@ class StableDiffusionProcessingTxt2Img(StableDiffusionProcessing):
|
|||||||
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)
|
||||||
image = Image.fromarray(x_sample)
|
image = Image.fromarray(x_sample)
|
||||||
image = images.resize_image(0, image, self.width, self.height)
|
upscaler = [x for x in shared.sd_upscalers if x.name == opts.upscaler_for_img2img][0]
|
||||||
|
image = upscaler.upscale(image, self.width, self.height)
|
||||||
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)
|
||||||
batch_images.append(image)
|
batch_images.append(image)
|
||||||
@@ -568,8 +486,7 @@ class StableDiffusionProcessingTxt2Img(StableDiffusionProcessing):
|
|||||||
|
|
||||||
shared.state.nextjob()
|
shared.state.nextjob()
|
||||||
|
|
||||||
self.sampler = sd_samplers.create_sampler_with_index(sd_samplers.samplers, self.sampler_index, self.sd_model)
|
self.sampler = samplers[self.sampler_index].constructor(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)
|
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
|
# GC now before running the next img2img to prevent running out of memory
|
||||||
@@ -604,7 +521,7 @@ class StableDiffusionProcessingImg2Img(StableDiffusionProcessing):
|
|||||||
self.nmask = None
|
self.nmask = None
|
||||||
|
|
||||||
def init(self, all_prompts, all_seeds, all_subseeds):
|
def init(self, all_prompts, all_seeds, all_subseeds):
|
||||||
self.sampler = sd_samplers.create_sampler_with_index(sd_samplers.samplers_for_img2img, self.sampler_index, self.sd_model)
|
self.sampler = samplers_for_img2img[self.sampler_index].constructor(self.sd_model)
|
||||||
crop_region = None
|
crop_region = None
|
||||||
|
|
||||||
if self.image_mask is not None:
|
if self.image_mask is not None:
|
||||||
@@ -711,7 +628,4 @@ class StableDiffusionProcessingImg2Img(StableDiffusionProcessing):
|
|||||||
if self.mask is not None:
|
if self.mask is not None:
|
||||||
samples = samples * self.nmask + self.init_latent * self.mask
|
samples = samples * self.nmask + self.init_latent * self.mask
|
||||||
|
|
||||||
del x
|
|
||||||
devices.torch_gc()
|
|
||||||
|
|
||||||
return samples
|
return samples
|
||||||
+75
-311
@@ -1,7 +1,19 @@
|
|||||||
import re
|
import re
|
||||||
from collections import namedtuple
|
from collections import namedtuple
|
||||||
from typing import List
|
import torch
|
||||||
import lark
|
|
||||||
|
import modules.shared as shared
|
||||||
|
|
||||||
|
re_prompt = re.compile(r'''
|
||||||
|
(.*?)
|
||||||
|
\[
|
||||||
|
([^]:]+):
|
||||||
|
(?:([^]:]*):)?
|
||||||
|
([0-9]*\.?[0-9]+)
|
||||||
|
]
|
||||||
|
|
|
||||||
|
(.+)
|
||||||
|
''', re.X)
|
||||||
|
|
||||||
# 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]"
|
# 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):
|
# will be represented with prompt_schedule like this (assuming steps=100):
|
||||||
@@ -11,117 +23,71 @@ import lark
|
|||||||
# [75, 'fantasy landscape with a lake and an oak 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']
|
# [100, 'fantasy landscape with a lake and a christmas tree in background masterful']
|
||||||
|
|
||||||
schedule_parser = lark.Lark(r"""
|
|
||||||
!start: (prompt | /[][():]/+)*
|
|
||||||
prompt: (emphasized | scheduled | alternate | plain | WHITESPACE)*
|
|
||||||
!emphasized: "(" prompt ")"
|
|
||||||
| "(" prompt ":" prompt ")"
|
|
||||||
| "[" prompt "]"
|
|
||||||
scheduled: "[" [prompt ":"] prompt ":" [WHITESPACE] NUMBER "]"
|
|
||||||
alternate: "[" prompt ("|" prompt)+ "]"
|
|
||||||
WHITESPACE: /\s+/
|
|
||||||
plain: /([^\\\[\]():|]|\\.)+/
|
|
||||||
%import common.SIGNED_NUMBER -> NUMBER
|
|
||||||
""")
|
|
||||||
|
|
||||||
def get_learned_conditioning_prompt_schedules(prompts, steps):
|
def get_learned_conditioning_prompt_schedules(prompts, steps):
|
||||||
"""
|
res = []
|
||||||
>>> g = lambda p: get_learned_conditioning_prompt_schedules([p], 10)[0]
|
cache = {}
|
||||||
>>> 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):
|
for prompt in prompts:
|
||||||
l = [steps]
|
prompt_schedule: list[list[str | int]] = [[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])
|
|
||||||
def alternate(self, tree):
|
|
||||||
l.extend(range(1, steps+1))
|
|
||||||
CollectSteps().visit(tree)
|
|
||||||
return sorted(set(l))
|
|
||||||
|
|
||||||
def at_step(step, tree):
|
cached = cache.get(prompt, None)
|
||||||
class AtStep(lark.Transformer):
|
if cached is not None:
|
||||||
def scheduled(self, args):
|
res.append(cached)
|
||||||
before, after, _, when = args
|
continue
|
||||||
yield before or () if step <= when else after
|
|
||||||
def alternate(self, args):
|
|
||||||
yield next(args[(step - 1)%len(args)])
|
|
||||||
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):
|
for m in re_prompt.finditer(prompt):
|
||||||
try:
|
plaintext = m.group(1) if m.group(5) is None else m.group(5)
|
||||||
tree = schedule_parser.parse(prompt)
|
concept_from = m.group(2)
|
||||||
except lark.exceptions.LarkError as e:
|
concept_to = m.group(3)
|
||||||
if 0:
|
if concept_to is None:
|
||||||
import traceback
|
concept_to = concept_from
|
||||||
traceback.print_exc()
|
concept_from = ""
|
||||||
return [[steps, prompt]]
|
swap_position = float(m.group(4)) if m.group(4) is not None else None
|
||||||
return [[t, at_step(t, tree)] for t in collect_steps(steps, tree)]
|
|
||||||
|
|
||||||
promptdict = {prompt: get_schedule(prompt) for prompt in set(prompts)}
|
if swap_position is not None:
|
||||||
return [promptdict[prompt] for prompt in prompts]
|
if swap_position < 1:
|
||||||
|
swap_position = swap_position * steps
|
||||||
|
swap_position = int(min(swap_position, steps))
|
||||||
|
|
||||||
|
swap_index = None
|
||||||
|
found_exact_index = False
|
||||||
|
for i in range(len(prompt_schedule)):
|
||||||
|
end_step = prompt_schedule[i][0]
|
||||||
|
prompt_schedule[i][1] += plaintext
|
||||||
|
|
||||||
|
if swap_position is not None and swap_index is None:
|
||||||
|
if swap_position == end_step:
|
||||||
|
swap_index = i
|
||||||
|
found_exact_index = True
|
||||||
|
|
||||||
|
if swap_position < end_step:
|
||||||
|
swap_index = i
|
||||||
|
|
||||||
|
if swap_index is not None:
|
||||||
|
if not found_exact_index:
|
||||||
|
prompt_schedule.insert(swap_index, [swap_position, prompt_schedule[swap_index][1]])
|
||||||
|
|
||||||
|
for i in range(len(prompt_schedule)):
|
||||||
|
end_step = prompt_schedule[i][0]
|
||||||
|
must_replace = swap_position < end_step
|
||||||
|
|
||||||
|
prompt_schedule[i][1] += concept_to if must_replace else concept_from
|
||||||
|
|
||||||
|
res.append(prompt_schedule)
|
||||||
|
cache[prompt] = prompt_schedule
|
||||||
|
#for t in prompt_schedule:
|
||||||
|
# print(t)
|
||||||
|
|
||||||
|
return res
|
||||||
|
|
||||||
|
|
||||||
ScheduledPromptConditioning = namedtuple("ScheduledPromptConditioning", ["end_at_step", "cond"])
|
ScheduledPromptConditioning = namedtuple("ScheduledPromptConditioning", ["end_at_step", "cond"])
|
||||||
|
ScheduledPromptBatch = namedtuple("ScheduledPromptBatch", ["shape", "schedules"])
|
||||||
|
|
||||||
|
|
||||||
def get_learned_conditioning(model, prompts, steps):
|
def get_learned_conditioning(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 = []
|
res = []
|
||||||
|
|
||||||
prompt_schedules = get_learned_conditioning_prompt_schedules(prompts, steps)
|
prompt_schedules = get_learned_conditioning_prompt_schedules(prompts, steps)
|
||||||
@@ -135,7 +101,7 @@ def get_learned_conditioning(model, prompts, steps):
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
texts = [x[1] for x in prompt_schedule]
|
texts = [x[1] for x in prompt_schedule]
|
||||||
conds = model.get_learned_conditioning(texts)
|
conds = shared.sd_model.get_learned_conditioning(texts)
|
||||||
|
|
||||||
cond_schedule = []
|
cond_schedule = []
|
||||||
for i, (end_at_step, text) in enumerate(prompt_schedule):
|
for i, (end_at_step, text) in enumerate(prompt_schedule):
|
||||||
@@ -144,223 +110,21 @@ def get_learned_conditioning(model, prompts, steps):
|
|||||||
cache[prompt] = cond_schedule
|
cache[prompt] = cond_schedule
|
||||||
res.append(cond_schedule)
|
res.append(cond_schedule)
|
||||||
|
|
||||||
return res
|
return ScheduledPromptBatch((len(prompts),) + res[0][0].cond.shape, res)
|
||||||
|
|
||||||
|
|
||||||
re_AND = re.compile(r"\bAND\b")
|
def reconstruct_cond_batch(c: ScheduledPromptBatch, current_step):
|
||||||
re_weight = re.compile(r"^(.*?)(?:\s*:\s*([-+]?(?:\d+\.?|\d*\.\d+)))?\s*$")
|
res = torch.zeros(c.shape, device=shared.device, dtype=next(shared.sd_model.parameters()).dtype)
|
||||||
|
for i, cond_schedule in enumerate(c.schedules):
|
||||||
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
|
target_index = 0
|
||||||
for current, (end_at, cond) in enumerate(cond_schedule):
|
for curret_index, (end_at, cond) in enumerate(cond_schedule):
|
||||||
if current_step <= end_at:
|
if current_step <= end_at:
|
||||||
target_index = current
|
target_index = curret_index
|
||||||
break
|
break
|
||||||
res[i] = cond_schedule[target_index].cond
|
res[i] = cond_schedule[target_index].cond
|
||||||
|
|
||||||
return res
|
return res
|
||||||
|
|
||||||
|
|
||||||
def reconstruct_multicond_batch(c: MulticondLearnedConditioning, current_step):
|
|
||||||
param = c.batch[0][0].schedules[0].cond
|
|
||||||
|
|
||||||
tensors = []
|
#get_learned_conditioning_prompt_schedules(["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]"], 100)
|
||||||
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)
|
|
||||||
|
|
||||||
# if prompts have wildly different lengths above the limit we'll get tensors fo different shapes
|
|
||||||
# and won't be able to torch.stack them. So this fixes that.
|
|
||||||
token_count = max([x.shape[0] for x in tensors])
|
|
||||||
for i in range(len(tensors)):
|
|
||||||
if tensors[i].shape[0] != token_count:
|
|
||||||
last_vector = tensors[i][-1:]
|
|
||||||
last_vector_repeated = last_vector.repeat([token_count - tensors[i].shape[0], 1])
|
|
||||||
tensors[i] = torch.vstack([tensors[i], last_vector_repeated])
|
|
||||||
|
|
||||||
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
|
|
||||||
+88
-102
@@ -1,133 +1,119 @@
|
|||||||
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
|
from realesrgan import RealESRGANer
|
||||||
|
|
||||||
from modules.upscaler import Upscaler, UpscalerData
|
import modules.images
|
||||||
from modules.shared import cmd_opts, opts
|
from modules.shared import cmd_opts, opts
|
||||||
|
|
||||||
|
RealesrganModelInfo = namedtuple("RealesrganModelInfo", ["name", "location", "model", "netscale"])
|
||||||
class UpscalerRealESRGAN(Upscaler):
|
realesrgan_models = []
|
||||||
def __init__(self, path):
|
have_realesrgan = False
|
||||||
self.name = "RealESRGAN"
|
|
||||||
self.user_path = path
|
|
||||||
super().__init__()
|
|
||||||
try:
|
|
||||||
from basicsr.archs.rrdbnet_arch import RRDBNet
|
|
||||||
from realesrgan import RealESRGANer
|
|
||||||
from realesrgan.archs.srvgg_arch import SRVGGNetCompact
|
|
||||||
self.enable = True
|
|
||||||
self.scalers = []
|
|
||||||
scalers = self.load_models(path)
|
|
||||||
for scaler in scalers:
|
|
||||||
if scaler.name in opts.realesrgan_enabled_models:
|
|
||||||
self.scalers.append(scaler)
|
|
||||||
|
|
||||||
except Exception:
|
|
||||||
print("Error importing Real-ESRGAN:", file=sys.stderr)
|
|
||||||
print(traceback.format_exc(), file=sys.stderr)
|
|
||||||
self.enable = False
|
|
||||||
self.scalers = []
|
|
||||||
|
|
||||||
def do_upscale(self, img, path):
|
|
||||||
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
|
|
||||||
|
|
||||||
upsampler = RealESRGANer(
|
|
||||||
scale=info.scale,
|
|
||||||
model_path=info.data_path,
|
|
||||||
model=info.model(),
|
|
||||||
half=not cmd_opts.no_half,
|
|
||||||
tile=opts.ESRGAN_tile,
|
|
||||||
tile_pad=opts.ESRGAN_tile_overlap,
|
|
||||||
)
|
|
||||||
|
|
||||||
upsampled = upsampler.enhance(np.array(img), outscale=info.scale)[0]
|
|
||||||
|
|
||||||
image = Image.fromarray(upsampled)
|
|
||||||
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):
|
def get_realesrgan_models():
|
||||||
try:
|
try:
|
||||||
from basicsr.archs.rrdbnet_arch import RRDBNet
|
from basicsr.archs.rrdbnet_arch import RRDBNet
|
||||||
|
from realesrgan import RealESRGANer
|
||||||
from realesrgan.archs.srvgg_arch import SRVGGNetCompact
|
from realesrgan.archs.srvgg_arch import SRVGGNetCompact
|
||||||
models = [
|
models = [
|
||||||
UpscalerData(
|
RealesrganModelInfo(
|
||||||
name="R-ESRGAN General 4xV3",
|
name="Real-ESRGAN General x4x3",
|
||||||
path="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth",
|
location="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth",
|
||||||
scale=4,
|
netscale=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')
|
model=lambda: SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=32, upscale=4, act_type='prelu')
|
||||||
),
|
),
|
||||||
UpscalerData(
|
RealesrganModelInfo(
|
||||||
name="R-ESRGAN General WDN 4xV3",
|
name="Real-ESRGAN General WDN x4x3",
|
||||||
path="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-wdn-x4v3.pth",
|
location="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-wdn-x4v3.pth",
|
||||||
scale=4,
|
netscale=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')
|
model=lambda: SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=32, upscale=4, act_type='prelu')
|
||||||
),
|
),
|
||||||
UpscalerData(
|
RealesrganModelInfo(
|
||||||
name="R-ESRGAN AnimeVideo",
|
name="Real-ESRGAN AnimeVideo",
|
||||||
path="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth",
|
location="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth",
|
||||||
scale=4,
|
netscale=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')
|
model=lambda: SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=4, act_type='prelu')
|
||||||
),
|
),
|
||||||
UpscalerData(
|
RealesrganModelInfo(
|
||||||
name="R-ESRGAN 4x+",
|
name="Real-ESRGAN 4x plus",
|
||||||
path="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth",
|
location="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth",
|
||||||
scale=4,
|
netscale=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)
|
model=lambda: RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)
|
||||||
),
|
),
|
||||||
UpscalerData(
|
RealesrganModelInfo(
|
||||||
name="R-ESRGAN 4x+ Anime6B",
|
name="Real-ESRGAN 4x plus anime 6B",
|
||||||
path="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth",
|
location="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth",
|
||||||
scale=4,
|
netscale=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)
|
model=lambda: RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4)
|
||||||
),
|
),
|
||||||
UpscalerData(
|
RealesrganModelInfo(
|
||||||
name="R-ESRGAN 2x+",
|
name="Real-ESRGAN 2x plus",
|
||||||
path="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth",
|
location="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth",
|
||||||
scale=2,
|
netscale=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)
|
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
|
return models
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print("Error making Real-ESRGAN models list:", file=sys.stderr)
|
print("Error makeing Real-ESRGAN midels list:", file=sys.stderr)
|
||||||
print(traceback.format_exc(), file=sys.stderr)
|
print(traceback.format_exc(), file=sys.stderr)
|
||||||
|
|
||||||
|
|
||||||
|
class UpscalerRealESRGAN(modules.images.Upscaler):
|
||||||
|
def __init__(self, upscaling, model_index):
|
||||||
|
self.upscaling = upscaling
|
||||||
|
self.model_index = model_index
|
||||||
|
self.name = realesrgan_models[model_index].name
|
||||||
|
|
||||||
|
def do_upscale(self, img):
|
||||||
|
return upscale_with_realesrgan(img, self.upscaling, self.model_index)
|
||||||
|
|
||||||
|
|
||||||
|
def setup_realesrgan():
|
||||||
|
global realesrgan_models
|
||||||
|
global have_realesrgan
|
||||||
|
|
||||||
|
try:
|
||||||
|
from basicsr.archs.rrdbnet_arch import RRDBNet
|
||||||
|
from realesrgan import RealESRGANer
|
||||||
|
from realesrgan.archs.srvgg_arch import SRVGGNetCompact
|
||||||
|
|
||||||
|
realesrgan_models = get_realesrgan_models()
|
||||||
|
have_realesrgan = True
|
||||||
|
|
||||||
|
for i, model in enumerate(realesrgan_models):
|
||||||
|
if model.name in opts.realesrgan_enabled_models:
|
||||||
|
modules.shared.sd_upscalers.append(UpscalerRealESRGAN(model.netscale, i))
|
||||||
|
|
||||||
|
except Exception:
|
||||||
|
print("Error importing Real-ESRGAN:", file=sys.stderr)
|
||||||
|
print(traceback.format_exc(), file=sys.stderr)
|
||||||
|
|
||||||
|
realesrgan_models = [RealesrganModelInfo('None', '', 0, None)]
|
||||||
|
have_realesrgan = False
|
||||||
|
|
||||||
|
|
||||||
|
def upscale_with_realesrgan(image, RealESRGAN_upscaling, RealESRGAN_model_index):
|
||||||
|
if not have_realesrgan:
|
||||||
|
return image
|
||||||
|
|
||||||
|
info = realesrgan_models[RealESRGAN_model_index]
|
||||||
|
|
||||||
|
model = info.model()
|
||||||
|
upsampler = RealESRGANer(
|
||||||
|
scale=info.netscale,
|
||||||
|
model_path=info.location,
|
||||||
|
model=model,
|
||||||
|
half=not cmd_opts.no_half,
|
||||||
|
tile=opts.ESRGAN_tile,
|
||||||
|
tile_pad=opts.ESRGAN_tile_overlap,
|
||||||
|
)
|
||||||
|
|
||||||
|
upsampled = upsampler.enhance(np.array(image), outscale=RealESRGAN_upscaling)[0]
|
||||||
|
|
||||||
|
image = Image.fromarray(upsampled)
|
||||||
|
return image
|
||||||
-110
@@ -1,110 +0,0 @@
|
|||||||
# this code is adapted from the script contributed by anon from /h/
|
|
||||||
|
|
||||||
import io
|
|
||||||
import pickle
|
|
||||||
import collections
|
|
||||||
import sys
|
|
||||||
import traceback
|
|
||||||
|
|
||||||
import torch
|
|
||||||
import numpy
|
|
||||||
import _codecs
|
|
||||||
import zipfile
|
|
||||||
import re
|
|
||||||
|
|
||||||
|
|
||||||
# PyTorch 1.13 and later have _TypedStorage renamed to TypedStorage
|
|
||||||
TypedStorage = torch.storage.TypedStorage if hasattr(torch.storage, 'TypedStorage') else torch.storage._TypedStorage
|
|
||||||
|
|
||||||
|
|
||||||
def encode(*args):
|
|
||||||
out = _codecs.encode(*args)
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
class RestrictedUnpickler(pickle.Unpickler):
|
|
||||||
def persistent_load(self, saved_id):
|
|
||||||
assert saved_id[0] == 'storage'
|
|
||||||
return TypedStorage()
|
|
||||||
|
|
||||||
def find_class(self, module, name):
|
|
||||||
if module == 'collections' and name == 'OrderedDict':
|
|
||||||
return getattr(collections, name)
|
|
||||||
if module == 'torch._utils' and name in ['_rebuild_tensor_v2', '_rebuild_parameter']:
|
|
||||||
return getattr(torch._utils, name)
|
|
||||||
if module == 'torch' and name in ['FloatStorage', 'HalfStorage', 'IntStorage', 'LongStorage', 'DoubleStorage']:
|
|
||||||
return getattr(torch, name)
|
|
||||||
if module == 'torch.nn.modules.container' and name in ['ParameterDict']:
|
|
||||||
return getattr(torch.nn.modules.container, name)
|
|
||||||
if module == 'numpy.core.multiarray' and name == 'scalar':
|
|
||||||
return numpy.core.multiarray.scalar
|
|
||||||
if module == 'numpy' and name == 'dtype':
|
|
||||||
return numpy.dtype
|
|
||||||
if module == '_codecs' and name == 'encode':
|
|
||||||
return encode
|
|
||||||
if module == "pytorch_lightning.callbacks" and name == 'model_checkpoint':
|
|
||||||
import pytorch_lightning.callbacks
|
|
||||||
return pytorch_lightning.callbacks.model_checkpoint
|
|
||||||
if module == "pytorch_lightning.callbacks.model_checkpoint" and name == 'ModelCheckpoint':
|
|
||||||
import pytorch_lightning.callbacks.model_checkpoint
|
|
||||||
return pytorch_lightning.callbacks.model_checkpoint.ModelCheckpoint
|
|
||||||
if module == "__builtin__" and name == 'set':
|
|
||||||
return set
|
|
||||||
|
|
||||||
# Forbid everything else.
|
|
||||||
raise pickle.UnpicklingError(f"global '{module}/{name}' is forbidden")
|
|
||||||
|
|
||||||
|
|
||||||
allowed_zip_names = ["archive/data.pkl", "archive/version"]
|
|
||||||
allowed_zip_names_re = re.compile(r"^archive/data/\d+$")
|
|
||||||
|
|
||||||
|
|
||||||
def check_zip_filenames(filename, names):
|
|
||||||
for name in names:
|
|
||||||
if name in allowed_zip_names:
|
|
||||||
continue
|
|
||||||
if allowed_zip_names_re.match(name):
|
|
||||||
continue
|
|
||||||
|
|
||||||
raise Exception(f"bad file inside {filename}: {name}")
|
|
||||||
|
|
||||||
|
|
||||||
def check_pt(filename):
|
|
||||||
try:
|
|
||||||
|
|
||||||
# new pytorch format is a zip file
|
|
||||||
with zipfile.ZipFile(filename) as z:
|
|
||||||
check_zip_filenames(filename, z.namelist())
|
|
||||||
|
|
||||||
with z.open('archive/data.pkl') as file:
|
|
||||||
unpickler = RestrictedUnpickler(file)
|
|
||||||
unpickler.load()
|
|
||||||
|
|
||||||
except zipfile.BadZipfile:
|
|
||||||
|
|
||||||
# if it's not a zip file, it's an olf pytorch format, with five objects written to pickle
|
|
||||||
with open(filename, "rb") as file:
|
|
||||||
unpickler = RestrictedUnpickler(file)
|
|
||||||
for i in range(5):
|
|
||||||
unpickler.load()
|
|
||||||
|
|
||||||
|
|
||||||
def load(filename, *args, **kwargs):
|
|
||||||
from modules import shared
|
|
||||||
|
|
||||||
try:
|
|
||||||
if not shared.cmd_opts.disable_safe_unpickle:
|
|
||||||
check_pt(filename)
|
|
||||||
|
|
||||||
except Exception:
|
|
||||||
print(f"Error verifying pickled file from {filename}:", file=sys.stderr)
|
|
||||||
print(traceback.format_exc(), file=sys.stderr)
|
|
||||||
print(f"\nThe file may be malicious, so the program is not going to read it.", file=sys.stderr)
|
|
||||||
print(f"You can skip this check with --disable-safe-unpickle commandline argument.", file=sys.stderr)
|
|
||||||
return None
|
|
||||||
|
|
||||||
return unsafe_torch_load(filename, *args, **kwargs)
|
|
||||||
|
|
||||||
|
|
||||||
unsafe_torch_load = torch.load
|
|
||||||
torch.load = load
|
|
||||||
+1
-35
@@ -55,7 +55,7 @@ def load_scripts(basedir):
|
|||||||
if not os.path.exists(basedir):
|
if not os.path.exists(basedir):
|
||||||
return
|
return
|
||||||
|
|
||||||
for filename in sorted(os.listdir(basedir)):
|
for filename in 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):
|
||||||
@@ -162,40 +162,6 @@ class ScriptRunner:
|
|||||||
|
|
||||||
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()
|
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
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.scunet_model_arch import SCUNet as net
|
|
||||||
|
|
||||||
|
|
||||||
class UpscalerScuNET(modules.upscaler.Upscaler):
|
|
||||||
def __init__(self, dirname):
|
|
||||||
self.name = "ScuNET"
|
|
||||||
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
|
|
||||||
|
|
||||||
@@ -1,265 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
import numpy as np
|
|
||||||
import torch
|
|
||||||
import torch.nn as nn
|
|
||||||
from einops import rearrange
|
|
||||||
from einops.layers.torch import Rearrange
|
|
||||||
from timm.models.layers import trunc_normal_, DropPath
|
|
||||||
|
|
||||||
|
|
||||||
class WMSA(nn.Module):
|
|
||||||
""" Self-attention module in Swin Transformer
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, input_dim, output_dim, head_dim, window_size, type):
|
|
||||||
super(WMSA, self).__init__()
|
|
||||||
self.input_dim = input_dim
|
|
||||||
self.output_dim = output_dim
|
|
||||||
self.head_dim = head_dim
|
|
||||||
self.scale = self.head_dim ** -0.5
|
|
||||||
self.n_heads = input_dim // head_dim
|
|
||||||
self.window_size = window_size
|
|
||||||
self.type = type
|
|
||||||
self.embedding_layer = nn.Linear(self.input_dim, 3 * self.input_dim, bias=True)
|
|
||||||
|
|
||||||
self.relative_position_params = nn.Parameter(
|
|
||||||
torch.zeros((2 * window_size - 1) * (2 * window_size - 1), self.n_heads))
|
|
||||||
|
|
||||||
self.linear = nn.Linear(self.input_dim, self.output_dim)
|
|
||||||
|
|
||||||
trunc_normal_(self.relative_position_params, std=.02)
|
|
||||||
self.relative_position_params = torch.nn.Parameter(
|
|
||||||
self.relative_position_params.view(2 * window_size - 1, 2 * window_size - 1, self.n_heads).transpose(1,
|
|
||||||
2).transpose(
|
|
||||||
0, 1))
|
|
||||||
|
|
||||||
def generate_mask(self, h, w, p, shift):
|
|
||||||
""" generating the mask of SW-MSA
|
|
||||||
Args:
|
|
||||||
shift: shift parameters in CyclicShift.
|
|
||||||
Returns:
|
|
||||||
attn_mask: should be (1 1 w p p),
|
|
||||||
"""
|
|
||||||
# supporting square.
|
|
||||||
attn_mask = torch.zeros(h, w, p, p, p, p, dtype=torch.bool, device=self.relative_position_params.device)
|
|
||||||
if self.type == 'W':
|
|
||||||
return attn_mask
|
|
||||||
|
|
||||||
s = p - shift
|
|
||||||
attn_mask[-1, :, :s, :, s:, :] = True
|
|
||||||
attn_mask[-1, :, s:, :, :s, :] = True
|
|
||||||
attn_mask[:, -1, :, :s, :, s:] = True
|
|
||||||
attn_mask[:, -1, :, s:, :, :s] = True
|
|
||||||
attn_mask = rearrange(attn_mask, 'w1 w2 p1 p2 p3 p4 -> 1 1 (w1 w2) (p1 p2) (p3 p4)')
|
|
||||||
return attn_mask
|
|
||||||
|
|
||||||
def forward(self, x):
|
|
||||||
""" Forward pass of Window Multi-head Self-attention module.
|
|
||||||
Args:
|
|
||||||
x: input tensor with shape of [b h w c];
|
|
||||||
attn_mask: attention mask, fill -inf where the value is True;
|
|
||||||
Returns:
|
|
||||||
output: tensor shape [b h w c]
|
|
||||||
"""
|
|
||||||
if self.type != 'W': x = torch.roll(x, shifts=(-(self.window_size // 2), -(self.window_size // 2)), dims=(1, 2))
|
|
||||||
x = rearrange(x, 'b (w1 p1) (w2 p2) c -> b w1 w2 p1 p2 c', p1=self.window_size, p2=self.window_size)
|
|
||||||
h_windows = x.size(1)
|
|
||||||
w_windows = x.size(2)
|
|
||||||
# square validation
|
|
||||||
# assert h_windows == w_windows
|
|
||||||
|
|
||||||
x = rearrange(x, 'b w1 w2 p1 p2 c -> b (w1 w2) (p1 p2) c', p1=self.window_size, p2=self.window_size)
|
|
||||||
qkv = self.embedding_layer(x)
|
|
||||||
q, k, v = rearrange(qkv, 'b nw np (threeh c) -> threeh b nw np c', c=self.head_dim).chunk(3, dim=0)
|
|
||||||
sim = torch.einsum('hbwpc,hbwqc->hbwpq', q, k) * self.scale
|
|
||||||
# Adding learnable relative embedding
|
|
||||||
sim = sim + rearrange(self.relative_embedding(), 'h p q -> h 1 1 p q')
|
|
||||||
# Using Attn Mask to distinguish different subwindows.
|
|
||||||
if self.type != 'W':
|
|
||||||
attn_mask = self.generate_mask(h_windows, w_windows, self.window_size, shift=self.window_size // 2)
|
|
||||||
sim = sim.masked_fill_(attn_mask, float("-inf"))
|
|
||||||
|
|
||||||
probs = nn.functional.softmax(sim, dim=-1)
|
|
||||||
output = torch.einsum('hbwij,hbwjc->hbwic', probs, v)
|
|
||||||
output = rearrange(output, 'h b w p c -> b w p (h c)')
|
|
||||||
output = self.linear(output)
|
|
||||||
output = rearrange(output, 'b (w1 w2) (p1 p2) c -> b (w1 p1) (w2 p2) c', w1=h_windows, p1=self.window_size)
|
|
||||||
|
|
||||||
if self.type != 'W': output = torch.roll(output, shifts=(self.window_size // 2, self.window_size // 2),
|
|
||||||
dims=(1, 2))
|
|
||||||
return output
|
|
||||||
|
|
||||||
def relative_embedding(self):
|
|
||||||
cord = torch.tensor(np.array([[i, j] for i in range(self.window_size) for j in range(self.window_size)]))
|
|
||||||
relation = cord[:, None, :] - cord[None, :, :] + self.window_size - 1
|
|
||||||
# negative is allowed
|
|
||||||
return self.relative_position_params[:, relation[:, :, 0].long(), relation[:, :, 1].long()]
|
|
||||||
|
|
||||||
|
|
||||||
class Block(nn.Module):
|
|
||||||
def __init__(self, input_dim, output_dim, head_dim, window_size, drop_path, type='W', input_resolution=None):
|
|
||||||
""" SwinTransformer Block
|
|
||||||
"""
|
|
||||||
super(Block, self).__init__()
|
|
||||||
self.input_dim = input_dim
|
|
||||||
self.output_dim = output_dim
|
|
||||||
assert type in ['W', 'SW']
|
|
||||||
self.type = type
|
|
||||||
if input_resolution <= window_size:
|
|
||||||
self.type = 'W'
|
|
||||||
|
|
||||||
self.ln1 = nn.LayerNorm(input_dim)
|
|
||||||
self.msa = WMSA(input_dim, input_dim, head_dim, window_size, self.type)
|
|
||||||
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
|
||||||
self.ln2 = nn.LayerNorm(input_dim)
|
|
||||||
self.mlp = nn.Sequential(
|
|
||||||
nn.Linear(input_dim, 4 * input_dim),
|
|
||||||
nn.GELU(),
|
|
||||||
nn.Linear(4 * input_dim, output_dim),
|
|
||||||
)
|
|
||||||
|
|
||||||
def forward(self, x):
|
|
||||||
x = x + self.drop_path(self.msa(self.ln1(x)))
|
|
||||||
x = x + self.drop_path(self.mlp(self.ln2(x)))
|
|
||||||
return x
|
|
||||||
|
|
||||||
|
|
||||||
class ConvTransBlock(nn.Module):
|
|
||||||
def __init__(self, conv_dim, trans_dim, head_dim, window_size, drop_path, type='W', input_resolution=None):
|
|
||||||
""" SwinTransformer and Conv Block
|
|
||||||
"""
|
|
||||||
super(ConvTransBlock, self).__init__()
|
|
||||||
self.conv_dim = conv_dim
|
|
||||||
self.trans_dim = trans_dim
|
|
||||||
self.head_dim = head_dim
|
|
||||||
self.window_size = window_size
|
|
||||||
self.drop_path = drop_path
|
|
||||||
self.type = type
|
|
||||||
self.input_resolution = input_resolution
|
|
||||||
|
|
||||||
assert self.type in ['W', 'SW']
|
|
||||||
if self.input_resolution <= self.window_size:
|
|
||||||
self.type = 'W'
|
|
||||||
|
|
||||||
self.trans_block = Block(self.trans_dim, self.trans_dim, self.head_dim, self.window_size, self.drop_path,
|
|
||||||
self.type, self.input_resolution)
|
|
||||||
self.conv1_1 = nn.Conv2d(self.conv_dim + self.trans_dim, self.conv_dim + self.trans_dim, 1, 1, 0, bias=True)
|
|
||||||
self.conv1_2 = nn.Conv2d(self.conv_dim + self.trans_dim, self.conv_dim + self.trans_dim, 1, 1, 0, bias=True)
|
|
||||||
|
|
||||||
self.conv_block = nn.Sequential(
|
|
||||||
nn.Conv2d(self.conv_dim, self.conv_dim, 3, 1, 1, bias=False),
|
|
||||||
nn.ReLU(True),
|
|
||||||
nn.Conv2d(self.conv_dim, self.conv_dim, 3, 1, 1, bias=False)
|
|
||||||
)
|
|
||||||
|
|
||||||
def forward(self, x):
|
|
||||||
conv_x, trans_x = torch.split(self.conv1_1(x), (self.conv_dim, self.trans_dim), dim=1)
|
|
||||||
conv_x = self.conv_block(conv_x) + conv_x
|
|
||||||
trans_x = Rearrange('b c h w -> b h w c')(trans_x)
|
|
||||||
trans_x = self.trans_block(trans_x)
|
|
||||||
trans_x = Rearrange('b h w c -> b c h w')(trans_x)
|
|
||||||
res = self.conv1_2(torch.cat((conv_x, trans_x), dim=1))
|
|
||||||
x = x + res
|
|
||||||
|
|
||||||
return x
|
|
||||||
|
|
||||||
|
|
||||||
class SCUNet(nn.Module):
|
|
||||||
# def __init__(self, in_nc=3, config=[2, 2, 2, 2, 2, 2, 2], dim=64, drop_path_rate=0.0, input_resolution=256):
|
|
||||||
def __init__(self, in_nc=3, config=None, dim=64, drop_path_rate=0.0, input_resolution=256):
|
|
||||||
super(SCUNet, self).__init__()
|
|
||||||
if config is None:
|
|
||||||
config = [2, 2, 2, 2, 2, 2, 2]
|
|
||||||
self.config = config
|
|
||||||
self.dim = dim
|
|
||||||
self.head_dim = 32
|
|
||||||
self.window_size = 8
|
|
||||||
|
|
||||||
# drop path rate for each layer
|
|
||||||
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(config))]
|
|
||||||
|
|
||||||
self.m_head = [nn.Conv2d(in_nc, dim, 3, 1, 1, bias=False)]
|
|
||||||
|
|
||||||
begin = 0
|
|
||||||
self.m_down1 = [ConvTransBlock(dim // 2, dim // 2, self.head_dim, self.window_size, dpr[i + begin],
|
|
||||||
'W' if not i % 2 else 'SW', input_resolution)
|
|
||||||
for i in range(config[0])] + \
|
|
||||||
[nn.Conv2d(dim, 2 * dim, 2, 2, 0, bias=False)]
|
|
||||||
|
|
||||||
begin += config[0]
|
|
||||||
self.m_down2 = [ConvTransBlock(dim, dim, self.head_dim, self.window_size, dpr[i + begin],
|
|
||||||
'W' if not i % 2 else 'SW', input_resolution // 2)
|
|
||||||
for i in range(config[1])] + \
|
|
||||||
[nn.Conv2d(2 * dim, 4 * dim, 2, 2, 0, bias=False)]
|
|
||||||
|
|
||||||
begin += config[1]
|
|
||||||
self.m_down3 = [ConvTransBlock(2 * dim, 2 * dim, self.head_dim, self.window_size, dpr[i + begin],
|
|
||||||
'W' if not i % 2 else 'SW', input_resolution // 4)
|
|
||||||
for i in range(config[2])] + \
|
|
||||||
[nn.Conv2d(4 * dim, 8 * dim, 2, 2, 0, bias=False)]
|
|
||||||
|
|
||||||
begin += config[2]
|
|
||||||
self.m_body = [ConvTransBlock(4 * dim, 4 * dim, self.head_dim, self.window_size, dpr[i + begin],
|
|
||||||
'W' if not i % 2 else 'SW', input_resolution // 8)
|
|
||||||
for i in range(config[3])]
|
|
||||||
|
|
||||||
begin += config[3]
|
|
||||||
self.m_up3 = [nn.ConvTranspose2d(8 * dim, 4 * dim, 2, 2, 0, bias=False), ] + \
|
|
||||||
[ConvTransBlock(2 * dim, 2 * dim, self.head_dim, self.window_size, dpr[i + begin],
|
|
||||||
'W' if not i % 2 else 'SW', input_resolution // 4)
|
|
||||||
for i in range(config[4])]
|
|
||||||
|
|
||||||
begin += config[4]
|
|
||||||
self.m_up2 = [nn.ConvTranspose2d(4 * dim, 2 * dim, 2, 2, 0, bias=False), ] + \
|
|
||||||
[ConvTransBlock(dim, dim, self.head_dim, self.window_size, dpr[i + begin],
|
|
||||||
'W' if not i % 2 else 'SW', input_resolution // 2)
|
|
||||||
for i in range(config[5])]
|
|
||||||
|
|
||||||
begin += config[5]
|
|
||||||
self.m_up1 = [nn.ConvTranspose2d(2 * dim, dim, 2, 2, 0, bias=False), ] + \
|
|
||||||
[ConvTransBlock(dim // 2, dim // 2, self.head_dim, self.window_size, dpr[i + begin],
|
|
||||||
'W' if not i % 2 else 'SW', input_resolution)
|
|
||||||
for i in range(config[6])]
|
|
||||||
|
|
||||||
self.m_tail = [nn.Conv2d(dim, in_nc, 3, 1, 1, bias=False)]
|
|
||||||
|
|
||||||
self.m_head = nn.Sequential(*self.m_head)
|
|
||||||
self.m_down1 = nn.Sequential(*self.m_down1)
|
|
||||||
self.m_down2 = nn.Sequential(*self.m_down2)
|
|
||||||
self.m_down3 = nn.Sequential(*self.m_down3)
|
|
||||||
self.m_body = nn.Sequential(*self.m_body)
|
|
||||||
self.m_up3 = nn.Sequential(*self.m_up3)
|
|
||||||
self.m_up2 = nn.Sequential(*self.m_up2)
|
|
||||||
self.m_up1 = nn.Sequential(*self.m_up1)
|
|
||||||
self.m_tail = nn.Sequential(*self.m_tail)
|
|
||||||
# self.apply(self._init_weights)
|
|
||||||
|
|
||||||
def forward(self, x0):
|
|
||||||
|
|
||||||
h, w = x0.size()[-2:]
|
|
||||||
paddingBottom = int(np.ceil(h / 64) * 64 - h)
|
|
||||||
paddingRight = int(np.ceil(w / 64) * 64 - w)
|
|
||||||
x0 = nn.ReplicationPad2d((0, paddingRight, 0, paddingBottom))(x0)
|
|
||||||
|
|
||||||
x1 = self.m_head(x0)
|
|
||||||
x2 = self.m_down1(x1)
|
|
||||||
x3 = self.m_down2(x2)
|
|
||||||
x4 = self.m_down3(x3)
|
|
||||||
x = self.m_body(x4)
|
|
||||||
x = self.m_up3(x + x4)
|
|
||||||
x = self.m_up2(x + x3)
|
|
||||||
x = self.m_up1(x + x2)
|
|
||||||
x = self.m_tail(x + x1)
|
|
||||||
|
|
||||||
x = x[..., :h, :w]
|
|
||||||
|
|
||||||
return x
|
|
||||||
|
|
||||||
def _init_weights(self, m):
|
|
||||||
if isinstance(m, nn.Linear):
|
|
||||||
trunc_normal_(m.weight, std=.02)
|
|
||||||
if m.bias is not None:
|
|
||||||
nn.init.constant_(m.bias, 0)
|
|
||||||
elif isinstance(m, nn.LayerNorm):
|
|
||||||
nn.init.constant_(m.bias, 0)
|
|
||||||
nn.init.constant_(m.weight, 1.0)
|
|
||||||
+254
-222
@@ -5,57 +5,237 @@ import traceback
|
|||||||
import torch
|
import torch
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from torch import einsum
|
from torch import einsum
|
||||||
from torch.nn.functional import silu
|
|
||||||
|
|
||||||
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
|
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
|
|
||||||
|
|
||||||
def apply_optimizations():
|
# see https://github.com/basujindal/stable-diffusion/pull/117 for discussion
|
||||||
undo_optimizations()
|
def split_cross_attention_forward_v1(self, x, context=None, mask=None):
|
||||||
|
h = self.heads
|
||||||
|
|
||||||
ldm.modules.diffusionmodules.model.nonlinearity = silu
|
q = self.to_q(x)
|
||||||
|
context = default(context, x)
|
||||||
|
k = self.to_k(context)
|
||||||
|
v = self.to_v(context)
|
||||||
|
del context, x
|
||||||
|
|
||||||
if cmd_opts.force_enable_xformers or (cmd_opts.xformers and shared.xformers_available and torch.version.cuda and (6, 0) <= torch.cuda.get_device_capability(shared.device) <= (8, 6)):
|
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
|
||||||
print("Applying xformers cross attention optimization.")
|
|
||||||
ldm.modules.attention.CrossAttention.forward = sd_hijack_optimizations.xformers_attention_forward
|
r1 = torch.zeros(q.shape[0], q.shape[1], v.shape[2], device=q.device)
|
||||||
ldm.modules.diffusionmodules.model.AttnBlock.forward = sd_hijack_optimizations.xformers_attnblock_forward
|
for i in range(0, q.shape[0], 2):
|
||||||
elif cmd_opts.opt_split_attention_v1:
|
end = i + 2
|
||||||
print("Applying v1 cross attention optimization.")
|
s1 = einsum('b i d, b j d -> b i j', q[i:end], k[i:end])
|
||||||
ldm.modules.attention.CrossAttention.forward = sd_hijack_optimizations.split_cross_attention_forward_v1
|
s1 *= self.scale
|
||||||
elif not cmd_opts.disable_opt_split_attention and (cmd_opts.opt_split_attention or torch.cuda.is_available()):
|
|
||||||
print("Applying cross attention optimization.")
|
s2 = s1.softmax(dim=-1)
|
||||||
ldm.modules.attention.CrossAttention.forward = sd_hijack_optimizations.split_cross_attention_forward
|
del s1
|
||||||
ldm.modules.diffusionmodules.model.AttnBlock.forward = sd_hijack_optimizations.cross_attention_attnblock_forward
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
|
||||||
def undo_optimizations():
|
# taken from https://github.com/Doggettx/stable-diffusion
|
||||||
from modules.hypernetworks import hypernetwork
|
def split_cross_attention_forward(self, x, context=None, mask=None):
|
||||||
|
h = self.heads
|
||||||
|
|
||||||
ldm.modules.attention.CrossAttention.forward = hypernetwork.attention_CrossAttention_forward
|
q_in = self.to_q(x)
|
||||||
ldm.modules.diffusionmodules.model.nonlinearity = diffusionmodules_model_nonlinearity
|
context = default(context, x)
|
||||||
ldm.modules.diffusionmodules.model.AttnBlock.forward = diffusionmodules_model_AttnBlock_forward
|
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
|
||||||
|
|
||||||
def get_target_prompt_token_count(token_count):
|
r1 = torch.zeros(q.shape[0], q.shape[1], v.shape[2], device=q.device, dtype=q.dtype)
|
||||||
return math.ceil(max(token_count, 1) / 75) * 75
|
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
embedding_db = modules.textual_inversion.textual_inversion.EmbeddingDatabase(cmd_opts.embeddings_dir)
|
def load_textual_inversion_embeddings(self, dirname, model):
|
||||||
|
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, 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]
|
||||||
|
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)
|
||||||
|
|
||||||
|
self.word_embeddings[name] = emb.detach().to(device)
|
||||||
|
self.word_embeddings_checksums[name] = f'{const_hash(emb.reshape(-1)*100)&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
|
||||||
@@ -63,9 +243,12 @@ 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)
|
||||||
|
|
||||||
self.clip = m.cond_stage_model
|
if cmd_opts.opt_split_attention_v1:
|
||||||
|
ldm.modules.attention.CrossAttention.forward = split_cross_attention_forward_v1
|
||||||
apply_optimizations()
|
elif not cmd_opts.disable_opt_split_attention and (cmd_opts.opt_split_attention or torch.cuda.is_available()):
|
||||||
|
ldm.modules.attention.CrossAttention.forward = split_cross_attention_forward
|
||||||
|
ldm.modules.diffusionmodules.model.nonlinearity = nonlinearity_hijack
|
||||||
|
ldm.modules.diffusionmodules.model.AttnBlock.forward = cross_attention_attnblock_forward
|
||||||
|
|
||||||
def flatten(el):
|
def flatten(el):
|
||||||
flattened = [flatten(children) for children in el.children()]
|
flattened = [flatten(children) for children in el.children()]
|
||||||
@@ -76,14 +259,6 @@ 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
|
||||||
@@ -93,24 +268,16 @@ 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 clear_comments(self):
|
|
||||||
self.comments = []
|
|
||||||
|
|
||||||
def tokenize(self, text):
|
|
||||||
_, remade_batch_tokens, _, _, _, token_count = self.clip.process_text([text])
|
|
||||||
return remade_batch_tokens[0], token_count, get_target_prompt_token_count(token_count)
|
|
||||||
|
|
||||||
|
|
||||||
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: StableDiffusionModelHijack = hijack
|
self.hijack = hijack
|
||||||
self.tokenizer = wrapped.tokenizer
|
self.tokenizer = wrapped.tokenizer
|
||||||
|
self.max_length = wrapped.max_length
|
||||||
self.token_mults = {}
|
self.token_mults = {}
|
||||||
|
|
||||||
self.comma_token = [v for k, v in self.tokenizer.get_vocab().items() if k == ',</w>'][0]
|
|
||||||
|
|
||||||
tokens_with_parens = [(k, v) for k, v in self.tokenizer.get_vocab().items() if '(' in k or ')' in k or '[' in k or ']' in k]
|
tokens_with_parens = [(k, v) for k, v in self.tokenizer.get_vocab().items() if '(' in k or ')' in k or '[' in k or ']' in k]
|
||||||
for text, ident in tokens_with_parens:
|
for text, ident in tokens_with_parens:
|
||||||
mult = 1.0
|
mult = 1.0
|
||||||
@@ -127,104 +294,14 @@ class FrozenCLIPEmbedderWithCustomWords(torch.nn.Module):
|
|||||||
if mult != 1.0:
|
if mult != 1.0:
|
||||||
self.token_mults[ident] = mult
|
self.token_mults[ident] = mult
|
||||||
|
|
||||||
def tokenize_line(self, line, used_custom_terms, hijack_comments):
|
def forward(self, text):
|
||||||
id_end = self.wrapped.tokenizer.eos_token_id
|
self.hijack.fixes = []
|
||||||
|
self.hijack.comments = []
|
||||||
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 = []
|
|
||||||
last_comma = -1
|
|
||||||
|
|
||||||
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 token == self.comma_token:
|
|
||||||
last_comma = len(remade_tokens)
|
|
||||||
elif opts.comma_padding_backtrack != 0 and max(len(remade_tokens), 1) % 75 == 0 and last_comma != -1 and len(remade_tokens) - last_comma <= opts.comma_padding_backtrack:
|
|
||||||
last_comma += 1
|
|
||||||
reloc_tokens = remade_tokens[last_comma:]
|
|
||||||
reloc_mults = multipliers[last_comma:]
|
|
||||||
|
|
||||||
remade_tokens = remade_tokens[:last_comma]
|
|
||||||
length = len(remade_tokens)
|
|
||||||
|
|
||||||
rem = int(math.ceil(length / 75)) * 75 - length
|
|
||||||
remade_tokens += [id_end] * rem + reloc_tokens
|
|
||||||
multipliers = multipliers[:last_comma] + [1.0] * rem + reloc_mults
|
|
||||||
|
|
||||||
if embedding is None:
|
|
||||||
remade_tokens.append(token)
|
|
||||||
multipliers.append(weight)
|
|
||||||
i += 1
|
|
||||||
else:
|
|
||||||
emb_len = int(embedding.vec.shape[0])
|
|
||||||
iteration = len(remade_tokens) // 75
|
|
||||||
if (len(remade_tokens) + emb_len) // 75 != iteration:
|
|
||||||
rem = (75 * (iteration + 1) - len(remade_tokens))
|
|
||||||
remade_tokens += [id_end] * rem
|
|
||||||
multipliers += [1.0] * rem
|
|
||||||
iteration += 1
|
|
||||||
fixes.append((iteration, (len(remade_tokens) % 75, embedding)))
|
|
||||||
remade_tokens += [0] * emb_len
|
|
||||||
multipliers += [weight] * emb_len
|
|
||||||
used_custom_terms.append((embedding.name, embedding.checksum()))
|
|
||||||
i += embedding_length_in_tokens
|
|
||||||
|
|
||||||
token_count = len(remade_tokens)
|
|
||||||
prompt_target_length = get_target_prompt_token_count(token_count)
|
|
||||||
tokens_to_add = prompt_target_length - len(remade_tokens)
|
|
||||||
|
|
||||||
remade_tokens = remade_tokens + [id_end] * tokens_to_add
|
|
||||||
multipliers = multipliers + [1.0] * tokens_to_add
|
|
||||||
|
|
||||||
return remade_tokens, fixes, multipliers, token_count
|
|
||||||
|
|
||||||
def process_text(self, texts):
|
|
||||||
used_custom_terms = []
|
|
||||||
remade_batch_tokens = []
|
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, current_token_count = self.tokenize_line(line, used_custom_terms, hijack_comments)
|
|
||||||
token_count = max(current_token_count, token_count)
|
|
||||||
|
|
||||||
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_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 # you get to stay at 77
|
maxlen = self.wrapped.max_length
|
||||||
used_custom_terms = []
|
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"]
|
||||||
@@ -244,32 +321,41 @@ class FrozenCLIPEmbedderWithCustomWords(torch.nn.Module):
|
|||||||
while i < len(tokens):
|
while i < len(tokens):
|
||||||
token = tokens[i]
|
token = tokens[i]
|
||||||
|
|
||||||
embedding, embedding_length_in_tokens = self.hijack.embedding_db.find_embedding_at_position(tokens, i)
|
possible_matches = self.hijack.ids_lookup.get(token, None)
|
||||||
|
|
||||||
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
|
||||||
i += 1
|
elif possible_matches is None:
|
||||||
elif embedding is None:
|
|
||||||
remade_tokens.append(token)
|
remade_tokens.append(token)
|
||||||
multipliers.append(mult)
|
multipliers.append(mult)
|
||||||
i += 1
|
|
||||||
else:
|
else:
|
||||||
emb_len = int(embedding.vec.shape[0])
|
found = False
|
||||||
fixes.append((len(remade_tokens), embedding))
|
for ids, word in possible_matches:
|
||||||
remade_tokens += [0] * emb_len
|
if tokens[i:i+len(ids)] == ids:
|
||||||
multipliers += [mult] * emb_len
|
emb_len = int(self.hijack.word_embeddings[word].shape[0])
|
||||||
used_custom_terms.append((embedding.name, embedding.checksum()))
|
fixes.append((len(remade_tokens), word))
|
||||||
i += embedding_length_in_tokens
|
remade_tokens += [0] * emb_len
|
||||||
|
multipliers += [mult] * emb_len
|
||||||
|
i += len(ids) - 1
|
||||||
|
found = True
|
||||||
|
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")
|
|
||||||
|
|
||||||
token_count = len(remade_tokens)
|
self.hijack.comments.append(f"Warning: too many input tokens; some ({len(overflowing_words)}) have been truncated:\n{overflowing_text}\n")
|
||||||
|
|
||||||
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)
|
||||||
@@ -278,67 +364,18 @@ 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)
|
||||||
hijack_fixes.append(fixes)
|
self.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):
|
|
||||||
use_old = opts.use_old_emphasis_implementation
|
|
||||||
if use_old:
|
|
||||||
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.comments += hijack_comments
|
|
||||||
|
|
||||||
if len(used_custom_terms) > 0:
|
if len(used_custom_terms) > 0:
|
||||||
self.hijack.comments.append("Used embeddings: " + ", ".join([f'{word} [{checksum}]' for word, checksum in used_custom_terms]))
|
self.hijack.comments.append("Used custom terms: " + ", ".join([f'{word} [{checksum}]' for word, checksum in used_custom_terms]))
|
||||||
|
|
||||||
if use_old:
|
|
||||||
self.hijack.fixes = hijack_fixes
|
|
||||||
return self.process_tokens(remade_batch_tokens, batch_multipliers)
|
|
||||||
|
|
||||||
z = None
|
|
||||||
i = 0
|
|
||||||
while max(map(len, remade_batch_tokens)) != 0:
|
|
||||||
rem_tokens = [x[75:] for x in remade_batch_tokens]
|
|
||||||
rem_multipliers = [x[75:] for x in batch_multipliers]
|
|
||||||
|
|
||||||
self.hijack.fixes = []
|
|
||||||
for unfiltered in hijack_fixes:
|
|
||||||
fixes = []
|
|
||||||
for fix in unfiltered:
|
|
||||||
if fix[0] == i:
|
|
||||||
fixes.append(fix[1])
|
|
||||||
self.hijack.fixes.append(fixes)
|
|
||||||
|
|
||||||
z1 = self.process_tokens([x[:75] for x in remade_batch_tokens], [x[:75] for x in batch_multipliers])
|
|
||||||
z = z1 if z is None else torch.cat((z, z1), axis=-2)
|
|
||||||
|
|
||||||
remade_batch_tokens = rem_tokens
|
|
||||||
batch_multipliers = rem_multipliers
|
|
||||||
i += 1
|
|
||||||
|
|
||||||
return z
|
|
||||||
|
|
||||||
|
|
||||||
def process_tokens(self, remade_batch_tokens, batch_multipliers):
|
|
||||||
if not opts.use_old_emphasis_implementation:
|
|
||||||
remade_batch_tokens = [[self.wrapped.tokenizer.bos_token_id] + x[:75] + [self.wrapped.tokenizer.eos_token_id] for x in remade_batch_tokens]
|
|
||||||
batch_multipliers = [[1.0] + x[:75] + [1.0] for x in batch_multipliers]
|
|
||||||
|
|
||||||
tokens = torch.asarray(remade_batch_tokens).to(device)
|
tokens = torch.asarray(remade_batch_tokens).to(device)
|
||||||
outputs = self.wrapped.transformer(input_ids=tokens, output_hidden_states=-opts.CLIP_stop_at_last_layers)
|
outputs = self.wrapped.transformer(input_ids=tokens)
|
||||||
|
z = outputs.last_hidden_state
|
||||||
if opts.CLIP_stop_at_last_layers > 1:
|
|
||||||
z = outputs.hidden_states[-opts.CLIP_stop_at_last_layers]
|
|
||||||
z = self.wrapped.transformer.text_model.final_layer_norm(z)
|
|
||||||
else:
|
|
||||||
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_of_same_length = [x + [1.0] * (75 - len(x)) for x in batch_multipliers]
|
batch_multipliers = torch.asarray(batch_multipliers).to(device)
|
||||||
batch_multipliers = torch.asarray(batch_multipliers_of_same_length).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()
|
||||||
@@ -359,19 +396,14 @@ class EmbeddingsWithFixes(torch.nn.Module):
|
|||||||
|
|
||||||
inputs_embeds = self.wrapped(input_ids)
|
inputs_embeds = self.wrapped(input_ids)
|
||||||
|
|
||||||
if batch_fixes is None or len(batch_fixes) == 0 or max([len(x) for x in batch_fixes]) == 0:
|
if batch_fixes is not None:
|
||||||
return inputs_embeds
|
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-1, emb.shape[0])
|
||||||
|
tensor[offset+1:offset+1+emb_len] = self.embeddings.word_embeddings[word][0:emb_len]
|
||||||
|
|
||||||
vecs = []
|
return inputs_embeds
|
||||||
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():
|
||||||
|
|||||||
@@ -1,209 +0,0 @@
|
|||||||
import math
|
|
||||||
import sys
|
|
||||||
import traceback
|
|
||||||
|
|
||||||
import torch
|
|
||||||
from torch import einsum
|
|
||||||
|
|
||||||
from ldm.util import default
|
|
||||||
from einops import rearrange
|
|
||||||
|
|
||||||
from modules import shared
|
|
||||||
from modules.hypernetworks import hypernetwork
|
|
||||||
|
|
||||||
|
|
||||||
if shared.cmd_opts.xformers or shared.cmd_opts.force_enable_xformers:
|
|
||||||
try:
|
|
||||||
import xformers.ops
|
|
||||||
shared.xformers_available = True
|
|
||||||
except Exception:
|
|
||||||
print("Cannot import xformers", file=sys.stderr)
|
|
||||||
print(traceback.format_exc(), file=sys.stderr)
|
|
||||||
|
|
||||||
|
|
||||||
# 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_in = self.to_q(x)
|
|
||||||
context = default(context, x)
|
|
||||||
|
|
||||||
context_k, context_v = hypernetwork.apply_hypernetwork(shared.loaded_hypernetwork, context)
|
|
||||||
k_in = self.to_k(context_k)
|
|
||||||
v_in = self.to_v(context_v)
|
|
||||||
del context, context_k, context_v, 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)
|
|
||||||
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
|
|
||||||
del q, k, v
|
|
||||||
|
|
||||||
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 and modified
|
|
||||||
def split_cross_attention_forward(self, x, context=None, mask=None):
|
|
||||||
h = self.heads
|
|
||||||
|
|
||||||
q_in = self.to_q(x)
|
|
||||||
context = default(context, x)
|
|
||||||
|
|
||||||
context_k, context_v = hypernetwork.apply_hypernetwork(shared.loaded_hypernetwork, context)
|
|
||||||
k_in = self.to_k(context_k)
|
|
||||||
v_in = self.to_v(context_v)
|
|
||||||
|
|
||||||
k_in *= self.scale
|
|
||||||
|
|
||||||
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 xformers_attention_forward(self, x, context=None, mask=None):
|
|
||||||
h = self.heads
|
|
||||||
q_in = self.to_q(x)
|
|
||||||
context = default(context, x)
|
|
||||||
|
|
||||||
context_k, context_v = hypernetwork.apply_hypernetwork(shared.loaded_hypernetwork, context)
|
|
||||||
k_in = self.to_k(context_k)
|
|
||||||
v_in = self.to_v(context_v)
|
|
||||||
|
|
||||||
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b n h d', h=h), (q_in, k_in, v_in))
|
|
||||||
del q_in, k_in, v_in
|
|
||||||
out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None)
|
|
||||||
|
|
||||||
out = rearrange(out, 'b n h d -> b n (h d)', h=h)
|
|
||||||
return self.to_out(out)
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
def xformers_attnblock_forward(self, x):
|
|
||||||
try:
|
|
||||||
h_ = x
|
|
||||||
h_ = self.norm(h_)
|
|
||||||
q1 = self.q(h_).contiguous()
|
|
||||||
k1 = self.k(h_).contiguous()
|
|
||||||
v = self.v(h_).contiguous()
|
|
||||||
out = xformers.ops.memory_efficient_attention(q1, k1, v)
|
|
||||||
out = self.proj_out(out)
|
|
||||||
return x + out
|
|
||||||
except NotImplementedError:
|
|
||||||
return cross_attention_attnblock_forward(self, x)
|
|
||||||
+27
-99
@@ -5,15 +5,12 @@ from collections import namedtuple
|
|||||||
import torch
|
import torch
|
||||||
from omegaconf import OmegaConf
|
from omegaconf import OmegaConf
|
||||||
|
|
||||||
|
|
||||||
from ldm.util import instantiate_from_config
|
from ldm.util import instantiate_from_config
|
||||||
|
|
||||||
from modules import shared, modelloader, devices
|
from modules import shared
|
||||||
from modules.paths import models_path
|
|
||||||
|
|
||||||
model_dir = "Stable-diffusion"
|
CheckpointInfo = namedtuple("CheckpointInfo", ['filename', 'title', 'hash'])
|
||||||
model_path = os.path.abspath(os.path.join(models_path, model_dir))
|
|
||||||
|
|
||||||
CheckpointInfo = namedtuple("CheckpointInfo", ['filename', 'title', 'hash', 'model_name', 'config'])
|
|
||||||
checkpoints_list = {}
|
checkpoints_list = {}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -26,63 +23,37 @@ except Exception:
|
|||||||
pass
|
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():
|
def list_models():
|
||||||
checkpoints_list.clear()
|
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):
|
model_dir = os.path.abspath(shared.cmd_opts.ckpt_dir)
|
||||||
|
|
||||||
|
def modeltitle(path, h):
|
||||||
abspath = os.path.abspath(path)
|
abspath = os.path.abspath(path)
|
||||||
|
|
||||||
if shared.cmd_opts.ckpt_dir is not None and abspath.startswith(shared.cmd_opts.ckpt_dir):
|
if abspath.startswith(model_dir):
|
||||||
name = abspath.replace(shared.cmd_opts.ckpt_dir, '')
|
name = abspath.replace(model_dir, '')
|
||||||
elif abspath.startswith(model_path):
|
|
||||||
name = abspath.replace(model_path, '')
|
|
||||||
else:
|
else:
|
||||||
name = os.path.basename(path)
|
name = os.path.basename(path)
|
||||||
|
|
||||||
if name.startswith("\\") or name.startswith("/"):
|
if name.startswith("\\") or name.startswith("/"):
|
||||||
name = name[1:]
|
name = name[1:]
|
||||||
|
|
||||||
shortname = os.path.splitext(name.replace("/", "_").replace("\\", "_"))[0]
|
return f'{name} [{h}]'
|
||||||
|
|
||||||
return f'{name} [{shorthash}]', shortname
|
|
||||||
|
|
||||||
cmd_ckpt = shared.cmd_opts.ckpt
|
cmd_ckpt = shared.cmd_opts.ckpt
|
||||||
if os.path.exists(cmd_ckpt):
|
if os.path.exists(cmd_ckpt):
|
||||||
h = model_hash(cmd_ckpt)
|
h = model_hash(cmd_ckpt)
|
||||||
title, short_model_name = modeltitle(cmd_ckpt, h)
|
title = modeltitle(cmd_ckpt, h)
|
||||||
checkpoints_list[title] = CheckpointInfo(cmd_ckpt, title, h, short_model_name, shared.cmd_opts.config)
|
checkpoints_list[title] = CheckpointInfo(cmd_ckpt, title, h)
|
||||||
shared.opts.data['sd_model_checkpoint'] = title
|
|
||||||
elif cmd_ckpt is not None and cmd_ckpt != shared.default_sd_model_file:
|
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)
|
print(f"Checkpoint in --ckpt argument not found: {cmd_ckpt}", file=sys.stderr)
|
||||||
for filename in model_list:
|
|
||||||
h = model_hash(filename)
|
|
||||||
title, short_model_name = modeltitle(filename, h)
|
|
||||||
|
|
||||||
basename, _ = os.path.splitext(filename)
|
if os.path.exists(model_dir):
|
||||||
config = basename + ".yaml"
|
for filename in glob.glob(model_dir + '/**/*.ckpt', recursive=True):
|
||||||
if not os.path.exists(config):
|
h = model_hash(filename)
|
||||||
config = shared.cmd_opts.config
|
title = modeltitle(filename, h)
|
||||||
|
checkpoints_list[title] = CheckpointInfo(filename, title, h)
|
||||||
checkpoints_list[title] = CheckpointInfo(filename, title, h, short_model_name, config)
|
|
||||||
|
|
||||||
|
|
||||||
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):
|
def model_hash(filename):
|
||||||
@@ -106,11 +77,8 @@ def select_checkpoint():
|
|||||||
|
|
||||||
if len(checkpoints_list) == 0:
|
if len(checkpoints_list) == 0:
|
||||||
print(f"No checkpoints found. When searching for checkpoints, looked at:", file=sys.stderr)
|
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" - file {os.path.abspath(shared.cmd_opts.ckpt)}", file=sys.stderr)
|
print(f" - directory {os.path.abspath(shared.cmd_opts.ckpt_dir)}", 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)
|
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)
|
exit(1)
|
||||||
|
|
||||||
@@ -121,24 +89,13 @@ def select_checkpoint():
|
|||||||
return checkpoint_info
|
return checkpoint_info
|
||||||
|
|
||||||
|
|
||||||
def get_state_dict_from_checkpoint(pl_sd):
|
def load_model_weights(model, checkpoint_file, sd_model_hash):
|
||||||
if "state_dict" in pl_sd:
|
|
||||||
return pl_sd["state_dict"]
|
|
||||||
|
|
||||||
return pl_sd
|
|
||||||
|
|
||||||
|
|
||||||
def load_model_weights(model, checkpoint_info):
|
|
||||||
checkpoint_file = checkpoint_info.filename
|
|
||||||
sd_model_hash = checkpoint_info.hash
|
|
||||||
|
|
||||||
print(f"Loading weights [{sd_model_hash}] from {checkpoint_file}")
|
print(f"Loading weights [{sd_model_hash}] from {checkpoint_file}")
|
||||||
|
|
||||||
pl_sd = torch.load(checkpoint_file, map_location="cpu")
|
pl_sd = torch.load(checkpoint_file, map_location="cpu")
|
||||||
if "global_step" in pl_sd:
|
if "global_step" in pl_sd:
|
||||||
print(f"Global Step: {pl_sd['global_step']}")
|
print(f"Global Step: {pl_sd['global_step']}")
|
||||||
|
sd = pl_sd["state_dict"]
|
||||||
sd = get_state_dict_from_checkpoint(pl_sd)
|
|
||||||
|
|
||||||
model.load_state_dict(sd, strict=False)
|
model.load_state_dict(sd, strict=False)
|
||||||
|
|
||||||
@@ -148,38 +105,17 @@ def load_model_weights(model, checkpoint_info):
|
|||||||
if not shared.cmd_opts.no_half:
|
if not shared.cmd_opts.no_half:
|
||||||
model.half()
|
model.half()
|
||||||
|
|
||||||
devices.dtype = torch.float32 if shared.cmd_opts.no_half else torch.float16
|
|
||||||
devices.dtype_vae = torch.float32 if shared.cmd_opts.no_half or shared.cmd_opts.no_half_vae else torch.float16
|
|
||||||
|
|
||||||
vae_file = os.path.splitext(checkpoint_file)[0] + ".vae.pt"
|
|
||||||
|
|
||||||
if not os.path.exists(vae_file) and shared.cmd_opts.vae_path is not None:
|
|
||||||
vae_file = shared.cmd_opts.vae_path
|
|
||||||
|
|
||||||
if os.path.exists(vae_file):
|
|
||||||
print(f"Loading VAE weights from: {vae_file}")
|
|
||||||
vae_ckpt = torch.load(vae_file, map_location="cpu")
|
|
||||||
vae_dict = {k: v for k, v in vae_ckpt["state_dict"].items() if k[0:4] != "loss"}
|
|
||||||
|
|
||||||
model.first_stage_model.load_state_dict(vae_dict)
|
|
||||||
|
|
||||||
model.first_stage_model.to(devices.dtype_vae)
|
|
||||||
|
|
||||||
model.sd_model_hash = sd_model_hash
|
model.sd_model_hash = sd_model_hash
|
||||||
model.sd_model_checkpoint = checkpoint_file
|
model.sd_model_checkpint = checkpoint_file
|
||||||
model.sd_checkpoint_info = checkpoint_info
|
|
||||||
|
|
||||||
|
|
||||||
def load_model():
|
def load_model():
|
||||||
from modules import lowvram, sd_hijack
|
from modules import lowvram, sd_hijack
|
||||||
checkpoint_info = select_checkpoint()
|
checkpoint_info = select_checkpoint()
|
||||||
|
|
||||||
if checkpoint_info.config != shared.cmd_opts.config:
|
sd_config = OmegaConf.load(shared.cmd_opts.config)
|
||||||
print(f"Loading config from: {checkpoint_info.config}")
|
|
||||||
|
|
||||||
sd_config = OmegaConf.load(checkpoint_info.config)
|
|
||||||
sd_model = instantiate_from_config(sd_config.model)
|
sd_model = instantiate_from_config(sd_config.model)
|
||||||
load_model_weights(sd_model, checkpoint_info)
|
load_model_weights(sd_model, checkpoint_info.filename, checkpoint_info.hash)
|
||||||
|
|
||||||
if shared.cmd_opts.lowvram or shared.cmd_opts.medvram:
|
if shared.cmd_opts.lowvram or shared.cmd_opts.medvram:
|
||||||
lowvram.setup_for_low_vram(sd_model, shared.cmd_opts.medvram)
|
lowvram.setup_for_low_vram(sd_model, shared.cmd_opts.medvram)
|
||||||
@@ -195,26 +131,18 @@ def load_model():
|
|||||||
|
|
||||||
|
|
||||||
def reload_model_weights(sd_model, info=None):
|
def reload_model_weights(sd_model, info=None):
|
||||||
from modules import lowvram, devices, sd_hijack
|
from modules import lowvram, devices
|
||||||
checkpoint_info = info or select_checkpoint()
|
checkpoint_info = info or select_checkpoint()
|
||||||
|
|
||||||
if sd_model.sd_model_checkpoint == checkpoint_info.filename:
|
if sd_model.sd_model_checkpint == checkpoint_info.filename:
|
||||||
return
|
return
|
||||||
|
|
||||||
if sd_model.sd_checkpoint_info.config != checkpoint_info.config:
|
|
||||||
shared.sd_model = load_model()
|
|
||||||
return shared.sd_model
|
|
||||||
|
|
||||||
if shared.cmd_opts.lowvram or shared.cmd_opts.medvram:
|
if shared.cmd_opts.lowvram or shared.cmd_opts.medvram:
|
||||||
lowvram.send_everything_to_cpu()
|
lowvram.send_everything_to_cpu()
|
||||||
else:
|
else:
|
||||||
sd_model.to(devices.cpu)
|
sd_model.to(devices.cpu)
|
||||||
|
|
||||||
sd_hijack.model_hijack.undo_hijack(sd_model)
|
load_model_weights(sd_model, checkpoint_info.filename, checkpoint_info.hash)
|
||||||
|
|
||||||
load_model_weights(sd_model, checkpoint_info)
|
|
||||||
|
|
||||||
sd_hijack.model_hijack.hijack(sd_model)
|
|
||||||
|
|
||||||
if not shared.cmd_opts.lowvram and not shared.cmd_opts.medvram:
|
if not shared.cmd_opts.lowvram and not shared.cmd_opts.medvram:
|
||||||
sd_model.to(devices.device)
|
sd_model.to(devices.device)
|
||||||
|
|||||||
+70
-189
@@ -3,73 +3,40 @@ 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, devices, processing
|
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', 'options'])
|
SamplerData = namedtuple('SamplerData', ['name', 'constructor', 'aliases'])
|
||||||
|
|
||||||
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, options)
|
SamplerData(label, lambda model, funcname=funcname: KDiffusionSampler(funcname, model), aliases)
|
||||||
for label, funcname, aliases, options in samplers_k_diffusion
|
for label, funcname, aliases in samplers_k_diffusion
|
||||||
if hasattr(k_diffusion.sampling, funcname)
|
if hasattr(k_diffusion.sampling, funcname)
|
||||||
]
|
]
|
||||||
|
|
||||||
all_samplers = [
|
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'])
|
|
||||||
|
|
||||||
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):
|
def setup_img2img_steps(p, steps=None):
|
||||||
if opts.img2img_fix_steps or steps is not None:
|
if opts.img2img_fix_steps or steps is not None:
|
||||||
@@ -83,7 +50,7 @@ def setup_img2img_steps(p, steps=None):
|
|||||||
|
|
||||||
|
|
||||||
def sample_to_image(samples):
|
def sample_to_image(samples):
|
||||||
x_sample = processing.decode_first_stage(shared.sd_model, samples[0:1])[0]
|
x_sample = shared.sd_model.decode_first_stage(samples[0:1].type(shared.sd_model.dtype))[0]
|
||||||
x_sample = torch.clamp((x_sample + 1.0) / 2.0, min=0.0, max=1.0)
|
x_sample = torch.clamp((x_sample + 1.0) / 2.0, min=0.0, max=1.0)
|
||||||
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)
|
||||||
@@ -103,10 +70,8 @@ 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
|
||||||
|
|
||||||
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 tqdm.tqdm(sequence, *args, desc=state.job, file=shared.progress_print_out, **kwargs):
|
||||||
|
if state.interrupted:
|
||||||
for x in seq:
|
|
||||||
if state.interrupted or state.skipped:
|
|
||||||
break
|
break
|
||||||
|
|
||||||
yield x
|
yield x
|
||||||
@@ -128,30 +93,14 @@ class VanillaStableDiffusionSampler:
|
|||||||
self.init_latent = None
|
self.init_latent = None
|
||||||
self.sampler_noises = None
|
self.sampler_noises = None
|
||||||
self.step = 0
|
self.step = 0
|
||||||
self.eta = None
|
|
||||||
self.default_eta = 0.0
|
|
||||||
self.config = None
|
|
||||||
|
|
||||||
def number_of_needed_noises(self, p):
|
def number_of_needed_noises(self, p):
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
def p_sample_ddim_hook(self, x_dec, cond, ts, unconditional_conditioning, *args, **kwargs):
|
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)
|
cond = prompt_parser.reconstruct_cond_batch(cond, self.step)
|
||||||
unconditional_conditioning = prompt_parser.reconstruct_cond_batch(unconditional_conditioning, 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
|
|
||||||
|
|
||||||
# for DDIM, shapes must match, we can't just process cond and uncond independently;
|
|
||||||
# filling unconditional_conditioning with repeats of the last vector to match length is
|
|
||||||
# not 100% correct but should work well enough
|
|
||||||
if unconditional_conditioning.shape[1] < cond.shape[1]:
|
|
||||||
last_vector = unconditional_conditioning[:, -1:]
|
|
||||||
last_vector_repeated = last_vector.repeat([1, cond.shape[1] - unconditional_conditioning.shape[1], 1])
|
|
||||||
unconditional_conditioning = torch.hstack([unconditional_conditioning, last_vector_repeated])
|
|
||||||
elif unconditional_conditioning.shape[1] > cond.shape[1]:
|
|
||||||
unconditional_conditioning = unconditional_conditioning[:, :cond.shape[1]]
|
|
||||||
|
|
||||||
if self.mask is not None:
|
if self.mask is not None:
|
||||||
img_orig = self.sampler.model.q_sample(self.init_latent, ts)
|
img_orig = self.sampler.model.q_sample(self.init_latent, ts)
|
||||||
x_dec = img_orig * self.mask + self.nmask * x_dec
|
x_dec = img_orig * self.mask + self.nmask * x_dec
|
||||||
@@ -166,29 +115,20 @@ class VanillaStableDiffusionSampler:
|
|||||||
self.step += 1
|
self.step += 1
|
||||||
return res
|
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):
|
def sample_img2img(self, p, x, noise, conditioning, unconditional_conditioning, steps=None):
|
||||||
steps, t_enc = setup_img2img_steps(p, steps)
|
steps, t_enc = setup_img2img_steps(p, steps)
|
||||||
|
|
||||||
self.initialize(p)
|
# existing code fails with cetain step counts, like 9
|
||||||
|
|
||||||
# existing code fails with certain step counts, like 9
|
|
||||||
try:
|
try:
|
||||||
self.sampler.make_schedule(ddim_num_steps=steps, ddim_eta=self.eta, ddim_discretize=p.ddim_discretize, verbose=False)
|
self.sampler.make_schedule(ddim_num_steps=steps, verbose=False)
|
||||||
except Exception:
|
except Exception:
|
||||||
self.sampler.make_schedule(ddim_num_steps=steps+1, ddim_eta=self.eta, ddim_discretize=p.ddim_discretize, verbose=False)
|
self.sampler.make_schedule(ddim_num_steps=steps+1, 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 = 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
|
||||||
self.init_latent = x
|
self.init_latent = x
|
||||||
self.step = 0
|
self.step = 0
|
||||||
|
|
||||||
@@ -197,18 +137,21 @@ class VanillaStableDiffusionSampler:
|
|||||||
return samples
|
return samples
|
||||||
|
|
||||||
def sample(self, p, x, conditioning, unconditional_conditioning, steps=None):
|
def sample(self, p, x, conditioning, unconditional_conditioning, steps=None):
|
||||||
self.initialize(p)
|
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 = None
|
||||||
|
self.nmask = None
|
||||||
self.init_latent = None
|
self.init_latent = None
|
||||||
self.step = 0
|
self.step = 0
|
||||||
|
|
||||||
steps = steps or p.steps
|
steps = steps or p.steps
|
||||||
|
|
||||||
# existing code fails with certain step counts, like 9
|
# existing code fails with cetin step counts, like 9
|
||||||
try:
|
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)
|
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)
|
||||||
except Exception:
|
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)
|
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)
|
||||||
|
|
||||||
return samples_ddim
|
return samples_ddim
|
||||||
|
|
||||||
@@ -223,42 +166,19 @@ class CFGDenoiser(torch.nn.Module):
|
|||||||
self.step = 0
|
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)
|
cond = prompt_parser.reconstruct_cond_batch(cond, self.step)
|
||||||
uncond = prompt_parser.reconstruct_cond_batch(uncond, self.step)
|
uncond = prompt_parser.reconstruct_cond_batch(uncond, self.step)
|
||||||
|
|
||||||
batch_size = len(conds_list)
|
if shared.batch_cond_uncond:
|
||||||
repeats = [len(conds_list[i]) for i in range(batch_size)]
|
x_in = torch.cat([x] * 2)
|
||||||
|
sigma_in = torch.cat([sigma] * 2)
|
||||||
x_in = torch.cat([torch.stack([x[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [x])
|
cond_in = torch.cat([uncond, cond])
|
||||||
sigma_in = torch.cat([torch.stack([sigma[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [sigma])
|
uncond, cond = self.inner_model(x_in, sigma_in, cond=cond_in).chunk(2)
|
||||||
|
denoised = uncond + (cond - uncond) * cond_scale
|
||||||
if tensor.shape[1] == uncond.shape[1]:
|
|
||||||
cond_in = torch.cat([tensor, uncond])
|
|
||||||
|
|
||||||
if shared.batch_cond_uncond:
|
|
||||||
x_out = self.inner_model(x_in, sigma_in, cond=cond_in)
|
|
||||||
else:
|
|
||||||
x_out = torch.zeros_like(x_in)
|
|
||||||
for batch_offset in range(0, x_out.shape[0], batch_size):
|
|
||||||
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])
|
|
||||||
else:
|
else:
|
||||||
x_out = torch.zeros_like(x_in)
|
uncond = self.inner_model(x, sigma, cond=uncond)
|
||||||
batch_size = batch_size*2 if shared.batch_cond_uncond else batch_size
|
cond = self.inner_model(x, sigma, cond=cond)
|
||||||
for batch_offset in range(0, tensor.shape[0], batch_size):
|
denoised = uncond + (cond - uncond) * cond_scale
|
||||||
a = batch_offset
|
|
||||||
b = min(a + batch_size, tensor.shape[0])
|
|
||||||
x_out[a:b] = self.inner_model(x_in[a:b], sigma_in[a:b], cond=tensor[a:b])
|
|
||||||
|
|
||||||
x_out[-uncond.shape[0]:] = self.inner_model(x_in[-uncond.shape[0]:], sigma_in[-uncond.shape[0]:], cond=uncond)
|
|
||||||
|
|
||||||
denoised_uncond = x_out[-uncond.shape[0]:]
|
|
||||||
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
|
||||||
@@ -272,10 +192,8 @@ def extended_trange(sampler, count, *args, **kwargs):
|
|||||||
state.sampling_steps = count
|
state.sampling_steps = count
|
||||||
state.sampling_step = 0
|
state.sampling_step = 0
|
||||||
|
|
||||||
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 tqdm.trange(count, *args, desc=state.job, file=shared.progress_print_out, **kwargs):
|
||||||
|
if state.interrupted:
|
||||||
for x in seq:
|
|
||||||
if state.interrupted or state.skipped:
|
|
||||||
break
|
break
|
||||||
|
|
||||||
if sampler.stop_at is not None and x > sampler.stop_at:
|
if sampler.stop_at is not None and x > sampler.stop_at:
|
||||||
@@ -306,14 +224,10 @@ class KDiffusionSampler:
|
|||||||
self.model_wrap = k_diffusion.external.CompVisDenoiser(sd_model, quantize=shared.opts.enable_quantization)
|
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_noises = None
|
||||||
self.sampler_noise_index = 0
|
self.sampler_noise_index = 0
|
||||||
self.stop_at = None
|
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"])
|
||||||
@@ -332,12 +246,22 @@ class KDiffusionSampler:
|
|||||||
self.sampler_noise_index += 1
|
self.sampler_noise_index += 1
|
||||||
return res
|
return res
|
||||||
|
|
||||||
def initialize(self, p):
|
def sample_img2img(self, p, x, noise, conditioning, unconditional_conditioning, steps=None):
|
||||||
|
steps, t_enc = setup_img2img_steps(p, steps)
|
||||||
|
|
||||||
|
sigmas = self.model_wrap.get_sigmas(steps)
|
||||||
|
|
||||||
|
noise = noise * sigmas[steps - t_enc - 1]
|
||||||
|
|
||||||
|
xi = x + noise
|
||||||
|
|
||||||
|
sigma_sched = sigmas[steps - t_enc - 1:]
|
||||||
|
|
||||||
self.model_wrap_cfg.mask = p.mask if hasattr(p, 'mask') else None
|
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_cfg.nmask = p.nmask if hasattr(p, 'nmask') else None
|
||||||
|
self.model_wrap_cfg.init_latent = x
|
||||||
self.model_wrap.step = 0
|
self.model_wrap.step = 0
|
||||||
self.sampler_noise_index = 0
|
self.sampler_noise_index = 0
|
||||||
self.eta = p.eta or opts.eta_ancestral
|
|
||||||
|
|
||||||
if hasattr(k_diffusion.sampling, 'trange'):
|
if hasattr(k_diffusion.sampling, 'trange'):
|
||||||
k_diffusion.sampling.trange = lambda *args, **kwargs: extended_trange(self, *args, **kwargs)
|
k_diffusion.sampling.trange = lambda *args, **kwargs: extended_trange(self, *args, **kwargs)
|
||||||
@@ -345,67 +269,24 @@ class KDiffusionSampler:
|
|||||||
if self.sampler_noises is not None:
|
if self.sampler_noises is not None:
|
||||||
k_diffusion.sampling.torch = TorchHijack(self)
|
k_diffusion.sampling.torch = TorchHijack(self)
|
||||||
|
|
||||||
extra_params_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)
|
||||||
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)
|
|
||||||
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)
|
|
||||||
|
|
||||||
sigma_sched = sigmas[steps - t_enc - 1:]
|
|
||||||
xi = x + noise * sigma_sched[0]
|
|
||||||
|
|
||||||
extra_params_kwargs = self.initialize(p)
|
|
||||||
if 'sigma_min' in inspect.signature(self.func).parameters:
|
|
||||||
## last sigma is zero which isn't allowed by DPM Fast & Adaptive so taking value before last
|
|
||||||
extra_params_kwargs['sigma_min'] = sigma_sched[-2]
|
|
||||||
if 'sigma_max' in inspect.signature(self.func).parameters:
|
|
||||||
extra_params_kwargs['sigma_max'] = sigma_sched[0]
|
|
||||||
if 'n' in inspect.signature(self.func).parameters:
|
|
||||||
extra_params_kwargs['n'] = len(sigma_sched) - 1
|
|
||||||
if 'sigma_sched' in inspect.signature(self.func).parameters:
|
|
||||||
extra_params_kwargs['sigma_sched'] = sigma_sched
|
|
||||||
if 'sigmas' in inspect.signature(self.func).parameters:
|
|
||||||
extra_params_kwargs['sigmas'] = sigma_sched
|
|
||||||
|
|
||||||
self.model_wrap_cfg.init_latent = x
|
|
||||||
|
|
||||||
return self.func(self.model_wrap_cfg, xi, 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):
|
def sample(self, p, x, conditioning, unconditional_conditioning, steps=None):
|
||||||
steps = steps or p.steps
|
steps = steps or p.steps
|
||||||
|
|
||||||
if p.sampler_noise_scheduler_override:
|
sigmas = self.model_wrap.get_sigmas(steps)
|
||||||
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)
|
|
||||||
|
|
||||||
x = x * sigmas[0]
|
x = x * sigmas[0]
|
||||||
|
|
||||||
extra_params_kwargs = self.initialize(p)
|
self.model_wrap_cfg.step = 0
|
||||||
if 'sigma_min' in inspect.signature(self.func).parameters:
|
self.sampler_noise_index = 0
|
||||||
extra_params_kwargs['sigma_min'] = self.model_wrap.sigmas[0].item()
|
|
||||||
extra_params_kwargs['sigma_max'] = self.model_wrap.sigmas[-1].item()
|
if hasattr(k_diffusion.sampling, 'trange'):
|
||||||
if 'n' in inspect.signature(self.func).parameters:
|
k_diffusion.sampling.trange = lambda *args, **kwargs: extended_trange(self, *args, **kwargs)
|
||||||
extra_params_kwargs['n'] = steps
|
|
||||||
else:
|
if self.sampler_noises is not None:
|
||||||
extra_params_kwargs['sigmas'] = sigmas
|
k_diffusion.sampling.torch = TorchHijack(self)
|
||||||
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)
|
|
||||||
|
samples = 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)
|
||||||
|
|
||||||
return samples
|
return samples
|
||||||
|
|
||||||
+35
-93
@@ -1,36 +1,32 @@
|
|||||||
|
import sys
|
||||||
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 tqdm
|
import tqdm
|
||||||
|
import datetime
|
||||||
|
|
||||||
import modules.artists
|
import modules.artists
|
||||||
|
from modules.paths import script_path, sd_path
|
||||||
|
from modules.devices import get_optimal_device
|
||||||
|
import modules.styles
|
||||||
import modules.interrogate
|
import modules.interrogate
|
||||||
import modules.memmon
|
import modules.memmon
|
||||||
import modules.sd_models
|
import modules.sd_models
|
||||||
import modules.styles
|
|
||||||
import modules.devices as devices
|
|
||||||
from modules import sd_samplers
|
|
||||||
from modules.hypernetworks import hypernetwork
|
|
||||||
from modules.paths import models_path, script_path, sd_path
|
|
||||||
|
|
||||||
sd_model_file = os.path.join(script_path, 'model.ckpt')
|
sd_model_file = os.path.join(script_path, 'model.ckpt')
|
||||||
default_sd_model_file = sd_model_file
|
default_sd_model_file = sd_model_file
|
||||||
|
|
||||||
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=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", type=str, default=sd_model_file, help="path to checkpoint of stable diffusion model; this checkpoint will be added to the list of checkpoints and loaded by default if you don't have a checkpoint selected in settings",)
|
||||||
parser.add_argument("--ckpt-dir", type=str, default=None, help="Path to directory with stable diffusion checkpoints")
|
parser.add_argument("--ckpt-dir", type=str, default=os.path.join(script_path, 'models'), 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=None)
|
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-half-vae", action='store_true', help="do not switch the VAE 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 acceleration 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=os.path.join(script_path, 'embeddings'), help="embeddings directory 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("--hypernetwork-dir", type=str, default=os.path.join(models_path, 'hypernetworks'), help="hypernetwork directory")
|
|
||||||
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 sacrificing 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 sacrificing 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")
|
||||||
@@ -38,22 +34,11 @@ parser.add_argument("--always-batch-cond-uncond", action='store_true', help="dis
|
|||||||
parser.add_argument("--unload-gfpgan", action='store_true', help="does not do anything.")
|
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("--ngrok", type=str, help="ngrok authtoken, alternative to gradio --share", default=None)
|
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(models_path, 'Codeformer'))
|
parser.add_argument("--swinir-models-path", type=str, help="path to directory with SwinIR models", default=os.path.join(script_path, 'SwinIR'))
|
||||||
parser.add_argument("--gfpgan-models-path", type=str, help="Path to directory with GFPGAN model file(s).", default=os.path.join(models_path, 'GFPGAN'))
|
|
||||||
parser.add_argument("--esrgan-models-path", type=str, help="Path to directory with ESRGAN model file(s).", default=os.path.join(models_path, 'ESRGAN'))
|
|
||||||
parser.add_argument("--bsrgan-models-path", type=str, help="Path to directory with BSRGAN model file(s).", default=os.path.join(models_path, 'BSRGAN'))
|
|
||||||
parser.add_argument("--realesrgan-models-path", type=str, help="Path to directory with RealESRGAN model file(s).", default=os.path.join(models_path, 'RealESRGAN'))
|
|
||||||
parser.add_argument("--scunet-models-path", type=str, help="Path to directory with ScuNET model file(s).", default=os.path.join(models_path, 'ScuNET'))
|
|
||||||
parser.add_argument("--swinir-models-path", type=str, help="Path to directory with SwinIR model file(s).", default=os.path.join(models_path, 'SwinIR'))
|
|
||||||
parser.add_argument("--ldsr-models-path", type=str, help="Path to directory with LDSR model file(s).", default=os.path.join(models_path, 'LDSR'))
|
|
||||||
parser.add_argument("--xformers", action='store_true', help="enable xformers for cross attention layers")
|
|
||||||
parser.add_argument("--force-enable-xformers", action='store_true', help="enable xformers for cross attention layers regardless of whether the checking code thinks you can run it; do not make bug reports if this fails to work")
|
|
||||||
parser.add_argument("--deepdanbooru", action='store_true', help="enable deepdanbooru interrogator")
|
|
||||||
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("--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("--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("--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("--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("--show-negative-prompt", action='store_true', help="does not do anything", default=False)
|
||||||
@@ -62,56 +47,31 @@ parser.add_argument("--hide-ui-dir-config", action='store_true', help="hide dire
|
|||||||
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("--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-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-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("--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("--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("--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("--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)
|
|
||||||
parser.add_argument('--vae-path', type=str, help='Path to Variational Autoencoders model', default=None)
|
|
||||||
parser.add_argument("--disable-safe-unpickle", action='store_true', help="disable checking pytorch models for malicious code", default=False)
|
|
||||||
|
|
||||||
|
|
||||||
cmd_opts = parser.parse_args()
|
cmd_opts = parser.parse_args()
|
||||||
|
|
||||||
devices.device, devices.device_gfpgan, devices.device_bsrgan, devices.device_esrgan, devices.device_scunet, devices.device_codeformer = \
|
device = get_optimal_device()
|
||||||
(devices.cpu if x in cmd_opts.use_cpu else devices.get_optimal_device() for x in ['SD', 'GFPGAN', 'BSRGAN', 'ESRGAN', 'SCUNet', 'CodeFormer'])
|
|
||||||
|
|
||||||
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
|
||||||
xformers_available = False
|
|
||||||
config_filename = cmd_opts.ui_settings_file
|
config_filename = cmd_opts.ui_settings_file
|
||||||
|
|
||||||
hypernetworks = hypernetwork.list_hypernetworks(cmd_opts.hypernetwork_dir)
|
|
||||||
loaded_hypernetwork = None
|
|
||||||
|
|
||||||
|
|
||||||
def reload_hypernetworks():
|
|
||||||
global hypernetworks
|
|
||||||
|
|
||||||
hypernetworks = hypernetwork.list_hypernetworks(cmd_opts.hypernetwork_dir)
|
|
||||||
hypernetwork.load_hypernetwork(opts.sd_hypernetwork)
|
|
||||||
|
|
||||||
|
|
||||||
class State:
|
class State:
|
||||||
skipped = False
|
|
||||||
interrupted = False
|
interrupted = False
|
||||||
job = ""
|
job = ""
|
||||||
job_no = 0
|
job_no = 0
|
||||||
job_count = 0
|
job_count = 0
|
||||||
job_timestamp = '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 skip(self):
|
|
||||||
self.skipped = True
|
|
||||||
|
|
||||||
def interrupt(self):
|
def interrupt(self):
|
||||||
self.interrupted = True
|
self.interrupted = True
|
||||||
@@ -120,9 +80,8 @@ class State:
|
|||||||
self.job_no += 1
|
self.job_no += 1
|
||||||
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):
|
def get_job_timestamp(self):
|
||||||
return datetime.datetime.now().strftime("%Y%m%d%H%M%S") # shouldn't this return job_timestamp?
|
return datetime.datetime.now().strftime("%Y%m%d%H%M%S")
|
||||||
|
|
||||||
|
|
||||||
state = State()
|
state = State()
|
||||||
@@ -136,26 +95,27 @@ interrogator = modules.interrogate.InterrogateModels("interrogate")
|
|||||||
|
|
||||||
face_restorers = []
|
face_restorers = []
|
||||||
|
|
||||||
|
modules.sd_models.list_models()
|
||||||
|
|
||||||
|
|
||||||
def realesrgan_models_names():
|
def realesrgan_models_names():
|
||||||
import modules.realesrgan_model
|
import modules.realesrgan_model
|
||||||
return [x.name for x in modules.realesrgan_model.get_realesrgan_models(None)]
|
return [x.name for x in modules.realesrgan_model.get_realesrgan_models()]
|
||||||
|
|
||||||
|
|
||||||
class OptionInfo:
|
class OptionInfo:
|
||||||
def __init__(self, default=None, label="", component=None, component_args=None, onchange=None, show_on_main_page=False):
|
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.onchange = onchange
|
||||||
self.section = None
|
self.section = None
|
||||||
self.show_on_main_page = show_on_main_page
|
|
||||||
|
|
||||||
|
|
||||||
def options_section(section_identifier, options_dict):
|
def options_section(section_identifer, options_dict):
|
||||||
for k, v in options_dict.items():
|
for k, v in options_dict.items():
|
||||||
v.section = section_identifier
|
v.section = section_identifer
|
||||||
|
|
||||||
return options_dict
|
return options_dict
|
||||||
|
|
||||||
@@ -182,8 +142,6 @@ options_templates.update(options_section(('saving-images', "Saving images/grids"
|
|||||||
"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"),
|
||||||
|
|
||||||
"use_original_name_batch": OptionInfo(False, "Use original name for output filename during batch process in extras tab"),
|
"use_original_name_batch": OptionInfo(False, "Use original name for output filename during batch process in extras tab"),
|
||||||
"save_selected_only": OptionInfo(True, "When using 'Save' button, only save a single selected image"),
|
|
||||||
"do_not_add_watermark": OptionInfo(False, "Do not add watermark to images"),
|
|
||||||
}))
|
}))
|
||||||
|
|
||||||
options_templates.update(options_section(('saving-paths', "Paths for saving"), {
|
options_templates.update(options_section(('saving-paths', "Paths for saving"), {
|
||||||
@@ -199,47 +157,46 @@ options_templates.update(options_section(('saving-paths', "Paths for saving"), {
|
|||||||
|
|
||||||
options_templates.update(options_section(('saving-to-dirs', "Saving to a directory"), {
|
options_templates.update(options_section(('saving-to-dirs', "Saving to a directory"), {
|
||||||
"save_to_dirs": OptionInfo(False, "Save images to a subdirectory"),
|
"save_to_dirs": OptionInfo(False, "Save images to a subdirectory"),
|
||||||
"grid_save_to_dirs": OptionInfo(False, "Save grids to a subdirectory"),
|
"grid_save_to_dirs": OptionInfo(False, "Save grids to 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_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}),
|
"directories_max_prompt_words": OptionInfo(8, "Max prompt words", gr.Slider, {"minimum": 1, "maximum": 20, "step": 1}),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
options_templates.update(options_section(('upscaling', "Upscaling"), {
|
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": 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}),
|
"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()}),
|
"realesrgan_enabled_models": OptionInfo(["Real-ESRGAN 4x plus", "Real-ESRGAN 4x plus anime 6B"], "Select which RealESRGAN 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": 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}),
|
"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}),
|
"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]}),
|
"ldsr_pre_down": OptionInfo(1, "LDSR Pre-process downssample scale. 1 = no down-sampling, 4 = 1/4 scale.", gr.Slider, {"minimum": 1, "maximum": 4, "step": 1}),
|
||||||
|
"ldsr_post_down": OptionInfo(1, "LDSR Post-process down-sample scale. 1 = no down-sampling, 4 = 1/4 scale.", gr.Slider, {"minimum": 1, "maximum": 4, "step": 1}),
|
||||||
|
|
||||||
|
"upscaler_for_img2img": OptionInfo(None, "Upscaler for img2img", gr.Radio, lambda: {"choices": [x.name for x in sd_upscalers]}),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
options_templates.update(options_section(('face-restoration', "Face restoration"), {
|
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"),
|
"face_restoration_unload": OptionInfo(False, "Move face restoration model from VRAM into RAM after processing"),
|
||||||
|
"save_selected_only": OptionInfo(False, "When using 'Save' button, only save a single selected image"),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
options_templates.update(options_section(('system', "System"), {
|
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}),
|
"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"),
|
"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."),
|
"multiple_tqdm": OptionInfo(True, "Add a second progress bar to the console that shows progress for an entire job. Broken in PyCharm console."),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
options_templates.update(options_section(('sd', "Stable Diffusion"), {
|
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()}, show_on_main_page=True),
|
"sd_model_checkpoint": OptionInfo(None, "Stable Diffusion checkpoint", gr.Radio, lambda: {"choices": [x.title for x in modules.sd_models.checkpoints_list.values()]}),
|
||||||
"sd_hypernetwork": OptionInfo("None", "Stable Diffusion finetune hypernetwork", gr.Dropdown, lambda: {"choices": ["None"] + [x for x in hypernetworks.keys()]}),
|
|
||||||
"img2img_color_correction": OptionInfo(False, "Apply color correction to img2img results to match original colors."),
|
"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"),
|
"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)."),
|
"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_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"),
|
"enable_emphasis": OptionInfo(True, "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"),
|
"enable_batch_seeds": OptionInfo(True, "Make K-diffusion samplers produce same images in a batch as when making a single image"),
|
||||||
"comma_padding_backtrack": OptionInfo(20, "Increase coherency by padding from the last comma within n tokens when using more than 75 tokens", gr.Slider, {"minimum": 0, "maximum": 74, "step": 1 }),
|
|
||||||
"filter_nsfw": OptionInfo(False, "Filter NSFW content"),
|
"filter_nsfw": OptionInfo(False, "Filter NSFW content"),
|
||||||
'CLIP_stop_at_last_layers': OptionInfo(1, "Stop At last layers of CLIP model", gr.Slider, {"minimum": 1, "maximum": 12, "step": 1}),
|
|
||||||
"random_artist_categories": OptionInfo([], "Allowed categories for random artists selection when using the Roll button", gr.CheckboxGroup, {"choices": artist_db.categories()}),
|
"random_artist_categories": OptionInfo([], "Allowed categories for random artists selection when using the Roll button", gr.CheckboxGroup, {"choices": artist_db.categories()}),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
@@ -250,31 +207,16 @@ options_templates.update(options_section(('interrogate', "Interrogate Options"),
|
|||||||
"interrogate_clip_min_length": OptionInfo(24, "Interrogate: minimum description length (excluding artists, etc..)", gr.Slider, {"minimum": 1, "maximum": 128, "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_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)"),
|
"interrogate_clip_dict_limit": OptionInfo(1500, "Interrogate: maximum number of lines in text file (0 = No limit)"),
|
||||||
"interrogate_deepbooru_score_threshold": OptionInfo(0.5, "Interrogate: deepbooru score threshold", gr.Slider, {"minimum": 0, "maximum": 1, "step": 0.01}),
|
|
||||||
}))
|
}))
|
||||||
|
|
||||||
options_templates.update(options_section(('ui', "User interface"), {
|
options_templates.update(options_section(('ui', "User interface"), {
|
||||||
"show_progressbar": OptionInfo(True, "Show progressbar"),
|
"show_progressbar": OptionInfo(True, "Show progressbar"),
|
||||||
"show_progress_every_n_steps": OptionInfo(0, "Show image creation progress every N sampling steps. Set 0 to disable.", gr.Slider, {"minimum": 0, "maximum": 32, "step": 1}),
|
"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"),
|
"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"),
|
"add_model_hash_to_info": OptionInfo(True, "Add model hash to generation information"),
|
||||||
"add_model_name_to_info": OptionInfo(False, "Add model name to generation information"),
|
|
||||||
"font": OptionInfo("", "Font for image grids that have text"),
|
"font": OptionInfo("", "Font for image grids that have text"),
|
||||||
"js_modal_lightbox": OptionInfo(True, "Enable full page image viewer"),
|
"js_modal_lightbox": OptionInfo(True, "Enable full page image viewer"),
|
||||||
"js_modal_lightbox_initially_zoomed": OptionInfo(True, "Show images zoomed in by default in full page image viewer"),
|
"js_modal_lightbox_initialy_zoomed": OptionInfo(True, "Show images zoomed in by default in full page image viewer"),
|
||||||
"show_progress_in_title": OptionInfo(True, "Show generation progress in window title."),
|
|
||||||
}))
|
|
||||||
|
|
||||||
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}),
|
|
||||||
'eta_noise_seed_delta': OptionInfo(0, "Eta noise seed delta", gr.Number, {"precision": 0}),
|
|
||||||
}))
|
}))
|
||||||
|
|
||||||
|
|
||||||
@@ -363,14 +305,14 @@ class TotalTQDM:
|
|||||||
)
|
)
|
||||||
|
|
||||||
def update(self):
|
def update(self):
|
||||||
if not opts.multiple_tqdm or cmd_opts.disable_console_progressbars:
|
if not opts.multiple_tqdm:
|
||||||
return
|
return
|
||||||
if self._tqdm is None:
|
if self._tqdm is None:
|
||||||
self.reset()
|
self.reset()
|
||||||
self._tqdm.update()
|
self._tqdm.update()
|
||||||
|
|
||||||
def updateTotal(self, new_total):
|
def updateTotal(self, new_total):
|
||||||
if not opts.multiple_tqdm or cmd_opts.disable_console_progressbars:
|
if not opts.multiple_tqdm:
|
||||||
return
|
return
|
||||||
if self._tqdm is None:
|
if self._tqdm is None:
|
||||||
self.reset()
|
self.reset()
|
||||||
|
|||||||
@@ -53,12 +53,6 @@ class StyleDatabase:
|
|||||||
negative_prompt = row.get("negative_prompt", "")
|
negative_prompt = row.get("negative_prompt", "")
|
||||||
self.styles[row["name"]] = PromptStyle(row["name"], prompt, 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):
|
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])
|
return apply_styles_to_prompt(prompt, [self.styles.get(x, self.no_style).prompt for x in styles])
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
import sys
|
||||||
|
import traceback
|
||||||
|
import cv2
|
||||||
|
import os
|
||||||
|
import contextlib
|
||||||
|
import numpy as np
|
||||||
|
from PIL import Image
|
||||||
|
import torch
|
||||||
|
import modules.images
|
||||||
|
from modules.shared import cmd_opts, opts, device
|
||||||
|
from modules.swinir_arch import SwinIR as net
|
||||||
|
|
||||||
|
precision_scope = (
|
||||||
|
torch.autocast if cmd_opts.precision == "autocast" else contextlib.nullcontext
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def load_model(filename, scale=4):
|
||||||
|
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 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(UpscalerSwin(path, model_name))
|
||||||
|
except Exception:
|
||||||
|
print(f"Error loading SwinIR model: {path}", file=sys.stderr)
|
||||||
|
print(traceback.format_exc(), file=sys.stderr)
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
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)
|
||||||
|
output = E.div_(W)
|
||||||
|
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
class UpscalerSwin(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(device)
|
||||||
|
img = upscale(img, model)
|
||||||
|
return img
|
||||||
@@ -166,7 +166,7 @@ class SwinTransformerBlock(nn.Module):
|
|||||||
|
|
||||||
Args:
|
Args:
|
||||||
dim (int): Number of input channels.
|
dim (int): Number of input channels.
|
||||||
input_resolution (tuple[int]): Input resolution.
|
input_resolution (tuple[int]): Input resulotion.
|
||||||
num_heads (int): Number of attention heads.
|
num_heads (int): Number of attention heads.
|
||||||
window_size (int): Window size.
|
window_size (int): Window size.
|
||||||
shift_size (int): Shift size for SW-MSA.
|
shift_size (int): Shift size for SW-MSA.
|
||||||
@@ -1,161 +0,0 @@
|
|||||||
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.shared import cmd_opts, opts, device
|
|
||||||
from modules.swinir_model_arch import SwinIR as net
|
|
||||||
from modules.swinir_model_arch_v2 import Swin2SR as net2
|
|
||||||
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.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
|
|
||||||
if filename.endswith(".v2.pth"):
|
|
||||||
model = net2(
|
|
||||||
upscale=scale,
|
|
||||||
in_chans=3,
|
|
||||||
img_size=64,
|
|
||||||
window_size=8,
|
|
||||||
img_range=1.0,
|
|
||||||
depths=[6, 6, 6, 6, 6, 6],
|
|
||||||
embed_dim=180,
|
|
||||||
num_heads=[6, 6, 6, 6, 6, 6],
|
|
||||||
mlp_ratio=2,
|
|
||||||
upsampler="nearest+conv",
|
|
||||||
resi_connection="1conv",
|
|
||||||
)
|
|
||||||
params = None
|
|
||||||
else:
|
|
||||||
model = net(
|
|
||||||
upscale=scale,
|
|
||||||
in_chans=3,
|
|
||||||
img_size=64,
|
|
||||||
window_size=8,
|
|
||||||
img_range=1.0,
|
|
||||||
depths=[6, 6, 6, 6, 6, 6, 6, 6, 6],
|
|
||||||
embed_dim=240,
|
|
||||||
num_heads=[8, 8, 8, 8, 8, 8, 8, 8, 8],
|
|
||||||
mlp_ratio=2,
|
|
||||||
upsampler="nearest+conv",
|
|
||||||
resi_connection="3conv",
|
|
||||||
)
|
|
||||||
params = "params_ema"
|
|
||||||
|
|
||||||
pretrained_model = torch.load(filename)
|
|
||||||
if params is not None:
|
|
||||||
model.load_state_dict(pretrained_model[params], strict=True)
|
|
||||||
else:
|
|
||||||
model.load_state_dict(pretrained_model, 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
|
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -1,80 +0,0 @@
|
|||||||
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, width, height, repeats, flip_p=0.5, placeholder_token="*", model=None, device=None, template_file=None):
|
|
||||||
|
|
||||||
self.placeholder_token = placeholder_token
|
|
||||||
|
|
||||||
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
|
|
||||||
@@ -1,105 +0,0 @@
|
|||||||
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_width, process_height, process_flip, process_split, process_caption):
|
|
||||||
width = process_width
|
|
||||||
height = process_height
|
|
||||||
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((width, height * img.height // img.width))
|
|
||||||
|
|
||||||
top = img.crop((0, 0, width, height))
|
|
||||||
save_pic(top, index)
|
|
||||||
|
|
||||||
bot = img.crop((0, img.height - height, width, img.height))
|
|
||||||
save_pic(bot, index)
|
|
||||||
elif process_split and is_wide:
|
|
||||||
img = img.resize((width * img.width // img.height, height))
|
|
||||||
|
|
||||||
left = img.crop((0, 0, width, height))
|
|
||||||
save_pic(left, index)
|
|
||||||
|
|
||||||
right = img.crop((img.width - width, 0, img.width, height))
|
|
||||||
save_pic(right, index)
|
|
||||||
else:
|
|
||||||
img = images.resize_image(1, img, width, height)
|
|
||||||
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()
|
|
||||||
@@ -1,281 +0,0 @@
|
|||||||
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, training_width, training_height, steps, num_repeats, create_image_every, save_embedding_every, template_file, preview_image_prompt):
|
|
||||||
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, width=training_width, height=training_height, repeats=num_repeats, 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
|
|
||||||
|
|
||||||
tr_img_len = len([os.path.join(data_root, file_path) for file_path in os.listdir(data_root)])
|
|
||||||
epoch_len = (tr_img_len * num_repeats) + tr_img_len
|
|
||||||
|
|
||||||
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()
|
|
||||||
|
|
||||||
epoch_num = embedding.step // epoch_len
|
|
||||||
epoch_step = embedding.step - (epoch_num * epoch_len) + 1
|
|
||||||
|
|
||||||
pbar.set_description(f"[Epoch {epoch_num}: {epoch_step}/{epoch_len}]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')
|
|
||||||
|
|
||||||
preview_text = text if preview_image_prompt == "" else preview_image_prompt
|
|
||||||
|
|
||||||
p = processing.StableDiffusionProcessingTxt2Img(
|
|
||||||
sd_model=shared.sd_model,
|
|
||||||
prompt=preview_text,
|
|
||||||
steps=20,
|
|
||||||
height=training_height,
|
|
||||||
width=training_width,
|
|
||||||
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: {preview_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
|
|
||||||
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
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()
|
|
||||||
|
|
||||||
+1
-6
@@ -34,9 +34,7 @@ def txt2img(prompt: str, negative_prompt: str, prompt_style: str, prompt_style2:
|
|||||||
denoising_strength=denoising_strength 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)
|
||||||
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 None:
|
if processed is None:
|
||||||
@@ -48,8 +46,5 @@ def txt2img(prompt: str, negative_prompt: str, prompt_style: str, prompt_style2:
|
|||||||
if opts.samples_log_stdout:
|
if opts.samples_log_stdout:
|
||||||
print(generation_info_js)
|
print(generation_info_js)
|
||||||
|
|
||||||
if opts.do_not_show_images:
|
|
||||||
processed.images = []
|
|
||||||
|
|
||||||
return processed.images, generation_info_js, plaintext_to_html(processed.info)
|
return processed.images, generation_info_js, plaintext_to_html(processed.info)
|
||||||
|
|
||||||
+71
-545
File diff suppressed because it is too large.
Load diff
@@ -1,122 +0,0 @@
|
|||||||
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.model_path is None and self.name:
|
|
||||||
self.model_path = os.path.join(models_path, self.name)
|
|
||||||
if self.model_path and create_dirs:
|
|
||||||
os.makedirs(self.model_path, exist_ok=True)
|
|
||||||
|
|
||||||
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)]
|
|
||||||
|
|
||||||
+4
-9
@@ -4,8 +4,9 @@ fairscale==0.4.4
|
|||||||
fonts
|
fonts
|
||||||
font-roboto
|
font-roboto
|
||||||
gfpgan
|
gfpgan
|
||||||
gradio==3.4b3
|
gradio
|
||||||
invisible-watermark
|
invisible-watermark
|
||||||
|
git+https://github.com/crowsonkb/k-diffusion.git
|
||||||
numpy
|
numpy
|
||||||
omegaconf
|
omegaconf
|
||||||
piexif
|
piexif
|
||||||
@@ -13,13 +14,7 @@ Pillow
|
|||||||
pytorch_lightning
|
pytorch_lightning
|
||||||
realesrgan
|
realesrgan
|
||||||
scikit-image>=0.19
|
scikit-image>=0.19
|
||||||
|
git+https://github.com/TencentARC/GFPGAN.git@8d2447a2d918f8eba5a4a01463fd48e45126a379
|
||||||
timm==0.4.12
|
timm==0.4.12
|
||||||
transformers==4.19.2
|
transformers
|
||||||
torch
|
torch
|
||||||
einops
|
|
||||||
jsonmerge
|
|
||||||
clean-fid
|
|
||||||
resize-right
|
|
||||||
torchdiffeq
|
|
||||||
kornia
|
|
||||||
lark
|
|
||||||
@@ -15,10 +15,3 @@ font-roboto
|
|||||||
timm==0.6.7
|
timm==0.6.7
|
||||||
fairscale==0.4.9
|
fairscale==0.4.9
|
||||||
piexif==1.1.3
|
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
|
|
||||||
@@ -6,10 +6,6 @@ function get_uiCurrentTab() {
|
|||||||
return gradioApp().querySelector('.tabs button:not(.border-transparent)')
|
return gradioApp().querySelector('.tabs button:not(.border-transparent)')
|
||||||
}
|
}
|
||||||
|
|
||||||
function get_uiCurrentTabContent() {
|
|
||||||
return gradioApp().querySelector('.tabitem[id^=tab_]:not([style*="display: none"])')
|
|
||||||
}
|
|
||||||
|
|
||||||
uiUpdateCallbacks = []
|
uiUpdateCallbacks = []
|
||||||
uiTabChangeCallbacks = []
|
uiTabChangeCallbacks = []
|
||||||
let uiCurrentTab = null
|
let uiCurrentTab = null
|
||||||
@@ -44,25 +40,6 @@ document.addEventListener("DOMContentLoaded", function() {
|
|||||||
mutationObserver.observe( gradioApp(), { childList:true, subtree:true })
|
mutationObserver.observe( gradioApp(), { childList:true, subtree:true })
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
|
||||||
* Add a ctrl+enter as a shortcut to start a generation
|
|
||||||
*/
|
|
||||||
document.addEventListener('keydown', function(e) {
|
|
||||||
var handled = false;
|
|
||||||
if (e.key !== undefined) {
|
|
||||||
if((e.key == "Enter" && (e.metaKey || e.ctrlKey))) handled = true;
|
|
||||||
} else if (e.keyCode !== undefined) {
|
|
||||||
if((e.keyCode == 13 && (e.metaKey || e.ctrlKey))) handled = true;
|
|
||||||
}
|
|
||||||
if (handled) {
|
|
||||||
button = get_uiCurrentTabContent().querySelector('button[id$=_generate]');
|
|
||||||
if (button) {
|
|
||||||
button.click();
|
|
||||||
}
|
|
||||||
e.preventDefault();
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* checks that a UI element is not in another hidden element or tab content
|
* checks that a UI element is not in another hidden element or tab content
|
||||||
*/
|
*/
|
||||||
|
|||||||
+8
-63
@@ -8,6 +8,7 @@ import gradio as gr
|
|||||||
|
|
||||||
from modules import processing, shared, sd_samplers, prompt_parser
|
from modules import processing, shared, sd_samplers, prompt_parser
|
||||||
from modules.processing import Processed
|
from modules.processing import Processed
|
||||||
|
from modules.sd_samplers import samplers
|
||||||
from modules.shared import opts, cmd_opts, state
|
from modules.shared import opts, cmd_opts, state
|
||||||
|
|
||||||
import torch
|
import torch
|
||||||
@@ -58,55 +59,7 @@ def find_noise_for_image(p, cond, uncond, cfg_scale, steps):
|
|||||||
return x / x.std()
|
return x / x.std()
|
||||||
|
|
||||||
|
|
||||||
Cached = namedtuple("Cached", ["noise", "cfg_scale", "steps", "latent", "original_prompt", "original_negative_prompt", "sigma_adjustment"])
|
Cached = namedtuple("Cached", ["noise", "cfg_scale", "steps", "latent", "original_prompt", "original_negative_prompt"])
|
||||||
|
|
||||||
|
|
||||||
# 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):
|
class Script(scripts.Script):
|
||||||
@@ -125,10 +78,9 @@ class Script(scripts.Script):
|
|||||||
cfg = gr.Slider(label="Decode CFG scale", minimum=0.0, maximum=15.0, step=0.1, value=1.0)
|
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)
|
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)
|
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]
|
||||||
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):
|
def run(self, p, original_prompt, original_negative_prompt, cfg, st, randomness):
|
||||||
p.batch_size = 1
|
p.batch_size = 1
|
||||||
p.batch_count = 1
|
p.batch_count = 1
|
||||||
|
|
||||||
@@ -136,10 +88,7 @@ class Script(scripts.Script):
|
|||||||
def sample_extra(conditioning, unconditional_conditioning, seeds, subseeds, subseed_strength):
|
def sample_extra(conditioning, unconditional_conditioning, seeds, subseeds, subseed_strength):
|
||||||
lat = (p.init_latent.cpu().numpy() * 10).astype(int)
|
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 \
|
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.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
|
same_everything = same_params and self.cache.latent.shape == lat.shape and np.abs(self.cache.latent-lat).sum() < 100
|
||||||
|
|
||||||
if same_everything:
|
if same_everything:
|
||||||
@@ -148,17 +97,14 @@ class Script(scripts.Script):
|
|||||||
shared.state.job_count += 1
|
shared.state.job_count += 1
|
||||||
cond = p.sd_model.get_learned_conditioning(p.batch_size * [original_prompt])
|
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])
|
uncond = p.sd_model.get_learned_conditioning(p.batch_size * [original_negative_prompt])
|
||||||
if sigma_adjustment:
|
rec_noise = find_noise_for_image(p, cond, uncond, cfg, st)
|
||||||
rec_noise = find_noise_for_image_sigma_adjustment(p, cond, uncond, cfg, st)
|
self.cache = Cached(rec_noise, cfg, st, lat, original_prompt, original_negative_prompt)
|
||||||
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])])
|
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)
|
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)
|
sampler = samplers[p.sampler_index].constructor(p.sd_model)
|
||||||
|
|
||||||
sigmas = sampler.model_wrap.get_sigmas(p.steps)
|
sigmas = sampler.model_wrap.get_sigmas(p.steps)
|
||||||
|
|
||||||
@@ -175,7 +121,6 @@ class Script(scripts.Script):
|
|||||||
p.extra_generation_params["Decode CFG scale"] = cfg
|
p.extra_generation_params["Decode CFG scale"] = cfg
|
||||||
p.extra_generation_params["Decode steps"] = st
|
p.extra_generation_params["Decode steps"] = st
|
||||||
p.extra_generation_params["Randomness"] = randomness
|
p.extra_generation_params["Randomness"] = randomness
|
||||||
p.extra_generation_params["Sigma Adjustment"] = sigma_adjustment
|
|
||||||
|
|
||||||
processed = processing.process_images(p)
|
processed = processing.process_images(p)
|
||||||
|
|
||||||
|
|||||||
@@ -38,7 +38,6 @@ class Script(scripts.Script):
|
|||||||
|
|
||||||
grids = []
|
grids = []
|
||||||
all_images = []
|
all_images = []
|
||||||
original_init_image = p.init_images
|
|
||||||
state.job_count = loops * batch_count
|
state.job_count = loops * batch_count
|
||||||
|
|
||||||
initial_color_corrections = [processing.setup_color_correction(p.init_images[0])]
|
initial_color_corrections = [processing.setup_color_correction(p.init_images[0])]
|
||||||
@@ -46,9 +45,6 @@ class Script(scripts.Script):
|
|||||||
for n in range(batch_count):
|
for n in range(batch_count):
|
||||||
history = []
|
history = []
|
||||||
|
|
||||||
# Reset to original init image at the start of each batch
|
|
||||||
p.init_images = original_init_image
|
|
||||||
|
|
||||||
for i in range(loops):
|
for i in range(loops):
|
||||||
p.n_iter = 1
|
p.n_iter = 1
|
||||||
p.batch_size = 1
|
p.batch_size = 1
|
||||||
|
|||||||
@@ -11,8 +11,46 @@ 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
|
||||||
|
|
||||||
|
# https://github.com/parlance-zz/g-diffuser-bot
|
||||||
|
def expand(x, dir, amount, power=0.75):
|
||||||
|
is_left = dir == 3
|
||||||
|
is_right = dir == 1
|
||||||
|
is_up = dir == 0
|
||||||
|
is_down = dir == 2
|
||||||
|
|
||||||
|
if is_left or is_right:
|
||||||
|
noise = np.zeros((x.shape[0], amount, 3), dtype=float)
|
||||||
|
indexes = np.random.random((x.shape[0], amount)) ** power * (1 - np.arange(amount) / amount)
|
||||||
|
if is_right:
|
||||||
|
indexes = 1 - indexes
|
||||||
|
indexes = (indexes * (x.shape[1] - 1)).astype(int)
|
||||||
|
|
||||||
|
for row in range(x.shape[0]):
|
||||||
|
if is_left:
|
||||||
|
noise[row] = x[row][indexes[row]]
|
||||||
|
else:
|
||||||
|
noise[row] = np.flip(x[row][indexes[row]], axis=0)
|
||||||
|
|
||||||
|
x = np.concatenate([noise, x] if is_left else [x, noise], axis=1)
|
||||||
|
return x
|
||||||
|
|
||||||
|
if is_up or is_down:
|
||||||
|
noise = np.zeros((amount, x.shape[1], 3), dtype=float)
|
||||||
|
indexes = np.random.random((x.shape[1], amount)) ** power * (1 - np.arange(amount) / amount)
|
||||||
|
if is_down:
|
||||||
|
indexes = 1 - indexes
|
||||||
|
indexes = (indexes * x.shape[0] - 1).astype(int)
|
||||||
|
|
||||||
|
for row in range(x.shape[1]):
|
||||||
|
if is_up:
|
||||||
|
noise[:, row] = x[:, row][indexes[row]]
|
||||||
|
else:
|
||||||
|
noise[:, row] = np.flip(x[:, row][indexes[row]], axis=0)
|
||||||
|
|
||||||
|
x = np.concatenate([noise, x] if is_up else [x, noise], axis=0)
|
||||||
|
return x
|
||||||
|
|
||||||
|
|
||||||
# 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):
|
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
|
# helper fft routines that keep ortho normalization and auto-shift before and after fft
|
||||||
def _fft2(data):
|
def _fft2(data):
|
||||||
@@ -85,11 +123,8 @@ def get_matched_noise(_np_src_image, np_mask_rgb, noise_q=1, color_variation=0.0
|
|||||||
src_dist = np.absolute(src_fft)
|
src_dist = np.absolute(src_fft)
|
||||||
src_phase = src_fft / src_dist
|
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_window = _get_gaussian_window(width, height, mode=1) # start with simple gaussian noise
|
||||||
noise_rgb = rng.random((width, height, num_channels))
|
noise_rgb = np.random.random_sample((width, height, num_channels))
|
||||||
noise_grey = (np.sum(noise_rgb, axis=2) / 3.)
|
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
|
noise_rgb *= color_variation # the colorfulness of the starting noise is blended to greyscale with a parameter
|
||||||
for c in range(num_channels):
|
for c in range(num_channels):
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ from modules.processing import Processed, process_images
|
|||||||
from PIL import Image
|
from PIL import Image
|
||||||
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 "Prompts from file or textbox"
|
return "Prompts from file or textbox"
|
||||||
@@ -28,9 +29,6 @@ class Script(scripts.Script):
|
|||||||
checkbox_txt.change(fn=lambda x: [gr.File.update(visible = not x), gr.TextArea.update(visible = x)], inputs=[checkbox_txt], outputs=[file, prompt_txt])
|
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]
|
return [checkbox_txt, file, prompt_txt]
|
||||||
|
|
||||||
def on_show(self, checkbox_txt, file, prompt_txt):
|
|
||||||
return [ gr.Checkbox.update(visible = True), gr.File.update(visible = not checkbox_txt), gr.TextArea.update(visible = checkbox_txt) ]
|
|
||||||
|
|
||||||
def run(self, p, checkbox_txt, data: bytes, prompt_txt: str):
|
def run(self, p, checkbox_txt, data: bytes, prompt_txt: str):
|
||||||
if (checkbox_txt):
|
if (checkbox_txt):
|
||||||
lines = [x.strip() for x in prompt_txt.splitlines()]
|
lines = [x.strip() for x in prompt_txt.splitlines()]
|
||||||
|
|||||||
@@ -34,11 +34,7 @@ class Script(scripts.Script):
|
|||||||
seed = p.seed
|
seed = p.seed
|
||||||
|
|
||||||
init_img = p.init_images[0]
|
init_img = p.init_images[0]
|
||||||
|
img = upscaler.upscale(init_img, init_img.width * 2, init_img.height * 2)
|
||||||
if(upscaler.name != "None"):
|
|
||||||
img = upscaler.scaler.upscale(init_img, 2, upscaler.data_path)
|
|
||||||
else:
|
|
||||||
img = init_img
|
|
||||||
|
|
||||||
devices.torch_gc()
|
devices.torch_gc()
|
||||||
|
|
||||||
|
|||||||
+25
-110
@@ -1,18 +1,14 @@
|
|||||||
from collections import namedtuple
|
from collections import namedtuple
|
||||||
from copy import copy
|
from copy import copy
|
||||||
from itertools import permutations, chain
|
|
||||||
import random
|
import random
|
||||||
import csv
|
|
||||||
from io import StringIO
|
|
||||||
from PIL import Image
|
|
||||||
import numpy as np
|
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.hypernetworks import hypernetwork
|
from modules.processing import process_images, Processed
|
||||||
from modules.processing import process_images, Processed, get_correct_sampler
|
|
||||||
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.sd_samplers
|
import modules.sd_samplers
|
||||||
@@ -28,49 +24,19 @@ def apply_field(field):
|
|||||||
|
|
||||||
|
|
||||||
def apply_prompt(p, x, xs):
|
def apply_prompt(p, x, xs):
|
||||||
if xs[0] not in p.prompt and xs[0] not in p.negative_prompt:
|
|
||||||
raise RuntimeError(f"Prompt S/R did not find {xs[0]} in prompt or negative prompt.")
|
|
||||||
|
|
||||||
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)
|
p.negative_prompt = p.negative_prompt.replace(xs[0], x)
|
||||||
|
|
||||||
|
|
||||||
def apply_order(p, x, xs):
|
samplers_dict = {}
|
||||||
token_order = []
|
for i, sampler in enumerate(modules.sd_samplers.samplers):
|
||||||
|
samplers_dict[sampler.name.lower()] = i
|
||||||
# Initally grab the tokens from the prompt, so they can be replaced in order of earliest seen
|
for alias in sampler.aliases:
|
||||||
for token in x:
|
samplers_dict[alias.lower()] = i
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
def build_samplers_dict(p):
|
|
||||||
samplers_dict = {}
|
|
||||||
for i, sampler in enumerate(get_correct_sampler(p)):
|
|
||||||
samplers_dict[sampler.name.lower()] = i
|
|
||||||
for alias in sampler.aliases:
|
|
||||||
samplers_dict[alias.lower()] = i
|
|
||||||
return samplers_dict
|
|
||||||
|
|
||||||
|
|
||||||
def apply_sampler(p, x, xs):
|
def apply_sampler(p, x, xs):
|
||||||
sampler_index = build_samplers_dict(p).get(x.lower(), None)
|
sampler_index = samplers_dict.get(x.lower(), None)
|
||||||
if sampler_index is None:
|
if sampler_index is None:
|
||||||
raise RuntimeError(f"Unknown sampler: {x}")
|
raise RuntimeError(f"Unknown sampler: {x}")
|
||||||
|
|
||||||
@@ -78,19 +44,14 @@ def apply_sampler(p, x, xs):
|
|||||||
|
|
||||||
|
|
||||||
def apply_checkpoint(p, x, xs):
|
def apply_checkpoint(p, x, xs):
|
||||||
info = modules.sd_models.get_closet_checkpoint_match(x)
|
applicable = [info for info in modules.sd_models.checkpoints_list.values() if x in info.title]
|
||||||
assert info is not None, f'Checkpoint for {x} not found'
|
assert len(applicable) > 0, f'Checkpoint {x} for found'
|
||||||
|
|
||||||
|
info = applicable[0]
|
||||||
|
|
||||||
modules.sd_models.reload_model_weights(shared.sd_model, info)
|
modules.sd_models.reload_model_weights(shared.sd_model, info)
|
||||||
|
|
||||||
|
|
||||||
def apply_hypernetwork(p, x, xs):
|
|
||||||
hypernetwork.load_hypernetwork(x)
|
|
||||||
|
|
||||||
|
|
||||||
def apply_clip_skip(p, x, xs):
|
|
||||||
opts.data["CLIP_stop_at_last_layers"] = x
|
|
||||||
|
|
||||||
|
|
||||||
def format_value_add_label(p, opt, x):
|
def format_value_add_label(p, opt, x):
|
||||||
if type(x) == float:
|
if type(x) == float:
|
||||||
x = round(x, 8)
|
x = round(x, 8)
|
||||||
@@ -101,26 +62,16 @@ def format_value_add_label(p, opt, x):
|
|||||||
def format_value(p, opt, x):
|
def format_value(p, opt, x):
|
||||||
if type(x) == float:
|
if type(x) == float:
|
||||||
x = round(x, 8)
|
x = round(x, 8)
|
||||||
|
|
||||||
return x
|
return x
|
||||||
|
|
||||||
|
|
||||||
def format_value_join_list(p, opt, x):
|
|
||||||
return ", ".join(x)
|
|
||||||
|
|
||||||
|
|
||||||
def do_nothing(p, x, xs):
|
def do_nothing(p, x, xs):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
def format_nothing(p, opt, x):
|
def format_nothing(p, opt, x):
|
||||||
return ""
|
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
|
|
||||||
|
|
||||||
|
|
||||||
AxisOption = namedtuple("AxisOption", ["label", "type", "apply", "format_value"])
|
AxisOption = namedtuple("AxisOption", ["label", "type", "apply", "format_value"])
|
||||||
AxisOptionImg2Img = namedtuple("AxisOptionImg2Img", ["label", "type", "apply", "format_value"])
|
AxisOptionImg2Img = namedtuple("AxisOptionImg2Img", ["label", "type", "apply", "format_value"])
|
||||||
|
|
||||||
@@ -133,17 +84,9 @@ axis_options = [
|
|||||||
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),
|
||||||
AxisOption("Checkpoint name", str, apply_checkpoint, format_value),
|
AxisOption("Checkpoint name", str, apply_checkpoint, format_value),
|
||||||
AxisOption("Hypernetwork", str, apply_hypernetwork, 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("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),
|
|
||||||
AxisOption("Clip skip", int, apply_clip_skip, 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
|
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@@ -153,7 +96,7 @@ def draw_xy_grid(p, xs, ys, x_labels, y_labels, cell, draw_legend):
|
|||||||
ver_texts = [[images.GridAnnotation(y)] for y in y_labels]
|
ver_texts = [[images.GridAnnotation(y)] for y in y_labels]
|
||||||
hor_texts = [[images.GridAnnotation(x)] for x in x_labels]
|
hor_texts = [[images.GridAnnotation(x)] for x in x_labels]
|
||||||
|
|
||||||
first_processed = None
|
first_pocessed = None
|
||||||
|
|
||||||
state.job_count = len(xs) * len(ys) * p.n_iter
|
state.job_count = len(xs) * len(ys) * p.n_iter
|
||||||
|
|
||||||
@@ -162,21 +105,18 @@ def draw_xy_grid(p, xs, ys, x_labels, y_labels, cell, draw_legend):
|
|||||||
state.job = f"{ix + iy * len(xs) + 1} out of {len(xs) * len(ys)}"
|
state.job = f"{ix + iy * len(xs) + 1} out of {len(xs) * len(ys)}"
|
||||||
|
|
||||||
processed = cell(x, y)
|
processed = cell(x, y)
|
||||||
if first_processed is None:
|
if first_pocessed is None:
|
||||||
first_processed = 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:
|
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_processed.images = [grid]
|
first_pocessed.images = [grid]
|
||||||
|
|
||||||
return first_processed
|
return first_pocessed
|
||||||
|
|
||||||
|
|
||||||
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*")
|
||||||
@@ -206,20 +146,11 @@ class Script(scripts.Script):
|
|||||||
return [x_type, x_values, y_type, y_values, draw_legend, no_fixed_seeds]
|
return [x_type, x_values, y_type, y_values, draw_legend, no_fixed_seeds]
|
||||||
|
|
||||||
def run(self, p, x_type, x_values, y_type, y_values, draw_legend, no_fixed_seeds):
|
def run(self, p, x_type, x_values, y_type, y_values, draw_legend, no_fixed_seeds):
|
||||||
if not no_fixed_seeds:
|
modules.processing.fix_seed(p)
|
||||||
modules.processing.fix_seed(p)
|
p.batch_size = 1
|
||||||
|
|
||||||
if not opts.return_grid:
|
|
||||||
p.batch_size = 1
|
|
||||||
|
|
||||||
|
|
||||||
CLIP_stop_at_last_layers = opts.CLIP_stop_at_last_layers
|
|
||||||
|
|
||||||
def process_axis(opt, vals):
|
def process_axis(opt, vals):
|
||||||
if opt.label == 'Nothing':
|
valslist = [x.strip() for x in vals.split(",")]
|
||||||
return [0]
|
|
||||||
|
|
||||||
valslist = [x.strip() for x in chain.from_iterable(csv.reader(StringIO(vals)))]
|
|
||||||
|
|
||||||
if opt.type == int:
|
if opt.type == int:
|
||||||
valslist_ext = []
|
valslist_ext = []
|
||||||
@@ -228,6 +159,7 @@ class Script(scripts.Script):
|
|||||||
m = re_range.fullmatch(val)
|
m = re_range.fullmatch(val)
|
||||||
mc = re_range_count.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))
|
||||||
end = int(m.group(2))+1
|
end = int(m.group(2))+1
|
||||||
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
|
||||||
@@ -265,22 +197,9 @@ class Script(scripts.Script):
|
|||||||
valslist_ext.append(val)
|
valslist_ext.append(val)
|
||||||
|
|
||||||
valslist = valslist_ext
|
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]
|
||||||
|
|
||||||
# Confirm options are valid before starting
|
|
||||||
if opt.label == "Sampler":
|
|
||||||
samplers_dict = build_samplers_dict(p)
|
|
||||||
for sampler_val in valslist:
|
|
||||||
if sampler_val.lower() not in samplers_dict.keys():
|
|
||||||
raise RuntimeError(f"Unknown sampler: {sampler_val}")
|
|
||||||
elif opt.label == "Checkpoint name":
|
|
||||||
for ckpt_val in valslist:
|
|
||||||
if modules.sd_models.get_closet_checkpoint_match(ckpt_val) is None:
|
|
||||||
raise RuntimeError(f"Checkpoint for {ckpt_val} not found")
|
|
||||||
|
|
||||||
return valslist
|
return valslist
|
||||||
|
|
||||||
x_opt = axis_options[x_type]
|
x_opt = axis_options[x_type]
|
||||||
@@ -332,8 +251,4 @@ class Script(scripts.Script):
|
|||||||
# restore checkpoint in case it was changed by axes
|
# restore checkpoint in case it was changed by axes
|
||||||
modules.sd_models.reload_model_weights(shared.sd_model)
|
modules.sd_models.reload_model_weights(shared.sd_model)
|
||||||
|
|
||||||
hypernetwork.load_hypernetwork(opts.sd_hypernetwork)
|
|
||||||
|
|
||||||
opts.data["CLIP_stop_at_last_layers"] = CLIP_stop_at_last_layers
|
|
||||||
|
|
||||||
return processed
|
return processed
|
||||||
@@ -1,36 +1,5 @@
|
|||||||
.container {
|
|
||||||
max-width: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
#txt2img_token_counter {
|
|
||||||
height: 0px;
|
|
||||||
}
|
|
||||||
|
|
||||||
#img2img_token_counter {
|
|
||||||
height: 0px;
|
|
||||||
}
|
|
||||||
|
|
||||||
#sh{
|
|
||||||
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;
|
|
||||||
opacity: 0%;
|
|
||||||
cursor: default;
|
|
||||||
}
|
|
||||||
|
|
||||||
.output-html p {margin: 0 0.5em;}
|
.output-html p {margin: 0 0.5em;}
|
||||||
|
|
||||||
.row > *,
|
|
||||||
.row > .gr-form > * {
|
|
||||||
min-width: min(120px, 100%);
|
|
||||||
flex: 1 1 0%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.performance {
|
.performance {
|
||||||
font-size: 0.85em;
|
font-size: 0.85em;
|
||||||
color: #444;
|
color: #444;
|
||||||
@@ -48,7 +17,7 @@
|
|||||||
text-align: right;
|
text-align: right;
|
||||||
}
|
}
|
||||||
|
|
||||||
#txt2img_generate, #img2img_generate {
|
#generate{
|
||||||
min-height: 4.5em;
|
min-height: 4.5em;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,17 +43,13 @@
|
|||||||
margin-right: auto;
|
margin-right: auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
#random_seed, #random_subseed, #reuse_seed, #reuse_subseed, #open_folder{
|
#random_seed, #random_subseed, #reuse_seed, #reuse_subseed{
|
||||||
min-width: auto;
|
min-width: auto;
|
||||||
flex-grow: 0;
|
flex-grow: 0;
|
||||||
padding-left: 0.25em;
|
padding-left: 0.25em;
|
||||||
padding-right: 0.25em;
|
padding-right: 0.25em;
|
||||||
}
|
}
|
||||||
|
|
||||||
#hidden_element{
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
#seed_row, #subseed_row{
|
#seed_row, #subseed_row{
|
||||||
gap: 0.5rem;
|
gap: 0.5rem;
|
||||||
}
|
}
|
||||||
@@ -128,12 +93,7 @@
|
|||||||
|
|
||||||
#style_apply, #style_create, #interrogate{
|
#style_apply, #style_create, #interrogate{
|
||||||
margin: 0.75em 0.25em 0.25em 0.25em;
|
margin: 0.75em 0.25em 0.25em 0.25em;
|
||||||
min-width: 5em;
|
min-width: 3em;
|
||||||
}
|
|
||||||
|
|
||||||
#style_apply, #style_create, #deepbooru{
|
|
||||||
margin: 0.75em 0.25em 0.25em 0.25em;
|
|
||||||
min-width: 5em;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#style_pos_col, #style_neg_col{
|
#style_pos_col, #style_neg_col{
|
||||||
@@ -187,7 +147,7 @@ button{
|
|||||||
max-width: 10em;
|
max-width: 10em;
|
||||||
}
|
}
|
||||||
|
|
||||||
#txt2img_preview, #img2img_preview, #ti_preview{
|
#txt2img_preview, #img2img_preview{
|
||||||
position: absolute;
|
position: absolute;
|
||||||
width: 320px;
|
width: 320px;
|
||||||
left: 0;
|
left: 0;
|
||||||
@@ -202,18 +162,18 @@ button{
|
|||||||
}
|
}
|
||||||
|
|
||||||
@media screen and (min-width: 768px) {
|
@media screen and (min-width: 768px) {
|
||||||
#txt2img_preview, #img2img_preview, #ti_preview {
|
#txt2img_preview, #img2img_preview {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@media screen and (max-width: 767px) {
|
@media screen and (max-width: 767px) {
|
||||||
#txt2img_preview, #img2img_preview, #ti_preview {
|
#txt2img_preview, #img2img_preview {
|
||||||
position: relative;
|
position: relative;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#txt2img_preview div.left-0.top-0, #img2img_preview div.left-0.top-0, #ti_preview div.left-0.top-0{
|
#txt2img_preview div.left-0.top-0, #img2img_preview div.left-0.top-0{
|
||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -277,7 +237,7 @@ input[type="range"]{
|
|||||||
#txt2img_negative_prompt, #img2img_negative_prompt{
|
#txt2img_negative_prompt, #img2img_negative_prompt{
|
||||||
}
|
}
|
||||||
|
|
||||||
#txt2img_progressbar, #img2img_progressbar, #ti_progressbar{
|
#txt2img_progressbar, #img2img_progressbar{
|
||||||
position: absolute;
|
position: absolute;
|
||||||
z-index: 1000;
|
z-index: 1000;
|
||||||
right: 0;
|
right: 0;
|
||||||
@@ -423,75 +383,9 @@ input[type="range"]{
|
|||||||
|
|
||||||
#txt2img_interrupt, #img2img_interrupt{
|
#txt2img_interrupt, #img2img_interrupt{
|
||||||
position: absolute;
|
position: absolute;
|
||||||
width: 50%;
|
width: 100%;
|
||||||
height: 72px;
|
height: 72px;
|
||||||
background: #b4c0cc;
|
background: #b4c0cc;
|
||||||
border-radius: 0px;
|
border-radius: 8px;
|
||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
#txt2img_skip, #img2img_skip{
|
|
||||||
position: absolute;
|
|
||||||
width: 50%;
|
|
||||||
right: 0px;
|
|
||||||
height: 72px;
|
|
||||||
background: #b4c0cc;
|
|
||||||
border-radius: 0px;
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.red {
|
|
||||||
color: red;
|
|
||||||
}
|
|
||||||
|
|
||||||
.gallery-item {
|
|
||||||
--tw-bg-opacity: 0 !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
#img2img_image div.h-60{
|
|
||||||
height: 480px;
|
|
||||||
}
|
|
||||||
|
|
||||||
#context-menu{
|
|
||||||
z-index:9999;
|
|
||||||
position:absolute;
|
|
||||||
display:block;
|
|
||||||
padding:0px 0;
|
|
||||||
border:2px solid #a55000;
|
|
||||||
border-radius:8px;
|
|
||||||
box-shadow:1px 1px 2px #CE6400;
|
|
||||||
width: 200px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.context-menu-items{
|
|
||||||
list-style: none;
|
|
||||||
margin: 0;
|
|
||||||
padding: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.context-menu-items a{
|
|
||||||
display:block;
|
|
||||||
padding:5px;
|
|
||||||
cursor:pointer;
|
|
||||||
}
|
|
||||||
|
|
||||||
.context-menu-items a:hover{
|
|
||||||
background: #a55000;
|
|
||||||
}
|
|
||||||
|
|
||||||
#quicksettings > div{
|
|
||||||
border: none;
|
|
||||||
background: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
#quicksettings > div > div{
|
|
||||||
max-width: 32em;
|
|
||||||
padding: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
canvas[key="mask"] {
|
|
||||||
z-index: 12 !important;
|
|
||||||
filter: invert();
|
|
||||||
mix-blend-mode: multiply;
|
|
||||||
pointer-events: none;
|
|
||||||
}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
a photo of a [filewords]
|
|
||||||
a rendering of a [filewords]
|
|
||||||
a cropped photo of the [filewords]
|
|
||||||
the photo of a [filewords]
|
|
||||||
a photo of a clean [filewords]
|
|
||||||
a photo of a dirty [filewords]
|
|
||||||
a dark photo of the [filewords]
|
|
||||||
a photo of my [filewords]
|
|
||||||
a photo of the cool [filewords]
|
|
||||||
a close-up photo of a [filewords]
|
|
||||||
a bright photo of the [filewords]
|
|
||||||
a cropped photo of a [filewords]
|
|
||||||
a photo of the [filewords]
|
|
||||||
a good photo of the [filewords]
|
|
||||||
a photo of one [filewords]
|
|
||||||
a close-up photo of the [filewords]
|
|
||||||
a rendition of the [filewords]
|
|
||||||
a photo of the clean [filewords]
|
|
||||||
a rendition of a [filewords]
|
|
||||||
a photo of a nice [filewords]
|
|
||||||
a good photo of a [filewords]
|
|
||||||
a photo of the nice [filewords]
|
|
||||||
a photo of the small [filewords]
|
|
||||||
a photo of the weird [filewords]
|
|
||||||
a photo of the large [filewords]
|
|
||||||
a photo of a cool [filewords]
|
|
||||||
a photo of a small [filewords]
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
picture
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
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]
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
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]
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
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]
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
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.
|
Before Width: | Height: | Size: 329 KiB After Width: | Height: | Size: 526 KiB |
@@ -21,9 +21,6 @@ export COMMANDLINE_ARGS=""
|
|||||||
# python3 venv without trailing slash (defaults to ${install_dir}/${clone_dir}/venv)
|
# python3 venv without trailing slash (defaults to ${install_dir}/${clone_dir}/venv)
|
||||||
#venv_dir="venv"
|
#venv_dir="venv"
|
||||||
|
|
||||||
# script to launch to start the app
|
|
||||||
#export LAUNCH_SCRIPT="launch.py"
|
|
||||||
|
|
||||||
# install command for torch
|
# install command for torch
|
||||||
#export TORCH_COMMAND="pip install torch==1.12.1+cu113 --extra-index-url https://download.pytorch.org/whl/cu113"
|
#export TORCH_COMMAND="pip install torch==1.12.1+cu113 --extra-index-url https://download.pytorch.org/whl/cu113"
|
||||||
|
|
||||||
|
|||||||
@@ -1,42 +1,37 @@
|
|||||||
import os
|
import os
|
||||||
import threading
|
import threading
|
||||||
import time
|
|
||||||
import importlib
|
|
||||||
import signal
|
|
||||||
import threading
|
|
||||||
|
|
||||||
from fastapi.middleware.gzip import GZipMiddleware
|
|
||||||
|
|
||||||
from modules.paths import script_path
|
from modules.paths import script_path
|
||||||
|
|
||||||
from modules import devices, sd_samplers
|
import signal
|
||||||
import modules.codeformer_model as codeformer
|
|
||||||
import modules.extras
|
|
||||||
import modules.face_restoration
|
|
||||||
import modules.gfpgan_model as gfpgan
|
|
||||||
import modules.img2img
|
|
||||||
|
|
||||||
import modules.lowvram
|
from modules.shared import opts, cmd_opts, state
|
||||||
import modules.paths
|
import modules.shared as shared
|
||||||
|
import modules.ui
|
||||||
import modules.scripts
|
import modules.scripts
|
||||||
import modules.sd_hijack
|
import modules.sd_hijack
|
||||||
import modules.sd_models
|
import modules.codeformer_model
|
||||||
import modules.shared as shared
|
import modules.gfpgan_model
|
||||||
|
import modules.face_restoration
|
||||||
|
import modules.realesrgan_model as realesrgan
|
||||||
|
import modules.esrgan_model as esrgan
|
||||||
|
import modules.ldsr_model as ldsr
|
||||||
|
import modules.extras
|
||||||
|
import modules.lowvram
|
||||||
import modules.txt2img
|
import modules.txt2img
|
||||||
|
import modules.img2img
|
||||||
|
import modules.swinir as swinir
|
||||||
|
import modules.sd_models
|
||||||
|
|
||||||
import modules.ui
|
|
||||||
from modules import devices
|
|
||||||
from modules import modelloader
|
|
||||||
from modules.paths import script_path
|
|
||||||
from modules.shared import cmd_opts
|
|
||||||
import modules.hypernetworks.hypernetwork
|
|
||||||
|
|
||||||
modelloader.cleanup_models()
|
modules.codeformer_model.setup_codeformer()
|
||||||
modules.sd_models.setup_model()
|
modules.gfpgan_model.setup_gfpgan()
|
||||||
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)
|
||||||
|
swinir.load_models(cmd_opts.swinir_models_path)
|
||||||
|
realesrgan.setup_realesrgan()
|
||||||
|
ldsr.add_lsdr()
|
||||||
queue_lock = threading.Lock()
|
queue_lock = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
@@ -50,10 +45,8 @@ def wrap_queued_call(func):
|
|||||||
return f
|
return f
|
||||||
|
|
||||||
|
|
||||||
def wrap_gradio_gpu_call(func, extra_outputs=None):
|
def wrap_gradio_gpu_call(func):
|
||||||
def f(*args, **kwargs):
|
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
|
||||||
@@ -61,9 +54,7 @@ def wrap_gradio_gpu_call(func, extra_outputs=None):
|
|||||||
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.skipped = False
|
|
||||||
shared.state.interrupted = False
|
shared.state.interrupted = False
|
||||||
shared.state.textinfo = None
|
|
||||||
|
|
||||||
with queue_lock:
|
with queue_lock:
|
||||||
res = func(*args, **kwargs)
|
res = func(*args, **kwargs)
|
||||||
@@ -71,11 +62,9 @@ def wrap_gradio_gpu_call(func, extra_outputs=None):
|
|||||||
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, extra_outputs=extra_outputs)
|
return modules.ui.wrap_gradio_call(f)
|
||||||
|
|
||||||
|
|
||||||
modules.scripts.load_scripts(os.path.join(script_path, "scripts"))
|
modules.scripts.load_scripts(os.path.join(script_path, "scripts"))
|
||||||
@@ -83,8 +72,6 @@ modules.scripts.load_scripts(os.path.join(script_path, "scripts"))
|
|||||||
shared.sd_model = modules.sd_models.load_model()
|
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)))
|
shared.opts.onchange("sd_model_checkpoint", wrap_queued_call(lambda: modules.sd_models.reload_model_weights(shared.sd_model)))
|
||||||
|
|
||||||
shared.opts.onchange("sd_hypernetwork", wrap_queued_call(lambda: modules.hypernetworks.hypernetwork.load_hypernetwork(shared.opts.sd_hypernetwork)))
|
|
||||||
|
|
||||||
|
|
||||||
def webui():
|
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
|
||||||
@@ -94,40 +81,21 @@ def webui():
|
|||||||
|
|
||||||
signal.signal(signal.SIGINT, sigint_handler)
|
signal.signal(signal.SIGINT, sigint_handler)
|
||||||
|
|
||||||
while 1:
|
demo = modules.ui.create_ui(
|
||||||
|
txt2img=wrap_gradio_gpu_call(modules.txt2img.txt2img),
|
||||||
demo = modules.ui.create_ui(wrap_gradio_gpu_call=wrap_gradio_gpu_call)
|
img2img=wrap_gradio_gpu_call(modules.img2img.img2img),
|
||||||
|
run_extras=wrap_gradio_gpu_call(modules.extras.run_extras),
|
||||||
app,local_url,share_url = demo.launch(
|
run_pnginfo=modules.extras.run_pnginfo
|
||||||
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
|
|
||||||
)
|
|
||||||
|
|
||||||
app.add_middleware(GZipMiddleware, minimum_size=1000)
|
|
||||||
|
|
||||||
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('Refreshing Model List')
|
|
||||||
modules.sd_models.list_models()
|
|
||||||
print('Restarting Gradio')
|
|
||||||
|
|
||||||
|
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,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -41,11 +41,6 @@ then
|
|||||||
venv_dir="venv"
|
venv_dir="venv"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ -z "${LAUNCH_SCRIPT}" ]]
|
|
||||||
then
|
|
||||||
LAUNCH_SCRIPT="launch.py"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Disable sentry logging
|
# Disable sentry logging
|
||||||
export ERROR_REPORTING=FALSE
|
export ERROR_REPORTING=FALSE
|
||||||
|
|
||||||
@@ -138,4 +133,4 @@ fi
|
|||||||
printf "\n%s\n" "${delimiter}"
|
printf "\n%s\n" "${delimiter}"
|
||||||
printf "Launching launch.py..."
|
printf "Launching launch.py..."
|
||||||
printf "\n%s\n" "${delimiter}"
|
printf "\n%s\n" "${delimiter}"
|
||||||
"${python_cmd}" "${LAUNCH_SCRIPT}"
|
"${python_cmd}" launch.py
|
||||||
Reference in new issue
Block a user