Spaces:
Build error
Build error
Add files
Browse filesFiles changed (27)
- .gitignoreAdded+162
- .pre-commit-config.yamlAdded+36
- .style.yapfAdded+5
- LICENSEAdded+21
- LICENSE.ControlNetAdded+201
- README.md+4-3
- app.pyAdded+132
- app_canny.pyAdded+106
- app_depth.pyAdded+105
- app_ip2p.pyAdded+92
- app_lineart.pyAdded+114
- app_mlsd.pyAdded+113
- app_normal.pyAdded+104
- app_openpose.pyAdded+104
- app_scribble.pyAdded+105
- app_scribble_interactive.pyAdded+112
- app_segmentation.pyAdded+104
- app_shuffle.pyAdded+98
- app_softedge.pyAdded+110
- cv_utils.pyAdded+17
- depth_estimator.pyAdded+25
- image_segmentor.pyAdded+39
- model.pyAdded+591
- preprocessor.pyAdded+77
- requirements.txtAdded+12
- style.cssAdded+3
- utils.pyAdded+7
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162gradio_cached_examples/
# Byte-compiled / optimized / DLL files__pycache__/*.py[cod]*$py.class
# C extensions*.so
# Distribution / packaging.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/share/python-wheels/*.egg-info/.installed.cfg*.eggMANIFEST
# PyInstaller# Usually these files are written by a python script from a template# before PyInstaller builds the exe, so as to inject date/other infos into it.*.manifest*.spec
# Installer logspip-log.txtpip-delete-this-directory.txt
# Unit test / coverage reportshtmlcov/.tox/.nox/.coverage.coverage.*.cachenosetests.xmlcoverage.xml*.cover*.py,cover.hypothesis/.pytest_cache/cover/
# Translations*.mo*.pot
# Django stuff:*.loglocal_settings.pydb.sqlite3db.sqlite3-journal
# Flask stuff:instance/.webassets-cache
# Scrapy stuff:.scrapy
# Sphinx documentationdocs/_build/
# PyBuilder.pybuilder/target/
# Jupyter Notebook.ipynb_checkpoints
# IPythonprofile_default/ipython_config.py
# pyenv# For a library or package, you might want to ignore these files since the code is# intended to run in multiple environments; otherwise, check them in:# .python-version
# pipenv# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.# However, in case of collaboration, if having platform-specific dependencies or dependencies# having no cross-platform support, pipenv may install dependencies that don't work, or not# install all needed dependencies.#Pipfile.lock
# poetry# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.# This is especially recommended for binary packages to ensure reproducibility, and is more# commonly ignored for libraries.# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control#poetry.lock
# pdm# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.#pdm.lock# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it# in version control.# https://pdm.fming.dev/#use-with-ide.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm__pypackages__/
# Celery stuffcelerybeat-schedulecelerybeat.pid
# SageMath parsed files*.sage.py
# Environments.env.venvenv/venv/ENV/env.bak/venv.bak/
# Spyder project settings.spyderproject.spyproject
# Rope project settings.ropeproject
# mkdocs documentation/site
# mypy.mypy_cache/.dmypy.jsondmypy.json
# Pyre type checker.pyre/
# pytype static type analyzer.pytype/
# Cython debug symbolscython_debug/
# PyCharm# JetBrains specific template is maintained in a separate JetBrains.gitignore that can# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore# and can be added to the global gitignore or merged into this file. For a more nuclear# option (not recommended) you can uncomment the following to ignore the entire idea folder.#.idea/123456789101112131415161718192021222324252627282930313233343536repos:- repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.2.0 hooks: - id: check-executables-have-shebangs - id: check-json - id: check-merge-conflict - id: check-shebang-scripts-are-executable - id: check-toml - id: check-yaml - id: double-quote-string-fixer - id: end-of-file-fixer - id: mixed-line-ending args: ['--fix=lf'] - id: requirements-txt-fixer - id: trailing-whitespace- repo: https://github.com/myint/docformatter rev: v1.4 hooks: - id: docformatter args: ['--in-place']- repo: https://github.com/pycqa/isort rev: 5.12.0 hooks: - id: isort- repo: https://github.com/pre-commit/mirrors-mypy rev: v0.991 hooks: - id: mypy args: ['--ignore-missing-imports'] additional_dependencies: ['types-python-slugify']- repo: https://github.com/google/yapf rev: v0.32.0 hooks: - id: yapf args: ['--parallel', '--in-place']12345[style]based_on_style = pep8blank_line_before_nested_class_or_def = falsespaces_before_comment = 2split_before_logical_operator = true123456789101112131415161718192021MIT License
Copyright (c) 2023 hysts
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.12345678910111213---title: ControlNet V1 1emoji: 📉colorFrom: yellowcolorTo: greensdk: gradiosdk_version: 3.24.1app_file: app.pypinned: falselicense: other---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference1234567891011121314---title: ControlNet V1.1emoji: 📉colorFrom: yellowcolorTo: greensdk: gradiosdk_version: 3.26.0python_version: 3.10.11app_file: app.pypinned: falselicense: mit---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132#!/usr/bin/env python
from __future__ import annotations
import os
import gradio as grimport torch
from app_canny import create_demo as create_demo_cannyfrom app_depth import create_demo as create_demo_depthfrom app_ip2p import create_demo as create_demo_ip2pfrom app_lineart import create_demo as create_demo_lineartfrom app_mlsd import create_demo as create_demo_mlsdfrom app_normal import create_demo as create_demo_normalfrom app_openpose import create_demo as create_demo_openposefrom app_scribble import create_demo as create_demo_scribblefrom app_scribble_interactive import \ create_demo as create_demo_scribble_interactivefrom app_segmentation import create_demo as create_demo_segmentationfrom app_shuffle import create_demo as create_demo_shufflefrom app_softedge import create_demo as create_demo_softedgefrom model import Model
DESCRIPTION = '# ControlNet v1.1'
SPACE_ID = os.getenv('SPACE_ID')ALLOW_CHANGING_BASE_MODEL = SPACE_ID != 'hysts/ControlNet-v1-1'
if SPACE_ID is not None: DESCRIPTION += f'\n<p>For faster inference without waiting in queue, you may duplicate the space and upgrade to GPU in settings. <a href="https://huggingface.co/spaces/{SPACE_ID}?duplicate=true"><img style="display: inline; margin-top: 0em; margin-bottom: 0em" src="https://bit.ly/3gLdBN6" alt="Duplicate Space" /></a></p>'
if torch.cuda.is_available(): DESCRIPTION += '\n<p>Running on GPU 🔥</p>'else: DESCRIPTION += '\n<p>Running on CPU 🥶 This demo does not work on CPU.'
MAX_NUM_IMAGES = int(os.getenv('MAX_NUM_IMAGES', '3'))DEFAULT_NUM_IMAGES = min(MAX_NUM_IMAGES, int(os.getenv('DEFAULT_NUM_IMAGES', '1')))
DEFAULT_MODEL_ID = os.getenv('DEFAULT_MODEL_ID', 'runwayml/stable-diffusion-v1-5')model = Model(base_model_id=DEFAULT_MODEL_ID, task_name='Canny')
with gr.Blocks(css='style.css') as demo: gr.Markdown(DESCRIPTION) with gr.Tabs(): with gr.TabItem('Canny'): create_demo_canny(model.process_canny, max_images=MAX_NUM_IMAGES, default_num_images=DEFAULT_NUM_IMAGES) with gr.TabItem('MLSD'): create_demo_mlsd(model.process_mlsd, max_images=MAX_NUM_IMAGES, default_num_images=DEFAULT_NUM_IMAGES) with gr.TabItem('Scribble'): create_demo_scribble(model.process_scribble, max_images=MAX_NUM_IMAGES, default_num_images=DEFAULT_NUM_IMAGES) with gr.TabItem('Scribble Interactive'): create_demo_scribble_interactive( model.process_scribble_interactive, max_images=MAX_NUM_IMAGES, default_num_images=DEFAULT_NUM_IMAGES) with gr.TabItem('SoftEdge'): create_demo_softedge(model.process_softedge, max_images=MAX_NUM_IMAGES, default_num_images=DEFAULT_NUM_IMAGES) with gr.TabItem('OpenPose'): create_demo_openpose(model.process_openpose, max_images=MAX_NUM_IMAGES, default_num_images=DEFAULT_NUM_IMAGES) with gr.TabItem('Segmentation'): create_demo_segmentation(model.process_segmentation, max_images=MAX_NUM_IMAGES, default_num_images=DEFAULT_NUM_IMAGES) with gr.TabItem('Depth'): create_demo_depth(model.process_depth, max_images=MAX_NUM_IMAGES, default_num_images=DEFAULT_NUM_IMAGES) with gr.TabItem('Normal map'): create_demo_normal(model.process_normal, max_images=MAX_NUM_IMAGES, default_num_images=DEFAULT_NUM_IMAGES) with gr.TabItem('Lineart'): create_demo_lineart(model.process_lineart, max_images=MAX_NUM_IMAGES, default_num_images=DEFAULT_NUM_IMAGES) with gr.TabItem('Content Shuffle'): create_demo_shuffle(model.process_shuffle, max_images=MAX_NUM_IMAGES, default_num_images=DEFAULT_NUM_IMAGES) with gr.TabItem('Instruct Pix2Pix'): create_demo_ip2p(model.process_ip2p, max_images=MAX_NUM_IMAGES, default_num_images=DEFAULT_NUM_IMAGES)
with gr.Accordion(label='Base model', open=False): with gr.Row(): with gr.Column(): current_base_model = gr.Text(label='Current base model') with gr.Column(scale=0.3): check_base_model_button = gr.Button('Check current base model') with gr.Row(): with gr.Column(): new_base_model_id = gr.Text( label='New base model', max_lines=1, placeholder='runwayml/stable-diffusion-v1-5', info= 'The base model must be compatible with Stable Diffusion v1.5.', interactive=ALLOW_CHANGING_BASE_MODEL) with gr.Column(scale=0.3): change_base_model_button = gr.Button( 'Change base model', interactive=ALLOW_CHANGING_BASE_MODEL) if not ALLOW_CHANGING_BASE_MODEL: gr.Markdown( '''The base model is not allowed to be changed in this Space so as not to slow down the demo, but it can be changed if you duplicate the Space. <a href="https://huggingface.co/spaces/{SPACE_ID}?duplicate=true"><img style="display: inline; margin-top: 0em; margin-bottom: 0em" src="https://bit.ly/3gLdBN6" alt="Duplicate Space" /></a>''' )
check_base_model_button.click(fn=lambda: model.base_model_id, outputs=current_base_model, queue=False) new_base_model_id.submit(fn=model.set_base_model, inputs=new_base_model_id, outputs=current_base_model) change_base_model_button.click(fn=model.set_base_model, inputs=new_base_model_id, outputs=current_base_model)
demo.queue(api_open=False, max_size=10).launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106#!/usr/bin/env python
import gradio as gr
from utils import randomize_seed_fn
def create_demo(process, max_images=12, default_num_images=3): with gr.Blocks() as demo: with gr.Row(): with gr.Column(): image = gr.Image() prompt = gr.Textbox(label='Prompt') run_button = gr.Button('Run') with gr.Accordion('Advanced options', open=False): num_samples = gr.Slider(label='Number of images', minimum=1, maximum=max_images, value=default_num_images, step=1) image_resolution = gr.Slider(label='Image resolution', minimum=256, maximum=512, value=512, step=256) canny_low_threshold = gr.Slider( label='Canny low threshold', minimum=1, maximum=255, value=100, step=1) canny_high_threshold = gr.Slider( label='Canny high threshold', minimum=1, maximum=255, value=200, step=1) num_steps = gr.Slider(label='Number of steps', minimum=1, maximum=100, value=20, step=1) guidance_scale = gr.Slider(label='Guidance scale', minimum=0.1, maximum=30.0, value=9.0, step=0.1) seed = gr.Slider(label='Seed', minimum=0, maximum=1000000, step=1, value=0, randomize=True) randomize_seed = gr.Checkbox(label='Randomize seed', value=True) a_prompt = gr.Textbox( label='Additional prompt', value='best quality, extremely detailed') n_prompt = gr.Textbox( label='Negative prompt', value= 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality' ) with gr.Column(): result = gr.Gallery(label='Output', show_label=False).style( columns=2, object_fit='scale-down') inputs = [ image, prompt, a_prompt, n_prompt, num_samples, image_resolution, num_steps, guidance_scale, seed, canny_low_threshold, canny_high_threshold, ] prompt.submit( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, ).then( fn=process, inputs=inputs, outputs=result, ) run_button.click( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, ).then( fn=process, inputs=inputs, outputs=result, api_name='canny', ) return demo
if __name__ == '__main__': from model import Model model = Model(task_name='Canny') demo = create_demo(model.process_canny) demo.queue().launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105#!/usr/bin/env python
import gradio as gr
from utils import randomize_seed_fn
def create_demo(process, max_images=12, default_num_images=3): with gr.Blocks() as demo: with gr.Row(): with gr.Column(): image = gr.Image() prompt = gr.Textbox(label='Prompt') run_button = gr.Button('Run') with gr.Accordion('Advanced options', open=False): preprocessor_name = gr.Radio( label='Preprocessor', choices=['Midas', 'DPT', 'None'], type='value', value='DPT') num_samples = gr.Slider(label='Number of images', minimum=1, maximum=max_images, value=default_num_images, step=1) image_resolution = gr.Slider(label='Image resolution', minimum=256, maximum=512, value=512, step=256) preprocess_resolution = gr.Slider( label='Preprocess resolution', minimum=128, maximum=512, value=384, step=1) num_steps = gr.Slider(label='Number of steps', minimum=1, maximum=100, value=20, step=1) guidance_scale = gr.Slider(label='Guidance scale', minimum=0.1, maximum=30.0, value=9.0, step=0.1) seed = gr.Slider(label='Seed', minimum=0, maximum=1000000, step=1, value=0, randomize=True) randomize_seed = gr.Checkbox(label='Randomize seed', value=True) a_prompt = gr.Textbox( label='Additional prompt', value='best quality, extremely detailed') n_prompt = gr.Textbox( label='Negative prompt', value= 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality' ) with gr.Column(): result = gr.Gallery(label='Output', show_label=False).style( columns=2, object_fit='scale-down') inputs = [ image, prompt, a_prompt, n_prompt, num_samples, image_resolution, preprocess_resolution, num_steps, guidance_scale, seed, preprocessor_name, ] prompt.submit( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, ).then( fn=process, inputs=inputs, outputs=result, ) run_button.click( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, ).then( fn=process, inputs=inputs, outputs=result, api_name='depth', ) return demo
if __name__ == '__main__': from model import Model model = Model(task_name='depth') demo = create_demo(model.process_depth) demo.queue().launch()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192#!/usr/bin/env python
import gradio as gr
from utils import randomize_seed_fn
def create_demo(process, max_images=12, default_num_images=3): with gr.Blocks() as demo: with gr.Row(): with gr.Column(): image = gr.Image() prompt = gr.Textbox(label='Prompt') run_button = gr.Button('Run') with gr.Accordion('Advanced options', open=False): num_samples = gr.Slider(label='Number of images', minimum=1, maximum=max_images, value=default_num_images, step=1) image_resolution = gr.Slider(label='Image resolution', minimum=256, maximum=512, value=512, step=256) num_steps = gr.Slider(label='Number of steps', minimum=1, maximum=100, value=20, step=1) guidance_scale = gr.Slider(label='Guidance scale', minimum=0.1, maximum=30.0, value=9.0, step=0.1) seed = gr.Slider(label='Seed', minimum=0, maximum=1000000, step=1, value=0, randomize=True) randomize_seed = gr.Checkbox(label='Randomize seed', value=True) a_prompt = gr.Textbox( label='Additional prompt', value='best quality, extremely detailed') n_prompt = gr.Textbox( label='Negative prompt', value= 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality' ) with gr.Column(): result = gr.Gallery(label='Output', show_label=False).style( columns=2, object_fit='scale-down') inputs = [ image, prompt, a_prompt, n_prompt, num_samples, image_resolution, num_steps, guidance_scale, seed, ] prompt.submit( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, ).then( fn=process, inputs=inputs, outputs=result, ) run_button.click( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, ).then( fn=process, inputs=inputs, outputs=result, api_name='scribble', ) return demo
if __name__ == '__main__': from model import Model model = Model(task_name='ip2p') demo = create_demo(model.process_ip2p) demo.queue().launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114#!/usr/bin/env python
import gradio as gr
from utils import randomize_seed_fn
def create_demo(process, max_images=12, default_num_images=3): with gr.Blocks() as demo: with gr.Row(): with gr.Column(): image = gr.Image() prompt = gr.Textbox(label='Prompt') run_button = gr.Button('Run') with gr.Accordion('Advanced options', open=False): preprocessor_name = gr.Radio( label='Preprocessor', choices=[ 'Lineart', 'Lineart coarse', 'None', 'Lineart (anime)', 'None (anime)', ], type='value', value='Lineart', info= 'Note that "Lineart (anime)" and "None (anime)" are for anime base models like Anything-v3.' ) num_samples = gr.Slider(label='Number of images', minimum=1, maximum=max_images, value=default_num_images, step=1) image_resolution = gr.Slider(label='Image resolution', minimum=256, maximum=512, value=512, step=256) preprocess_resolution = gr.Slider( label='Preprocess resolution', minimum=128, maximum=512, value=512, step=1) num_steps = gr.Slider(label='Number of steps', minimum=1, maximum=100, value=20, step=1) guidance_scale = gr.Slider(label='Guidance scale', minimum=0.1, maximum=30.0, value=9.0, step=0.1) seed = gr.Slider(label='Seed', minimum=0, maximum=1000000, step=1, value=0, randomize=True) randomize_seed = gr.Checkbox(label='Randomize seed', value=True) a_prompt = gr.Textbox( label='Additional prompt', value='best quality, extremely detailed') n_prompt = gr.Textbox( label='Negative prompt', value= 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality' ) with gr.Column(): result = gr.Gallery(label='Output', show_label=False).style( columns=2, object_fit='scale-down') inputs = [ image, prompt, a_prompt, n_prompt, num_samples, image_resolution, preprocess_resolution, num_steps, guidance_scale, seed, preprocessor_name, ] prompt.submit( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, ).then( fn=process, inputs=inputs, outputs=result, ) run_button.click( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, ).then( fn=process, inputs=inputs, outputs=result, api_name='scribble', ) return demo
if __name__ == '__main__': from model import Model model = Model(task_name='lineart') demo = create_demo(model.process_lineart) demo.queue().launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113#!/usr/bin/env python
import gradio as gr
from utils import randomize_seed_fn
def create_demo(process, max_images=12, default_num_images=3): with gr.Blocks() as demo: with gr.Row(): with gr.Column(): image = gr.Image() prompt = gr.Textbox(label='Prompt') run_button = gr.Button('Run') with gr.Accordion('Advanced options', open=False): num_samples = gr.Slider(label='Number of images', minimum=1, maximum=max_images, value=default_num_images, step=1) image_resolution = gr.Slider(label='Image resolution', minimum=256, maximum=512, value=512, step=256) preprocess_resolution = gr.Slider( label='Preprocess resolution', minimum=128, maximum=512, value=512, step=1) mlsd_value_threshold = gr.Slider( label='Hough value threshold (MLSD)', minimum=0.01, maximum=2.0, value=0.1, step=0.01) mlsd_distance_threshold = gr.Slider( label='Hough distance threshold (MLSD)', minimum=0.01, maximum=20.0, value=0.1, step=0.01) num_steps = gr.Slider(label='Number of steps', minimum=1, maximum=100, value=20, step=1) guidance_scale = gr.Slider(label='Guidance scale', minimum=0.1, maximum=30.0, value=9.0, step=0.1) seed = gr.Slider(label='Seed', minimum=0, maximum=1000000, step=1, value=0, randomize=True) randomize_seed = gr.Checkbox(label='Randomize seed', value=True) a_prompt = gr.Textbox( label='Additional prompt', value='best quality, extremely detailed') n_prompt = gr.Textbox( label='Negative prompt', value= 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality' ) with gr.Column(): result = gr.Gallery(label='Output', show_label=False).style( columns=2, object_fit='scale-down') inputs = [ image, prompt, a_prompt, n_prompt, num_samples, image_resolution, preprocess_resolution, num_steps, guidance_scale, seed, mlsd_value_threshold, mlsd_distance_threshold, ] prompt.submit( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, ).then( fn=process, inputs=inputs, outputs=result, ) run_button.click( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, ).then( fn=process, inputs=inputs, outputs=result, api_name='mlsd', ) return demo
if __name__ == '__main__': from model import Model model = Model(task_name='MLSD') demo = create_demo(model.process_mlsd) demo.queue().launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104#!/usr/bin/env python
import gradio as gr
from utils import randomize_seed_fn
def create_demo(process, max_images=12, default_num_images=3): with gr.Blocks() as demo: with gr.Row(): with gr.Column(): image = gr.Image() prompt = gr.Textbox(label='Prompt') run_button = gr.Button('Run') with gr.Accordion('Advanced options', open=False): preprocessor_name = gr.Radio(label='Preprocessor', choices=['NormalBae', 'None'], type='value', value='NormalBae') num_samples = gr.Slider(label='Images', minimum=1, maximum=max_images, value=default_num_images, step=1) image_resolution = gr.Slider(label='Image resolution', minimum=256, maximum=512, value=512, step=256) preprocess_resolution = gr.Slider( label='Preprocess resolution', minimum=128, maximum=512, value=384, step=1) num_steps = gr.Slider(label='Number of steps', minimum=1, maximum=100, value=20, step=1) guidance_scale = gr.Slider(label='Guidance scale', minimum=0.1, maximum=30.0, value=9.0, step=0.1) seed = gr.Slider(label='Seed', minimum=0, maximum=1000000, step=1, value=0, randomize=True) randomize_seed = gr.Checkbox(label='Randomize seed', value=True) a_prompt = gr.Textbox( label='Additional prompt', value='best quality, extremely detailed') n_prompt = gr.Textbox( label='Negative prompt', value= 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality' ) with gr.Column(): result = gr.Gallery(label='Output', show_label=False).style( columns=2, object_fit='scale-down') inputs = [ image, prompt, a_prompt, n_prompt, num_samples, image_resolution, preprocess_resolution, num_steps, guidance_scale, seed, preprocessor_name, ] prompt.submit( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, ).then( fn=process, inputs=inputs, outputs=result, ) run_button.click( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, ).then( fn=process, inputs=inputs, outputs=result, api_name='normal', ) return demo
if __name__ == '__main__': from model import Model model = Model(task_name='NormalBae') demo = create_demo(model.process_normal) demo.queue().launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104#!/usr/bin/env python
import gradio as gr
from utils import randomize_seed_fn
def create_demo(process, max_images=12, default_num_images=3): with gr.Blocks() as demo: with gr.Row(): with gr.Column(): image = gr.Image() prompt = gr.Textbox(label='Prompt') run_button = gr.Button(label='Run') with gr.Accordion('Advanced options', open=False): preprocessor_name = gr.Radio(label='Preprocessor', choices=['Openpose', 'None'], type='value', value='Openpose') num_samples = gr.Slider(label='Number of images', minimum=1, maximum=max_images, value=default_num_images, step=1) image_resolution = gr.Slider(label='Image resolution', minimum=256, maximum=512, value=512, step=256) preprocess_resolution = gr.Slider( label='Preprocess resolution', minimum=128, maximum=512, value=512, step=1) num_steps = gr.Slider(label='Number of steps', minimum=1, maximum=100, value=20, step=1) guidance_scale = gr.Slider(label='Guidance scale', minimum=0.1, maximum=30.0, value=9.0, step=0.1) seed = gr.Slider(label='Seed', minimum=0, maximum=1000000, step=1, value=0, randomize=True) randomize_seed = gr.Checkbox(label='Randomize seed', value=True) a_prompt = gr.Textbox( label='Additional prompt', value='best quality, extremely detailed') n_prompt = gr.Textbox( label='Negative prompt', value= 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality' ) with gr.Column(): result = gr.Gallery(label='Output', show_label=False).style( columns=2, object_fit='scale-down') inputs = [ image, prompt, a_prompt, n_prompt, num_samples, image_resolution, preprocess_resolution, num_steps, guidance_scale, seed, preprocessor_name, ] prompt.submit( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, ).then( fn=process, inputs=inputs, outputs=result, ) run_button.click( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, ).then( fn=process, inputs=inputs, outputs=result, api_name='openpose', ) return demo
if __name__ == '__main__': from model import Model model = Model(task_name='Openpose') demo = create_demo(model.process_openpose) demo.queue().launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105#!/usr/bin/env python
import gradio as gr
from utils import randomize_seed_fn
def create_demo(process, max_images=12, default_num_images=3): with gr.Blocks() as demo: with gr.Row(): with gr.Column(): image = gr.Image() prompt = gr.Textbox(label='Prompt') run_button = gr.Button('Run') with gr.Accordion('Advanced options', open=False): preprocessor_name = gr.Radio( label='Preprocessor', choices=['HED', 'PidiNet', 'None'], type='value', value='HED') num_samples = gr.Slider(label='Number of images', minimum=1, maximum=max_images, value=default_num_images, step=1) image_resolution = gr.Slider(label='Image resolution', minimum=256, maximum=512, value=512, step=256) preprocess_resolution = gr.Slider( label='Preprocess resolution', minimum=128, maximum=512, value=512, step=1) num_steps = gr.Slider(label='Number of steps', minimum=1, maximum=100, value=20, step=1) guidance_scale = gr.Slider(label='Guidance scale', minimum=0.1, maximum=30.0, value=9.0, step=0.1) seed = gr.Slider(label='Seed', minimum=0, maximum=1000000, step=1, value=0, randomize=True) randomize_seed = gr.Checkbox(label='Randomize seed', value=True) a_prompt = gr.Textbox( label='Additional prompt', value='best quality, extremely detailed') n_prompt = gr.Textbox( label='Negative prompt', value= 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality' ) with gr.Column(): result = gr.Gallery(label='Output', show_label=False).style( columns=2, object_fit='scale-down') inputs = [ image, prompt, a_prompt, n_prompt, num_samples, image_resolution, preprocess_resolution, num_steps, guidance_scale, seed, preprocessor_name, ] prompt.submit( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, ).then( fn=process, inputs=inputs, outputs=result, ) run_button.click( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, ).then( fn=process, inputs=inputs, outputs=result, api_name='scribble', ) return demo
if __name__ == '__main__': from model import Model model = Model(task_name='scribble') demo = create_demo(model.process_scribble) demo.queue().launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112#!/usr/bin/env python
import gradio as grimport numpy as np
from utils import randomize_seed_fn
def create_canvas(w, h): return np.zeros(shape=(h, w, 3), dtype=np.uint8) + 255
def create_demo(process, max_images=12, default_num_images=3): with gr.Blocks() as demo: with gr.Row(): with gr.Column(): canvas_width = gr.Slider(label='Canvas width', minimum=256, maximum=512, value=512, step=1) canvas_height = gr.Slider(label='Canvas height', minimum=256, maximum=512, value=512, step=1) create_button = gr.Button('Open drawing canvas!') image = gr.Image(tool='sketch', brush_radius=10) prompt = gr.Textbox(label='Prompt') run_button = gr.Button('Run') with gr.Accordion('Advanced options', open=False): num_samples = gr.Slider(label='Number of images', minimum=1, maximum=max_images, value=default_num_images, step=1) image_resolution = gr.Slider(label='Image resolution', minimum=256, maximum=512, value=512, step=256) num_steps = gr.Slider(label='Number of steps', minimum=1, maximum=100, value=20, step=1) guidance_scale = gr.Slider(label='Guidance scale', minimum=0.1, maximum=30.0, value=9.0, step=0.1) seed = gr.Slider(label='Seed', minimum=0, maximum=1000000, step=1, value=0, randomize=True) randomize_seed = gr.Checkbox(label='Randomize seed', value=True) a_prompt = gr.Textbox( label='Additional prompt', value='best quality, extremely detailed') n_prompt = gr.Textbox( label='Negative prompt', value= 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality' ) with gr.Column(): result = gr.Gallery(label='Output', show_label=False).style( columns=2, object_fit='scale-down')
create_button.click(fn=create_canvas, inputs=[canvas_width, canvas_height], outputs=image, queue=False) inputs = [ image, prompt, a_prompt, n_prompt, num_samples, image_resolution, num_steps, guidance_scale, seed, ] prompt.submit( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, ).then( fn=process, inputs=inputs, outputs=result, ) run_button.click( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, ).then( fn=process, inputs=inputs, outputs=result, ) return demo
if __name__ == '__main__': from model import Model model = Model(task_name='scribble') demo = create_demo(model.process_scribble_interactive) demo.queue().launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104#!/usr/bin/env python
import gradio as gr
from utils import randomize_seed_fn
def create_demo(process, max_images=12, default_num_images=3): with gr.Blocks() as demo: with gr.Row(): with gr.Column(): image = gr.Image() prompt = gr.Textbox(label='Prompt') run_button = gr.Button('Run') with gr.Accordion('Advanced options', open=False): preprocessor_name = gr.Radio(label='Preprocessor', choices=['UPerNet', 'None'], type='value', value='UPerNet') num_samples = gr.Slider(label='Number of images', minimum=1, maximum=max_images, value=default_num_images, step=1) image_resolution = gr.Slider(label='Image resolution', minimum=256, maximum=512, value=512, step=256) preprocess_resolution = gr.Slider( label='Preprocess resolution', minimum=128, maximum=512, value=512, step=1) num_steps = gr.Slider(label='Number of steps', minimum=1, maximum=100, value=20, step=1) guidance_scale = gr.Slider(label='Guidance scale', minimum=0.1, maximum=30.0, value=9.0, step=0.1) seed = gr.Slider(label='Seed', minimum=0, maximum=1000000, step=1, value=0, randomize=True) randomize_seed = gr.Checkbox(label='Randomize seed', value=True) a_prompt = gr.Textbox( label='Additional prompt', value='best quality, extremely detailed') n_prompt = gr.Textbox( label='Negative prompt', value= 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality' ) with gr.Column(): result = gr.Gallery(label='Output', show_label=False).style( columns=2, object_fit='scale-down') inputs = [ image, prompt, a_prompt, n_prompt, num_samples, image_resolution, preprocess_resolution, num_steps, guidance_scale, seed, preprocessor_name, ] prompt.submit( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, ).then( fn=process, inputs=inputs, outputs=result, ) run_button.click( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, ).then( fn=process, inputs=inputs, outputs=result, api_name='segmentation', ) return demo
if __name__ == '__main__': from model import Model model = Model(task_name='segmentation') demo = create_demo(model.process_segmentation) demo.queue().launch()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798#!/usr/bin/env python
import gradio as gr
from utils import randomize_seed_fn
def create_demo(process, max_images=12, default_num_images=3): with gr.Blocks() as demo: with gr.Row(): with gr.Column(): image = gr.Image() prompt = gr.Textbox(label='Prompt') run_button = gr.Button('Run') with gr.Accordion('Advanced options', open=False): preprocessor_name = gr.Radio( label='Preprocessor', choices=['ContentShuffle', 'None'], type='value', value='ContentShuffle') num_samples = gr.Slider(label='Number of images', minimum=1, maximum=max_images, value=default_num_images, step=1) image_resolution = gr.Slider(label='Image resolution', minimum=256, maximum=512, value=512, step=256) num_steps = gr.Slider(label='Number of steps', minimum=1, maximum=100, value=20, step=1) guidance_scale = gr.Slider(label='Guidance scale', minimum=0.1, maximum=30.0, value=9.0, step=0.1) seed = gr.Slider(label='Seed', minimum=0, maximum=1000000, step=1, value=0, randomize=True) randomize_seed = gr.Checkbox(label='Randomize seed', value=True) a_prompt = gr.Textbox( label='Additional prompt', value='best quality, extremely detailed') n_prompt = gr.Textbox( label='Negative prompt', value= 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality' ) with gr.Column(): result = gr.Gallery(label='Output', show_label=False).style( columns=2, object_fit='scale-down') inputs = [ image, prompt, a_prompt, n_prompt, num_samples, image_resolution, num_steps, guidance_scale, seed, preprocessor_name, ] prompt.submit( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, ).then( fn=process, inputs=inputs, outputs=result, ) run_button.click( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, ).then( fn=process, inputs=inputs, outputs=result, api_name='content-shuffle', ) return demo
if __name__ == '__main__': from model import Model model = Model(task_name='shuffle') demo = create_demo(model.process_shuffle) demo.queue().launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110#!/usr/bin/env python
import gradio as gr
from utils import randomize_seed_fn
def create_demo(process, max_images=12, default_num_images=3): with gr.Blocks() as demo: with gr.Row(): with gr.Column(): image = gr.Image() prompt = gr.Textbox(label='Prompt') run_button = gr.Button('Run') with gr.Accordion('Advanced options', open=False): preprocessor_name = gr.Radio(label='Preprocessor', choices=[ 'HED', 'PidiNet', 'HED safe', 'PidiNet safe', 'None', ], type='value', value='PidiNet') num_samples = gr.Slider(label='Number of images', minimum=1, maximum=max_images, value=default_num_images, step=1) image_resolution = gr.Slider(label='Image resolution', minimum=256, maximum=512, value=512, step=256) preprocess_resolution = gr.Slider( label='Preprocess resolution', minimum=128, maximum=512, value=512, step=1) num_steps = gr.Slider(label='Number of steps', minimum=1, maximum=100, value=20, step=1) guidance_scale = gr.Slider(label='Guidance scale', minimum=0.1, maximum=30.0, value=9.0, step=0.1) seed = gr.Slider(label='Seed', minimum=0, maximum=1000000, step=1, value=0, randomize=True) randomize_seed = gr.Checkbox(label='Randomize seed', value=True) a_prompt = gr.Textbox( label='Additional prompt', value='best quality, extremely detailed') n_prompt = gr.Textbox( label='Negative prompt', value= 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality' ) with gr.Column(): result = gr.Gallery(label='Output', show_label=False).style( columns=2, object_fit='scale-down') inputs = [ image, prompt, a_prompt, n_prompt, num_samples, image_resolution, preprocess_resolution, num_steps, guidance_scale, seed, preprocessor_name, ] prompt.submit( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, ).then( fn=process, inputs=inputs, outputs=result, ) run_button.click( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, ).then( fn=process, inputs=inputs, outputs=result, api_name='scribble', ) return demo
if __name__ == '__main__': from model import Model model = Model(task_name='softedge') demo = create_demo(model.process_softedge) demo.queue().launch()1234567891011121314151617import cv2import numpy as np
def resize_image(input_image, resolution, interpolation=None): H, W, C = input_image.shape H = float(H) W = float(W) k = float(resolution) / max(H, W) H *= k W *= k H = int(np.round(H / 64.0)) * 64 W = int(np.round(W / 64.0)) * 64 if interpolation is None: interpolation = cv2.INTER_LANCZOS4 if k > 1 else cv2.INTER_AREA img = cv2.resize(input_image, (W, H), interpolation=interpolation) return img12345678910111213141516171819202122232425import numpy as npimport PIL.Imagefrom controlnet_aux.util import HWC3from transformers import pipeline
from cv_utils import resize_image
class DepthEstimator: def __init__(self): self.model = pipeline('depth-estimation')
def __call__(self, image: np.ndarray, **kwargs) -> PIL.Image.Image: detect_resolution = kwargs.pop('detect_resolution', 512) image_resolution = kwargs.pop('image_resolution', 512) image = np.array(image) image = HWC3(image) image = resize_image(image, resolution=detect_resolution) image = PIL.Image.fromarray(image) image = self.model(image) image = image['depth'] image = np.array(image) image = HWC3(image) image = resize_image(image, resolution=image_resolution) return PIL.Image.fromarray(image)123456789101112131415161718192021222324252627282930313233343536373839import cv2import numpy as npimport PIL.Imageimport torchfrom controlnet_aux.util import HWC3, ade_palettefrom transformers import AutoImageProcessor, UperNetForSemanticSegmentation
from cv_utils import resize_image
class ImageSegmentor: def __init__(self): self.image_processor = AutoImageProcessor.from_pretrained( 'openmmlab/upernet-convnext-small') self.image_segmentor = UperNetForSemanticSegmentation.from_pretrained( 'openmmlab/upernet-convnext-small')
@torch.inference_mode() def __call__(self, image: np.ndarray, **kwargs) -> PIL.Image.Image: detect_resolution = kwargs.pop('detect_resolution', 512) image_resolution = kwargs.pop('image_resolution', 512) image = HWC3(image) image = resize_image(image, resolution=detect_resolution) image = PIL.Image.fromarray(image)
pixel_values = self.image_processor(image, return_tensors='pt').pixel_values outputs = self.image_segmentor(pixel_values) seg = self.image_processor.post_process_semantic_segmentation( outputs, target_sizes=[image.size[::-1]])[0] color_seg = np.zeros((seg.shape[0], seg.shape[1], 3), dtype=np.uint8) for label, color in enumerate(ade_palette()): color_seg[seg == label, :] = color color_seg = color_seg.astype(np.uint8)
color_seg = resize_image(color_seg, resolution=image_resolution, interpolation=cv2.INTER_NEAREST) return PIL.Image.fromarray(color_seg)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591from __future__ import annotations
import gc
import numpy as npimport PIL.Imageimport torchfrom controlnet_aux.util import HWC3from diffusers import (ControlNetModel, DiffusionPipeline, StableDiffusionControlNetPipeline, UniPCMultistepScheduler)
from cv_utils import resize_imagefrom preprocessor import Preprocessor
CONTROLNET_MODEL_IDS = { 'Openpose': 'lllyasviel/control_v11p_sd15_openpose', 'Canny': 'lllyasviel/control_v11p_sd15_canny', 'MLSD': 'lllyasviel/control_v11p_sd15_mlsd', 'scribble': 'lllyasviel/control_v11p_sd15_scribble', 'softedge': 'lllyasviel/control_v11p_sd15_softedge', 'segmentation': 'lllyasviel/control_v11p_sd15_seg', 'depth': 'lllyasviel/control_v11p_sd15_depth', 'NormalBae': 'lllyasviel/control_v11p_sd15_normalbae', 'lineart': 'lllyasviel/control_v11p_sd15_lineart', 'lineart_anime': 'lllyasviel/control_v11p_sd15s2_lineart_anime', 'shuffle': 'lllyasviel/control_v11e_sd15_shuffle', 'ip2p': 'lllyasviel/control_v11e_sd15_ip2p', 'inpaint': 'lllyasviel/control_v11e_sd15_inpaint',}
def download_all_controlnet_weights() -> None: for model_id in CONTROLNET_MODEL_IDS.values(): ControlNetModel.from_pretrained(model_id)
class Model: def __init__(self, base_model_id: str = 'runwayml/stable-diffusion-v1-5', task_name: str = 'Canny'): self.device = torch.device( 'cuda:0' if torch.cuda.is_available() else 'cpu') self.base_model_id = '' self.task_name = '' self.pipe = self.load_pipe(base_model_id, task_name) self.preprocessor = Preprocessor()
def load_pipe(self, base_model_id: str, task_name) -> DiffusionPipeline: if base_model_id == self.base_model_id and task_name == self.task_name and hasattr( self, 'pipe') and self.pipe is not None: return self.pipe model_id = CONTROLNET_MODEL_IDS[task_name] controlnet = ControlNetModel.from_pretrained(model_id, torch_dtype=torch.float16) pipe = StableDiffusionControlNetPipeline.from_pretrained( base_model_id, safety_checker=None, controlnet=controlnet, torch_dtype=torch.float16) pipe.scheduler = UniPCMultistepScheduler.from_config( pipe.scheduler.config) if self.device.type == 'cuda': pipe.enable_xformers_memory_efficient_attention() pipe.to(self.device) torch.cuda.empty_cache() gc.collect() self.base_model_id = base_model_id self.task_name = task_name return pipe
def set_base_model(self, base_model_id: str) -> str: if not base_model_id or base_model_id == self.base_model_id: return self.base_model_id del self.pipe torch.cuda.empty_cache() gc.collect() try: self.pipe = self.load_pipe(base_model_id, self.task_name) except Exception: self.pipe = self.load_pipe(self.base_model_id, self.task_name) return self.base_model_id
def load_controlnet_weight(self, task_name: str) -> None: if task_name == self.task_name: return if self.pipe is not None and hasattr(self.pipe, 'controlnet'): del self.pipe.controlnet torch.cuda.empty_cache() gc.collect() model_id = CONTROLNET_MODEL_IDS[task_name] controlnet = ControlNetModel.from_pretrained(model_id, torch_dtype=torch.float16) controlnet.to(self.device) torch.cuda.empty_cache() gc.collect() self.pipe.controlnet = controlnet self.task_name = task_name
def get_prompt(self, prompt: str, additional_prompt: str) -> str: if not prompt: prompt = additional_prompt else: prompt = f'{prompt}, {additional_prompt}' return prompt
@torch.autocast('cuda') def run_pipe( self, prompt: str, negative_prompt: str, control_image: PIL.Image.Image, num_images: int, num_steps: int, guidance_scale: float, seed: int, ) -> list[PIL.Image.Image]: if seed == -1: seed = np.random.randint(0, np.iinfo(np.int64).max) generator = torch.Generator().manual_seed(seed) return self.pipe(prompt=prompt, negative_prompt=negative_prompt, guidance_scale=guidance_scale, num_images_per_prompt=num_images, num_inference_steps=num_steps, generator=generator, image=control_image).images
@torch.inference_mode() def process_canny( self, image: np.ndarray, prompt: str, additional_prompt: str, negative_prompt: str, num_images: int, image_resolution: int, num_steps: int, guidance_scale: float, seed: int, low_threshold: int, high_threshold: int, ) -> list[PIL.Image.Image]: self.preprocessor.load('Canny') control_image = self.preprocessor(image=image, low_threshold=low_threshold, high_threshold=high_threshold, detect_resolution=image_resolution)
self.load_controlnet_weight('Canny') results = self.run_pipe( prompt=self.get_prompt(prompt, additional_prompt), negative_prompt=negative_prompt, control_image=control_image, num_images=num_images, num_steps=num_steps, guidance_scale=guidance_scale, seed=seed, ) return [control_image] + results
@torch.inference_mode() def process_mlsd( self, image: np.ndarray, prompt: str, additional_prompt: str, negative_prompt: str, num_images: int, image_resolution: int, preprocess_resolution: int, num_steps: int, guidance_scale: float, seed: int, value_threshold: float, distance_threshold: float, ) -> list[PIL.Image.Image]: self.preprocessor.load('MLSD') control_image = self.preprocessor( image=image, image_resolution=image_resolution, detect_resolution=preprocess_resolution, thr_v=value_threshold, thr_d=distance_threshold, ) self.load_controlnet_weight('MLSD') results = self.run_pipe( prompt=self.get_prompt(prompt, additional_prompt), negative_prompt=negative_prompt, control_image=control_image, num_images=num_images, num_steps=num_steps, guidance_scale=guidance_scale, seed=seed, ) return [control_image] + results
@torch.inference_mode() def process_scribble( self, image: np.ndarray, prompt: str, additional_prompt: str, negative_prompt: str, num_images: int, image_resolution: int, preprocess_resolution: int, num_steps: int, guidance_scale: float, seed: int, preprocessor_name: str, ) -> list[PIL.Image.Image]: if preprocessor_name == 'None': image = HWC3(image) image = resize_image(image, resolution=image_resolution) control_image = PIL.Image.fromarray(image) elif preprocessor_name == 'HED': self.preprocessor.load(preprocessor_name) control_image = self.preprocessor( image=image, image_resolution=image_resolution, detect_resolution=preprocess_resolution, scribble=False, ) elif preprocessor_name == 'PidiNet': self.preprocessor.load(preprocessor_name) control_image = self.preprocessor( image=image, image_resolution=image_resolution, detect_resolution=preprocess_resolution, safe=False, ) self.load_controlnet_weight('scribble') results = self.run_pipe( prompt=self.get_prompt(prompt, additional_prompt), negative_prompt=negative_prompt, control_image=control_image, num_images=num_images, num_steps=num_steps, guidance_scale=guidance_scale, seed=seed, ) return [control_image] + results
@torch.inference_mode() def process_scribble_interactive( self, image_and_mask: dict[str, np.ndarray], prompt: str, additional_prompt: str, negative_prompt: str, num_images: int, image_resolution: int, num_steps: int, guidance_scale: float, seed: int, ) -> list[PIL.Image.Image]: image = image_and_mask['mask'] image = HWC3(image) image = resize_image(image, resolution=image_resolution) control_image = PIL.Image.fromarray(image)
self.load_controlnet_weight('scribble') results = self.run_pipe( prompt=self.get_prompt(prompt, additional_prompt), negative_prompt=negative_prompt, control_image=control_image, num_images=num_images, num_steps=num_steps, guidance_scale=guidance_scale, seed=seed, ) return [control_image] + results
@torch.inference_mode() def process_softedge( self, image: np.ndarray, prompt: str, additional_prompt: str, negative_prompt: str, num_images: int, image_resolution: int, preprocess_resolution: int, num_steps: int, guidance_scale: float, seed: int, preprocessor_name: str, ) -> list[PIL.Image.Image]: if preprocessor_name == 'None': image = HWC3(image) image = resize_image(image, resolution=image_resolution) control_image = PIL.Image.fromarray(image) elif preprocessor_name in ['HED', 'HED safe']: safe = 'safe' in preprocessor_name self.preprocessor.load('HED') control_image = self.preprocessor( image=image, image_resolution=image_resolution, detect_resolution=preprocess_resolution, scribble=safe, ) elif preprocessor_name in ['PidiNet', 'PidiNet safe']: safe = 'safe' in preprocessor_name self.preprocessor.load('PidiNet') control_image = self.preprocessor( image=image, image_resolution=image_resolution, detect_resolution=preprocess_resolution, safe=safe, ) else: raise ValueError self.load_controlnet_weight('softedge') results = self.run_pipe( prompt=self.get_prompt(prompt, additional_prompt), negative_prompt=negative_prompt, control_image=control_image, num_images=num_images, num_steps=num_steps, guidance_scale=guidance_scale, seed=seed, ) return [control_image] + results
@torch.inference_mode() def process_openpose( self, image: np.ndarray, prompt: str, additional_prompt: str, negative_prompt: str, num_images: int, image_resolution: int, preprocess_resolution: int, num_steps: int, guidance_scale: float, seed: int, preprocessor_name: str, ) -> list[PIL.Image.Image]: if preprocessor_name == 'None': image = HWC3(image) image = resize_image(image, resolution=image_resolution) control_image = PIL.Image.fromarray(image) else: self.preprocessor.load('Openpose') control_image = self.preprocessor( image=image, image_resolution=image_resolution, detect_resolution=preprocess_resolution, hand_and_face=True, ) self.load_controlnet_weight('Openpose') results = self.run_pipe( prompt=self.get_prompt(prompt, additional_prompt), negative_prompt=negative_prompt, control_image=control_image, num_images=num_images, num_steps=num_steps, guidance_scale=guidance_scale, seed=seed, ) return [control_image] + results
@torch.inference_mode() def process_segmentation( self, image: np.ndarray, prompt: str, additional_prompt: str, negative_prompt: str, num_images: int, image_resolution: int, preprocess_resolution: int, num_steps: int, guidance_scale: float, seed: int, preprocessor_name: str, ) -> list[PIL.Image.Image]: if preprocessor_name == 'None': image = HWC3(image) image = resize_image(image, resolution=image_resolution) control_image = PIL.Image.fromarray(image) else: self.preprocessor.load(preprocessor_name) control_image = self.preprocessor( image=image, image_resolution=image_resolution, detect_resolution=preprocess_resolution, ) self.load_controlnet_weight('segmentation') results = self.run_pipe( prompt=self.get_prompt(prompt, additional_prompt), negative_prompt=negative_prompt, control_image=control_image, num_images=num_images, num_steps=num_steps, guidance_scale=guidance_scale, seed=seed, ) return [control_image] + results
@torch.inference_mode() def process_depth( self, image: np.ndarray, prompt: str, additional_prompt: str, negative_prompt: str, num_images: int, image_resolution: int, preprocess_resolution: int, num_steps: int, guidance_scale: float, seed: int, preprocessor_name: str, ) -> list[PIL.Image.Image]: if preprocessor_name == 'None': image = HWC3(image) image = resize_image(image, resolution=image_resolution) control_image = PIL.Image.fromarray(image) else: self.preprocessor.load(preprocessor_name) control_image = self.preprocessor( image=image, image_resolution=image_resolution, detect_resolution=preprocess_resolution, ) self.load_controlnet_weight('depth') results = self.run_pipe( prompt=self.get_prompt(prompt, additional_prompt), negative_prompt=negative_prompt, control_image=control_image, num_images=num_images, num_steps=num_steps, guidance_scale=guidance_scale, seed=seed, ) return [control_image] + results
@torch.inference_mode() def process_normal( self, image: np.ndarray, prompt: str, additional_prompt: str, negative_prompt: str, num_images: int, image_resolution: int, preprocess_resolution: int, num_steps: int, guidance_scale: float, seed: int, preprocessor_name: str, ) -> list[PIL.Image.Image]: if preprocessor_name == 'None': image = HWC3(image) image = resize_image(image, resolution=image_resolution) control_image = PIL.Image.fromarray(image) else: self.preprocessor.load('NormalBae') control_image = self.preprocessor( image=image, image_resolution=image_resolution, detect_resolution=preprocess_resolution, ) self.load_controlnet_weight('NormalBae') results = self.run_pipe( prompt=self.get_prompt(prompt, additional_prompt), negative_prompt=negative_prompt, control_image=control_image, num_images=num_images, num_steps=num_steps, guidance_scale=guidance_scale, seed=seed, ) return [control_image] + results
@torch.inference_mode() def process_lineart( self, image: np.ndarray, prompt: str, additional_prompt: str, negative_prompt: str, num_images: int, image_resolution: int, preprocess_resolution: int, num_steps: int, guidance_scale: float, seed: int, preprocessor_name: str, ) -> list[PIL.Image.Image]: if preprocessor_name in ['None', 'None (anime)']: image = HWC3(image) image = resize_image(image, resolution=image_resolution) control_image = PIL.Image.fromarray(image) elif preprocessor_name in ['Lineart', 'Lineart coarse']: coarse = 'coarse' in preprocessor_name self.preprocessor.load('Lineart') control_image = self.preprocessor( image=image, image_resolution=image_resolution, detect_resolution=preprocess_resolution, coarse=coarse, ) elif preprocessor_name == 'Lineart (anime)': self.preprocessor.load('LineartAnime') control_image = self.preprocessor( image=image, image_resolution=image_resolution, detect_resolution=preprocess_resolution, ) if 'anime' in preprocessor_name: self.load_controlnet_weight('lineart_anime') else: self.load_controlnet_weight('lineart') results = self.run_pipe( prompt=self.get_prompt(prompt, additional_prompt), negative_prompt=negative_prompt, control_image=control_image, num_images=num_images, num_steps=num_steps, guidance_scale=guidance_scale, seed=seed, ) return [control_image] + results
@torch.inference_mode() def process_shuffle( self, image: np.ndarray, prompt: str, additional_prompt: str, negative_prompt: str, num_images: int, image_resolution: int, num_steps: int, guidance_scale: float, seed: int, preprocessor_name: str, ) -> list[PIL.Image.Image]: if preprocessor_name == 'None': image = HWC3(image) image = resize_image(image, resolution=image_resolution) control_image = PIL.Image.fromarray(image) else: self.preprocessor.load(preprocessor_name) control_image = self.preprocessor( image=image, image_resolution=image_resolution, ) self.load_controlnet_weight('shuffle') results = self.run_pipe( prompt=self.get_prompt(prompt, additional_prompt), negative_prompt=negative_prompt, control_image=control_image, num_images=num_images, num_steps=num_steps, guidance_scale=guidance_scale, seed=seed, ) return [control_image] + results
@torch.inference_mode() def process_ip2p( self, image: np.ndarray, prompt: str, additional_prompt: str, negative_prompt: str, num_images: int, image_resolution: int, num_steps: int, guidance_scale: float, seed: int, ) -> list[PIL.Image.Image]: image = HWC3(image) image = resize_image(image, resolution=image_resolution) control_image = PIL.Image.fromarray(image) self.load_controlnet_weight('ip2p') results = self.run_pipe( prompt=self.get_prompt(prompt, additional_prompt), negative_prompt=negative_prompt, control_image=control_image, num_images=num_images, num_steps=num_steps, guidance_scale=guidance_scale, seed=seed, ) return [control_image] + results1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677import gc
import numpy as npimport PIL.Imageimport torchfrom controlnet_aux import (CannyDetector, ContentShuffleDetector, HEDdetector, LineartAnimeDetector, LineartDetector, MidasDetector, MLSDdetector, NormalBaeDetector, OpenposeDetector, PidiNetDetector)from controlnet_aux.util import HWC3
from cv_utils import resize_imagefrom depth_estimator import DepthEstimatorfrom image_segmentor import ImageSegmentor
class Preprocessor: MODEL_ID = 'lllyasviel/Annotators'
def __init__(self): self.model = None self.name = ''
def load(self, name: str) -> None: if name == self.name: return if name == 'HED': self.model = HEDdetector.from_pretrained(self.MODEL_ID) elif name == 'Midas': self.model = MidasDetector.from_pretrained(self.MODEL_ID) elif name == 'MLSD': self.model = MLSDdetector.from_pretrained(self.MODEL_ID) elif name == 'Openpose': self.model = OpenposeDetector.from_pretrained(self.MODEL_ID) elif name == 'PidiNet': self.model = PidiNetDetector.from_pretrained(self.MODEL_ID) elif name == 'NormalBae': self.model = NormalBaeDetector.from_pretrained(self.MODEL_ID) elif name == 'Lineart': self.model = LineartDetector.from_pretrained(self.MODEL_ID) elif name == 'LineartAnime': self.model = LineartAnimeDetector.from_pretrained(self.MODEL_ID) elif name == 'Canny': self.model = CannyDetector() elif name == 'ContentShuffle': self.model = ContentShuffleDetector() elif name == 'DPT': self.model = DepthEstimator() elif name == 'UPerNet': self.model = ImageSegmentor() else: raise ValueError torch.cuda.empty_cache() gc.collect() self.name = name
def __call__(self, image: PIL.Image.Image, **kwargs) -> PIL.Image.Image: if self.name == 'Canny': if 'detect_resolution' in kwargs: detect_resolution = kwargs.pop('detect_resolution') image = np.array(image) image = HWC3(image) image = resize_image(image, resolution=detect_resolution) image = self.model(image, **kwargs) return PIL.Image.fromarray(image) elif self.name == 'Midas': detect_resolution = kwargs.pop('detect_resolution', 512) image_resolution = kwargs.pop('image_resolution', 512) image = np.array(image) image = HWC3(image) image = resize_image(image, resolution=detect_resolution) image = self.model(image, **kwargs) image = HWC3(image) image = resize_image(image, resolution=image_resolution) return PIL.Image.fromarray(image) else: return self.model(image, **kwargs)123456789101112accelerate==0.18.0controlnet_aux==0.0.3diffusers==0.15.0einops==0.6.0gradio==3.26.0huggingface-hub==0.13.4opencv-python-headless==4.7.0.72safetensors==0.3.0torch==2.0.0torchvision==0.15.1transformers==4.28.1xformers==0.0.18123h1 { text-align: center;}1234567import random
def randomize_seed_fn(seed: int, randomize_seed: bool) -> int: if randomize_seed: seed = random.randint(0, 1000000) return seed.gitignoreAdded+162
.pre-commit-config.yamlAdded+36
.style.yapfAdded+5
LICENSEAdded+21
LICENSE.ControlNetAdded+201
README.md+4-3
app.pyAdded+132
app_canny.pyAdded+106
app_depth.pyAdded+105
app_ip2p.pyAdded+92
app_lineart.pyAdded+114
app_mlsd.pyAdded+113
app_normal.pyAdded+104
app_openpose.pyAdded+104
app_scribble.pyAdded+105
app_scribble_interactive.pyAdded+112
app_segmentation.pyAdded+104
app_shuffle.pyAdded+98
app_softedge.pyAdded+110
cv_utils.pyAdded+17
depth_estimator.pyAdded+25
image_segmentor.pyAdded+39
model.pyAdded+591
preprocessor.pyAdded+77
requirements.txtAdded+12
style.cssAdded+3
utils.pyAdded+7