├── .flake8 ├── .github ├── ISSUE_TEMPLATE │ ├── bug-report.yml │ ├── config.yml │ └── feature-request.yml ├── pull_request_template.md └── workflows │ └── lint.yml ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── assets ├── nsfw_censor_censorlist.png ├── nsfw_censor_sfw_request.png ├── nsfw_censor_sfw_worker.png └── readme.md ├── install.py ├── javascript └── stable-horde.js ├── logo.png ├── readme.md ├── requirements.txt ├── screenshots └── settings.png ├── scripts └── script.py └── stable_horde ├── __init__.py ├── config.py ├── horde.py └── job.py /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | max-line-length = 88 3 | exclude = .git,__pycache__,old,build,dist 4 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug-report.yml: -------------------------------------------------------------------------------- 1 | name: Bug Report 2 | description: File a bug report 3 | title: "[Bug]: " 4 | labels: ["bug"] 5 | 6 | body: 7 | - type: markdown 8 | attributes: 9 | value: | 10 | Thanks for taking the time to fill out this bug report! 11 | 12 | - type: checkboxes 13 | id: no-duplicate-issues 14 | attributes: 15 | label: Is there existing issue for this? 16 | description: Please search to see if an issue already exists for the bug you encountered. 17 | options: 18 | - label: I checked and didn't find similar issue 19 | required: true 20 | 21 | - type: checkboxes 22 | id: happen-on-latest 23 | attributes: 24 | label: Does this happen on the latest commit? 25 | description: | 26 | If you are not on the latest commit, please try updating to see if the issue is resolved. 27 | options: 28 | - label: I have confirmed this happens on the latest commit 29 | required: true 30 | 31 | - type: textarea 32 | id: what-happened 33 | attributes: 34 | label: What happened? 35 | description: A clear and concise description of what the bug is. 36 | placeholder: Tell us what you see! 37 | validations: 38 | required: true 39 | 40 | - type: textarea 41 | id: steps 42 | attributes: 43 | label: Steps to reproduce 44 | description: | 45 | How do we reproduce the issue? 46 | Please provide detailed steps for reproducing the issue. 47 | placeholder: | 48 | 1. Go to '...' 49 | 2. Click on '....' 50 | 3. Scroll down to '....' 51 | 4. See error 52 | 53 | - type: textarea 54 | id: what-expected 55 | attributes: 56 | label: What did you expect to happen? 57 | description: A clear and concise description of what you expected to happen. 58 | placeholder: Tell us what you expected! 59 | validations: 60 | required: true 61 | 62 | - type: input 63 | id: sd-webui-commit 64 | attributes: 65 | label: Stable Diffusion WebUI Commit SHA 66 | description: | 67 | Which commit of Stable Diffusion WebUI are you running? 68 | You can copy the SHA from the bottom of the WebUI, or the top of the terminal output. 69 | validations: 70 | required: true 71 | 72 | - type: dropdown 73 | id: os 74 | attributes: 75 | label: What operating system are you seeing the problem on? 76 | multiple: true 77 | options: 78 | - Windows 11 / 10 / 8 79 | - Windows 7 or below 80 | - macOS 81 | - Debian / Ubuntu 82 | - Other Linux 83 | - Other 84 | validations: 85 | required: true 86 | 87 | - type: dropdown 88 | id: browsers 89 | attributes: 90 | label: What browsers are you seeing the problem on? 91 | multiple: true 92 | options: 93 | - Firefox 94 | - Chrome 95 | - Safari 96 | - Microsoft Edge 97 | - Other 98 | validations: 99 | required: true 100 | 101 | - type: textarea 102 | id: additional-info 103 | attributes: 104 | label: Additional information 105 | description: | 106 | Add any other context about the problem here. 107 | If you have any logs or screenshots, please attach them here. 108 | 109 | # - type: checkboxes 110 | # id: terms 111 | # attributes: 112 | # label: Code of Conduct 113 | # description: By submitting this issue, you agree to follow our [Code of Conduct](https://example.com) 114 | # options: 115 | # - label: I agree to follow this project's Code of Conduct 116 | # required: true 117 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | contact_links: 3 | - name: Discussion 4 | url: https://github.com/sdwebui-w-horde/sd-webui-stable-horde-worker/discussions 5 | about: Please ask and answer questions here 6 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature-request.yml: -------------------------------------------------------------------------------- 1 | name: Feature Request 2 | description: Suggest an idea for this project 3 | title: "[Feature]: " 4 | labels: ["enhancement"] 5 | 6 | body: 7 | - type: markdown 8 | attributes: 9 | value: | 10 | Thanks for taking the time to suggest a new feature! Please make sure to fill out the form below. 11 | 12 | - type: checkboxes 13 | id: no-duplicate-issues 14 | attributes: 15 | label: Is there existing issue for this? 16 | description: Please search to see if an issue already exists for the feature you are suggesting, also checked the latest commit to make sure this feature is still not implemented. 17 | options: 18 | - label: I didn't find similar issue, also checked the latest commit. 19 | required: true 20 | 21 | - type: textarea 22 | id: feature-description 23 | attributes: 24 | label: Feature Description 25 | description: A clear and concise description of what the feature is. 26 | placeholder: Tell us what you want! 27 | validations: 28 | required: true 29 | 30 | - type: textarea 31 | id: solution 32 | attributes: 33 | label: Proposed Solution 34 | description: A clear and concise description of how do you implement this feature. 35 | placeholder: Tell us how you want it to work! 36 | validations: 37 | required: true 38 | 39 | - type: textarea 40 | id: additional-info 41 | attributes: 42 | label: Additional Information 43 | description: Add any other context or screenshots about the feature request here. 44 | placeholder: | 45 | Add any other context or screenshots about the feature request here. 46 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | 3 | 8 | 9 | ## Type of changes 10 | 11 | 12 | 13 | - [ ] Bugfix 14 | - [ ] Feature 15 | - [ ] Refactoring 16 | - [ ] Optimization 17 | - [ ] Documentation 18 | - [ ] CI/CD 19 | - [ ] Other 20 | 21 | ## Please check the following items before submitting your pull request 22 | 26 | 27 | - [ ] I've checked that this isn't a duplicate pull request. 28 | - [ ] I've tested my changes with the latest SD-Webui version. 29 | - [ ] I've format my code with [black](https://black.readthedocs.io/): `black .` 30 | - [ ] I've lint my code with [flake8](https://flake8.pycqa.org/): `flake8 .` 31 | - [ ] I've read the [Contribution Guidelines](https://github.com/sdwebui-w-horde/sd-webui-stable-horde-worker/blob/master/CONTRIBUTING.md) 32 | - [ ] I've read the [Code of Conduct](https://github.com/sdwebui-w-horde/.github/blob/master/CODE_OF_CONDUCT.md) 33 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: Lint 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | jobs: 9 | lint: 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - uses: actions/checkout@v3 14 | 15 | - uses: actions/setup-python@v2 16 | with: 17 | python-version: "3.10" 18 | 19 | - name: Install dependencies 20 | run: | 21 | python -m pip install --upgrade pip 22 | pip install -r requirements.txt 23 | 24 | - name: Lint with flake8 25 | run: | 26 | flake8 . --count --show-source --statistics 27 | 28 | - name: Lint with black 29 | run: | 30 | black --check . -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | 162 | # Data files 163 | stablehorde_supported_models.json 164 | 165 | # Config files 166 | config.json 167 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Welcome to the SD-WebUI Stable Horde Worker Bridge Extension Project 2 | 3 | :tada: Thank you for investing your time to help us make this project better! :tada: 4 | 5 | Read our [Code of Conduct](https://github.com/sdwebui-w-horde/.github/blob/master/CODE_OF_CONDUCT.md) to keep this community open and inclusive. 6 | 7 | ## What can I contribute? 8 | 9 | - [Report bugs](#reporting-bugs) 10 | - [Suggest enhancements](#suggesting-enhancements) 11 | - [Code contribution](#code-contribution) 12 | 13 | ## Reporting bugs 14 | 15 | This section guides you through submitting a bug report for our project. 16 | Following these guidelines helps maintainers and the community understand your report :pencil:, reproduce the behavior :computer:, and find related reports :mag_right:. 17 | 18 | ### Before submitting a bug report 19 | 20 | - Update your SD-WebUI and extension to the latest version to see if the problem has been fixed. 21 | - Search the [existing issues](https://github.com/sdwebui-w-horde/sd-webui-stable-horde-worker/issues) to see if the problem has already been reported. 22 | - If you find an existing issue report, please add a comment to the existing issue instead of opening a new one. 23 | - If you find an existing issue report that seems similar to your problem, but the solutions or workarounds don't work for you, please open a new issue report. 24 | - Make sure you are able to reproduce the problem on the latest version of SD-WebUI and the extension. 25 | 26 | ### How do I submit a good bug report? 27 | 28 | Explain the problem and include additional details to help maintainers reproduce the problem: 29 | 30 | - Use a clear and descriptive title for the issue to identify the problem. 31 | - Describe the exact steps which reproduce the problem in as many details as possible. 32 | - Provide specific examples to demonstrate the steps. 33 | - Describe the behavior you observed after following the steps and point out what exactly is the problem with that behavior. 34 | - Explain which behavior you expected to see instead and why. 35 | - Include screenshots and corresponding logs which show you following the described steps and clearly demonstrate the problem. 36 | - Clarify which version of SD-WebUI and the extension you are using, not just "latest version". 37 | 38 | ## Suggesting enhancements 39 | 40 | This section guides you through submitting an enhancement suggestion for our project, including completely new features and minor improvements to existing functionality. 41 | 42 | ### Before submitting an enhancement suggestion 43 | 44 | - Check the [existing issues](https://github.com/sdwebui-w-horde/sd-webui-stable-horde-worker/issues) to see if the enhancement has already been suggested. 45 | - If you find an existing issue report, please add a comment to the existing issue instead of opening a new one. 46 | 47 | ### How to submit a good enhancement suggestion 48 | 49 | Explain the enhancement and include additional details to help maintainers understand the enhancement: 50 | 51 | - Use a clear and descriptive title for the issue to identify the enhancement. 52 | - Provide a step-by-step description of the suggested enhancement in as many details as possible. 53 | - Provide specific examples to demonstrate the steps. 54 | - Describe the current behavior and explain which behavior you expected to see instead and why. 55 | - Describe alternatives you've considered. 56 | 57 | ## Code contribution 58 | 59 | This section guides you through submitting a code contribution for our project. 60 | 61 | ### Before submitting a code contribution 62 | 63 | - Update your extension to the latest version to see if your contribution has already been implemented. 64 | - Search the [existing pull requests](https://github.com/sdwebui-w-horde/sd-webui-stable-horde-worker/pulls) to see if the enhancement has already been implemented by someone else. 65 | 66 | ### Submit a code contribution 67 | 68 | - Fork the repository and create your branch from `master`. 69 | - Format your code with `black .` 70 | - Lint your code with `flake8 .` 71 | - If you've added code that should be tested, add tests. 72 | - If you've changed usage or APIs, update the documentation. 73 | - Ensure the test suite passes. 74 | - Make sure your code lints. 75 | - Issue that pull request! 76 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 2022-2023 Maiko Tan 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /assets/nsfw_censor_censorlist.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sdwebui-w-horde/sd-webui-stable-horde-worker/e206c3645233545f6d89d426928e66f6f4ce69a5/assets/nsfw_censor_censorlist.png -------------------------------------------------------------------------------- /assets/nsfw_censor_sfw_request.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sdwebui-w-horde/sd-webui-stable-horde-worker/e206c3645233545f6d89d426928e66f6f4ce69a5/assets/nsfw_censor_sfw_request.png -------------------------------------------------------------------------------- /assets/nsfw_censor_sfw_worker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sdwebui-w-horde/sd-webui-stable-horde-worker/e206c3645233545f6d89d426928e66f6f4ce69a5/assets/nsfw_censor_sfw_worker.png -------------------------------------------------------------------------------- /assets/readme.md: -------------------------------------------------------------------------------- 1 | **Images in this folder was copied from https://github.com/Sygil-Dev/nataili and licenced as AGPL-3.0 without any modification.** 2 | -------------------------------------------------------------------------------- /install.py: -------------------------------------------------------------------------------- 1 | import launch 2 | 3 | if not launch.is_installed("diffusers"): 4 | launch.run_pip("install diffusers", "diffusers") # NSFW filter 5 | launch.run_pip("install aiohttp", "aiohttp") # asynchroneous HTTP requests 6 | -------------------------------------------------------------------------------- /javascript/stable-horde.js: -------------------------------------------------------------------------------- 1 | let globalHordeTimer 2 | let globalHordeCurrentId 3 | 4 | function stableHordeStartTimer() { 5 | if (!globalHordeTimer) { 6 | globalHordeTimer = setInterval(() => { 7 | const currentId = gradioApp().querySelector('#stable-horde #stable-horde-current-id textarea')?.value 8 | const refreshBtn = gradioApp().querySelector('#stable-horde #stable-horde-refresh') 9 | if (refreshBtn) { 10 | refreshBtn.click() 11 | } 12 | if (currentId !== globalHordeCurrentId) { 13 | globalHordeCurrentId = currentId 14 | gradioApp().querySelector('#stable-horde #stable-horde-refresh-image').click() 15 | } 16 | }, 1000) 17 | } 18 | } 19 | 20 | function stableHordeStopTimer() { 21 | if (globalHordeTimer) { 22 | clearInterval(globalHordeTimer) 23 | globalHordeTimer = null 24 | } 25 | } 26 | 27 | stableHordeStartTimer() 28 | -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sdwebui-w-horde/sd-webui-stable-horde-worker/e206c3645233545f6d89d426928e66f6f4ce69a5/logo.png -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | 5 |
6 | 7 | # SD WebUI ❤️ Stable Horde 8 | 9 | ![python](https://img.shields.io/badge/python-3.10-blue) 10 | [![issues](https://img.shields.io/github/issues/sdwebui-w-horde/sd-webui-stable-horde-worker)](https://github.com/sdwebui-w-horde/sd-webui-stable-horde-worker/issues) 11 | [![pr](https://img.shields.io/github/issues-pr/sdwebui-w-horde/sd-webui-stable-horde-worker)](https://github.com/sdwebui-w-horde/sd-webui-stable-horde-worker/pulls) 12 | [![license](https://img.shields.io/github/license/sdwebui-w-horde/sd-webui-stable-horde-worker)](LICENSE) 13 | [![Lint](https://github.com/sdwebui-w-horde/sd-webui-stable-horde-worker/actions/workflows/lint.yml/badge.svg)](https://github.com/sdwebui-w-horde/sd-webui-stable-horde-worker/actions/workflows/lint.yml) 14 | 15 | ✨ *Stable Horde Worker Bridge for Stable Diffusion WebUI* ✨ 16 | 17 |
18 | 19 | An unofficial [Stable Horde](https://stablehorde.net/) worker bridge as a [Stable Diffusion WebUI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) extension. 20 | 21 | ## Features 22 | 23 | **This extension is still WORKING IN PROGRESS**, and is not ready for production use. 24 | 25 | - Get jobs from Stable Horde, generate images and submit generations 26 | - Configurable interval between every jobs 27 | - Enable and disable extension whenever 28 | - Detect current model and fetch corresponding jobs on the fly 29 | - Show generation images in the Stable Diffusion WebUI 30 | - Save generation images with png info text to local 31 | 32 | ## Install 33 | 34 | - Run the following command in the root directory of your Stable Diffusion WebUI installation: 35 | 36 | ```bash 37 | git clone https://github.com/sdwebui-w-horde/sd-webui-stable-horde-worker.git extensions/stable-horde-worker 38 | ``` 39 | 40 | - Launch the Stable Diffusion WebUI, You would see the `Stable Horde Worker` tab page. 41 | 42 | ![settings](./screenshots/settings.png) 43 | 44 | - Register an account on [Stable Horde](https://stablehorde.net/) and get your `API key` if you don't have one. 45 | 46 | **Note**: the default anonymous key `00000000` is not working for a worker, you need to register an account and get your own key. 47 | 48 | - Setup your `API key` here. 49 | - Setup `Worker name` here with a proper name. 50 | - Make sure `Enable` is checked. 51 | - Click the `Apply settings` buttons. 52 | 53 | ## Compatibility 54 | 55 | Here is the compatibilities with the [official bridge](https://github.com/db0/AI-Horde-Worker). 56 | 57 | |Features|Supported?| 58 | |:-:|:-:| 59 | |img2img|✔️| 60 | |Inpainting|✔️| 61 | |Interrogate|❌| 62 | |Tiling|✔️| 63 | |Hi-res Fix|✔️| 64 | |Clip Skip|❌| 65 | |Face Restoration (GFPGAN)|✔️| 66 | |Upscale (ESRGAN)|✔️| 67 | |Sample Karras Scheduler|⭕*| 68 | |R2 upload|✔️| 69 | |R2 source image|❌| 70 | |Multiple Models|✔️| 71 | 72 | \* Karras scheduler is partially supported in SD-WebUI Bridge, see below. 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 |
SamplersOfficial BridgeSD-WebUI Bridge
No KarrasKarrasNo KarrasKarras
k_lms✔️✔️✔️✔️
k_heun✔️✔️✔️✔️
k_euler✔️✔️✔️✔️
k_euler_a✔️✔️✔️✔️
k_dpm_2✔️✔️✔️✔️
k_dpm_2_a✔️✔️✔️✔️
k_dpm_fast✔️✔️✔️✔️
k_dpm_adaptive✔️✔️✔️✔️
k_dpmpp_2s_a✔️✔️✔️✔️
k_dpmpp_2m✔️✔️✔️✔️
k_dpmpp_sde✔️✔️✔️✔️
dpmsolver✔️✔️
ddim✔️
plms✔️
189 | 190 | ## License 191 | 192 | This project is licensed under the terms of the [AGPL-3.0 License](LICENSE). 193 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # Formatters and linters 2 | black ~= 22.0 3 | flake8 4 | -------------------------------------------------------------------------------- /screenshots/settings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sdwebui-w-horde/sd-webui-stable-horde-worker/e206c3645233545f6d89d426928e66f6f4ce69a5/screenshots/settings.png -------------------------------------------------------------------------------- /scripts/script.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | from fastapi import FastAPI 4 | import gradio as gr 5 | import asyncio 6 | import requests 7 | from threading import Thread 8 | 9 | from modules import scripts, script_callbacks, sd_models, shared 10 | 11 | from stable_horde import StableHorde, StableHordeConfig 12 | 13 | basedir = scripts.basedir() 14 | config = StableHordeConfig(basedir) 15 | horde = StableHorde(basedir, config) 16 | 17 | 18 | def on_app_started(demo: Optional[gr.Blocks], app: FastAPI): 19 | started = False 20 | 21 | @app.on_event("startup") 22 | @app.get("/horde/startup-events") 23 | async def startup_event(): 24 | nonlocal started 25 | if not started: 26 | thread = Thread(daemon=True, target=horde_thread) 27 | thread.start() 28 | started = True 29 | 30 | # This is a hack to make sure the startup event is 31 | # called even it is not in an async scope 32 | # fix https://github.com/sdwebui-w-horde/sd-webui-stable-horde-worker/issues/109 33 | if demo is None: 34 | # flake8: noqa: E501 35 | local_url = f"http://localhost:{shared.cmd_opts.port if shared.cmd_opts.port else 7861}/" 36 | else: 37 | local_url = demo.local_url 38 | requests.get(f"{local_url}horde/startup-events") 39 | 40 | 41 | def horde_thread(): 42 | asyncio.run(horde.run()) 43 | 44 | 45 | def apply_stable_horde_settings( 46 | enable: bool, 47 | name: str, 48 | apikey: str, 49 | allow_img2img: bool, 50 | allow_painting: bool, 51 | allow_unsafe_ipaddr: bool, 52 | allow_post_processing, 53 | restore_settings: bool, 54 | nsfw: bool, 55 | interval: int, 56 | max_pixels: str, 57 | endpoint: str, 58 | show_images: bool, 59 | save_images: bool, 60 | save_images_folder: str, 61 | ): 62 | config.enabled = enable 63 | config.allow_img2img = allow_img2img 64 | config.allow_painting = allow_painting 65 | config.allow_unsafe_ipaddr = allow_unsafe_ipaddr 66 | config.allow_post_processing = allow_post_processing 67 | config.restore_settings = restore_settings 68 | config.interval = interval 69 | config.endpoint = endpoint 70 | config.apikey = apikey 71 | config.name = name 72 | config.max_pixels = int(max_pixels) 73 | config.nsfw = nsfw 74 | config.show_image_preview = show_images 75 | config.save_images = save_images 76 | config.save_images_folder = save_images_folder 77 | config.save() 78 | 79 | return ( 80 | f'Status: {"Running" if config.enabled else "Stopped"}', 81 | "Running Type: Image Generation", 82 | ) 83 | 84 | 85 | def on_ui_tabs(): 86 | tab_prefix = "stable-horde-" 87 | with gr.Blocks() as demo: 88 | with gr.Column(elem_id="stable-horde"): 89 | with gr.Row(): 90 | status = gr.Textbox( 91 | f'Status: {"Running" if config.enabled else "Stopped"}', 92 | label="", 93 | elem_id=tab_prefix + "status", 94 | readonly=True, 95 | ) 96 | running_type = gr.Textbox( 97 | "Running Type: Image Generation", 98 | label="", 99 | elem_id=tab_prefix + "running-type", 100 | readonly=True, 101 | ) 102 | 103 | apply_settings = gr.Button( 104 | "Apply Settings", elem_id=tab_prefix + "apply-settings" 105 | ) 106 | with gr.Row(): 107 | state = gr.Textbox("", label="", readonly=True) 108 | with gr.Row(equal_height=False): 109 | with gr.Column(): 110 | with gr.Box(scale=2): 111 | enable = gr.Checkbox( 112 | config.enabled, 113 | label="Enable", 114 | elem_id=tab_prefix + "enable", 115 | ) 116 | name = gr.Textbox( 117 | config.name, 118 | label="Worker Name", 119 | elem_id=tab_prefix + "name", 120 | ) 121 | apikey = gr.Textbox( 122 | config.apikey, 123 | label="Stable Horde API Key", 124 | elem_id=tab_prefix + "apikey", 125 | ) 126 | allow_img2img = gr.Checkbox( 127 | config.allow_img2img, label="Allow img2img" 128 | ) 129 | allow_painting = gr.Checkbox( 130 | config.allow_painting, label="Allow Painting" 131 | ) 132 | allow_unsafe_ipaddr = gr.Checkbox( 133 | config.allow_unsafe_ipaddr, 134 | label="Allow Unsafe IP Address", 135 | ) 136 | allow_post_processing = gr.Checkbox( 137 | config.allow_post_processing, 138 | label="Allow Post Processing", 139 | ) 140 | restore_settings = gr.Checkbox( 141 | config.restore_settings, 142 | label="Restore settings after rendering a job", 143 | ) 144 | nsfw = gr.Checkbox(config.nsfw, label="Allow NSFW") 145 | interval = gr.Slider( 146 | 0, 147 | 60, 148 | config.interval, 149 | step=1, 150 | label="Duration Between Generations (seconds)", 151 | ) 152 | max_pixels = gr.Textbox( 153 | str(config.max_pixels), 154 | label="Max Pixels", 155 | elem_id=tab_prefix + "max-pixels", 156 | ) 157 | endpoint = gr.Textbox( 158 | config.endpoint, 159 | label="Stable Horde Endpoint", 160 | elem_id=tab_prefix + "endpoint", 161 | ) 162 | save_images_folder = gr.Textbox( 163 | config.save_images_folder, 164 | label="Folder to Save Generation Images", 165 | elem_id=tab_prefix + "save-images-folder", 166 | ) 167 | 168 | with gr.Box(scale=2): 169 | 170 | def on_apply_selected_models(local_selected_models): 171 | status.update( 172 | f'Status: \ 173 | {"Running" if config.enabled else "Stopped"}, \ 174 | Updating selected models...' 175 | ) 176 | selected_models = horde.set_current_models( 177 | local_selected_models 178 | ) 179 | local_selected_models_dropdown.update( 180 | value=list(selected_models.values()) 181 | ) 182 | return f'Status: \ 183 | {"Running" if config.enabled else "Stopped"}, \ 184 | Selected models \ 185 | {list(selected_models.values())} updated' 186 | 187 | local_selected_models_dropdown = gr.Dropdown( 188 | [ 189 | model.name 190 | for model in sd_models.checkpoints_list.values() 191 | ], 192 | value=[ 193 | model.name 194 | for model in sd_models.checkpoints_list.values() 195 | if model.name in list(config.current_models.values()) 196 | ], 197 | label="Selected models for sharing", 198 | elem_id=tab_prefix + "local-selected-models", 199 | multiselect=True, 200 | interactive=True, 201 | ) 202 | 203 | local_selected_models_dropdown.change( 204 | on_apply_selected_models, 205 | inputs=[local_selected_models_dropdown], 206 | outputs=[status], 207 | ) 208 | gr.Markdown( 209 | "Once you select a model it will take some time to load." 210 | ) 211 | 212 | with gr.Column(): 213 | show_images = gr.Checkbox( 214 | config.show_image_preview, label="Show Images" 215 | ) 216 | save_images = gr.Checkbox(config.save_images, label="Save Images") 217 | 218 | refresh = gr.Button( 219 | "Refresh", 220 | visible=False, 221 | elem_id=tab_prefix + "refresh", 222 | ) 223 | refresh_image = gr.Button( 224 | "Refresh Image", 225 | visible=False, 226 | elem_id=tab_prefix + "refresh-image", 227 | ) 228 | 229 | current_id = gr.Textbox( 230 | "Current ID: ", 231 | label="", 232 | elem_id=tab_prefix + "current-id", 233 | readonly=True, 234 | ) 235 | preview = gr.Gallery( 236 | label="Preview", 237 | elem_id=tab_prefix + "preview", 238 | visible=config.show_image_preview, 239 | readonly=True, 240 | columns=4, 241 | ) 242 | 243 | def on_refresh(image=False, show_images=config.show_image_preview): 244 | cid = f"Current ID: {horde.state.id}" 245 | html = "".join( 246 | map( 247 | lambda x: f"

{x[0]}: {x[1]}

", 248 | horde.state.to_dict().items(), 249 | ) 250 | ) 251 | images = ( 252 | [horde.state.image] if horde.state.image is not None else [] 253 | ) 254 | if image and show_images: 255 | return cid, html, horde.state.status, images 256 | return cid, html, horde.state.status 257 | 258 | with gr.Row(): 259 | log = gr.HTML(elem_id=tab_prefix + "log") 260 | 261 | refresh.click( 262 | fn=lambda: on_refresh(), 263 | outputs=[current_id, log, state], 264 | show_progress=False, 265 | ) 266 | refresh_image.click( 267 | fn=lambda: on_refresh(True), 268 | outputs=[current_id, log, state, preview], 269 | show_progress=False, 270 | ) 271 | apply_settings.click( 272 | fn=apply_stable_horde_settings, 273 | inputs=[ 274 | enable, 275 | name, 276 | apikey, 277 | allow_img2img, 278 | allow_painting, 279 | allow_unsafe_ipaddr, 280 | allow_post_processing, 281 | restore_settings, 282 | nsfw, 283 | interval, 284 | max_pixels, 285 | endpoint, 286 | show_images, 287 | save_images, 288 | save_images_folder, 289 | ], 290 | outputs=[status, running_type], 291 | ) 292 | 293 | return ((demo, "Stable Horde Worker", "stable-horde"),) 294 | 295 | 296 | script_callbacks.on_app_started(on_app_started) 297 | script_callbacks.on_ui_tabs(on_ui_tabs) 298 | -------------------------------------------------------------------------------- /stable_horde/__init__.py: -------------------------------------------------------------------------------- 1 | from .horde import StableHorde 2 | from .config import StableHordeConfig 3 | 4 | __all__ = ["StableHorde", "StableHordeConfig"] 5 | -------------------------------------------------------------------------------- /stable_horde/config.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os.path as path 3 | from typing import Any 4 | 5 | 6 | class StableHordeConfig(object): 7 | enabled: bool = False 8 | endpoint: str = "https://stablehorde.net/" 9 | apikey: str = "00000000" 10 | name: str = "" 11 | interval: int = 10 12 | max_pixels: int = 1048576 # 1024x1024 13 | nsfw: bool = False 14 | restore_settings: bool = True 15 | allow_img2img: bool = True 16 | allow_painting: bool = True 17 | allow_unsafe_ipaddr: bool = True 18 | allow_post_processing: bool = True 19 | show_image_preview: bool = False 20 | save_images: bool = False 21 | save_images_folder: str = "horde" 22 | current_models: dict = {} 23 | hires_firstphase_resolution: int = 512 24 | hr_upscaler: str = "Latent" 25 | 26 | def __init__(self, basedir: str): 27 | self.basedir = basedir 28 | self.config = self.load() 29 | 30 | def __getattribute__(self, item: str): 31 | if item in ["config", "basedir", "load", "save"]: 32 | return super().__getattribute__(item) 33 | value = self.config.get(item, None) 34 | if value is None: 35 | return super().__getattribute__(item) 36 | return value 37 | 38 | def __setattr__(self, key: str, value: Any): 39 | if key == "config" or key == "basedir": 40 | super().__setattr__(key, value) 41 | else: 42 | self.config[key] = value 43 | self.save() 44 | 45 | def load(self): 46 | if not path.exists(path.join(self.basedir, "config.json")): 47 | self.config = { 48 | "enabled": False, 49 | "allow_img2img": True, 50 | "allow_painting": True, 51 | "allow_unsafe_ipaddr": True, 52 | "allow_post_processing": True, 53 | "restore_settings": True, 54 | "show_image_preview": False, 55 | "save_images": False, 56 | "save_images_folder": "horde", 57 | "endpoint": "https://stablehorde.net/", 58 | "apikey": "00000000", 59 | "name": "", 60 | "interval": 10, 61 | "max_pixels": 1048576, 62 | "nsfw": False, 63 | "hr_upscaler": "Latent", 64 | "hires_firstphase_resolution": 512, 65 | } 66 | self.save() 67 | 68 | with open(path.join(self.basedir, "config.json"), "r") as f: 69 | return json.load(f) 70 | 71 | def save(self): 72 | with open(path.join(self.basedir, "config.json"), "w") as f: 73 | json.dump(self.config, f, indent=2) 74 | -------------------------------------------------------------------------------- /stable_horde/horde.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import json 3 | from os import path 4 | from typing import Any, Dict, Optional 5 | from re import sub 6 | 7 | import aiohttp 8 | from .job import HordeJob 9 | from .config import StableHordeConfig 10 | import numpy as np 11 | from diffusers.pipelines.stable_diffusion.safety_checker import ( 12 | StableDiffusionSafetyChecker, 13 | ) 14 | from PIL import Image 15 | from transformers.models.auto.feature_extraction_auto import ( 16 | AutoFeatureExtractor, 17 | ) 18 | 19 | from modules.images import save_image 20 | from modules import ( 21 | shared, 22 | call_queue, 23 | processing, 24 | sd_models, 25 | sd_samplers, 26 | ) 27 | 28 | # flake8: noqa: E501 29 | stable_horde_supported_models_url = "https://raw.githubusercontent.com/Haidra-Org/AI-Horde-image-model-reference/main/stable_diffusion.json" 30 | 31 | safety_model_id = "CompVis/stable-diffusion-safety-checker" 32 | safety_feature_extractor = None 33 | safety_checker = None 34 | 35 | 36 | class State: 37 | def __init__(self): 38 | self._status = "" 39 | self.id: Optional[str] = None 40 | self.prompt: Optional[str] = None 41 | self.negative_prompt: Optional[str] = None 42 | self.scale: Optional[float] = None 43 | self.steps: Optional[int] = None 44 | self.sampler: Optional[str] = None 45 | self.image: Optional[Image.Image] = None 46 | 47 | @property 48 | def status(self): 49 | return self._status 50 | 51 | @status.setter 52 | def status(self, value): 53 | self._status = value 54 | if shared.cmd_opts.nowebui: 55 | print(value) 56 | 57 | def to_dict(self): 58 | return { 59 | "status": self.status, 60 | "prompt": self.prompt, 61 | "negative_prompt": self.negative_prompt, 62 | "scale": self.scale, 63 | "steps": self.steps, 64 | "sampler": self.sampler, 65 | } 66 | 67 | 68 | class StableHorde: 69 | def __init__(self, basedir: str, config: StableHordeConfig): 70 | self.basedir = basedir 71 | self.config = config 72 | self.session: Optional[aiohttp.ClientSession] = None 73 | 74 | self.sfw_request_censor = Image.open( 75 | path.join(self.config.basedir, "assets", "nsfw_censor_sfw_request.png") 76 | ) 77 | 78 | self.supported_models = [] 79 | self.current_models = {} 80 | 81 | self.state = State() 82 | 83 | async def get_supported_models(self): 84 | attempts = 10 85 | while attempts > 0: 86 | attempts -= 1 87 | async with aiohttp.ClientSession() as session: 88 | try: 89 | async with session.get(stable_horde_supported_models_url) as resp: 90 | if resp.status != 200: 91 | raise aiohttp.ClientError() 92 | data = await resp.text() 93 | supported_models: Dict[str, Any] = json.loads(data) 94 | 95 | self.supported_models = list(supported_models.values()) 96 | return 97 | except Exception: 98 | print( 99 | f"Failed to get supported models, retrying in 1 second... \ 100 | ({attempts} attempts left" 101 | ) 102 | await asyncio.sleep(1) 103 | raise Exception("Failed to get supported models after 10 attempts") 104 | 105 | def detect_current_model(self): 106 | model_checkpoint = shared.opts.sd_model_checkpoint 107 | checkpoint_info = sd_models.checkpoints_list.get(model_checkpoint, None) 108 | if checkpoint_info is None: 109 | return f"Model checkpoint {model_checkpoint} not found" 110 | 111 | for model in self.supported_models: 112 | try: 113 | remote_hash = model["config"]["files"][0]["sha256sum"] 114 | except KeyError: 115 | continue 116 | 117 | if shared.opts.sd_checkpoint_hash == remote_hash: 118 | self.current_models = {model["name"]: checkpoint_info.name} 119 | 120 | if len(self.current_models) == 0: 121 | return f"Current model {model_checkpoint} not found on StableHorde" 122 | 123 | def set_current_models(self, model_names: list): 124 | """Set the current models in horde and config""" 125 | remote_hashes = {} 126 | self.current_models = { 127 | k: v for k, v in self.current_models.items() if v in model_names 128 | } 129 | # get the sha256 of all supported models 130 | for model in self.supported_models: 131 | try: 132 | remote_hashes[model["config"]["files"][0]["sha256sum"].lower()] = model[ 133 | "name" 134 | ] 135 | except KeyError: 136 | continue 137 | # get the sha256 of all local models and compare it to the remote hashes 138 | # if the sha256 matches, add the model to the current models list 139 | for checkpoint in sd_models.checkpoints_list.values(): 140 | checkpoint: sd_models.CheckpointInfo 141 | if checkpoint.name in model_names: 142 | # skip sha256 calculation if the model already has hash 143 | if checkpoint.sha256 is None: 144 | local_hash = sd_models.hashes.sha256( 145 | checkpoint.filename, f"checkpoint/{checkpoint.name}" 146 | ) 147 | else: 148 | local_hash = checkpoint.sha256 149 | if checkpoint.name in self.config.current_models.values(): 150 | continue 151 | 152 | if local_hash in remote_hashes: 153 | self.current_models[remote_hashes[local_hash]] = checkpoint.name 154 | print( 155 | f"sha256 for {checkpoint.name} is {local_hash} \ 156 | and it's supported by StableHorde" 157 | ) 158 | else: 159 | print( 160 | f"sha256 for {checkpoint.name} is {local_hash} \ 161 | but it's not supported by StableHorde" 162 | ) 163 | 164 | self.config.current_models = self.current_models 165 | self.config.save() 166 | return self.current_models 167 | 168 | async def run(self): 169 | await self.get_supported_models() 170 | self.current_models = self.config.current_models 171 | 172 | while True: 173 | if len(self.current_models) == 0: 174 | result = self.detect_current_model() 175 | if result is not None: 176 | self.state.status = result 177 | # Wait 10 seconds before retrying to detect the current model 178 | # if the current model is not listed in the Stable Horde supported 179 | # models, we don't want to spam the server with requests 180 | await asyncio.sleep(10) 181 | continue 182 | 183 | await asyncio.sleep(self.config.interval) 184 | 185 | if self.config.enabled: 186 | try: 187 | # Require a queue lock to prevent getting jobs when 188 | # there are generation jobs from webui. 189 | with call_queue.queue_lock: 190 | req = await HordeJob.get( 191 | await self.get_session(), 192 | self.config, 193 | list(self.current_models.keys()), 194 | ) 195 | if req is None: 196 | continue 197 | 198 | await self.handle_request(req) 199 | except Exception: 200 | import traceback 201 | 202 | traceback.print_exc() 203 | 204 | def patch_sampler_names(self): 205 | """Add more samplers that the Stable Horde supports, 206 | but are not included in the default sd_samplers module. 207 | """ 208 | from modules import sd_samplers 209 | 210 | try: 211 | # Old versions of webui put every samplers in `modules.sd_samplers` 212 | # But the newer version split them into several files 213 | # Happened in https://github.com/AUTOMATIC1111/stable-diffusion-webui/commit/4df63d2d197f26181758b5108f003f225fe84874 # noqa E501 214 | from modules.sd_samplers import KDiffusionSampler, SamplerData 215 | except ImportError: 216 | from modules.sd_samplers_kdiffusion import KDiffusionSampler 217 | from modules.sd_samplers_common import SamplerData 218 | 219 | if sd_samplers.samplers_map.get("euler a karras"): 220 | # already patched 221 | return 222 | 223 | samplers = [ 224 | SamplerData( 225 | name, 226 | lambda model, fn=func: KDiffusionSampler(fn, model), 227 | [alias], 228 | {"scheduler": "karras"}, 229 | ) 230 | for name, func, alias in [ 231 | ("Euler a Karras", "sample_euler_ancestral", "k_euler_a_ka"), 232 | ("Euler Karras", "sample_euler", "k_euler_ka"), 233 | ("LMS Karras", "sample_lms", "k_lms_ka"), 234 | ("Heun Karras", "sample_heun", "k_heun_ka"), 235 | ("DPM2 Karras", "sample_dpm_2", "k_dpm_2_ka"), 236 | ("DPM2 a Karras", "sample_dpm_2_ancestral", "k_dpm_2_a_ka"), 237 | ("DPM++ 2S a Karras", "sample_dpmpp_2s_ancestral", "k_dpmpp_2s_a_ka"), 238 | ("DPM++ 2M Karras", "sample_dpmpp_2m", "k_dpmpp_2m_ka"), 239 | ("DPM++ SDE Karras", "sample_dpmpp_sde", "k_dpmpp_sde_ka"), 240 | ("DPM fast Karras", "sample_dpm_fast", "k_dpm_fast_ka"), 241 | ("DPM adaptive Karras", "sample_dpm_adaptive", "k_dpm_ad_ka"), 242 | ] 243 | ] 244 | sd_samplers.samplers.extend(samplers) 245 | sd_samplers.samplers_for_img2img.extend(samplers) 246 | sd_samplers.all_samplers_map.update({s.name: s for s in samplers}) 247 | for sampler in samplers: 248 | sd_samplers.samplers_map[sampler.name.lower()] = sampler.name 249 | for alias in sampler.aliases: 250 | sd_samplers.samplers_map[alias.lower()] = sampler.name 251 | 252 | async def handle_request(self, job: HordeJob): 253 | self.patch_sampler_names() 254 | 255 | self.state.status = f"Get popped generation request {job.id}, \ 256 | model {job.model}, sampler {job.sampler}" 257 | sampler_name = job.sampler 258 | if sampler_name == "k_dpm_adaptive": 259 | sampler_name = "k_dpm_ad" 260 | if sampler_name not in sd_samplers.samplers_map: 261 | self.state.status = f"ERROR: Unknown sampler {sampler_name}" 262 | return 263 | if job.karras: 264 | sampler_name += "_ka" 265 | 266 | # Map model name to model 267 | local_model = self.current_models.get(job.model, shared.sd_model) 268 | # Short hash for info text 269 | local_model_shorthash = None 270 | for checkpoint in sd_models.checkpoints_list.values(): 271 | checkpoint: sd_models.CheckpointInfo 272 | if checkpoint.name == local_model: 273 | if not checkpoint.shorthash: 274 | checkpoint.calculate_shorthash() 275 | local_model_shorthash = checkpoint.shorthash 276 | break 277 | if local_model_shorthash is None: 278 | raise Exception(f"ERROR: Unknown model {local_model}") 279 | 280 | sampler = sd_samplers.samplers_map.get(sampler_name, None) 281 | if sampler is None: 282 | raise Exception(f"ERROR: Unknown sampler {sampler_name}") 283 | 284 | postprocessors = job.postprocessors 285 | 286 | params = { 287 | "sd_model": local_model, 288 | "prompt": job.prompt, 289 | "negative_prompt": job.negative_prompt, 290 | "sampler_name": sampler, 291 | "cfg_scale": job.cfg_scale, 292 | "seed": job.seed, 293 | "denoising_strength": job.denoising_strength, 294 | "height": job.height, 295 | "width": job.width, 296 | "subseed": job.subseed, 297 | "steps": job.steps, 298 | "tiling": job.tiling, 299 | "n_iter": job.n_iter, 300 | "do_not_save_samples": True, 301 | "do_not_save_grid": True, 302 | "override_settings": { 303 | "sd_model_checkpoint": local_model, 304 | }, 305 | "enable_hr": job.hires_fix, 306 | "hr_upscaler": self.config.hr_upscaler, 307 | "override_settings_restore_afterwards": self.config.restore_settings, 308 | } 309 | 310 | if job.hires_fix: 311 | ar = job.width / job.height 312 | params["firstphase_width"] = min( 313 | self.config.hires_firstphase_resolution, 314 | int(self.config.hires_firstphase_resolution * ar), 315 | ) 316 | params["firstphase_height"] = min( 317 | self.config.hires_firstphase_resolution, 318 | int(self.config.hires_firstphase_resolution / ar), 319 | ) 320 | 321 | if job.source_image is not None: 322 | p = processing.StableDiffusionProcessingImg2Img( 323 | init_images=[job.source_image], 324 | mask=job.source_mask, 325 | **params, 326 | ) 327 | else: 328 | p = processing.StableDiffusionProcessingTxt2Img(**params) 329 | 330 | with call_queue.queue_lock: 331 | shared.state.begin() 332 | # hijack clip skip 333 | hijacked = False 334 | old_clip_skip = shared.opts.CLIP_stop_at_last_layers 335 | if ( 336 | job.clip_skip >= 1 337 | and job.clip_skip != shared.opts.CLIP_stop_at_last_layers 338 | ): 339 | shared.opts.CLIP_stop_at_last_layers = job.clip_skip 340 | hijacked = True 341 | processed = processing.process_images(p) 342 | 343 | if hijacked: 344 | shared.opts.CLIP_stop_at_last_layers = old_clip_skip 345 | shared.state.end() 346 | 347 | has_nsfw = False 348 | 349 | with call_queue.queue_lock: 350 | if job.nsfw_censor: 351 | x_image = np.array(processed.images[0]) 352 | image, has_nsfw = self.check_safety(x_image) 353 | if has_nsfw: 354 | job.censored = True 355 | 356 | else: 357 | image = processed.images[0] 358 | 359 | if not has_nsfw and ( 360 | "GFPGAN" in postprocessors or "CodeFormers" in postprocessors 361 | ): 362 | model = "CodeFormer" if "CodeFormers" in postprocessors else "GFPGAN" 363 | face_restorators = [x for x in shared.face_restorers if x.name() == model] 364 | if len(face_restorators) == 0: 365 | print(f"ERROR: No face restorer for {model}") 366 | 367 | else: 368 | with call_queue.queue_lock: 369 | image = face_restorators[0].restore(np.array(image)) 370 | image = Image.fromarray(image) 371 | 372 | if "RealESRGAN_x4plus" in postprocessors and not has_nsfw: 373 | from modules.postprocessing import run_extras 374 | 375 | with call_queue.queue_lock: 376 | images, _info, _wtf = run_extras( 377 | image=image, 378 | extras_mode=0, 379 | resize_mode=0, 380 | show_extras_results=True, 381 | upscaling_resize=2, 382 | upscaling_resize_h=None, 383 | upscaling_resize_w=None, 384 | upscaling_crop=False, 385 | upscale_first=False, 386 | extras_upscaler_1="R-ESRGAN 4x+", # 8 - RealESRGAN_x4plus 387 | extras_upscaler_2=None, 388 | extras_upscaler_2_visibility=0.0, 389 | gfpgan_visibility=0.0, 390 | codeformer_visibility=0.0, 391 | codeformer_weight=0.0, 392 | image_folder="", 393 | input_dir="", 394 | output_dir="", 395 | save_output=False, 396 | ) 397 | 398 | image = images[0] 399 | 400 | # Saving image locally 401 | infotext = ( 402 | processing.create_infotext( 403 | p, 404 | p.all_prompts, 405 | p.all_seeds, 406 | p.all_subseeds, 407 | "Stable Horde", 408 | 0, 409 | 0, 410 | ) 411 | if shared.opts.enable_pnginfo 412 | else None 413 | ) 414 | # workaround for model name and hash since webui 415 | # uses shard.sd_model instead of local_model 416 | infotext = sub( 417 | "Model:(.*?),", 418 | "Model: " + local_model.split(".")[0] + ",", 419 | infotext, 420 | ) 421 | infotext = sub( 422 | "Model hash:(.*?),", 423 | "Model hash: " + local_model_shorthash + ",", 424 | infotext, 425 | ) 426 | if self.config.save_images: 427 | save_image( 428 | image, 429 | self.config.save_images_folder, 430 | "", 431 | job.seed, 432 | job.prompt, 433 | "png", 434 | info=infotext, 435 | p=p, 436 | ) 437 | 438 | self.state.id = job.id 439 | self.state.prompt = job.prompt 440 | self.state.negative_prompt = job.negative_prompt 441 | self.state.scale = job.cfg_scale 442 | self.state.steps = job.steps 443 | self.state.sampler = sampler_name 444 | self.state.image = image 445 | 446 | res = await job.submit(image) 447 | if res: 448 | self.state.status = f"Submission accepted, reward {res} received." 449 | 450 | # check and replace nsfw content 451 | def check_safety(self, x_image): 452 | global safety_feature_extractor, safety_checker 453 | 454 | if safety_feature_extractor is None: 455 | safety_feature_extractor = AutoFeatureExtractor.from_pretrained( 456 | safety_model_id 457 | ) 458 | safety_checker = StableDiffusionSafetyChecker.from_pretrained( 459 | safety_model_id 460 | ) 461 | 462 | safety_checker_input = safety_feature_extractor(x_image, return_tensors="pt") 463 | image, has_nsfw_concept = safety_checker( 464 | images=x_image, clip_input=safety_checker_input.pixel_values 465 | ) 466 | 467 | if has_nsfw_concept and any(has_nsfw_concept): 468 | return self.sfw_request_censor, has_nsfw_concept 469 | return Image.fromarray(image), has_nsfw_concept 470 | 471 | async def get_session(self) -> aiohttp.ClientSession: 472 | if self.session is None: 473 | headers = { 474 | "apikey": self.config.apikey, 475 | "Content-Type": "application/json", 476 | } 477 | self.session = aiohttp.ClientSession(self.config.endpoint, headers=headers) 478 | # check if apikey has changed 479 | elif self.session.headers["apikey"] != self.config.apikey: 480 | await self.session.close() 481 | self.session = None 482 | self.session = await self.get_session() 483 | return self.session 484 | 485 | def handle_error(self, status: int, res: Dict[str, Any]): 486 | if status == 401: 487 | self.state.status = "ERROR: Invalid API Key" 488 | elif status == 403: 489 | self.state.status = f"ERROR: Access Denied. ({res.get('message', '')})" 490 | elif status == 404: 491 | self.state.status = "ERROR: Request Not Found" 492 | else: 493 | self.state.status = f"ERROR: Unknown Error {status}" 494 | print(f"ERROR: Unknown Error, {res}") 495 | -------------------------------------------------------------------------------- /stable_horde/job.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import base64 3 | from enum import Enum 4 | import io 5 | from random import randint 6 | from typing import List, Optional 7 | from PIL import Image 8 | 9 | import aiohttp 10 | from .config import StableHordeConfig 11 | 12 | 13 | class JobStatus(Enum): 14 | PENDING = "pending" 15 | RUNNING = "running" 16 | GENERATED = "generated" 17 | SUBMITTING = "submitting" 18 | UPLOADED = "uploaded" 19 | SUBMITTED = "submitted" 20 | DONE = "done" 21 | ERROR = "error" 22 | 23 | 24 | class HordeJob: 25 | retry_interval: int = 1 26 | censored = False 27 | 28 | def __init__( 29 | self, 30 | session: aiohttp.ClientSession, 31 | id: str, 32 | model: str, 33 | prompt: str, 34 | negative_prompt: str, 35 | sampler: str, 36 | cfg_scale: float, 37 | seed: int, 38 | denoising_strength: float, 39 | n_iter: int, 40 | height: int, 41 | width: int, 42 | subseed: int, 43 | steps: int, 44 | karras: bool, 45 | tiling: bool, 46 | postprocessors: List[str], 47 | nsfw_censor: bool = False, 48 | clip_skip: int = 0, 49 | source_image: Optional[Image.Image] = None, 50 | source_processing: Optional[str] = "img2img", 51 | source_mask: Optional[Image.Image] = None, 52 | r2_upload: Optional[str] = None, 53 | hires_fix: bool = False, 54 | ): 55 | self.status: JobStatus = JobStatus.PENDING 56 | self.session = session 57 | self.id = id 58 | self.model = model 59 | self.prompt = prompt 60 | self.negative_prompt = negative_prompt 61 | self.sampler = sampler 62 | self.cfg_scale = cfg_scale 63 | self.seed = seed 64 | self.denoising_strength = denoising_strength 65 | self.n_iter = n_iter 66 | self.height = height 67 | self.width = width 68 | self.subseed = subseed 69 | self.steps = steps 70 | self.karras = karras 71 | self.tiling = tiling 72 | self.postprocessors = postprocessors 73 | self.nsfw_censor = nsfw_censor 74 | self.clip_skip = clip_skip 75 | self.source_image = source_image 76 | self.source_processing = ( 77 | source_processing # "img2img", "inpainting", "outpainting" 78 | ) 79 | self.source_mask = source_mask 80 | self.r2_upload = r2_upload 81 | self.hires_fix = hires_fix 82 | 83 | async def submit(self, image: Image.Image): 84 | self.status = JobStatus.SUBMITTING 85 | 86 | bytesio = io.BytesIO() 87 | image.save(bytesio, format="WebP", quality=95) 88 | 89 | if self.r2_upload: 90 | async with aiohttp.ClientSession() as session: 91 | attempts = 10 92 | while attempts > 0: 93 | try: 94 | r = await session.put(self.r2_upload, data=bytesio.getvalue()) 95 | break 96 | except aiohttp.ClientConnectorError: 97 | attempts -= 1 98 | await asyncio.sleep(self.retry_interval) 99 | continue 100 | generation = "R2" 101 | 102 | self.status = JobStatus.UPLOADED 103 | 104 | else: 105 | generation = base64.b64encode(bytesio.getvalue()).decode("utf8") 106 | 107 | post_data = { 108 | "id": self.id, 109 | "generation": generation, 110 | "seed": self.seed, 111 | "state": "censored" if self.censored else "ok", 112 | } 113 | 114 | attempts = 10 115 | while attempts > 0: 116 | try: 117 | r = await self.session.post("/api/v2/generate/submit", json=post_data) 118 | 119 | try: 120 | res = await r.json() 121 | 122 | if r.status == 404: 123 | print(f"job {self.id} has been submitted already") 124 | return 125 | 126 | if r.status == 500: 127 | print( 128 | f"Failed to submit job with status code {r.status}, retry!" 129 | ) 130 | attempts -= 1 131 | await asyncio.sleep(self.retry_interval) 132 | continue 133 | 134 | if r.ok: 135 | self.status = JobStatus.SUBMITTED 136 | reward = res.get("reward", None) 137 | if reward: 138 | self.status = JobStatus.DONE 139 | return reward 140 | else: 141 | print( 142 | "Failed to submit job with status code" 143 | + f"{r.status}: {res.get('message')}" 144 | ) 145 | return None 146 | except Exception: 147 | print("Error when decoding response, the server might be down.") 148 | return None 149 | 150 | except aiohttp.ClientConnectorError: 151 | attempts -= 1 152 | await asyncio.sleep(self.retry_interval) 153 | continue 154 | 155 | self.status = JobStatus.ERROR 156 | 157 | async def error(self): 158 | self.status = JobStatus.ERROR 159 | 160 | post_data = {"id": self.id, "state": "faulted"} 161 | attempts = 10 162 | while attempts > 0: 163 | try: 164 | r = await self.session.post("/api/v2/generate/submit", json=post_data) 165 | if r.ok: 166 | print("Successfully reported error to Stable Horde") 167 | return 168 | else: 169 | res = await r.json() 170 | print( 171 | "Failed to report error with status code" 172 | + f"{r.status}: {res.get('message')}" 173 | ) 174 | return 175 | except aiohttp.ClientConnectorError: 176 | attempts -= 1 177 | await asyncio.sleep(self.retry_interval) 178 | continue 179 | 180 | @classmethod 181 | async def get( 182 | cls, 183 | session: aiohttp.ClientSession, 184 | config: StableHordeConfig, 185 | models: List[str], 186 | ): 187 | # Stable Horde uses a bridge version to differentiate between different 188 | # bridge agents which is used to determine the bridge agent's capabilities. 189 | # We should increment the version number when we add new features to the bridge 190 | # agent. 191 | # 192 | # When we increment the version number, we should also update the AI-Horde side: 193 | # https://github.com/db0/AI-Horde/blob/main/horde/bridge_reference.py 194 | # 195 | # 1 - img2img, inpainting, karras, r2, CodeFormers 196 | # 2 - tiling 197 | # 3 - r2 source 198 | # 4 - hires_fix, clip_skip 199 | version = 4 200 | name = "SD-WebUI Stable Horde Worker Bridge" 201 | repo = "https://github.com/sdwebui-w-horde/sd-webui-stable-horde-worker" 202 | # https://stablehorde.net/api/ 203 | post_data = { 204 | "name": config.name, 205 | "priority_usernames": [], 206 | "nsfw": config.nsfw, 207 | "blacklist": [], 208 | "models": models, 209 | # TODO: add support for bridge version 14 (r2_source) 210 | "bridge_version": 13, 211 | "bridge_agent": f"{name}:{version}:{repo}", 212 | "threads": 1, 213 | "max_pixels": config.max_pixels, 214 | "allow_img2img": config.allow_img2img, 215 | "allow_painting": config.allow_painting, 216 | "allow_unsafe_ipaddr": config.allow_unsafe_ipaddr, 217 | } 218 | 219 | r = await session.post("/api/v2/generate/pop", json=post_data) 220 | 221 | req = await r.json() 222 | 223 | if r.status != 200: 224 | raise Exception(f"Failed to get job: {req.get('message')}") 225 | 226 | if not req.get("id"): 227 | return 228 | 229 | payload = req.get("payload") 230 | prompt = payload.get("prompt") 231 | if "###" in prompt: 232 | prompt, negative = map(lambda x: x.strip(), prompt.rsplit("###", 1)) 233 | else: 234 | negative = "" 235 | 236 | async def to_image(base64str: Optional[str]) -> Optional[Image.Image]: 237 | if not base64str: 238 | return None 239 | # support for r2 source, which is a url rather than a base64 string 240 | if base64str.startswith("http"): 241 | async with aiohttp.ClientSession() as session: 242 | attempts = 10 243 | while attempts > 0: 244 | try: 245 | r = await session.get(base64str) 246 | return Image.open(await r.read()) 247 | except aiohttp.ClientConnectorError: 248 | attempts -= 1 249 | await asyncio.sleep(1) 250 | continue 251 | raise Exception("Failed to download source image") 252 | 253 | return Image.open(base64.b64decode(base64str)) 254 | 255 | return cls( 256 | session=session, 257 | id=req["id"], 258 | prompt=prompt, 259 | negative_prompt=negative, 260 | sampler=payload.get("sampler_name"), 261 | cfg_scale=payload.get("cfg_scale", 5), 262 | seed=int(payload.get("seed", randint(0, 2**32))), 263 | denoising_strength=payload.get("denoising_strength", 0.75), 264 | n_iter=payload.get("n_iter", 1), 265 | height=payload["height"], 266 | width=payload["width"], 267 | subseed=payload.get("seed_variation", 1), 268 | steps=payload.get("ddim_steps", 30), 269 | karras=payload.get("karras", False), 270 | tiling=payload.get("tiling", False), 271 | clip_skip=payload.get("clip_skip", 1), 272 | postprocessors=payload.get("post_processing", []), 273 | nsfw_censor=payload.get("use_nsfw_censor", False), 274 | model=req["model"], 275 | source_image=await to_image(req.get("source_image")), 276 | source_processing=req.get("source_processing"), 277 | source_mask=await to_image(req.get("source_mask")), 278 | r2_upload=req.get("r2_upload"), 279 | hires_fix=payload.get("hires_fix", False), 280 | ) 281 | --------------------------------------------------------------------------------