Spaces:
Shawt
/
Build error

Shawt hysts HF staff commited on
Commit
0a286b8
0 Parent(s):

Duplicate from DeepFloyd/IF

Browse files

Co-authored-by: hysts <hysts@users.noreply.huggingface.co>

Files changed (12) hide show
  1. .gitattributes +35 -0
  2. .gitignore +162 -0
  3. .pre-commit-config.yaml +38 -0
  4. .style.yapf +5 -0
  5. Dockerfile +90 -0
  6. README.md +14 -0
  7. app.py +701 -0
  8. model.py +313 -0
  9. requirements.txt +16 -0
  10. settings.py +57 -0
  11. share_btn.py +69 -0
  12. style.css +238 -0
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
35
+ *.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio_cached_examples/
2
+
3
+ # Byte-compiled / optimized / DLL files
4
+ __pycache__/
5
+ *.py[cod]
6
+ *$py.class
7
+
8
+ # C extensions
9
+ *.so
10
+
11
+ # Distribution / packaging
12
+ .Python
13
+ build/
14
+ develop-eggs/
15
+ dist/
16
+ downloads/
17
+ eggs/
18
+ .eggs/
19
+ lib/
20
+ lib64/
21
+ parts/
22
+ sdist/
23
+ var/
24
+ wheels/
25
+ share/python-wheels/
26
+ *.egg-info/
27
+ .installed.cfg
28
+ *.egg
29
+ MANIFEST
30
+
31
+ # PyInstaller
32
+ # Usually these files are written by a python script from a template
33
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
34
+ *.manifest
35
+ *.spec
36
+
37
+ # Installer logs
38
+ pip-log.txt
39
+ pip-delete-this-directory.txt
40
+
41
+ # Unit test / coverage reports
42
+ htmlcov/
43
+ .tox/
44
+ .nox/
45
+ .coverage
46
+ .coverage.*
47
+ .cache
48
+ nosetests.xml
49
+ coverage.xml
50
+ *.cover
51
+ *.py,cover
52
+ .hypothesis/
53
+ .pytest_cache/
54
+ cover/
55
+
56
+ # Translations
57
+ *.mo
58
+ *.pot
59
+
60
+ # Django stuff:
61
+ *.log
62
+ local_settings.py
63
+ db.sqlite3
64
+ db.sqlite3-journal
65
+
66
+ # Flask stuff:
67
+ instance/
68
+ .webassets-cache
69
+
70
+ # Scrapy stuff:
71
+ .scrapy
72
+
73
+ # Sphinx documentation
74
+ docs/_build/
75
+
76
+ # PyBuilder
77
+ .pybuilder/
78
+ target/
79
+
80
+ # Jupyter Notebook
81
+ .ipynb_checkpoints
82
+
83
+ # IPython
84
+ profile_default/
85
+ ipython_config.py
86
+
87
+ # pyenv
88
+ # For a library or package, you might want to ignore these files since the code is
89
+ # intended to run in multiple environments; otherwise, check them in:
90
+ # .python-version
91
+
92
+ # pipenv
93
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
94
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
95
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
96
+ # install all needed dependencies.
97
+ #Pipfile.lock
98
+
99
+ # poetry
100
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
101
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
102
+ # commonly ignored for libraries.
103
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
104
+ #poetry.lock
105
+
106
+ # pdm
107
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
108
+ #pdm.lock
109
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
110
+ # in version control.
111
+ # https://pdm.fming.dev/#use-with-ide
112
+ .pdm.toml
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Celery stuff
118
+ celerybeat-schedule
119
+ celerybeat.pid
120
+
121
+ # SageMath parsed files
122
+ *.sage.py
123
+
124
+ # Environments
125
+ .env
126
+ .venv
127
+ env/
128
+ venv/
129
+ ENV/
130
+ env.bak/
131
+ venv.bak/
132
+
133
+ # Spyder project settings
134
+ .spyderproject
135
+ .spyproject
136
+
137
+ # Rope project settings
138
+ .ropeproject
139
+
140
+ # mkdocs documentation
141
+ /site
142
+
143
+ # mypy
144
+ .mypy_cache/
145
+ .dmypy.json
146
+ dmypy.json
147
+
148
+ # Pyre type checker
149
+ .pyre/
150
+
151
+ # pytype static type analyzer
152
+ .pytype/
153
+
154
+ # Cython debug symbols
155
+ cython_debug/
156
+
157
+ # PyCharm
158
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
161
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
+ #.idea/
.pre-commit-config.yaml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ exclude: diffusers-private
2
+ repos:
3
+ - repo: https://github.com/pre-commit/pre-commit-hooks
4
+ rev: v4.2.0
5
+ hooks:
6
+ - id: check-executables-have-shebangs
7
+ - id: check-json
8
+ - id: check-merge-conflict
9
+ - id: check-shebang-scripts-are-executable
10
+ - id: check-toml
11
+ - id: check-yaml
12
+ - id: double-quote-string-fixer
13
+ - id: end-of-file-fixer
14
+ - id: mixed-line-ending
15
+ args: ['--fix=lf']
16
+ - id: requirements-txt-fixer
17
+ - id: trailing-whitespace
18
+ - repo: https://github.com/myint/docformatter
19
+ rev: v1.4
20
+ hooks:
21
+ - id: docformatter
22
+ args: ['--in-place']
23
+ - repo: https://github.com/pycqa/isort
24
+ rev: 5.12.0
25
+ hooks:
26
+ - id: isort
27
+ - repo: https://github.com/pre-commit/mirrors-mypy
28
+ rev: v0.991
29
+ hooks:
30
+ - id: mypy
31
+ args: ['--ignore-missing-imports']
32
+ additional_dependencies: ['types-python-slugify']
33
+ files: ^diffusers-private
34
+ - repo: https://github.com/google/yapf
35
+ rev: v0.32.0
36
+ hooks:
37
+ - id: yapf
38
+ args: ['--parallel', '--in-place']
.style.yapf ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ [style]
2
+ based_on_style = pep8
3
+ blank_line_before_nested_class_or_def = false
4
+ spaces_before_comment = 2
5
+ split_before_logical_operator = true
Dockerfile ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Download LFS content while building in order to make this step cacheable
2
+ # #===== LFS =====
3
+ # FROM alpine/git:2.36.2 AS lfs
4
+ # WORKDIR /app
5
+ # COPY --link .lfs.hf.co .
6
+ # RUN --mount=type=secret,id=SPACE_REPOSITORY,mode=0444,required=true \
7
+ # git init \
8
+ # && git remote add origin $(cat /run/secrets/SPACE_REPOSITORY) \
9
+ # && git add --all \
10
+ # && git config user.email "name@mail.com" \
11
+ # && git config user.name "Name" \
12
+ # && git commit -m "lfs" \
13
+ # && git lfs pull \
14
+ # && rm -rf .git .gitattributes
15
+ # #===============
16
+
17
+ FROM nvidia/cuda:11.8.0-runtime-ubuntu18.04
18
+ # BEGIN Static part
19
+ ENV DEBIAN_FRONTEND=noninteractive \
20
+ TZ=Europe/Paris
21
+
22
+ RUN apt-get update && apt-get install -y \
23
+ git \
24
+ make build-essential libssl-dev zlib1g-dev \
25
+ libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm \
26
+ libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev git-lfs \
27
+ ffmpeg libsm6 libxext6 cmake libgl1-mesa-glx \
28
+ && rm -rf /var/lib/apt/lists/* \
29
+ && git lfs install
30
+
31
+ # User
32
+ RUN useradd -m -u 1000 user
33
+ USER user
34
+ ENV HOME=/home/user \
35
+ PATH=/home/user/.local/bin:$PATH
36
+ WORKDIR /home/user/app
37
+
38
+ # Pyenv
39
+ RUN curl https://pyenv.run | bash
40
+ ENV PATH=$HOME/.pyenv/shims:$HOME/.pyenv/bin:$PATH
41
+
42
+ ARG PIP_VERSION=22.3.1
43
+ ARG PYTHON_VERSION=3.10
44
+ # Python
45
+ RUN pyenv install $PYTHON_VERSION && \
46
+ pyenv global $PYTHON_VERSION && \
47
+ pyenv rehash && \
48
+ pip install --no-cache-dir --upgrade pip==${PIP_VERSION} setuptools wheel && \
49
+ pip install --no-cache-dir \
50
+ datasets \
51
+ "huggingface-hub>=0.12.1" "protobuf<4" "click<8.1"
52
+
53
+ #^ Waiting for https://github.com/huggingface/huggingface_hub/pull/1345/files to be merge
54
+
55
+ USER root
56
+ # User Debian packages
57
+ ## Security warning : Potential user code executed as root (build time)
58
+ RUN --mount=target=/root/packages.txt,source=packages.txt \
59
+ apt-get update && \
60
+ xargs -r -a /root/packages.txt apt-get install -y \
61
+ && rm -rf /var/lib/apt/lists/*
62
+
63
+ USER user
64
+
65
+ # Pre requirements (e.g. upgrading pip)
66
+ RUN --mount=target=pre-requirements.txt,source=pre-requirements.txt \
67
+ pip install --no-cache-dir -r pre-requirements.txt
68
+
69
+ # Python packages
70
+ RUN pip install --pre torch --index-url https://download.pytorch.org/whl/nightly/cu117
71
+ RUN --mount=target=requirements.txt,source=requirements.txt \
72
+ pip install --no-cache-dir -r requirements.txt
73
+
74
+ ARG SDK=gradio \
75
+ SDK_VERSION=3.27.0
76
+ RUN pip install --no-cache-dir \
77
+ ${SDK}==${SDK_VERSION}
78
+
79
+ # App
80
+ # COPY --link --chown=1000 --from=lfs /app /home/user/app
81
+ COPY --link --chown=1000 ./ /home/user/app
82
+ ENV PYTHONPATH=$HOME/app \
83
+ PYTHONUNBUFFERED=1 \
84
+ GRADIO_ALLOW_FLAGGING=never \
85
+ GRADIO_NUM_PORTS=1 \
86
+ GRADIO_SERVER_NAME=0.0.0.0 \
87
+ GRADIO_THEME=huggingface \
88
+ SYSTEM=spaces
89
+
90
+ CMD ["python", "app.py"]
README.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: IF
3
+ emoji: 🔥
4
+ colorFrom: pink
5
+ colorTo: red
6
+ sdk: docker
7
+ python_version: 3.10.11
8
+ app_file: app.py
9
+ pinned: false
10
+ license: other
11
+ duplicated_from: DeepFloyd/IF
12
+ ---
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,701 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ import datetime
4
+ import hashlib
5
+ import json
6
+ import os
7
+ import random
8
+ import tempfile
9
+ import shortuuid
10
+ from apscheduler.schedulers.background import BackgroundScheduler
11
+ import shutil
12
+
13
+ import gradio as gr
14
+ import torch
15
+ from huggingface_hub import HfApi
16
+ from share_btn import community_icon_html, loading_icon_html, share_js
17
+
18
+ # isort: off
19
+ from model import Model
20
+ from settings import (
21
+ DEBUG,
22
+ DEFAULT_CUSTOM_TIMESTEPS_1,
23
+ DEFAULT_CUSTOM_TIMESTEPS_2,
24
+ DEFAULT_NUM_IMAGES,
25
+ DEFAULT_NUM_STEPS_3,
26
+ DISABLE_SD_X4_UPSCALER,
27
+ GALLERY_COLUMN_NUM,
28
+ HF_TOKEN,
29
+ MAX_NUM_IMAGES,
30
+ MAX_NUM_STEPS,
31
+ MAX_QUEUE_SIZE,
32
+ MAX_SEED,
33
+ SHOW_ADVANCED_OPTIONS,
34
+ SHOW_CUSTOM_TIMESTEPS_1,
35
+ SHOW_CUSTOM_TIMESTEPS_2,
36
+ SHOW_DEVICE_WARNING,
37
+ SHOW_DUPLICATE_BUTTON,
38
+ SHOW_NUM_IMAGES,
39
+ SHOW_NUM_STEPS_1,
40
+ SHOW_NUM_STEPS_2,
41
+ SHOW_NUM_STEPS_3,
42
+ SHOW_UPSCALE_TO_256_BUTTON,
43
+ UPLOAD_REPO_ID,
44
+ UPLOAD_RESULT_IMAGE,
45
+ )
46
+ # isort: on
47
+
48
+ TITLE = '# [DeepFloyd IF](https://github.com/deep-floyd/IF)'
49
+ DESCRIPTION = 'The DeepFloyd IF model has been initially released as a non-commercial research-only model. Please make sure you read and abide to the [LICENSE](https://huggingface.co/spaces/DeepFloyd/deepfloyd-if-license) before using it.'
50
+ DISCLAIMER = 'In this demo, the DeepFloyd team may collect prompts, and user preferences (which of the images the user chose to upscale) for improving future models'
51
+ FOOTER = """<div class="footer">
52
+ <p>Model by <a href="https://huggingface.co/DeepFloyd" style="text-decoration: underline;" target="_blank">DeepFloyd</a> supported by <a href="https://huggingface.co/stabilityai" style="text-decoration: underline;" target="_blank">Stability AI</a>
53
+ </p>
54
+ </div>
55
+ <div class="acknowledgments">
56
+ <p><h4>LICENSE</h4>
57
+ The model is licensed with a bespoke non-commercial research-only license <a href="https://huggingface.co/spaces/DeepFloyd/deepfloyd-if-license" style="text-decoration: underline;" target="_blank">DeepFloyd IF Research License Agreement</a> license. The license forbids you from sharing any content for commercial use, or that violates any laws, produce any harm to a person, disseminate any personal information that would be meant for harm, spread misinformation and target vulnerable groups. For the full list of restrictions please <a href="https://huggingface.co/spaces/DeepFloyd/deepfloyd-if-license" style="text-decoration: underline;" target="_blank">read the license</a></p>
58
+ <p><h4>Biases and content acknowledgment</h4>
59
+ Despite how impressive being able to turn text into image is, beware to the fact that this model may output content that reinforces or exacerbates societal biases, as well as realistic faces, explicit content and violence. The model was trained on a subset of the <a href="https://laion.ai/blog/laion-5b/" style="text-decoration: underline;" target="_blank">LAION-5B dataset</a> and is meant for research purposes. You can read more in the <a href="https://huggingface.co/DeepFloyd/IF-I-IF-v1.0" style="text-decoration: underline;" target="_blank">model card</a></p>
60
+ </div>
61
+ """
62
+ if SHOW_DUPLICATE_BUTTON:
63
+ SPACE_ID = os.getenv('SPACE_ID')
64
+ DESCRIPTION += f'\n<p><a href="https://huggingface.co/spaces/{SPACE_ID}?duplicate=true"><img src="https://img.shields.io/badge/-Duplicate%20Space%20to%20skip%20the%20queue-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14" alt="Duplicate Space"></a></p>'
65
+
66
+ if SHOW_DEVICE_WARNING and not torch.cuda.is_available():
67
+ DESCRIPTION += '\n<p>Running on CPU 🥶 This demo does not work on CPU.</p>'
68
+
69
+ model = Model()
70
+
71
+
72
+ def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
73
+ if randomize_seed:
74
+ seed = random.randint(0, MAX_SEED)
75
+ return seed
76
+
77
+
78
+ def get_stage2_index(evt: gr.SelectData) -> int:
79
+ return evt.index
80
+
81
+
82
+ def check_if_stage2_selected(index: int) -> None:
83
+ if index == -1:
84
+ raise gr.Error(
85
+ 'You need to select the image you would like to upscale from the Stage 1 results by clicking.'
86
+ )
87
+
88
+
89
+ hf_api = HfApi(token=HF_TOKEN)
90
+ if UPLOAD_REPO_ID:
91
+ hf_api.create_repo(repo_id=UPLOAD_REPO_ID,
92
+ private=True,
93
+ repo_type='dataset',
94
+ exist_ok=True)
95
+
96
+
97
+ def get_param_file_hash_name(param_filepath: str) -> str:
98
+ if not UPLOAD_REPO_ID:
99
+ return ''
100
+ with open(param_filepath, 'rb') as f:
101
+ md5 = hashlib.md5(f.read()).hexdigest()
102
+ utcnow = datetime.datetime.utcnow().strftime('%Y-%m-%d-%H-%M-%S-%f')
103
+ return f'{utcnow}-{md5}'
104
+
105
+
106
+ def upload_stage1_result(stage1_param_path: str, stage1_result_path: str,
107
+ save_name: str) -> None:
108
+ if not UPLOAD_REPO_ID:
109
+ return
110
+ try:
111
+ folder_params = "tmp/results/stage1_params"
112
+ folder_results = "tmp/results/stage1_results"
113
+
114
+ path_params = f"{folder_params}/{save_name}.json"
115
+ path_results = f"{folder_results}/{save_name}.pth"
116
+
117
+ os.makedirs(folder_params, exist_ok=True)
118
+ os.makedirs(folder_results, exist_ok=True)
119
+
120
+ shutil.copy(stage1_param_path, path_params)
121
+ shutil.copy(stage1_result_path, path_results)
122
+
123
+ except Exception as e:
124
+ print(e)
125
+
126
+
127
+ def upload_stage2_info(stage1_param_file_hash_name: str,
128
+ stage2_output_path: str,
129
+ selected_index_for_upscale: int, seed_2: int,
130
+ guidance_scale_2: float, custom_timesteps_2: str,
131
+ num_inference_steps_2: int) -> None:
132
+ if not UPLOAD_REPO_ID:
133
+ return
134
+ if not stage1_param_file_hash_name:
135
+ raise ValueError
136
+
137
+ stage2_params = {
138
+ 'stage1_param_file_hash_name': stage1_param_file_hash_name,
139
+ 'selected_index_for_upscale': selected_index_for_upscale,
140
+ 'seed_2': seed_2,
141
+ 'guidance_scale_2': guidance_scale_2,
142
+ 'custom_timesteps_2': custom_timesteps_2,
143
+ 'num_inference_steps_2': num_inference_steps_2,
144
+ }
145
+ with tempfile.NamedTemporaryFile(mode='w', delete=False) as param_file:
146
+ param_file.write(json.dumps(stage2_params))
147
+ stage2_param_file_hash_name = get_param_file_hash_name(param_file.name)
148
+ save_name = f'{stage1_param_file_hash_name}_{stage2_param_file_hash_name}'
149
+
150
+ try:
151
+ folder_params = "tmp/results/stage2_params"
152
+
153
+ os.makedirs(folder_params, exist_ok=True)
154
+ path_params = f"{folder_params}/{save_name}.json"
155
+ shutil.copy(param_file.name, path_params)
156
+
157
+ if UPLOAD_RESULT_IMAGE:
158
+ folder_results = "tmp/results/stage2_results"
159
+ os.makedirs(folder_results, exist_ok=True)
160
+ path_results = f"{folder_results}/{save_name}.png"
161
+ shutil.copy(stage2_output_path, path_results)
162
+
163
+ except Exception as e:
164
+ print(e)
165
+
166
+
167
+ def upload_stage2_3_info(stage1_param_file_hash_name: str,
168
+ stage2_3_output_path: str,
169
+ selected_index_for_upscale: int, seed_2: int,
170
+ guidance_scale_2: float, custom_timesteps_2: str,
171
+ num_inference_steps_2: int, prompt: str,
172
+ negative_prompt: str, seed_3: int,
173
+ guidance_scale_3: float,
174
+ num_inference_steps_3: int) -> None:
175
+ if not UPLOAD_REPO_ID:
176
+ return
177
+ if not stage1_param_file_hash_name:
178
+ raise ValueError
179
+
180
+ stage2_3_params = {
181
+ 'stage1_param_file_hash_name': stage1_param_file_hash_name,
182
+ 'selected_index_for_upscale': selected_index_for_upscale,
183
+ 'seed_2': seed_2,
184
+ 'guidance_scale_2': guidance_scale_2,
185
+ 'custom_timesteps_2': custom_timesteps_2,
186
+ 'num_inference_steps_2': num_inference_steps_2,
187
+ 'prompt': prompt,
188
+ 'negative_prompt': negative_prompt,
189
+ 'seed_3': seed_3,
190
+ 'guidance_scale_3': guidance_scale_3,
191
+ 'num_inference_steps_3': num_inference_steps_3,
192
+ }
193
+ with tempfile.NamedTemporaryFile(mode='w', delete=False) as param_file:
194
+ param_file.write(json.dumps(stage2_3_params))
195
+ stage2_3_param_file_hash_name = get_param_file_hash_name(param_file.name)
196
+ save_name = f'{stage1_param_file_hash_name}_{stage2_3_param_file_hash_name}'
197
+
198
+ try:
199
+ folder_params = "tmp/results/stage2_3_params"
200
+ os.makedirs(folder_params, exist_ok=True)
201
+ path_params = f"{folder_params}/{save_name}.json"
202
+ shutil.copy(param_file.name, path_params)
203
+
204
+ if UPLOAD_RESULT_IMAGE:
205
+ folder_results = "tmp/results/stage2_3_results"
206
+ os.makedirs(folder_results, exist_ok=True)
207
+ path_results = f"{folder_results}/{save_name}.png"
208
+ shutil.copy(stage2_3_output_path, path_results)
209
+ except Exception as e:
210
+ print(e)
211
+
212
+
213
+ def update_upscale_button(selected_index: int) -> tuple[dict, dict]:
214
+ if selected_index == -1:
215
+ return gr.update(interactive=False), gr.update(interactive=False)
216
+ else:
217
+ return gr.update(interactive=True), gr.update(interactive=True)
218
+
219
+
220
+ def _update_result_view(show_gallery: bool) -> tuple[dict, dict]:
221
+ return gr.update(visible=show_gallery), gr.update(visible=not show_gallery)
222
+
223
+
224
+ def show_gallery_view() -> tuple[dict, dict]:
225
+ return _update_result_view(True)
226
+
227
+
228
+ def show_upscaled_view() -> tuple[dict, dict]:
229
+ return _update_result_view(False)
230
+
231
+ def upload_files():
232
+ """Zips files and uploads to dataset. Local data is deleted
233
+ """
234
+ if os.path.exists("tmp/results") and os.path.isdir("tmp/results"):
235
+ try:
236
+ random_folder = random.randint(0,1000)
237
+ shutil.make_archive("tmp/results", 'zip', "tmp/results")
238
+ hf_api.upload_file(
239
+ path_or_fileobj="tmp/results.zip",
240
+ path_in_repo=f"{random_folder}/results_{shortuuid.uuid()}.zip",
241
+ repo_id=UPLOAD_REPO_ID,
242
+ repo_type="dataset",
243
+ )
244
+ shutil.rmtree("tmp/results")
245
+ except Exception as e:
246
+ print(e)
247
+
248
+ examples = [
249
+ 'high quality dslr photo, a photo product of a lemon inspired by natural and organic materials, wooden accents, intricately decorated with glowing vines of led lights, inspired by baroque luxury',
250
+ 'paper quilling, extremely detailed, paper quilling of a nordic mountain landscape, 8k rendering',
251
+ 'letters made of candy on a plate that says "diet"',
252
+ 'a photo of a violet baseball cap with yellow text: "deep floyd". 50mm lens, photo realism, cine lens. violet baseball cap says "deep floyd". reflections, render. yellow stitch text "deep floyd"',
253
+ 'ultra close-up color photo portrait of rainbow owl with deer horns in the woods',
254
+ 'a cloth embroidered with the text "laion" and an embroidered cute baby lion face',
255
+ 'product image of a crochet Cthulhu the great old one emerging from a spacetime wormhole made of wool',
256
+ 'a little green budgie parrot driving small red toy car in new york street, photo',
257
+ 'origami dancer in white paper, 3d render, ultra-detailed, on white background, studio shot.',
258
+ 'glowing mushrooms in a natural environment with smoke in the frame',
259
+ 'a subway train\'s digital sign saying "open source", vsco preset, 35mm photo, film grain, in a dim subway station',
260
+ 'a bowl full of few adorable golden doodle puppies, the doodles dusted in powdered sugar and look delicious, bokeh, cannon. professional macro photo, super detailed. cute sweet golden doodle confectionery, baking puppies in powdered sugar in the bowl',
261
+ 'a face of a woman made completely out of foliage, twigs, leaves and flowers, side view'
262
+ ]
263
+
264
+ with gr.Blocks(css='style.css') as demo:
265
+ gr.Markdown(TITLE)
266
+ gr.Markdown(DESCRIPTION)
267
+ with gr.Box():
268
+ with gr.Row(elem_id='prompt-container').style(equal_height=True):
269
+ with gr.Column():
270
+ prompt = gr.Text(
271
+ label='Prompt',
272
+ show_label=False,
273
+ max_lines=1,
274
+ placeholder='Enter your prompt',
275
+ elem_id='prompt-text-input',
276
+ ).style(container=False)
277
+ negative_prompt = gr.Text(
278
+ label='Negative prompt',
279
+ show_label=False,
280
+ max_lines=1,
281
+ placeholder='Enter a negative prompt',
282
+ elem_id='negative-prompt-text-input',
283
+ ).style(container=False)
284
+ generate_button = gr.Button('Generate').style(full_width=False)
285
+
286
+ with gr.Column() as gallery_view:
287
+ gallery = gr.Gallery(label='Stage 1 results',
288
+ show_label=False,
289
+ elem_id='gallery').style(
290
+ columns=GALLERY_COLUMN_NUM,
291
+ object_fit='contain')
292
+ gr.Markdown('Pick your favorite generation to upscale.')
293
+ with gr.Row():
294
+ upscale_to_256_button = gr.Button(
295
+ 'Upscale to 256px',
296
+ visible=SHOW_UPSCALE_TO_256_BUTTON
297
+ or DISABLE_SD_X4_UPSCALER,
298
+ interactive=False)
299
+ upscale_button = gr.Button('Upscale',
300
+ interactive=False,
301
+ visible=not DISABLE_SD_X4_UPSCALER)
302
+ with gr.Column(visible=False) as upscale_view:
303
+ result = gr.Image(label='Result',
304
+ show_label=False,
305
+ type='filepath',
306
+ interactive=False,
307
+ elem_id='upscaled-image').style(height=640)
308
+ back_to_selection_button = gr.Button('Back to selection')
309
+ with gr.Group(elem_id="share-btn-container"):
310
+ community_icon = gr.HTML(community_icon_html)
311
+ loading_icon = gr.HTML(loading_icon_html)
312
+ share_button = gr.Button(
313
+ "Share to community", elem_id="share-btn")
314
+ share_button.click(None, [], [], _js=share_js)
315
+ with gr.Accordion('Advanced options',
316
+ open=False,
317
+ visible=SHOW_ADVANCED_OPTIONS):
318
+ with gr.Tabs():
319
+ with gr.Tab(label='Generation'):
320
+ seed_1 = gr.Slider(label='Seed',
321
+ minimum=0,
322
+ maximum=MAX_SEED,
323
+ step=1,
324
+ value=0)
325
+ randomize_seed_1 = gr.Checkbox(label='Randomize seed',
326
+ value=True)
327
+ guidance_scale_1 = gr.Slider(label='Guidance scale',
328
+ minimum=1,
329
+ maximum=20,
330
+ step=0.1,
331
+ value=7.0)
332
+ custom_timesteps_1 = gr.Dropdown(
333
+ label='Custom timesteps 1',
334
+ choices=[
335
+ 'none',
336
+ 'fast27',
337
+ 'smart27',
338
+ 'smart50',
339
+ 'smart100',
340
+ 'smart185',
341
+ ],
342
+ value=DEFAULT_CUSTOM_TIMESTEPS_1,
343
+ visible=SHOW_CUSTOM_TIMESTEPS_1)
344
+ num_inference_steps_1 = gr.Slider(
345
+ label='Number of inference steps',
346
+ minimum=1,
347
+ maximum=MAX_NUM_STEPS,
348
+ step=1,
349
+ value=100,
350
+ visible=SHOW_NUM_STEPS_1)
351
+ num_images = gr.Slider(label='Number of images',
352
+ minimum=1,
353
+ maximum=MAX_NUM_IMAGES,
354
+ step=1,
355
+ value=DEFAULT_NUM_IMAGES,
356
+ visible=SHOW_NUM_IMAGES)
357
+ with gr.Tab(label='Super-resolution 1'):
358
+ seed_2 = gr.Slider(label='Seed',
359
+ minimum=0,
360
+ maximum=MAX_SEED,
361
+ step=1,
362
+ value=0)
363
+ randomize_seed_2 = gr.Checkbox(label='Randomize seed',
364
+ value=True)
365
+ guidance_scale_2 = gr.Slider(label='Guidance scale',
366
+ minimum=1,
367
+ maximum=20,
368
+ step=0.1,
369
+ value=4.0)
370
+ custom_timesteps_2 = gr.Dropdown(
371
+ label='Custom timesteps 2',
372
+ choices=[
373
+ 'none',
374
+ 'fast27',
375
+ 'smart27',
376
+ 'smart50',
377
+ 'smart100',
378
+ 'smart185',
379
+ ],
380
+ value=DEFAULT_CUSTOM_TIMESTEPS_2,
381
+ visible=SHOW_CUSTOM_TIMESTEPS_2)
382
+ num_inference_steps_2 = gr.Slider(
383
+ label='Number of inference steps',
384
+ minimum=1,
385
+ maximum=MAX_NUM_STEPS,
386
+ step=1,
387
+ value=50,
388
+ visible=SHOW_NUM_STEPS_2)
389
+ with gr.Tab(label='Super-resolution 2'):
390
+ seed_3 = gr.Slider(label='Seed',
391
+ minimum=0,
392
+ maximum=MAX_SEED,
393
+ step=1,
394
+ value=0)
395
+ randomize_seed_3 = gr.Checkbox(label='Randomize seed',
396
+ value=True)
397
+ guidance_scale_3 = gr.Slider(label='Guidance scale',
398
+ minimum=1,
399
+ maximum=20,
400
+ step=0.1,
401
+ value=9.0)
402
+ num_inference_steps_3 = gr.Slider(
403
+ label='Number of inference steps',
404
+ minimum=1,
405
+ maximum=MAX_NUM_STEPS,
406
+ step=1,
407
+ value=DEFAULT_NUM_STEPS_3,
408
+ visible=SHOW_NUM_STEPS_3)
409
+
410
+ gr.Examples(examples=examples, inputs=prompt, examples_per_page=4)
411
+
412
+ with gr.Box(visible=DEBUG):
413
+ with gr.Row():
414
+ with gr.Accordion(label='Hidden params'):
415
+ stage1_param_path = gr.Text(label='Stage 1 param path')
416
+ stage1_result_path = gr.Text(label='Stage 1 result path')
417
+ stage1_param_file_hash_name = gr.Text(
418
+ label='Stage 1 param file hash name')
419
+ selected_index_for_stage2 = gr.Number(
420
+ label='Selected index for Stage 2', value=-1, precision=0)
421
+ gr.Markdown(DISCLAIMER)
422
+ gr.HTML(FOOTER)
423
+ stage1_inputs = [
424
+ prompt,
425
+ negative_prompt,
426
+ seed_1,
427
+ num_images,
428
+ guidance_scale_1,
429
+ custom_timesteps_1,
430
+ num_inference_steps_1,
431
+ ]
432
+ stage1_outputs = [
433
+ gallery,
434
+ stage1_param_path,
435
+ stage1_result_path,
436
+ ]
437
+
438
+ prompt.submit(
439
+ fn=randomize_seed_fn,
440
+ inputs=[seed_1, randomize_seed_1],
441
+ outputs=seed_1,
442
+ queue=False,
443
+ ).then(
444
+ fn=lambda: -1,
445
+ outputs=selected_index_for_stage2,
446
+ queue=False,
447
+ ).then(
448
+ fn=show_gallery_view,
449
+ outputs=[
450
+ gallery_view,
451
+ upscale_view,
452
+ ],
453
+ queue=False,
454
+ ).then(
455
+ fn=update_upscale_button,
456
+ inputs=selected_index_for_stage2,
457
+ outputs=[
458
+ upscale_button,
459
+ upscale_to_256_button,
460
+ ],
461
+ queue=False,
462
+ ).then(
463
+ fn=model.run_stage1,
464
+ inputs=stage1_inputs,
465
+ outputs=stage1_outputs,
466
+ ).success(
467
+ fn=get_param_file_hash_name,
468
+ inputs=stage1_param_path,
469
+ outputs=stage1_param_file_hash_name,
470
+ queue=False,
471
+ ).then(
472
+ fn=upload_stage1_result,
473
+ inputs=[
474
+ stage1_param_path,
475
+ stage1_result_path,
476
+ stage1_param_file_hash_name,
477
+ ],
478
+ queue=False,
479
+ )
480
+
481
+ negative_prompt.submit(
482
+ fn=randomize_seed_fn,
483
+ inputs=[seed_1, randomize_seed_1],
484
+ outputs=seed_1,
485
+ queue=False,
486
+ ).then(
487
+ fn=lambda: -1,
488
+ outputs=selected_index_for_stage2,
489
+ queue=False,
490
+ ).then(
491
+ fn=show_gallery_view,
492
+ outputs=[
493
+ gallery_view,
494
+ upscale_view,
495
+ ],
496
+ queue=False,
497
+ ).then(
498
+ fn=update_upscale_button,
499
+ inputs=selected_index_for_stage2,
500
+ outputs=[
501
+ upscale_button,
502
+ upscale_to_256_button,
503
+ ],
504
+ queue=False,
505
+ ).then(
506
+ fn=model.run_stage1,
507
+ inputs=stage1_inputs,
508
+ outputs=stage1_outputs,
509
+ ).success(
510
+ fn=get_param_file_hash_name,
511
+ inputs=stage1_param_path,
512
+ outputs=stage1_param_file_hash_name,
513
+ queue=False,
514
+ ).then(
515
+ fn=upload_stage1_result,
516
+ inputs=[
517
+ stage1_param_path,
518
+ stage1_result_path,
519
+ stage1_param_file_hash_name,
520
+ ],
521
+ queue=False,
522
+ )
523
+
524
+ generate_button.click(
525
+ fn=randomize_seed_fn,
526
+ inputs=[seed_1, randomize_seed_1],
527
+ outputs=seed_1,
528
+ queue=False,
529
+ ).then(
530
+ fn=lambda: -1,
531
+ outputs=selected_index_for_stage2,
532
+ queue=False,
533
+ ).then(
534
+ fn=show_gallery_view,
535
+ outputs=[
536
+ gallery_view,
537
+ upscale_view,
538
+ ],
539
+ queue=False,
540
+ ).then(
541
+ fn=update_upscale_button,
542
+ inputs=selected_index_for_stage2,
543
+ outputs=[
544
+ upscale_button,
545
+ upscale_to_256_button,
546
+ ],
547
+ queue=False,
548
+ ).then(
549
+ fn=model.run_stage1,
550
+ inputs=stage1_inputs,
551
+ outputs=stage1_outputs,
552
+ api_name='generate64',
553
+ ).success(
554
+ fn=get_param_file_hash_name,
555
+ inputs=stage1_param_path,
556
+ outputs=stage1_param_file_hash_name,
557
+ queue=False,
558
+ ).then(
559
+ fn=upload_stage1_result,
560
+ inputs=[
561
+ stage1_param_path,
562
+ stage1_result_path,
563
+ stage1_param_file_hash_name,
564
+ ],
565
+ queue=False,
566
+ )
567
+
568
+ gallery.select(
569
+ fn=get_stage2_index,
570
+ outputs=selected_index_for_stage2,
571
+ queue=False,
572
+ )
573
+
574
+ selected_index_for_stage2.change(
575
+ fn=update_upscale_button,
576
+ inputs=selected_index_for_stage2,
577
+ outputs=[
578
+ upscale_button,
579
+ upscale_to_256_button,
580
+ ],
581
+ queue=False,
582
+ )
583
+
584
+ stage2_inputs = [
585
+ stage1_result_path,
586
+ selected_index_for_stage2,
587
+ seed_2,
588
+ guidance_scale_2,
589
+ custom_timesteps_2,
590
+ num_inference_steps_2,
591
+ ]
592
+
593
+ upscale_to_256_button.click(
594
+ fn=check_if_stage2_selected,
595
+ inputs=selected_index_for_stage2,
596
+ queue=False,
597
+ ).then(
598
+ fn=randomize_seed_fn,
599
+ inputs=[seed_2, randomize_seed_2],
600
+ outputs=seed_2,
601
+ queue=False,
602
+ ).then(
603
+ fn=show_upscaled_view,
604
+ outputs=[
605
+ gallery_view,
606
+ upscale_view,
607
+ ],
608
+ queue=False,
609
+ ).then(
610
+ fn=model.run_stage2,
611
+ inputs=stage2_inputs,
612
+ outputs=result,
613
+ api_name='upscale256',
614
+ ).success(
615
+ fn=upload_stage2_info,
616
+ inputs=[
617
+ stage1_param_file_hash_name,
618
+ result,
619
+ selected_index_for_stage2,
620
+ seed_2,
621
+ guidance_scale_2,
622
+ custom_timesteps_2,
623
+ num_inference_steps_2,
624
+ ],
625
+ queue=False,
626
+ )
627
+
628
+ stage2_3_inputs = [
629
+ stage1_result_path,
630
+ selected_index_for_stage2,
631
+ seed_2,
632
+ guidance_scale_2,
633
+ custom_timesteps_2,
634
+ num_inference_steps_2,
635
+ prompt,
636
+ negative_prompt,
637
+ seed_3,
638
+ guidance_scale_3,
639
+ num_inference_steps_3,
640
+ ]
641
+
642
+ upscale_button.click(
643
+ fn=check_if_stage2_selected,
644
+ inputs=selected_index_for_stage2,
645
+ queue=False,
646
+ ).then(
647
+ fn=randomize_seed_fn,
648
+ inputs=[seed_2, randomize_seed_2],
649
+ outputs=seed_2,
650
+ queue=False,
651
+ ).then(
652
+ fn=randomize_seed_fn,
653
+ inputs=[seed_3, randomize_seed_3],
654
+ outputs=seed_3,
655
+ queue=False,
656
+ ).then(
657
+ fn=show_upscaled_view,
658
+ outputs=[
659
+ gallery_view,
660
+ upscale_view,
661
+ ],
662
+ queue=False,
663
+ ).then(
664
+ fn=model.run_stage2_3,
665
+ inputs=stage2_3_inputs,
666
+ outputs=result,
667
+ api_name='upscale1024',
668
+ ).success(
669
+ fn=upload_stage2_3_info,
670
+ inputs=[
671
+ stage1_param_file_hash_name,
672
+ result,
673
+ selected_index_for_stage2,
674
+ seed_2,
675
+ guidance_scale_2,
676
+ custom_timesteps_2,
677
+ num_inference_steps_2,
678
+ prompt,
679
+ negative_prompt,
680
+ seed_3,
681
+ guidance_scale_3,
682
+ num_inference_steps_3,
683
+ ],
684
+ queue=False,
685
+ )
686
+
687
+ back_to_selection_button.click(
688
+ fn=show_gallery_view,
689
+ outputs=[
690
+ gallery_view,
691
+ upscale_view,
692
+ ],
693
+ queue=False,
694
+ )
695
+
696
+ if UPLOAD_REPO_ID:
697
+ scheduler = BackgroundScheduler()
698
+ scheduler.add_job(func=upload_files, trigger="interval", seconds=60*20)
699
+ scheduler.start()
700
+
701
+ demo.queue(api_open=False, max_size=MAX_QUEUE_SIZE).launch(debug=DEBUG)
model.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import gc
4
+ import json
5
+ import tempfile
6
+ from typing import Generator
7
+
8
+ import numpy as np
9
+ import PIL.Image
10
+ import torch
11
+ from diffusers import DiffusionPipeline, StableDiffusionUpscalePipeline
12
+ from diffusers.pipelines.deepfloyd_if import (fast27_timesteps,
13
+ smart27_timesteps,
14
+ smart50_timesteps,
15
+ smart100_timesteps,
16
+ smart185_timesteps)
17
+
18
+ from settings import (DISABLE_AUTOMATIC_CPU_OFFLOAD, DISABLE_SD_X4_UPSCALER,
19
+ HF_TOKEN, MAX_NUM_IMAGES, MAX_NUM_STEPS, MAX_SEED,
20
+ RUN_GARBAGE_COLLECTION)
21
+
22
+
23
+ class Model:
24
+ def __init__(self):
25
+ self.device = torch.device(
26
+ 'cuda:0' if torch.cuda.is_available() else 'cpu')
27
+ self.pipe = None
28
+ self.super_res_1_pipe = None
29
+ self.super_res_2_pipe = None
30
+ self.watermark_image = None
31
+
32
+ if torch.cuda.is_available():
33
+ self.load_weights()
34
+ self.watermark_image = PIL.Image.fromarray(
35
+ self.pipe.watermarker.watermark_image.to(
36
+ torch.uint8).cpu().numpy(),
37
+ mode='RGBA')
38
+
39
+ def load_weights(self) -> None:
40
+ self.pipe = DiffusionPipeline.from_pretrained(
41
+ 'DeepFloyd/IF-I-XL-v1.0',
42
+ torch_dtype=torch.float16,
43
+ variant='fp16',
44
+ use_safetensors=True,
45
+ use_auth_token=HF_TOKEN)
46
+ self.super_res_1_pipe = DiffusionPipeline.from_pretrained(
47
+ 'DeepFloyd/IF-II-L-v1.0',
48
+ text_encoder=None,
49
+ torch_dtype=torch.float16,
50
+ variant='fp16',
51
+ use_safetensors=True,
52
+ use_auth_token=HF_TOKEN)
53
+
54
+ if not DISABLE_SD_X4_UPSCALER:
55
+ self.super_res_2_pipe = StableDiffusionUpscalePipeline.from_pretrained(
56
+ 'stabilityai/stable-diffusion-x4-upscaler',
57
+ torch_dtype=torch.float16)
58
+
59
+ if DISABLE_AUTOMATIC_CPU_OFFLOAD:
60
+ self.pipe.to(self.device)
61
+ self.super_res_1_pipe.to(self.device)
62
+
63
+ self.pipe.unet.to(memory_format=torch.channels_last)
64
+ self.pipe.unet = torch.compile(self.pipe.unet, mode="reduce-overhead", fullgraph=True)
65
+
66
+ if not DISABLE_SD_X4_UPSCALER:
67
+ self.super_res_2_pipe.to(self.device)
68
+ else:
69
+ self.pipe.enable_model_cpu_offload()
70
+ self.super_res_1_pipe.enable_model_cpu_offload()
71
+ if not DISABLE_SD_X4_UPSCALER:
72
+ self.super_res_2_pipe.enable_model_cpu_offload()
73
+
74
+ def apply_watermark_to_sd_x4_upscaler_results(
75
+ self, images: list[PIL.Image.Image]) -> None:
76
+ w, h = images[0].size
77
+
78
+ stability_x4_upscaler_sample_size = 128
79
+
80
+ coef = min(h / stability_x4_upscaler_sample_size,
81
+ w / stability_x4_upscaler_sample_size)
82
+ img_h, img_w = (int(h / coef), int(w / coef)) if coef < 1 else (h, w)
83
+
84
+ S1, S2 = 1024**2, img_w * img_h
85
+ K = (S2 / S1)**0.5
86
+ watermark_size = int(K * 62)
87
+ watermark_x = img_w - int(14 * K)
88
+ watermark_y = img_h - int(14 * K)
89
+
90
+ watermark_image = self.watermark_image.copy().resize(
91
+ (watermark_size, watermark_size),
92
+ PIL.Image.Resampling.BICUBIC,
93
+ reducing_gap=None)
94
+
95
+ for image in images:
96
+ image.paste(watermark_image,
97
+ box=(
98
+ watermark_x - watermark_size,
99
+ watermark_y - watermark_size,
100
+ watermark_x,
101
+ watermark_y,
102
+ ),
103
+ mask=watermark_image.split()[-1])
104
+
105
+ @staticmethod
106
+ def to_pil_images(images: torch.Tensor) -> list[PIL.Image.Image]:
107
+ images = (images / 2 + 0.5).clamp(0, 1)
108
+ images = images.cpu().permute(0, 2, 3, 1).float().numpy()
109
+ images = np.round(images * 255).astype(np.uint8)
110
+ return [PIL.Image.fromarray(image) for image in images]
111
+
112
+ @staticmethod
113
+ def check_seed(seed: int) -> None:
114
+ if not 0 <= seed <= MAX_SEED:
115
+ raise ValueError
116
+
117
+ @staticmethod
118
+ def check_num_images(num_images: int) -> None:
119
+ if not 1 <= num_images <= MAX_NUM_IMAGES:
120
+ raise ValueError
121
+
122
+ @staticmethod
123
+ def check_num_inference_steps(num_steps: int) -> None:
124
+ if not 1 <= num_steps <= MAX_NUM_STEPS:
125
+ raise ValueError
126
+
127
+ @staticmethod
128
+ def get_custom_timesteps(name: str) -> list[int] | None:
129
+ if name == 'none':
130
+ timesteps = None
131
+ elif name == 'fast27':
132
+ timesteps = fast27_timesteps
133
+ elif name == 'smart27':
134
+ timesteps = smart27_timesteps
135
+ elif name == 'smart50':
136
+ timesteps = smart50_timesteps
137
+ elif name == 'smart100':
138
+ timesteps = smart100_timesteps
139
+ elif name == 'smart185':
140
+ timesteps = smart185_timesteps
141
+ else:
142
+ raise ValueError
143
+ return timesteps
144
+
145
+ @staticmethod
146
+ def run_garbage_collection():
147
+ gc.collect()
148
+ torch.cuda.empty_cache()
149
+
150
+ def run_stage1(
151
+ self,
152
+ prompt: str,
153
+ negative_prompt: str = '',
154
+ seed: int = 0,
155
+ num_images: int = 1,
156
+ guidance_scale_1: float = 7.0,
157
+ custom_timesteps_1: str = 'smart100',
158
+ num_inference_steps_1: int = 100,
159
+ ) -> tuple[list[PIL.Image.Image], str, str]:
160
+ self.check_seed(seed)
161
+ self.check_num_images(num_images)
162
+ self.check_num_inference_steps(num_inference_steps_1)
163
+
164
+ if RUN_GARBAGE_COLLECTION:
165
+ self.run_garbage_collection()
166
+
167
+ generator = torch.Generator(device=self.device).manual_seed(seed)
168
+
169
+ prompt_embeds, negative_embeds = self.pipe.encode_prompt(
170
+ prompt=prompt, negative_prompt=negative_prompt)
171
+
172
+ timesteps = self.get_custom_timesteps(custom_timesteps_1)
173
+
174
+ images = self.pipe(prompt_embeds=prompt_embeds,
175
+ negative_prompt_embeds=negative_embeds,
176
+ num_images_per_prompt=num_images,
177
+ guidance_scale=guidance_scale_1,
178
+ timesteps=timesteps,
179
+ num_inference_steps=num_inference_steps_1,
180
+ generator=generator,
181
+ output_type='pt').images
182
+ pil_images = self.to_pil_images(images)
183
+ self.pipe.watermarker.apply_watermark(
184
+ pil_images, self.pipe.unet.config.sample_size)
185
+
186
+ stage1_params = {
187
+ 'prompt': prompt,
188
+ 'negative_prompt': negative_prompt,
189
+ 'seed': seed,
190
+ 'num_images': num_images,
191
+ 'guidance_scale_1': guidance_scale_1,
192
+ 'custom_timesteps_1': custom_timesteps_1,
193
+ 'num_inference_steps_1': num_inference_steps_1,
194
+ }
195
+ with tempfile.NamedTemporaryFile(mode='w', delete=False) as param_file:
196
+ param_file.write(json.dumps(stage1_params))
197
+ stage1_result = {
198
+ 'prompt_embeds': prompt_embeds,
199
+ 'negative_embeds': negative_embeds,
200
+ 'images': images,
201
+ 'pil_images': pil_images,
202
+ }
203
+ with tempfile.NamedTemporaryFile(delete=False) as result_file:
204
+ torch.save(stage1_result, result_file.name)
205
+ return pil_images, param_file.name, result_file.name
206
+
207
+ def run_stage2(
208
+ self,
209
+ stage1_result_path: str,
210
+ stage2_index: int,
211
+ seed_2: int = 0,
212
+ guidance_scale_2: float = 4.0,
213
+ custom_timesteps_2: str = 'smart50',
214
+ num_inference_steps_2: int = 50,
215
+ disable_watermark: bool = False,
216
+ ) -> PIL.Image.Image:
217
+ self.check_seed(seed_2)
218
+ self.check_num_inference_steps(num_inference_steps_2)
219
+
220
+ if RUN_GARBAGE_COLLECTION:
221
+ self.run_garbage_collection()
222
+
223
+ generator = torch.Generator(device=self.device).manual_seed(seed_2)
224
+
225
+ stage1_result = torch.load(stage1_result_path)
226
+ prompt_embeds = stage1_result['prompt_embeds']
227
+ negative_embeds = stage1_result['negative_embeds']
228
+ images = stage1_result['images']
229
+ images = images[[stage2_index]]
230
+
231
+ timesteps = self.get_custom_timesteps(custom_timesteps_2)
232
+
233
+ out = self.super_res_1_pipe(image=images,
234
+ prompt_embeds=prompt_embeds,
235
+ negative_prompt_embeds=negative_embeds,
236
+ num_images_per_prompt=1,
237
+ guidance_scale=guidance_scale_2,
238
+ timesteps=timesteps,
239
+ num_inference_steps=num_inference_steps_2,
240
+ generator=generator,
241
+ output_type='pt',
242
+ noise_level=250).images
243
+ pil_images = self.to_pil_images(out)
244
+
245
+ if disable_watermark:
246
+ return pil_images[0]
247
+
248
+ self.super_res_1_pipe.watermarker.apply_watermark(
249
+ pil_images, self.super_res_1_pipe.unet.config.sample_size)
250
+ return pil_images[0]
251
+
252
+ def run_stage3(
253
+ self,
254
+ image: PIL.Image.Image,
255
+ prompt: str = '',
256
+ negative_prompt: str = '',
257
+ seed_3: int = 0,
258
+ guidance_scale_3: float = 9.0,
259
+ num_inference_steps_3: int = 75,
260
+ ) -> PIL.Image.Image:
261
+ self.check_seed(seed_3)
262
+ self.check_num_inference_steps(num_inference_steps_3)
263
+
264
+ if RUN_GARBAGE_COLLECTION:
265
+ self.run_garbage_collection()
266
+
267
+ generator = torch.Generator(device=self.device).manual_seed(seed_3)
268
+ out = self.super_res_2_pipe(image=image,
269
+ prompt=prompt,
270
+ negative_prompt=negative_prompt,
271
+ num_images_per_prompt=1,
272
+ guidance_scale=guidance_scale_3,
273
+ num_inference_steps=num_inference_steps_3,
274
+ generator=generator,
275
+ noise_level=100).images
276
+ self.apply_watermark_to_sd_x4_upscaler_results(out)
277
+ return out[0]
278
+
279
+ def run_stage2_3(
280
+ self,
281
+ stage1_result_path: str,
282
+ stage2_index: int,
283
+ seed_2: int = 0,
284
+ guidance_scale_2: float = 4.0,
285
+ custom_timesteps_2: str = 'smart50',
286
+ num_inference_steps_2: int = 50,
287
+ prompt: str = '',
288
+ negative_prompt: str = '',
289
+ seed_3: int = 0,
290
+ guidance_scale_3: float = 9.0,
291
+ num_inference_steps_3: int = 75,
292
+ ) -> Generator[PIL.Image.Image]:
293
+ self.check_seed(seed_3)
294
+ self.check_num_inference_steps(num_inference_steps_3)
295
+
296
+ out_image = self.run_stage2(
297
+ stage1_result_path=stage1_result_path,
298
+ stage2_index=stage2_index,
299
+ seed_2=seed_2,
300
+ guidance_scale_2=guidance_scale_2,
301
+ custom_timesteps_2=custom_timesteps_2,
302
+ num_inference_steps_2=num_inference_steps_2,
303
+ disable_watermark=True)
304
+ temp_image = out_image.copy()
305
+ self.super_res_1_pipe.watermarker.apply_watermark(
306
+ [temp_image], self.super_res_1_pipe.unet.config.sample_size)
307
+ yield temp_image
308
+ yield self.run_stage3(image=out_image,
309
+ prompt=prompt,
310
+ negative_prompt=negative_prompt,
311
+ seed_3=seed_3,
312
+ guidance_scale_3=guidance_scale_3,
313
+ num_inference_steps_3=num_inference_steps_3)
requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate==0.18.0
2
+ beautifulsoup4==4.12.2
3
+ bitsandbytes==0.38.1
4
+ git+https://github.com/huggingface/diffusers
5
+ ftfy==6.1.1
6
+ gradio==3.27.0
7
+ huggingface_hub==0.14.1
8
+ numpy==1.24.3
9
+ Pillow==9.5.0
10
+ safetensors==0.3.0
11
+ sentencepiece==0.1.98
12
+ tokenizers==0.13.3
13
+ tqdm==4.65.0
14
+ transformers==4.28.1
15
+ shortuuid==1.0.11
16
+ apscheduler==3.10.1
settings.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import numpy as np
4
+
5
+ HF_TOKEN = os.getenv('HF_TOKEN')
6
+ UPLOAD_REPO_ID = os.getenv('UPLOAD_REPO_ID')
7
+ UPLOAD_RESULT_IMAGE = os.getenv('UPLOAD_RESULT_IMAGE') == '1'
8
+
9
+ # UI options
10
+ SHOW_DUPLICATE_BUTTON = os.getenv('SHOW_DUPLICATE_BUTTON', '0') == '1'
11
+ SHOW_DEVICE_WARNING = os.getenv('SHOW_DEVICE_WARNING', '1') == '1'
12
+ SHOW_ADVANCED_OPTIONS = os.getenv('SHOW_ADVANCED_OPTIONS', '1') == '1'
13
+ SHOW_UPSCALE_TO_256_BUTTON = os.getenv('SHOW_UPSCALE_TO_256_BUTTON',
14
+ '0') == '1'
15
+ SHOW_NUM_IMAGES = os.getenv('SHOW_NUM_IMAGES_OPTION', '1') == '1'
16
+ SHOW_CUSTOM_TIMESTEPS_1 = os.getenv('SHOW_CUSTOM_TIMESTEPS_1', '1') == '1'
17
+ SHOW_CUSTOM_TIMESTEPS_2 = os.getenv('SHOW_CUSTOM_TIMESTEPS_2', '1') == '1'
18
+ SHOW_NUM_STEPS_1 = os.getenv('SHOW_NUM_STEPS_1', '0') == '1'
19
+ SHOW_NUM_STEPS_2 = os.getenv('SHOW_NUM_STEPS_2', '0') == '1'
20
+ SHOW_NUM_STEPS_3 = os.getenv('SHOW_NUM_STEPS_3', '1') == '1'
21
+ GALLERY_COLUMN_NUM = int(os.getenv('GALLERY_COLUMN_NUM', '4'))
22
+
23
+ # Parameters
24
+ MAX_QUEUE_SIZE = int(os.getenv('MAX_QUEUE_SIZE', '10'))
25
+ MAX_SEED = np.iinfo(np.int32).max
26
+ MAX_NUM_IMAGES = int(os.getenv('MAX_NUM_IMAGES', '4'))
27
+ DEFAULT_NUM_IMAGES = min(MAX_NUM_IMAGES,
28
+ int(os.getenv('DEFAULT_NUM_IMAGES', '4')))
29
+ MAX_NUM_STEPS = int(os.getenv('MAX_NUM_STEPS', '200'))
30
+ DEFAULT_CUSTOM_TIMESTEPS_1 = os.getenv('DEFAULT_CUSTOM_TIMESTEPS_1',
31
+ 'smart100')
32
+ DEFAULT_CUSTOM_TIMESTEPS_2 = os.getenv('DEFAULT_CUSTOM_TIMESTEPS_2', 'smart50')
33
+ DEFAULT_NUM_STEPS_3 = int(os.getenv('DEFAULT_NUM_STEPS_3', '40'))
34
+
35
+ # Model options
36
+ DISABLE_AUTOMATIC_CPU_OFFLOAD = os.getenv(
37
+ 'DISABLE_AUTOMATIC_CPU_OFFLOAD') == '1'
38
+ DISABLE_SD_X4_UPSCALER = os.getenv('DISABLE_SD_X4_UPSCALER') == '1'
39
+
40
+ # Other options
41
+ RUN_GARBAGE_COLLECTION = os.getenv('RUN_GARBAGE_COLLECTION', '1') == '1'
42
+ DEBUG = os.getenv('DEBUG') == '1'
43
+
44
+ # Default options for the public demo
45
+ if os.getenv('IS_PUBLIC_DEMO') == '1':
46
+ # UI
47
+ SHOW_DUPLICATE_BUTTON = True
48
+ SHOW_NUM_STEPS_3 = False
49
+ SHOW_CUSTOM_TIMESTEPS_1 = False
50
+ SHOW_CUSTOM_TIMESTEPS_2 = False
51
+ SHOW_NUM_IMAGES = False
52
+ # parameters
53
+ DEFAULT_CUSTOM_TIMESTEPS_1 = 'smart50'
54
+ UPLOAD_RESULT_IMAGE = True
55
+ # model
56
+ DISABLE_AUTOMATIC_CPU_OFFLOAD = True
57
+ RUN_GARBAGE_COLLECTION = False
share_btn.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ community_icon_html = """<svg id="share-btn-share-icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32">
2
+ <path d="M20.6081 3C21.7684 3 22.8053 3.49196 23.5284 4.38415C23.9756 4.93678 24.4428 5.82749 24.4808 7.16133C24.9674 7.01707 25.4353 6.93643 25.8725 6.93643C26.9833 6.93643 27.9865 7.37587 28.696 8.17411C29.6075 9.19872 30.0124 10.4579 29.8361 11.7177C29.7523 12.3177 29.5581 12.8555 29.2678 13.3534C29.8798 13.8646 30.3306 14.5763 30.5485 15.4322C30.719 16.1032 30.8939 17.5006 29.9808 18.9403C30.0389 19.0342 30.0934 19.1319 30.1442 19.2318C30.6932 20.3074 30.7283 21.5229 30.2439 22.6548C29.5093 24.3704 27.6841 25.7219 24.1397 27.1727C21.9347 28.0753 19.9174 28.6523 19.8994 28.6575C16.9842 29.4379 14.3477 29.8345 12.0653 29.8345C7.87017 29.8345 4.8668 28.508 3.13831 25.8921C0.356375 21.6797 0.754104 17.8269 4.35369 14.1131C6.34591 12.058 7.67023 9.02782 7.94613 8.36275C8.50224 6.39343 9.97271 4.20438 12.4172 4.20438H12.4179C12.6236 4.20438 12.8314 4.2214 13.0364 4.25468C14.107 4.42854 15.0428 5.06476 15.7115 6.02205C16.4331 5.09583 17.134 4.359 17.7682 3.94323C18.7242 3.31737 19.6794 3 20.6081 3ZM20.6081 5.95917C20.2427 5.95917 19.7963 6.1197 19.3039 6.44225C17.7754 7.44319 14.8258 12.6772 13.7458 14.7131C13.3839 15.3952 12.7655 15.6837 12.2086 15.6837C11.1036 15.6837 10.2408 14.5497 12.1076 13.1085C14.9146 10.9402 13.9299 7.39584 12.5898 7.1776C12.5311 7.16799 12.4731 7.16355 12.4172 7.16355C11.1989 7.16355 10.6615 9.33114 10.6615 9.33114C10.6615 9.33114 9.0863 13.4148 6.38031 16.206C3.67434 18.998 3.5346 21.2388 5.50675 24.2246C6.85185 26.2606 9.42666 26.8753 12.0653 26.8753C14.8021 26.8753 17.6077 26.2139 19.1799 25.793C19.2574 25.7723 28.8193 22.984 27.6081 20.6107C27.4046 20.212 27.0693 20.0522 26.6471 20.0522C24.9416 20.0522 21.8393 22.6726 20.5057 22.6726C20.2076 22.6726 19.9976 22.5416 19.9116 22.222C19.3433 20.1173 28.552 19.2325 27.7758 16.1839C27.639 15.6445 27.2677 15.4256 26.746 15.4263C24.4923 15.4263 19.4358 19.5181 18.3759 19.5181C18.2949 19.5181 18.2368 19.4937 18.2053 19.4419C17.6743 18.557 17.9653 17.9394 21.7082 15.6009C25.4511 13.2617 28.0783 11.8545 26.5841 10.1752C26.4121 9.98141 26.1684 9.8956 25.8725 9.8956C23.6001 9.89634 18.2311 14.9403 18.2311 14.9403C18.2311 14.9403 16.7821 16.496 15.9057 16.496C15.7043 16.496 15.533 16.4139 15.4169 16.2112C14.7956 15.1296 21.1879 10.1286 21.5484 8.06535C21.7928 6.66715 21.3771 5.95917 20.6081 5.95917Z" fill="#FF9D00"></path>
3
+ <path d="M5.50686 24.2246C3.53472 21.2387 3.67446 18.9979 6.38043 16.206C9.08641 13.4147 10.6615 9.33111 10.6615 9.33111C10.6615 9.33111 11.2499 6.95933 12.59 7.17757C13.93 7.39581 14.9139 10.9401 12.1069 13.1084C9.29997 15.276 12.6659 16.7489 13.7459 14.713C14.8258 12.6772 17.7747 7.44316 19.304 6.44221C20.8326 5.44128 21.9089 6.00204 21.5484 8.06532C21.188 10.1286 14.795 15.1295 15.4171 16.2118C16.0391 17.2934 18.2312 14.9402 18.2312 14.9402C18.2312 14.9402 25.0907 8.49588 26.5842 10.1752C28.0776 11.8545 25.4512 13.2616 21.7082 15.6008C17.9646 17.9393 17.6744 18.557 18.2054 19.4418C18.7372 20.3266 26.9998 13.1351 27.7759 16.1838C28.5513 19.2324 19.3434 20.1173 19.9117 22.2219C20.48 24.3274 26.3979 18.2382 27.6082 20.6107C28.8193 22.9839 19.2574 25.7722 19.18 25.7929C16.0914 26.62 8.24723 28.3726 5.50686 24.2246Z" fill="#FFD21E"></path>
4
+ </svg>"""
5
+
6
+ loading_icon_html = """<svg id="share-btn-loading-icon" style="display:none;" class="animate-spin" style="color: #ffffff;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" fill="none" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><circle style="opacity: 0.25;" cx="12" cy="12" r="10" stroke="white" stroke-width="4"></circle><path style="opacity: 0.75;" fill="white" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>"""
7
+
8
+ share_js = """async () => {
9
+ async function uploadFile(file){
10
+ const UPLOAD_URL = 'https://huggingface.co/uploads';
11
+ const response = await fetch(UPLOAD_URL, {
12
+ method: 'POST',
13
+ headers: {
14
+ 'Content-Type': file.type,
15
+ 'X-Requested-With': 'XMLHttpRequest',
16
+ },
17
+ body: file, /// <- File inherits from Blob
18
+ });
19
+ const url = await response.text();
20
+ return url;
21
+ }
22
+ async function getInputImageFile(imageEl){
23
+ const res = await fetch(imageEl.src);
24
+ const blob = await res.blob();
25
+ const imageId = Date.now();
26
+ const fileName = `rich-text-image-${{imageId}}.png`;
27
+ return new File([blob], fileName, { type: 'image/png'});
28
+ }
29
+ const gradioEl = document.querySelector("gradio-app").shadowRoot || document.querySelector('body > gradio-app');
30
+ const negative_prompt = gradioEl.querySelector('#negative-prompt-text-input input').value;
31
+ const prompt = gradioEl.querySelector('#prompt-text-input input').value;
32
+ const upscaledImage = gradioEl.querySelector('#upscaled-image img');
33
+
34
+ const titleTxt = `DeepFloyd IF: ${prompt.slice(0, 50)}...`;
35
+
36
+ const shareBtnEl = gradioEl.querySelector('#share-btn');
37
+ const shareIconEl = gradioEl.querySelector('#share-btn-share-icon');
38
+ const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon');
39
+ if(!upscaledImage){
40
+ return;
41
+ };
42
+ shareBtnEl.style.pointerEvents = 'none';
43
+ shareIconEl.style.display = 'none';
44
+ loadingIconEl.style.removeProperty('display');
45
+
46
+ const upscaledImageFile = await getInputImageFile(upscaledImage);
47
+ const upscaledImageURL = await uploadFile(upscaledImageFile);
48
+
49
+ const descriptionMd = `
50
+ ### Prompt
51
+ ${prompt}
52
+
53
+ ### Negative Prompt
54
+ ${negative_prompt}
55
+
56
+ ### Upscaled Image
57
+ <img src="${upscaledImageURL}" alt="Upscaled Image" width="500"/>
58
+
59
+ `;
60
+ const params = new URLSearchParams({
61
+ title: titleTxt,
62
+ description: descriptionMd,
63
+ });
64
+ const paramsStr = params.toString();
65
+ window.open(`https://huggingface.co/spaces/DeepFloyd/IF/discussions/new?${paramsStr}`, '_blank');
66
+ shareBtnEl.style.removeProperty('pointer-events');
67
+ shareIconEl.style.removeProperty('display');
68
+ loadingIconEl.style.display = 'none';
69
+ }"""
style.css ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ This CSS file is modified from:
3
+ https://huggingface.co/spaces/stabilityai/stable-diffusion/blob/2794a3c3ba66115c307075098e713f572b08bf80/app.py
4
+ */
5
+
6
+ h1 {
7
+ text-align: center;
8
+ }
9
+
10
+ .gradio-container {
11
+ font-family: 'IBM Plex Sans', sans-serif;
12
+ }
13
+
14
+ .gr-button {
15
+ color: white;
16
+ border-color: black;
17
+ background: black;
18
+ }
19
+
20
+ input[type='range'] {
21
+ accent-color: black;
22
+ }
23
+
24
+ .dark input[type='range'] {
25
+ accent-color: #dfdfdf;
26
+ }
27
+
28
+ .container {
29
+ max-width: 730px;
30
+ margin: auto;
31
+ padding-top: 1.5rem;
32
+ }
33
+
34
+ #gallery {
35
+ min-height: auto;
36
+ height: 185px;
37
+ margin-top: 15px;
38
+ margin-left: auto;
39
+ margin-right: auto;
40
+ border-bottom-right-radius: .5rem !important;
41
+ border-bottom-left-radius: .5rem !important;
42
+ }
43
+ #gallery .grid-wrap, #gallery .empty{
44
+ height: 185px;
45
+ min-height: 185px;
46
+ }
47
+ #gallery .preview{
48
+ height: 185px;
49
+ min-height: 185px!important;
50
+ }
51
+ #gallery>div>.h-full {
52
+ min-height: 20rem;
53
+ }
54
+
55
+ .details:hover {
56
+ text-decoration: underline;
57
+ }
58
+
59
+ .gr-button {
60
+ white-space: nowrap;
61
+ }
62
+
63
+ .gr-button:focus {
64
+ border-color: rgb(147 197 253 / var(--tw-border-opacity));
65
+ outline: none;
66
+ box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000);
67
+ --tw-border-opacity: 1;
68
+ --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
69
+ --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px var(--tw-ring-offset-width)) var(--tw-ring-color);
70
+ --tw-ring-color: rgb(191 219 254 / var(--tw-ring-opacity));
71
+ --tw-ring-opacity: .5;
72
+ }
73
+
74
+ #advanced-btn {
75
+ font-size: .7rem !important;
76
+ line-height: 19px;
77
+ margin-top: 12px;
78
+ margin-bottom: 12px;
79
+ padding: 2px 8px;
80
+ border-radius: 14px !important;
81
+ }
82
+
83
+ #advanced-options {
84
+ display: none;
85
+ margin-bottom: 20px;
86
+ }
87
+
88
+ .footer {
89
+ margin-bottom: 45px;
90
+ margin-top: 35px;
91
+ text-align: center;
92
+ border-bottom: 1px solid #e5e5e5;
93
+ }
94
+
95
+ .footer>p {
96
+ font-size: .8rem;
97
+ display: inline-block;
98
+ padding: 0 10px;
99
+ transform: translateY(10px);
100
+ background: white;
101
+ }
102
+
103
+ .dark .footer {
104
+ border-color: #303030;
105
+ }
106
+
107
+ .dark .footer>p {
108
+ background: #0b0f19;
109
+ }
110
+
111
+ .acknowledgments h4 {
112
+ margin: 1.25em 0 .25em 0;
113
+ font-weight: bold;
114
+ font-size: 115%;
115
+ }
116
+
117
+ .animate-spin {
118
+ animation: spin 1s linear infinite;
119
+ }
120
+
121
+ @keyframes spin {
122
+ from {
123
+ transform: rotate(0deg);
124
+ }
125
+
126
+ to {
127
+ transform: rotate(360deg);
128
+ }
129
+ }
130
+
131
+ #share-btn-container {
132
+ display: flex;
133
+ padding-left: 0.5rem !important;
134
+ padding-right: 0.5rem !important;
135
+ background-color: #000000;
136
+ justify-content: center;
137
+ align-items: center;
138
+ border-radius: 9999px !important;
139
+ width: 13rem;
140
+ margin-top: 10px;
141
+ margin-left: auto;
142
+ }
143
+
144
+ #share-btn {
145
+ all: initial;
146
+ color: #ffffff;
147
+ font-weight: 600;
148
+ cursor: pointer;
149
+ font-family: 'IBM Plex Sans', sans-serif;
150
+ margin-left: 0.5rem !important;
151
+ padding-top: 0.25rem !important;
152
+ padding-bottom: 0.25rem !important;
153
+ right: 0;
154
+ }
155
+
156
+ #share-btn * {
157
+ all: unset;
158
+ }
159
+
160
+ #share-btn-container div:nth-child(-n+2) {
161
+ width: auto !important;
162
+ min-height: 0px !important;
163
+ }
164
+
165
+ #share-btn-container .wrap {
166
+ display: none !important;
167
+ }
168
+
169
+ .gr-form {
170
+ flex: 1 1 50%;
171
+ border-top-right-radius: 0;
172
+ border-bottom-right-radius: 0;
173
+ }
174
+
175
+ #prompt-container {
176
+ gap: 0;
177
+ }
178
+
179
+ #prompt-text-input,
180
+ #negative-prompt-text-input {
181
+ padding: .45rem 0.625rem
182
+ }
183
+
184
+ #component-16 {
185
+ border-top-width: 1px !important;
186
+ margin-top: 1em
187
+ }
188
+
189
+ .image_duplication {
190
+ position: absolute;
191
+ width: 100px;
192
+ left: 50px
193
+ }
194
+
195
+ #component-0 {
196
+ max-width: 730px;
197
+ margin: auto;
198
+ padding-top: 1.5rem;
199
+ }
200
+
201
+ #upscaled-image img {
202
+ object-fit: scale-down;
203
+ }
204
+ /* share button */
205
+ #share-btn-container {
206
+ display: flex;
207
+ padding-left: 0.5rem !important;
208
+ padding-right: 0.5rem !important;
209
+ background-color: #000000;
210
+ justify-content: center;
211
+ align-items: center;
212
+ border-radius: 9999px !important;
213
+ width: 13rem;
214
+ margin-top: 10px;
215
+ margin-left: auto;
216
+ flex: unset !important;
217
+ }
218
+ #share-btn {
219
+ all: initial;
220
+ color: #ffffff;
221
+ font-weight: 600;
222
+ cursor: pointer;
223
+ font-family: 'IBM Plex Sans', sans-serif;
224
+ margin-left: 0.5rem !important;
225
+ padding-top: 0.25rem !important;
226
+ padding-bottom: 0.25rem !important;
227
+ right:0;
228
+ }
229
+ #share-btn * {
230
+ all: unset !important;
231
+ }
232
+ #share-btn-container div:nth-child(-n+2){
233
+ width: auto !important;
234
+ min-height: 0px !important;
235
+ }
236
+ #share-btn-container .wrap {
237
+ display: none !important;
238
+ }