Spaces:
Runtime error
Runtime error
Add files
Browse filesFiles changed (9)
- .gitignoreAdded+162
- .pre-commit-config.yamlAdded+36
- .style.yapfAdded+5
- .vscode/settings.jsonAdded+18
- LICENSEAdded+21
- README.md+3-1
- app.pyAdded+301
- requirements.txtAdded+7
- style.cssAdded+16
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 = true123456789101112131415161718{ "python.linting.enabled": true, "python.linting.flake8Enabled": true, "python.linting.pylintEnabled": false, "python.linting.lintOnSave": true, "python.formatting.provider": "yapf", "python.formatting.yapfArgs": [ "--style={based_on_style: pep8, indent_width: 4, blank_line_before_nested_class_or_def: false, spaces_before_comment: 2, split_before_logical_operator: true}" ], "[python]": { "editor.formatOnType": true, "editor.codeActionsOnSave": { "source.organizeImports": true } }, "editor.formatOnSave": true, "files.insertFinalNewline": true}123456789101112131415161718192021MIT 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.123456789101112---title: SD XLemoji: 🌍colorFrom: graycolorTo: purplesdk: gradiosdk_version: 3.39.0app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference1234567891011121314---title: SD-XLemoji: 🌍colorFrom: graycolorTo: purplesdk: gradiosdk_version: 3.39.0app_file: app.pylicense: mitpinned: falsesuggested_hardware: a10g-small---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301#!/usr/bin/env python
from __future__ import annotations
import osimport random
import gradio as grimport numpy as npimport PIL.Imageimport torchfrom diffusers import DiffusionPipeline
DESCRIPTION = '# SD-XL'if not torch.cuda.is_available(): DESCRIPTION += '\n<p>Running on CPU 🥶 This demo does not work on CPU.</p>'
MAX_SEED = np.iinfo(np.int32).maxCACHE_EXAMPLES = torch.cuda.is_available() and os.getenv( 'CACHE_EXAMPLES') == '1'MAX_IMAGE_SIZE = int(os.getenv('MAX_IMAGE_SIZE', '1024'))USE_TORCH_COMPILE = os.getenv('USE_TORCH_COMPILE') == '1'ENABLE_CPU_OFFLOAD = os.getenv('ENABLE_CPU_OFFLOAD') == '1'
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')if torch.cuda.is_available(): pipe = DiffusionPipeline.from_pretrained( 'stabilityai/stable-diffusion-xl-base-1.0', torch_dtype=torch.float16, use_safetensors=True, variant='fp16') refiner = DiffusionPipeline.from_pretrained( 'stabilityai/stable-diffusion-xl-refiner-1.0', torch_dtype=torch.float16, use_safetensors=True, variant='fp16')
if ENABLE_CPU_OFFLOAD: pipe.enable_model_cpu_offload() refiner.enable_model_cpu_offload() else: pipe.to(device) refiner.to(device)
if USE_TORCH_COMPILE: pipe.unet = torch.compile(pipe.unet, mode='reduce-overhead', fullgraph=True)else: pipe = None refiner = None
def randomize_seed_fn(seed: int, randomize_seed: bool) -> int: if randomize_seed: seed = random.randint(0, MAX_SEED) return seed
def generate(prompt: str, negative_prompt: str = '', prompt_2: str = '', negative_prompt_2: str = '', use_negative_prompt: bool = False, use_prompt_2: bool = False, use_negative_prompt_2: bool = False, seed: int = 0, width: int = 1024, height: int = 1024, guidance_scale_base: float = 5.0, guidance_scale_refiner: float = 5.0, num_inference_steps_base: int = 50, num_inference_steps_refiner: int = 50, apply_refiner: bool = False) -> PIL.Image.Image: generator = torch.Generator().manual_seed(seed)
if not use_negative_prompt: negative_prompt = None # type: ignore if not use_prompt_2: prompt_2 = None # type: ignore if not use_negative_prompt_2: negative_prompt_2 = None # type: ignore
if not apply_refiner: return pipe(prompt=prompt, negative_prompt=negative_prompt, prompt_2=prompt_2, negative_prompt_2=negative_prompt_2, width=width, height=height, guidance_scale=guidance_scale_base, num_inference_steps=num_inference_steps_base, generator=generator, output_type='pil').images[0] else: latents = pipe(prompt=prompt, negative_prompt=negative_prompt, prompt_2=prompt_2, negative_prompt_2=negative_prompt_2, width=width, height=height, guidance_scale=guidance_scale_base, num_inference_steps=num_inference_steps_base, generator=generator, output_type='latent').images image = refiner(prompt=prompt, negative_prompt=negative_prompt, prompt_2=prompt_2, negative_prompt_2=negative_prompt_2, guidance_scale=guidance_scale_refiner, num_inference_steps=num_inference_steps_refiner, image=latents, generator=generator).images[0] return image
examples = [ 'Astronaut in a jungle, cold color palette, muted colors, detailed, 8k', 'An astronaut riding a green horse',]
with gr.Blocks(css='style.css') as demo: gr.Markdown(DESCRIPTION) gr.DuplicateButton(value='Duplicate Space for private use', elem_id='duplicate-button', visible=os.getenv('SHOW_DUPLICATE_BUTTON') == '1') with gr.Box(): with gr.Row(): prompt = gr.Text( label='Prompt', show_label=False, max_lines=1, placeholder='Enter your prompt', container=False, ) run_button = gr.Button('Run', scale=0) result = gr.Image(label='Result', show_label=False) with gr.Accordion('Advanced options', open=False): with gr.Row(): use_negative_prompt = gr.Checkbox(label='Use negative prompt', value=False) use_prompt_2 = gr.Checkbox(label='Use prompt 2', value=False) use_negative_prompt_2 = gr.Checkbox( label='Use negative prompt 2', value=False) negative_prompt = gr.Text( label='Negative prompt', max_lines=1, placeholder='Enter a negative prompt', visible=False, ) prompt_2 = gr.Text( label='Prompt 2', max_lines=1, placeholder='Enter your prompt', visible=False, ) negative_prompt_2 = gr.Text( label='Negative prompt 2', max_lines=1, placeholder='Enter a negative prompt', visible=False, )
seed = gr.Slider(label='Seed', minimum=0, maximum=MAX_SEED, step=1, value=0) randomize_seed = gr.Checkbox(label='Randomize seed', value=True) with gr.Row(): width = gr.Slider( label='Width', minimum=256, maximum=MAX_IMAGE_SIZE, step=32, value=1024, ) height = gr.Slider( label='Height', minimum=256, maximum=MAX_IMAGE_SIZE, step=32, value=1024, ) apply_refiner = gr.Checkbox(label='Apply refiner', value=False) with gr.Row(): guidance_scale_base = gr.Slider( label='Guidance scale for base', minimum=1, maximum=20, step=0.1, value=5.0) num_inference_steps_base = gr.Slider( label='Number of inference steps for base', minimum=10, maximum=100, step=1, value=50) with gr.Row(visible=False) as refiner_params: guidance_scale_refiner = gr.Slider( label='Guidance scale for refiner', minimum=1, maximum=20, step=0.1, value=5.0) num_inference_steps_refiner = gr.Slider( label='Number of inference steps for refiner', minimum=10, maximum=100, step=1, value=50)
gr.Examples(examples=examples, inputs=prompt, outputs=result, fn=generate, cache_examples=CACHE_EXAMPLES)
use_negative_prompt.change( fn=lambda x: gr.update(visible=x), inputs=use_negative_prompt, outputs=negative_prompt, queue=False, api_name=False, ) use_prompt_2.change( fn=lambda x: gr.update(visible=x), inputs=use_prompt_2, outputs=prompt_2, queue=False, api_name=False, ) use_negative_prompt_2.change( fn=lambda x: gr.update(visible=x), inputs=use_negative_prompt_2, outputs=negative_prompt_2, queue=False, api_name=False, ) apply_refiner.change( fn=lambda x: gr.update(visible=x), inputs=apply_refiner, outputs=refiner_params, queue=False, api_name=False, )
inputs = [ prompt, negative_prompt, prompt_2, negative_prompt_2, use_negative_prompt, use_prompt_2, use_negative_prompt_2, seed, width, height, guidance_scale_base, guidance_scale_refiner, num_inference_steps_base, num_inference_steps_refiner, apply_refiner, ] prompt.submit( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, queue=False, api_name=False, ).then( fn=generate, inputs=inputs, outputs=result, api_name='run', ) negative_prompt.submit( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, queue=False, api_name=False, ).then( fn=generate, inputs=inputs, outputs=result, api_name=False, ) run_button.click( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, queue=False, api_name=False, ).then( fn=generate, inputs=inputs, outputs=result, api_name=False, )demo.queue(max_size=20).launch()1234567accelerate==0.21.0diffusers==0.19.0gradio==3.39.0invisible-watermark==0.2.0Pillow==10.0.0torch==2.0.1transformers==4.31.012345678910111213141516h1 { text-align: center;}
#duplicate-button { margin: auto; color: #fff; background: #1565c0; border-radius: 100vh;}
#component-0 { max-width: 730px; margin: auto; padding-top: 1.5rem;}.gitignoreAdded+162
.pre-commit-config.yamlAdded+36
.style.yapfAdded+5
.vscode/settings.jsonAdded+18
LICENSEAdded+21
README.md+3-1
app.pyAdded+301
requirements.txtAdded+7
style.cssAdded+16