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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import datetime
|
2 |
+
import os
|
3 |
+
import re
|
4 |
+
import gc
|
5 |
+
import json
|
6 |
+
import time
|
7 |
+
import base64
|
8 |
+
import io
|
9 |
+
import tempfile
|
10 |
+
import zipfile
|
11 |
+
import PIL
|
12 |
+
from dataclasses import dataclass
|
13 |
+
from io import BytesIO
|
14 |
+
def sanitize_filename(filename):
|
15 |
+
"""Sanitizes a filename by replacing special characters with underscores"""
|
16 |
+
return re.sub(r'[\\/*?:"<>|]', "_", filename)
|
17 |
+
|
18 |
+
from typing import Optional, Literal, Union
|
19 |
+
from diffusers import DiffusionPipeline, DDIMScheduler
|
20 |
+
HF_TOKEN = os.environ.get("HF_TOKEN")
|
21 |
+
import streamlit as st
|
22 |
+
st.set_page_config(layout="wide")
|
23 |
+
import torch
|
24 |
+
from diffusers import (
|
25 |
+
StableDiffusionPipeline,
|
26 |
+
EulerDiscreteScheduler,
|
27 |
+
StableDiffusionInpaintPipeline,
|
28 |
+
StableDiffusionImg2ImgPipeline,
|
29 |
+
)
|
30 |
+
from PIL import Image
|
31 |
+
from PIL.PngImagePlugin import PngInfo
|
32 |
+
|
33 |
+
from datetime import datetime
|
34 |
+
from threading import Thread
|
35 |
+
|
36 |
+
import requests
|
37 |
+
|
38 |
+
from huggingface_hub import HfApi
|
39 |
+
from huggingface_hub.utils._errors import RepositoryNotFoundError
|
40 |
+
from huggingface_hub.utils._validators import HFValidationError
|
41 |
+
from loguru import logger
|
42 |
+
from PIL.PngImagePlugin import PngInfo
|
43 |
+
from st_clickable_images import clickable_images
|
44 |
+
|
45 |
+
import streamlit.components.v1 as components
|
46 |
+
|
47 |
+
prefix = 'image_generation'
|
48 |
+
|
49 |
+
def dict_to_style(d):
|
50 |
+
return ';'.join(f'{k}:{v}' for k, v in d.items())
|
51 |
+
|
52 |
+
def clickable_images(images, titles, div_style={}, img_style={}):
|
53 |
+
"""Generates a component with clickable images"""
|
54 |
+
img_tag = "".join(
|
55 |
+
f'<a href="{img}" target="_blank"><img src="{img}" title="{title}" style="{dict_to_style(img_style)}"></a>'
|
56 |
+
for img, title in zip(images, titles)
|
57 |
+
)
|
58 |
+
return components.html(f'<div style="{dict_to_style(div_style)}">{img_tag}</div>', scrolling=True)
|
59 |
+
|
60 |
+
def display_and_download_images(output_images, metadata):
|
61 |
+
with st.spinner("Preparing images..."):
|
62 |
+
# save images to a temporary directory
|
63 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
64 |
+
gallery_images = []
|
65 |
+
for i, image in enumerate(output_images):
|
66 |
+
image.save(os.path.join(tmpdir, f"{i + 1}.png"), pnginfo=metadata)
|
67 |
+
with open(os.path.join(tmpdir, f"{i + 1}.png"), "rb") as img:
|
68 |
+
encoded = base64.b64encode(img.read()).decode()
|
69 |
+
gallery_images.append(f"data:image/png;base64,{encoded}")
|
70 |
+
|
71 |
+
_ = clickable_images(
|
72 |
+
gallery_images,
|
73 |
+
titles=[f"Image #{str(i + 1)}" for i in range(len(gallery_images))],
|
74 |
+
div_style={"display": "flex", "justify-content": "center", "flex-wrap": "wrap"},
|
75 |
+
img_style={"margin": "5px", "height": "200px"},
|
76 |
+
)
|
77 |
+
|
78 |
+
|
79 |
+
PIPELINE_NAMES = Literal["txt2img", "inpaint", "img2img"]
|
80 |
+
|
81 |
+
DEFAULT_PROMPT = "a sprinkled donut sitting on top of a purple cherry apple with ice cubes, colorful hyperrealism, digital explosion of vibrant colors and abstract digital elements"
|
82 |
+
DEFAULT_WIDTH, DEFAULT_HEIGHT = 512, 512
|
83 |
+
OUTPUT_IMAGE_KEY = "output_img"
|
84 |
+
LOADED_IMAGE_KEY = "loaded_image"
|
85 |
+
|
86 |
+
|
87 |
+
|
88 |
+
def get_image(key: str) -> Optional[Image.Image]:
|
89 |
+
if key in st.session_state:
|
90 |
+
return st.session_state[key]
|
91 |
+
return None
|
92 |
+
|
93 |
+
|
94 |
+
def set_image(key: str, img: Image.Image):
|
95 |
+
st.session_state[key] = img
|
96 |
+
|
97 |
+
|
98 |
+
@st.cache_resource(max_entries=1)
|
99 |
+
def get_pipeline(
|
100 |
+
name: PIPELINE_NAMES,
|
101 |
+
) -> Union[
|
102 |
+
StableDiffusionPipeline,
|
103 |
+
StableDiffusionImg2ImgPipeline,
|
104 |
+
StableDiffusionInpaintPipeline,
|
105 |
+
]:
|
106 |
+
if name in ["txt2img", "img2img"]:
|
107 |
+
model_id = "FFusion/FFusion-BaSE"
|
108 |
+
|
109 |
+
pipeline = DiffusionPipeline.from_pretrained(model_id)
|
110 |
+
# switch the scheduler in the pipeline to use the DDIMScheduler
|
111 |
+
pipeline.scheduler = DDIMScheduler.from_config(
|
112 |
+
pipeline.scheduler.config, rescale_betas_zero_snr=True, timestep_spacing="trailing"
|
113 |
+
)
|
114 |
+
pipeline = pipeline.to("cuda")
|
115 |
+
return pipeline
|
116 |
+
|
117 |
+
|
118 |
+
def generate(
|
119 |
+
prompt,
|
120 |
+
pipeline_name: PIPELINE_NAMES,
|
121 |
+
num_images=1,
|
122 |
+
negative_prompt=None,
|
123 |
+
steps=22,
|
124 |
+
width=896,
|
125 |
+
height=1024,
|
126 |
+
guidance_scale=6,
|
127 |
+
enable_attention_slicing=True,
|
128 |
+
enable_xformers=True
|
129 |
+
):
|
130 |
+
"""Generates an image based on the given prompt and pipeline name"""
|
131 |
+
negative_prompt = negative_prompt if negative_prompt else None
|
132 |
+
p = st.progress(0)
|
133 |
+
callback = lambda step, *_: p.progress(step / steps)
|
134 |
+
|
135 |
+
pipe = get_pipeline(pipeline_name)
|
136 |
+
torch.cuda.empty_cache()
|
137 |
+
|
138 |
+
if enable_attention_slicing:
|
139 |
+
pipe.enable_attention_slicing()
|
140 |
+
else:
|
141 |
+
pipe.disable_attention_slicing()
|
142 |
+
|
143 |
+
if enable_xformers:
|
144 |
+
pipe.enable_xformers_memory_efficient_attention()
|
145 |
+
|
146 |
+
kwargs = dict(
|
147 |
+
prompt=prompt,
|
148 |
+
negative_prompt=negative_prompt,
|
149 |
+
num_inference_steps=steps,
|
150 |
+
callback=callback,
|
151 |
+
guidance_scale=guidance_scale,
|
152 |
+
guidance_rescale=0.7
|
153 |
+
)
|
154 |
+
print("kwargs", kwargs)
|
155 |
+
|
156 |
+
if pipeline_name == "txt2img":
|
157 |
+
kwargs.update(width=width, height=height)
|
158 |
+
|
159 |
+
elif pipeline_name in ["inpaint", "img2img"]:
|
160 |
+
kwargs.update(image_input=image_input)
|
161 |
+
|
162 |
+
else:
|
163 |
+
raise Exception(
|
164 |
+
f"Cannot generate image for pipeline {pipeline_name} and {prompt}"
|
165 |
+
)
|
166 |
+
|
167 |
+
output_images = [] # list to hold output image objects
|
168 |
+
for _ in range(num_images): # loop over number of images
|
169 |
+
result = pipe(**kwargs) # generate one image at a time
|
170 |
+
images = result.images
|
171 |
+
for i, image in enumerate(images): # loop over each image
|
172 |
+
filename = (
|
173 |
+
"data/"
|
174 |
+
+ sanitize_filename(re.sub(r"\s+", "_", prompt)[:50])
|
175 |
+
+ f"_{i}_{datetime.now().timestamp()}"
|
176 |
+
)
|
177 |
+
image.save(f"{filename}.png")
|
178 |
+
output_images.append(image) # add the image object to the list
|
179 |
+
|
180 |
+
for image in output_images:
|
181 |
+
with open(f"{filename}.txt", "w") as f:
|
182 |
+
f.write(prompt)
|
183 |
+
|
184 |
+
return output_images # return the list of image objects
|
185 |
+
|
186 |
+
|
187 |
+
|
188 |
+
def prompt_and_generate_button(prefix, pipeline_name: PIPELINE_NAMES, **kwargs):
|
189 |
+
prompt = st.text_area(
|
190 |
+
"Prompt",
|
191 |
+
value=DEFAULT_PROMPT,
|
192 |
+
key=f"{prefix}-prompt",
|
193 |
+
)
|
194 |
+
negative_prompt = st.text_area(
|
195 |
+
"Negative prompt",
|
196 |
+
value="(disfigured), bad quality, ((bad art)), ((deformed)), ((extra limbs)), (((duplicate))), ((morbid)), (((ugly)), blurry, ((bad anatomy)), (((bad proportions))), cloned face, body out of frame, out of frame, bad anatomy, gross proportions, (malformed limbs), ((missing arms)), ((missing legs)), (((extra arms))), (((extra legs))), (fused fingers), (too many fingers), (((long neck))), Deformed, blurry",
|
197 |
+
key=f"{prefix}-negative-prompt",
|
198 |
+
)
|
199 |
+
col1, col2 = st.columns(2)
|
200 |
+
with col1:
|
201 |
+
steps = st.slider("Number of inference steps", min_value=11, max_value=69, value=14, key=f"{prefix}-inference-steps")
|
202 |
+
with col2:
|
203 |
+
guidance_scale = st.slider(
|
204 |
+
"Guidance scale", min_value=0.0, max_value=20.0, value=7.5, step=0.5, key=f"{prefix}-guidance-scale"
|
205 |
+
)
|
206 |
+
# enable_attention_slicing = st.checkbox('Enable attention slicing (enables higher resolutions but is slower)', key=f"{prefix}-attention-slicing", value=True)
|
207 |
+
# enable_xformers = st.checkbox('Enable xformers library (better memory usage)', key=f"{prefix}-xformers", value=True)
|
208 |
+
num_images = st.slider("Number of images to generate", min_value=1, max_value=4, value=1, key=f"{prefix}-num-images")
|
209 |
+
|
210 |
+
images = []
|
211 |
+
|
212 |
+
|
213 |
+
if st.button("Generate images", key=f"{prefix}-btn"):
|
214 |
+
with st.spinner("Generating image..."):
|
215 |
+
images = generate(
|
216 |
+
prompt,
|
217 |
+
pipeline_name,
|
218 |
+
num_images=num_images, # add this
|
219 |
+
negative_prompt=negative_prompt,
|
220 |
+
steps=steps,
|
221 |
+
guidance_scale=guidance_scale,
|
222 |
+
enable_attention_slicing=True, # value always set to True
|
223 |
+
enable_xformers=True, # value always set to True
|
224 |
+
**kwargs,
|
225 |
+
)
|
226 |
+
|
227 |
+
for i, image in enumerate(images): # loop over each image
|
228 |
+
set_image(f"{OUTPUT_IMAGE_KEY}_{i}", image.copy()) # save each image with a unique key
|
229 |
+
|
230 |
+
|
231 |
+
image_indices = [int(key.split('_')[-1]) for key in st.session_state.keys() if OUTPUT_IMAGE_KEY in key]
|
232 |
+
cols = st.columns(len(image_indices) if image_indices else 1) # create a column for each image or a single one if no images
|
233 |
+
for i in range(max(image_indices) + 1 if image_indices else 1): # loop over each image index
|
234 |
+
output_image_key = f"{OUTPUT_IMAGE_KEY}_{i}"
|
235 |
+
output_image = get_image(output_image_key)
|
236 |
+
if output_image:
|
237 |
+
cols[i].image(output_image)
|
238 |
+
|
239 |
+
|
240 |
+
|
241 |
+
def width_and_height_sliders(prefix):
|
242 |
+
col1, col2 = st.columns(2)
|
243 |
+
with col1:
|
244 |
+
width = st.slider(
|
245 |
+
"Width",
|
246 |
+
min_value=768,
|
247 |
+
max_value=1024,
|
248 |
+
step=128,
|
249 |
+
value=768,
|
250 |
+
key=f"{prefix}-width",
|
251 |
+
)
|
252 |
+
with col2:
|
253 |
+
height = st.slider(
|
254 |
+
"Height",
|
255 |
+
min_value=768,
|
256 |
+
max_value=1024,
|
257 |
+
step=128,
|
258 |
+
value=768,
|
259 |
+
key=f"{prefix}-height",
|
260 |
+
)
|
261 |
+
return width, height
|
262 |
+
|
263 |
+
data_dir = "./data" # Update with the correct path
|
264 |
+
|
265 |
+
# Get all file names in the data directory
|
266 |
+
file_names = os.listdir(data_dir)
|
267 |
+
|
268 |
+
|
269 |
+
def txt2img_tab():
|
270 |
+
prefix = "txt2img"
|
271 |
+
width, height = width_and_height_sliders(prefix)
|
272 |
+
prompt_and_generate_button(prefix, "txt2img", width=width, height=height)
|
273 |
+
|
274 |
+
|
275 |
+
def inpainting_tab():
|
276 |
+
col1, col2 = st.columns(2)
|
277 |
+
|
278 |
+
with col1:
|
279 |
+
image_input, mask_input = inpainting()
|
280 |
+
|
281 |
+
with col2:
|
282 |
+
if image_input and mask_input:
|
283 |
+
prompt_and_generate_button(
|
284 |
+
"inpaint", "inpaint", image_input=image_input, mask_input=mask_input
|
285 |
+
)
|
286 |
+
|
287 |
+
|
288 |
+
def img2img_tab():
|
289 |
+
col1, col2 = st.columns(2)
|
290 |
+
|
291 |
+
with col1:
|
292 |
+
image = image_uploader("img2img")
|
293 |
+
if image:
|
294 |
+
st.image(image)
|
295 |
+
|
296 |
+
with col2:
|
297 |
+
if image:
|
298 |
+
prompt_and_generate_button("img2img", "img2img", image_input=image)
|
299 |
+
|
300 |
+
def main():
|
301 |
+
st.title("FFusion AI -beta- Playground")
|
302 |
+
|
303 |
+
tabs = ["FFusion BaSE 768+ (txt2img)"]
|
304 |
+
selected_tab = st.selectbox("Choose a di.FFusion.ai model", tabs)
|
305 |
+
|
306 |
+
if selected_tab == "FFusion BaSE 768+ (txt2img)":
|
307 |
+
txt2img_tab()
|
308 |
+
|
309 |
+
st.header("Citation")
|
310 |
+
|
311 |
+
"""
|
312 |
+
```
|
313 |
+
@misc {ffusion_ai_2023,
|
314 |
+
author = { {FFusion AI} },
|
315 |
+
title = { FFusion-BaSE (Revision ba72848) },
|
316 |
+
year = 2023,
|
317 |
+
url = { https://huggingface.co/FFusion/FFusion-BaSE },
|
318 |
+
doi = { 10.57967/hf/0851 },
|
319 |
+
publisher = { Hugging Face }
|
320 |
+
} http://doi.org/10.57967/hf/0851
|
321 |
+
```
|
322 |
+
"""
|
323 |
+
|
324 |
+
"""
|
325 |
+
Please note that the demo is intended for academic and research purposes ONLY. Any use of the demo for generating inappropriate content is strictly prohibited. The responsibility for any misuse or inappropriate use of the demo lies solely with the users who generated such content, and this demo shall not be held liable for any such use. By interacting within this environment, you hereby acknowledge and agree to the terms of the CreativeML Open RAIL-M License.
|
326 |
+
"""
|
327 |
+
|
328 |
+
if __name__ == "__main__":
|
329 |
+
main()
|