├── .gitignore ├── LICENSE ├── README.md ├── client_test.py ├── config-custom-models.json ├── config.json ├── environment-m1.yaml ├── environment.yaml └── server.py /.gitignore: -------------------------------------------------------------------------------- 1 | token.txt 2 | __pycache__ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Stable Diffusion API Server 2 | 3 | A local inference REST API server for the [Stable Diffusion Photoshop plugin](https://christiancantrell.com/#ai-ml). (Also a generic Stable Diffusion REST API for whatever you want.) 4 | 5 | The API server currently supports: 6 | 7 | 1. Stable Diffusion weights automatically downloaded from Hugging Face. 8 | 1. Custom fine-tuned models in the Hugging Face diffusers file format like those created with [DreamBooth](https://github.com/XavierXiao/Dreambooth-Stable-Diffusion). 9 | 10 | (Note that loading checkpoint files directly is not currently supported, but you can easily convert `.ckpt` files into the diffusers format using the aptly named [`convert_original_stable_diffusion_to_diffusers.py`](https://github.com/huggingface/diffusers/blob/main/scripts/convert_original_stable_diffusion_to_diffusers.py) script.) 11 | 12 | The server will run on Windows and Linux machines with NVIDIA GPUs, and on M1 Macs. M1 Mac support using MPS (Metal Performance Shaders) is highly experimental (and not easy to configure) but it does work, and it will get better over time. 13 | 14 | If you can swing it, for best results, use a dedicated Linux box. Performance on Windows is also very good, but I recommend a dedicated machine with no other apps running. You can run Photoshop on the same machine if you have to, but you will be giving up some of your GPU memory which is good for the Photoshop user experience, but bad for optimal local inference. 15 | 16 | **Note that this project uses the content safety filter.** 17 | 18 | ## Installation 19 | 20 | 🤞 If anyone wants to make a detailed installation video, I would love to embed it right here. 🤞 21 | 22 | ### Windows, Linux, and Mac Instructions 23 | 24 | 1. Install Python. 25 | 1. Install [Conda](https://conda.io/projects/conda/en/latest/user-guide/install/download.html). 26 | 1. Download this repo. 27 | 1. cd into the repo's directory. 28 | 1. Set up a [Conda](https://conda.io) environment named `sd-api-server` by running the following command: 29 | 30 | Windows and Linux: 31 | 32 | **(Note that the '%' character below is meant to denote the command prompt; do not include it when copying and pasting.)** 33 | 34 | ``` 35 | % conda env create -f environment.yaml 36 | ``` 37 | 38 | M1 Macs: 39 | 40 | ``` 41 | % conda env create -f environment-m1.yaml 42 | ``` 43 | 44 | Then activate the Conda environment: 45 | 46 | ``` 47 | % conda activate sd-api-server 48 | ``` 49 | 50 | If you are updating the server, make sure to update your Conda environment (using the platform-specific `yaml` file): 51 | 52 | ``` 53 | % conda env update -f environment.yaml 54 | % conda activate sd-api-server 55 | ``` 56 | 57 | If you want to remove an old environment and create it from scratch (using the platform-specific `yaml` file): 58 | 59 | ``` 60 | % conda env remove -n sd-api-server 61 | % conda env create -f environment.yaml 62 | % conda activate sd-api-server 63 | ``` 64 | 65 | ### Hugging Face Configuration 66 | 67 | There are two things you need to configure with Hugging Face in order to run the Stable Diffusion model locally: 68 | 69 | 1. You need to [agree to share your username and email address with Hugging Face](https://huggingface.co/CompVis/stable-diffusion-v1-4) in order to access the model. 70 | 1. You also need to set up [a Hugging Face token](https://huggingface.co/settings/tokens). Once you've created a read-only token, copy and paste it into the `config.json` file as the value to the `hf_token` key (and don't forget to save the file). 71 | 72 | Windows and Linux users, you're good to go! All you have to do now is start the server: 73 | 74 | ``` 75 | % python3 server.py 76 | ``` 77 | 78 | ### M1 Mac Additional Instructions 79 | 80 | Note that this is highly experimental, and may not work for you. But it will probably get easier with the next release of [PyTorch](https://pytorch.org/). 81 | 82 | #### Method 1: Nightly Builds 83 | 84 | In Terminal, at the Conda prompt, **with the `sd-api-server` environment activated**: 85 | 86 | ``` 87 | % conda install pytorch torchvision -c pytorch-nightly 88 | % conda deactivate 89 | % conda activate sd-api-server 90 | % python3 server.py 91 | ``` 92 | 93 | You might have noticed that you just installed a nightly build of PyTorch and Torchvision. Nightly builds come with neither warranties nor guarantees. If your server starts and you can generate images, you just won the nightly Lottery! If not, you can play again tomorrow. This is a temporary situation and probably won't be necessary with the next release of PyTorch. 94 | 95 | #### Method 2: Environment Variables 96 | 97 | If the nightly build didn't work for you — or if you're simply allergic to nightly builds — you can tell PyTorch to use use the CPU in addition to MPS. If you already installed the nightly build, remove your Conda environment using the command above, start all over again, skip the nightly build step, and try this (with the `sd-api-server` environment active): 98 | 99 | ``` 100 | % conda env config vars set PYTORCH_ENABLE_MPS_FALLBACK=1 101 | % conda activate sd-api-server 102 | % python3 server.py 103 | ``` 104 | 105 | If you get the message `ModuleNotFoundError: No module named 'flask'`, it probably means you're using the wrong version of Python. If you used `python3` then try `python`. If you used `python` then try `python3`. (These are the joys of old versions of Python being preinstalled on Macs.) 106 | 107 | ## Configuring Custom Models 108 | 109 | If you want to use the server (and the Photoshop plugin) with custom-trained models, the first thing you need are the custom-trained models themselves. Instructions for how to do so are beyond the scope of this README, but here are some resources: 110 | 111 | - [My custom fork of the DreamBooth repo](https://github.com/cantrell/Dreambooth-Stable-Diffusion-Tweaked) (dramatically simplified). 112 | - [A DreamBooth Stable Diffusion Colab notebook](https://colab.research.google.com/github/ShivamShrirao/diffusers/blob/main/examples/dreambooth/DreamBooth_Stable_Diffusion.ipynb) (much easier than training locally). 113 | - [A good YouTube tutorial on using the Colab notebook](https://www.youtube.com/watch?v=FaLTztGGueQ). 114 | - [The original DreamBooth paper](https://arxiv.org/abs/2208.12242). 115 | 116 | Loading checkpoint files directly is not currently supported, but you can easily convert `.ckpt` files into the diffusers format using the aptly named [`convert_original_stable_diffusion_to_diffusers.py`](https://github.com/huggingface/diffusers/blob/main/scripts/convert_original_stable_diffusion_to_diffusers.py) script. 117 | 118 | Once you have the models trained, the rest is easy. All you have to do is: 119 | 120 | 1. Replace your `config.json` file with the `config-custom-models.json` template (rename `config-custom-models.json` to `config.json`). 121 | 1. Make sure you copy and paste your Hugging Face token into the new `config.json` file. 122 | 1. Fill in the `custom_model` array of the config file appropriately. 123 | 124 | Here's an explanation of what the key/value pairs mean: 125 | 126 | - `model_path`: The full path to the directory which contains the `model_index.json` file (just the directory; don't include the file itself). **Do not** escape spaces, but **do** escape backslashes with backslashes (e.g. `G:\\My Drive\\stable_diffusion_weights\\MyCustomModelOutput`). 127 | - `ui_label`: The name of the model as you want it to appear in the Photoshop plugin. 128 | - `url_path`: A unique, URL-friendly value that will be used as the endpoint path (see the REST API section below). 129 | - `requires_safety_checker`: Whether or not your custom model expects the safety checker. For models in the Hugging Face diffusers file format, this will be true; for models compiled from checkpoint files into the diffusers file format, this will probably be false. 130 | 131 | Once your config file is ready, (re)start the server. If the Photoshop plugin is already loaded, you may need to restart it (or you can just click on the 'Reload Plugin' link in the lower right-hand corner of the 'Generate' tab). 132 | 133 | Note that the `custom_model` section of the `config.json` file is an array. That means you can include as many custom models as you want. Here's what it should look like for more than one custom-trained model: 134 | 135 | ``` 136 | { 137 | "hf_token": "your_hugging_face_token", 138 | "custom_models": [ 139 | { 140 | "model_path": "/path/to/directory/containing/model_index.json", 141 | "ui_label": "My First Model", 142 | "url_path": "my_first_model", 143 | "requires_safety_checker": true 144 | } 145 | ], 146 | [ 147 | { 148 | "model_path": "/path/to/another/directory/containing/model_index.json", 149 | "ui_label": "My Second Model", 150 | "url_path": "my_second_model", 151 | "requires_safety_checker": true 152 | } 153 | ] 154 | } 155 | ``` 156 | 157 | To see your custom models in the Generate tab of the Stable Diffusion Photoshop plugin, make sure you've configured your local inference server in the API Key tab. 158 | 159 | ## REST API 160 | 161 | Note that all `POST` requests use the `application/x-www-form-urlencoded` content type, and all images are base64 encoded strings. 162 | 163 | `GET /ping` 164 | 165 | #### Response 166 | 167 | ``` 168 | {'status':'success'} 169 | ``` 170 | 171 | `GET /custom_models` 172 | 173 | #### Response 174 | 175 | ``` 176 | [ 177 | { 178 | "model_path": "/path/to/directory/containing/model_index.json", 179 | "ui_label": "My First Model", 180 | "url_path": "my_first_model", 181 | "requires_safety_checker": "true | false" 182 | } 183 | ], [...] 184 | ``` 185 | 186 | (If no custom models are configured, you will get back an empty array.) 187 | 188 | `POST /txt2img` 189 | 190 | Parameters: 191 | 192 | - `prompt`: A text description. 193 | - `seed`: A numeric seed. 194 | - `num_outputs`: The number of images you want to get back. 195 | - `width`: The width of your results. 196 | - `height`: The height of your results. 197 | - `num_inference_steps`: The number of steps (more steps mean higher quality). 198 | - `guidance_scale`: Prompt strength. 199 | 200 | #### Response 201 | 202 | ``` 203 | { 204 | 'status':'success | failure', 205 | 'message':'Only if there was a failure', 206 | 'images': [ 207 | { 208 | 'base64': 'base64EncodedImage==', 209 | 'seed': 123456789, 210 | 'mimetype': 'image/png', 211 | 'nsfw': true | false 212 | } 213 | ] 214 | } 215 | ``` 216 | 217 | `POST /img2img` 218 | 219 | Parameters: 220 | 221 | - `prompt`: A text description. 222 | - `seed`: A numeric seed. 223 | - `num_outputs`: The number of images you want to get back. 224 | - `num_inference_steps`: The number of steps (more steps mean higher quality). 225 | - `guidance_scale`: Prompt strength. 226 | - `init_image`: The initial input image. 227 | - `strength`: The image strength. 228 | 229 | #### Response 230 | 231 | ``` 232 | { 233 | 'status':'success | failure', 234 | 'message':'Only if there was a failure', 235 | 'images': [ 236 | { 237 | 'base64': 'base64EncodedImage==', 238 | 'seed': 123456789, 239 | 'mimetype': 'image/png', 240 | 'nsfw': true | false 241 | } 242 | ] 243 | } 244 | ``` 245 | 246 | `POST /masking` 247 | 248 | Parameters: 249 | 250 | - `prompt`: A text description. 251 | - `seed`: A numeric seed. 252 | - `num_outputs`: The number of images you want to get back. 253 | - `num_inference_steps`: The number of steps (more steps mean higher quality). 254 | - `guidance_scale`: Prompt strength. 255 | - `init_image`: The initial input image. 256 | - `strength`: The image strength. 257 | - `mask_image`: A mask representing the pixels to replace. 258 | 259 | #### Response 260 | 261 | ``` 262 | { 263 | 'status':'success | failure', 264 | 'message':'Only if there was a failure', 265 | 'images': [ 266 | { 267 | 'base64': 'base64EncodedImage==', 268 | 'seed': 123456789, 269 | 'mimetype': 'image/png', 270 | 'nsfw': true | false 271 | } 272 | ] 273 | } 274 | ``` 275 | 276 | `POST /custom/` 277 | 278 | `url_path` refers to the `url_path` key/value pair you defined in your `config.json` file. 279 | 280 | Parameters: 281 | 282 | - `prompt`: A text description. 283 | - `seed`: A numeric seed. 284 | - `num_outputs`: The number of images you want to get back. 285 | - `width`: The width of your results. 286 | - `height`: The height of your results. 287 | - `num_inference_steps`: The number of steps (more steps mean higher quality). 288 | - `guidance_scale`: Prompt strength. 289 | 290 | #### Response 291 | 292 | ``` 293 | { 294 | 'status':'success | failure', 295 | 'message':'Only if there was a failure', 296 | 'images': [ 297 | { 298 | 'base64': 'base64EncodedImage==', 299 | 'seed': 123456789, 300 | 'mimetype': 'image/png', 301 | 'nsfw': true | false 302 | } 303 | ] 304 | } 305 | ``` 306 | -------------------------------------------------------------------------------- /client_test.py: -------------------------------------------------------------------------------- 1 | import json 2 | import requests 3 | import base64 4 | from PIL import Image 5 | from io import BytesIO 6 | import matplotlib.pyplot as plt 7 | 8 | def load_image_from_path(img_path): 9 | img = Image.open( img_path ) 10 | return img 11 | 12 | def load_image_from_url(img_url): 13 | res = requests.get( img_url ) 14 | img = Image.open( BytesIO( res.content ) ) 15 | return img 16 | 17 | def resize_image_preserve_aspect(img_pil, w): 18 | wp = ( w / float( img_pil.size[0] ) ) 19 | hs = int( float( img_pil.size[1] ) * float( wp ) ) 20 | return img_pil.resize( ( w, hs ), Image.ANTIALIAS ) 21 | 22 | def pil_to_b64(input): 23 | buffer = BytesIO() 24 | input.save( buffer, 'PNG' ) 25 | output = base64.b64encode( buffer.getvalue() ).decode( 'utf-8' ).replace( '\n', '' ) 26 | buffer.close() 27 | return output 28 | 29 | def b64_to_pil(input): 30 | output = Image.open( BytesIO( base64.b64decode( input ) ) ) 31 | return output 32 | 33 | def test_txt2img(): 34 | ENDPOINT = "http://localhost:1337/txt2img" 35 | 36 | data = { 37 | 'prompt':'a photo of a dog sitting on a bench', 38 | 'width':str( 512 ), 39 | 'height':str( 512 ), 40 | 'num_inference_steps':str( 100 ), 41 | 'guidance_scale':str( 7.5 ), 42 | 'num_outputs':str( 2 ), 43 | 'seed':str( 0 ), 44 | } 45 | 46 | response = json.loads( requests.post( url=ENDPOINT, data=data ).text ) 47 | 48 | def b64_to_pil(input): 49 | output = Image.open( BytesIO( base64.b64decode( input ) ) ) 50 | return output 51 | 52 | if 'status' in response: 53 | if response[ 'status' ] == 'success': 54 | images = response[ 'images' ] 55 | for i, image in enumerate( images ): 56 | plt.imshow( b64_to_pil( image['base64'] ) ) 57 | plt.show( block=True ) 58 | plt.pause( 10 ) 59 | plt.close() 60 | 61 | def test_img2img(): 62 | ENDPOINT = "http://localhost:1337/img2img" 63 | IMG_URL = 'https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg' 64 | 65 | #IMG_URL = 'https://minitravellers.co.uk/wp-content/uploads/2019/05/40612080213_81852c19fc_k.jpg' 66 | 67 | data = { 68 | 'prompt':'a family of pixar characters on vacation in new york', 69 | 'init_image':pil_to_b64( resize_image_preserve_aspect( load_image_from_url( IMG_URL ).convert( 'RGB' ), 512 ) ), 70 | 'num_inference_steps':str( 100 ), 71 | 'guidance_scale':str( 7.5 ), 72 | 'num_outputs':str( 2 ), 73 | 'seed':str( 0 ), 74 | 'strength':str( 0.5 ), 75 | 'eta':str( 0.0 ), 76 | } 77 | 78 | response = json.loads( requests.post( url=ENDPOINT, data=data ).text ) 79 | 80 | if 'status' in response: 81 | if response[ 'status' ] == 'success': 82 | images = response[ 'images' ] 83 | for i, image in enumerate( images ): 84 | plt.imshow( b64_to_pil( image['base64'] ) ) 85 | plt.show( block=True ) 86 | plt.pause( 10 ) 87 | plt.close() 88 | 89 | def test_inpaint(): 90 | ENDPOINT = "http://localhost:1337/masking" 91 | IMG_URL = 'https://raw.githubusercontent.com/CompVis/stable-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png' 92 | MSK_URL = 'https://raw.githubusercontent.com/CompVis/stable-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png' 93 | 94 | data = { 95 | 'prompt':'a cat sitting on a bench', 96 | 'init_image':pil_to_b64( resize_image_preserve_aspect( load_image_from_url( IMG_URL ).convert( 'RGB' ), 512 ) ), 97 | 'mask_image':pil_to_b64( resize_image_preserve_aspect( load_image_from_url( MSK_URL ).convert( 'RGB' ), 512 ) ), 98 | 'num_inference_steps':str( 100 ), 99 | 'guidance_scale':str( 7.5 ), 100 | 'num_outputs':str( 2 ), 101 | 'seed':str( 0 ), 102 | 'strength':str( 0.8 ), 103 | 'eta':str( 0.0 ), 104 | } 105 | 106 | response = json.loads( requests.post( url=ENDPOINT, data=data ).text ) 107 | 108 | if 'status' in response: 109 | if response[ 'status' ] == 'success': 110 | images = response[ 'images' ] 111 | for i, image in enumerate( images ): 112 | plt.imshow( b64_to_pil( image['base64'] ) ) 113 | plt.show( block=True ) 114 | plt.pause( 10 ) 115 | plt.close() 116 | 117 | 118 | # Run tests: 119 | 120 | # test_txt2img() 121 | # test_img2img() 122 | test_inpaint() -------------------------------------------------------------------------------- /config-custom-models.json: -------------------------------------------------------------------------------- 1 | { 2 | "hf_token": "your_hugging_face_token", 3 | "custom_models": [ 4 | { 5 | "model_path": "/path/to/directory/containing/model_index.json", 6 | "ui_label": "My Custom Model", 7 | "url_path": "my_custom_model", 8 | "requires_safety_checker": true 9 | } 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /config.json: -------------------------------------------------------------------------------- 1 | { 2 | "hf_token": "your_hugging_face_token" 3 | } 4 | -------------------------------------------------------------------------------- /environment-m1.yaml: -------------------------------------------------------------------------------- 1 | name: sd-api-server 2 | channels: 3 | - pytorch 4 | - defaults 5 | dependencies: 6 | - python=3.8.5 7 | - pip=20.3 8 | - pytorch=1.12.1 9 | - torchvision=0.13.1 10 | - numpy=1.19.2 11 | - pip: 12 | - diffusers 13 | - transformers==4.19.2 14 | - Pillow 15 | - Flask 16 | -------------------------------------------------------------------------------- /environment.yaml: -------------------------------------------------------------------------------- 1 | name: sd-api-server 2 | channels: 3 | - pytorch 4 | - defaults 5 | dependencies: 6 | - python=3.8.5 7 | - pip=20.3 8 | - cudatoolkit=11.3 9 | - pytorch=1.12.1 10 | - torchvision=0.13.1 11 | - numpy=1.19.2 12 | - pip: 13 | - diffusers 14 | - transformers==4.19.2 15 | - Pillow 16 | - Flask 17 | -------------------------------------------------------------------------------- /server.py: -------------------------------------------------------------------------------- 1 | import re 2 | import time 3 | import inspect 4 | import json 5 | import flask 6 | import sys 7 | import base64 8 | from PIL import Image 9 | from io import BytesIO 10 | 11 | import torch 12 | import diffusers 13 | 14 | 15 | ################################################## 16 | # Utils 17 | 18 | def retrieve_param(key, data, cast, default): 19 | if key in data: 20 | value = flask.request.form[ key ] 21 | value = cast( value ) 22 | return value 23 | return default 24 | 25 | def pil_to_b64(input): 26 | buffer = BytesIO() 27 | input.save( buffer, 'PNG' ) 28 | output = base64.b64encode( buffer.getvalue() ).decode( 'utf-8' ).replace( '\n', '' ) 29 | buffer.close() 30 | return output 31 | 32 | def b64_to_pil(input): 33 | output = Image.open( BytesIO( base64.b64decode( input ) ) ) 34 | return output 35 | 36 | def get_compute_platform(context): 37 | try: 38 | import torch 39 | if torch.cuda.is_available(): 40 | return 'cuda' 41 | elif torch.backends.mps.is_available() and context == 'engine': 42 | return 'mps' 43 | else: 44 | return 'cpu' 45 | except ImportError: 46 | return 'cpu' 47 | 48 | ################################################## 49 | # Engines 50 | 51 | class Engine(object): 52 | def __init__(self): 53 | pass 54 | 55 | def process(self, kwargs): 56 | return [] 57 | 58 | class EngineStableDiffusion(Engine): 59 | def __init__(self, pipe, sibling=None, custom_model_path=None, requires_safety_checker=True): 60 | super().__init__() 61 | if sibling == None: 62 | self.engine = pipe.from_pretrained( 'runwayml/stable-diffusion-v1-5', use_auth_token=hf_token.strip() ) 63 | elif custom_model_path: 64 | if requires_safety_checker: 65 | self.engine = diffusers.StableDiffusionPipeline.from_pretrained(custom_model_path, 66 | safety_checker=sibling.engine.safety_checker, 67 | feature_extractor=sibling.engine.feature_extractor) 68 | else: 69 | self.engine = diffusers.StableDiffusionPipeline.from_pretrained(custom_model_path, 70 | feature_extractor=sibling.engine.feature_extractor) 71 | else: 72 | self.engine = pipe( 73 | vae=sibling.engine.vae, 74 | text_encoder=sibling.engine.text_encoder, 75 | tokenizer=sibling.engine.tokenizer, 76 | unet=sibling.engine.unet, 77 | scheduler=sibling.engine.scheduler, 78 | safety_checker=sibling.engine.safety_checker, 79 | feature_extractor=sibling.engine.feature_extractor 80 | ) 81 | self.engine.to( get_compute_platform('engine') ) 82 | 83 | def process(self, kwargs): 84 | output = self.engine( **kwargs ) 85 | return {'image': output.images[0], 'nsfw':output.nsfw_content_detected[0]} 86 | 87 | class EngineManager(object): 88 | def __init__(self): 89 | self.engines = {} 90 | 91 | def has_engine(self, name): 92 | return ( name in self.engines ) 93 | 94 | def add_engine(self, name, engine): 95 | if self.has_engine( name ): 96 | return False 97 | self.engines[ name ] = engine 98 | return True 99 | 100 | def get_engine(self, name): 101 | if not self.has_engine( name ): 102 | return None 103 | engine = self.engines[ name ] 104 | return engine 105 | 106 | ################################################## 107 | # App 108 | 109 | # Load and parse the config file: 110 | try: 111 | config_file = open ('config.json', 'r') 112 | except: 113 | sys.exit('config.json not found.') 114 | 115 | config = json.loads(config_file.read()) 116 | 117 | hf_token = config['hf_token'] 118 | 119 | if (hf_token == None): 120 | sys.exit('No Hugging Face token found in config.json.') 121 | 122 | custom_models = config['custom_models'] if 'custom_models' in config else [] 123 | 124 | # Initialize app: 125 | app = flask.Flask( __name__ ) 126 | 127 | # Initialize engine manager: 128 | manager = EngineManager() 129 | 130 | # Add supported engines to manager: 131 | manager.add_engine( 'txt2img', EngineStableDiffusion( diffusers.StableDiffusionPipeline, sibling=None ) ) 132 | manager.add_engine( 'img2img', EngineStableDiffusion( diffusers.StableDiffusionImg2ImgPipeline, sibling=manager.get_engine( 'txt2img' ) ) ) 133 | manager.add_engine( 'masking', EngineStableDiffusion( diffusers.StableDiffusionInpaintPipeline, sibling=manager.get_engine( 'txt2img' ) ) ) 134 | for custom_model in custom_models: 135 | manager.add_engine( custom_model['url_path'], 136 | EngineStableDiffusion( diffusers.StableDiffusionPipeline, sibling=manager.get_engine( 'txt2img' ), 137 | custom_model_path=custom_model['model_path'], 138 | requires_safety_checker=custom_model['requires_safety_checker'] ) ) 139 | 140 | # Define routes: 141 | @app.route('/ping', methods=['GET']) 142 | def stable_ping(): 143 | return flask.jsonify( {'status':'success'} ) 144 | 145 | @app.route('/custom_models', methods=['GET']) 146 | def stable_custom_models(): 147 | if custom_models == None: 148 | return flask.jsonify( [] ) 149 | else: 150 | return custom_models 151 | 152 | @app.route('/txt2img', methods=['POST']) 153 | def stable_txt2img(): 154 | return _generate('txt2img') 155 | 156 | @app.route('/img2img', methods=['POST']) 157 | def stable_img2img(): 158 | return _generate('img2img') 159 | 160 | @app.route('/masking', methods=['POST']) 161 | def stable_masking(): 162 | return _generate('masking') 163 | 164 | @app.route('/custom/', methods=['POST']) 165 | def stable_custom(model): 166 | return _generate('txt2img', model) 167 | 168 | def _generate(task, engine=None): 169 | # Retrieve engine: 170 | if engine == None: 171 | engine = task 172 | 173 | engine = manager.get_engine( engine ) 174 | 175 | # Prepare output container: 176 | output_data = {} 177 | 178 | # Handle request: 179 | try: 180 | seed = retrieve_param( 'seed', flask.request.form, int, 0 ) 181 | count = retrieve_param( 'num_outputs', flask.request.form, int, 1 ) 182 | total_results = [] 183 | for i in range( count ): 184 | if (seed == 0): 185 | generator = torch.Generator( device=get_compute_platform('generator') ) 186 | else: 187 | generator = torch.Generator( device=get_compute_platform('generator') ).manual_seed( seed ) 188 | new_seed = generator.seed() 189 | prompt = flask.request.form[ 'prompt' ] 190 | args_dict = { 191 | 'prompt' : [ prompt ], 192 | 'num_inference_steps' : retrieve_param( 'num_inference_steps', flask.request.form, int, 100 ), 193 | 'guidance_scale' : retrieve_param( 'guidance_scale', flask.request.form, float, 7.5 ), 194 | 'eta' : retrieve_param( 'eta', flask.request.form, float, 0.0 ), 195 | 'generator' : generator 196 | } 197 | if (task == 'txt2img'): 198 | args_dict[ 'width' ] = retrieve_param( 'width', flask.request.form, int, 512 ) 199 | args_dict[ 'height' ] = retrieve_param( 'height', flask.request.form, int, 512 ) 200 | if (task == 'img2img' or task == 'masking'): 201 | init_img_b64 = flask.request.form[ 'init_image' ] 202 | init_img_b64 = re.sub( '^data:image/png;base64,', '', init_img_b64 ) 203 | init_img_pil = b64_to_pil( init_img_b64 ) 204 | args_dict[ 'init_image' ] = init_img_pil 205 | args_dict[ 'strength' ] = retrieve_param( 'strength', flask.request.form, float, 0.7 ) 206 | if (task == 'masking'): 207 | mask_img_b64 = flask.request.form[ 'mask_image' ] 208 | mask_img_b64 = re.sub( '^data:image/png;base64,', '', mask_img_b64 ) 209 | mask_img_pil = b64_to_pil( mask_img_b64 ) 210 | args_dict[ 'mask_image' ] = mask_img_pil 211 | # Perform inference: 212 | pipeline_output = engine.process( args_dict ) 213 | pipeline_output[ 'seed' ] = new_seed 214 | total_results.append( pipeline_output ) 215 | # Prepare response 216 | output_data[ 'status' ] = 'success' 217 | images = [] 218 | for result in total_results: 219 | images.append({ 220 | 'base64' : pil_to_b64( result['image'].convert( 'RGB' ) ), 221 | 'seed' : result['seed'], 222 | 'mime_type': 'image/png', 223 | 'nsfw': result['nsfw'] 224 | }) 225 | output_data[ 'images' ] = images 226 | except RuntimeError as e: 227 | output_data[ 'status' ] = 'failure' 228 | output_data[ 'message' ] = 'A RuntimeError occurred. You probably ran out of GPU memory. Check the server logs for more details.' 229 | print(str(e)) 230 | return flask.jsonify( output_data ) 231 | 232 | if __name__ == '__main__': 233 | app.run( host='0.0.0.0', port=1337, debug=False ) --------------------------------------------------------------------------------