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|
|
|
1 |
+
import os
|
2 |
+
import uuid
|
3 |
+
import gradio as gr
|
4 |
+
import spaces
|
5 |
+
from clip_slider_pipeline import CLIPSliderFlux
|
6 |
+
from diffusers import FluxPipeline, AutoencoderTiny
|
7 |
+
import torch
|
8 |
+
import numpy as np
|
9 |
+
import cv2
|
10 |
+
from PIL import Image
|
11 |
+
from diffusers.utils import load_image
|
12 |
+
from diffusers.utils import export_to_video
|
13 |
+
import random
|
14 |
+
from transformers import pipeline
|
15 |
+
|
16 |
+
# λ²μ λͺ¨λΈ λ‘λ
|
17 |
+
translator = pipeline("translation", model="Helsinki-NLP/opus-mt-ko-en")
|
18 |
+
|
19 |
+
# νκΈ λ©λ΄ μ΄λ¦ dictionary
|
20 |
+
korean_labels = {
|
21 |
+
"Prompt": "ν둬ννΈ",
|
22 |
+
"1st direction to steer": "첫 λ²μ§Έ λ°©ν₯",
|
23 |
+
"2nd direction to steer": "λ λ²μ§Έ λ°©ν₯",
|
24 |
+
"Strength": "κ°λ",
|
25 |
+
"Generate directions": "λ°©ν₯ μμ±",
|
26 |
+
"Generated Images": "μμ±λ μ΄λ―Έμ§",
|
27 |
+
"From 1st to 2nd direction": "첫 λ²μ§Έμμ λ λ²μ§Έ λ°©ν₯μΌλ‘",
|
28 |
+
"Strip": "μ΄λ―Έμ§ μ€νΈλ¦½",
|
29 |
+
"Looping video": "루ν λΉλμ€",
|
30 |
+
"Advanced options": "κ³ κΈ μ΅μ
",
|
31 |
+
"Num of intermediate images": "μ€κ° μ΄λ―Έμ§ μ",
|
32 |
+
"Num iterations for clip directions": "ν΄λ¦½ λ°©ν₯ λ°λ³΅ νμ",
|
33 |
+
"Num inference steps": "μΆλ‘ λ¨κ³ μ",
|
34 |
+
"Guidance scale": "κ°μ΄λμ€ μ€μΌμΌ",
|
35 |
+
"Randomize seed": "μλ 무μμν",
|
36 |
+
"Seed": "μλ"
|
37 |
+
}
|
38 |
+
|
39 |
+
# load pipelines
|
40 |
+
base_model = "black-forest-labs/FLUX.1-schnell"
|
41 |
+
|
42 |
+
taef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=torch.bfloat16).to("cuda")
|
43 |
+
pipe = FluxPipeline.from_pretrained(base_model,
|
44 |
+
vae=taef1,
|
45 |
+
torch_dtype=torch.bfloat16)
|
46 |
+
|
47 |
+
pipe.transformer.to(memory_format=torch.channels_last)
|
48 |
+
#pipe.transformer = torch.compile(pipe.transformer, mode="max-autotune", fullgraph=True)
|
49 |
+
# pipe.enable_model_cpu_offload()
|
50 |
+
clip_slider = CLIPSliderFlux(pipe, device=torch.device("cuda"))
|
51 |
+
|
52 |
+
MAX_SEED = 2**32-1
|
53 |
+
|
54 |
+
def save_images_with_unique_filenames(image_list, save_directory):
|
55 |
+
if not os.path.exists(save_directory):
|
56 |
+
os.makedirs(save_directory)
|
57 |
+
|
58 |
+
paths = []
|
59 |
+
for image in image_list:
|
60 |
+
unique_filename = f"{uuid.uuid4()}.png"
|
61 |
+
file_path = os.path.join(save_directory, unique_filename)
|
62 |
+
|
63 |
+
image.save(file_path)
|
64 |
+
paths.append(file_path)
|
65 |
+
|
66 |
+
return paths
|
67 |
+
|
68 |
+
def convert_to_centered_scale(num):
|
69 |
+
if num % 2 == 0: # even
|
70 |
+
start = -(num // 2 - 1)
|
71 |
+
end = num // 2
|
72 |
+
else: # odd
|
73 |
+
start = -(num // 2)
|
74 |
+
end = num // 2
|
75 |
+
return tuple(range(start, end + 1))
|
76 |
+
|
77 |
+
def translate_if_korean(text):
|
78 |
+
if any('\u3131' <= char <= '\u3163' or '\uac00' <= char <= '\ud7a3' for char in text):
|
79 |
+
return translator(text)[0]['translation_text']
|
80 |
+
return text
|
81 |
+
|
82 |
+
@spaces.GPU(duration=85)
|
83 |
+
def generate(prompt,
|
84 |
+
concept_1,
|
85 |
+
concept_2,
|
86 |
+
scale,
|
87 |
+
randomize_seed=True,
|
88 |
+
seed=42,
|
89 |
+
recalc_directions=True,
|
90 |
+
iterations=200,
|
91 |
+
steps=3,
|
92 |
+
interm_steps=33,
|
93 |
+
guidance_scale=3.5,
|
94 |
+
x_concept_1="", x_concept_2="",
|
95 |
+
avg_diff_x=None,
|
96 |
+
total_images=[],
|
97 |
+
progress=gr.Progress()
|
98 |
+
):
|
99 |
+
# ν둬ννΈμ 컨μ
λ²μ
|
100 |
+
prompt = translate_if_korean(prompt)
|
101 |
+
concept_1 = translate_if_korean(concept_1)
|
102 |
+
concept_2 = translate_if_korean(concept_2)
|
103 |
+
|
104 |
+
print(f"Prompt: {prompt}, β {concept_2}, {concept_1} β‘οΈ . scale {scale}, interm steps {interm_steps}")
|
105 |
+
slider_x = [concept_2, concept_1]
|
106 |
+
# check if avg diff for directions need to be re-calculated
|
107 |
+
if randomize_seed:
|
108 |
+
seed = random.randint(0, MAX_SEED)
|
109 |
+
|
110 |
+
if not sorted(slider_x) == sorted([x_concept_1, x_concept_2]) or recalc_directions:
|
111 |
+
progress(0, desc="Calculating directions...")
|
112 |
+
avg_diff = clip_slider.find_latent_direction(slider_x[0], slider_x[1], num_iterations=iterations)
|
113 |
+
x_concept_1, x_concept_2 = slider_x[0], slider_x[1]
|
114 |
+
|
115 |
+
images = []
|
116 |
+
high_scale = scale
|
117 |
+
low_scale = -1 * scale
|
118 |
+
for i in progress.tqdm(range(interm_steps), desc="Generating images"):
|
119 |
+
cur_scale = low_scale + (high_scale - low_scale) * i / (interm_steps - 1)
|
120 |
+
image = clip_slider.generate(prompt,
|
121 |
+
width=768,
|
122 |
+
height=768,
|
123 |
+
guidance_scale=guidance_scale,
|
124 |
+
scale=cur_scale, seed=seed, num_inference_steps=steps, avg_diff=avg_diff)
|
125 |
+
images.append(image)
|
126 |
+
canvas = Image.new('RGB', (256*interm_steps, 256))
|
127 |
+
for i, im in enumerate(images):
|
128 |
+
canvas.paste(im.resize((256,256)), (256 * i, 0))
|
129 |
+
|
130 |
+
comma_concepts_x = f"{slider_x[1]}, {slider_x[0]}"
|
131 |
+
|
132 |
+
scale_total = convert_to_centered_scale(interm_steps)
|
133 |
+
scale_min = scale_total[0]
|
134 |
+
scale_max = scale_total[-1]
|
135 |
+
scale_middle = scale_total.index(0)
|
136 |
+
post_generation_slider_update = gr.update(label=comma_concepts_x, value=0, minimum=scale_min, maximum=scale_max, interactive=True)
|
137 |
+
avg_diff_x = avg_diff.cpu()
|
138 |
+
|
139 |
+
video_path = f"{uuid.uuid4()}.mp4"
|
140 |
+
print(video_path)
|
141 |
+
return x_concept_1,x_concept_2, avg_diff_x, export_to_video(images, video_path, fps=5), canvas, images, images[scale_middle], post_generation_slider_update, seed
|
142 |
+
|
143 |
+
def update_pre_generated_images(slider_value, total_images):
|
144 |
+
number_images = len(total_images)
|
145 |
+
if(number_images > 0):
|
146 |
+
scale_tuple = convert_to_centered_scale(number_images)
|
147 |
+
return total_images[scale_tuple.index(slider_value)][0]
|
148 |
+
else:
|
149 |
+
return None
|
150 |
+
|
151 |
+
def reset_recalc_directions():
|
152 |
+
return True
|
153 |
+
|
154 |
+
examples = [["a dog in the park", "winter", "summer", 1.5], ["a house", "USA suburb", "Europe", 2.5], ["a tomato", "rotten", "super fresh", 2.5]]
|
155 |
+
|
156 |
+
css = """
|
157 |
+
footer {
|
158 |
+
visibility: hidden;
|
159 |
+
}
|
160 |
+
"""
|
161 |
+
|
162 |
+
with gr.Blocks(theme="Nymbo/Nymbo_Theme", css=css) as demo:
|
163 |
+
x_concept_1 = gr.State("")
|
164 |
+
x_concept_2 = gr.State("")
|
165 |
+
total_images = gr.Gallery(visible=False)
|
166 |
+
|
167 |
+
avg_diff_x = gr.State()
|
168 |
+
|
169 |
+
recalc_directions = gr.State(False)
|
170 |
+
|
171 |
+
with gr.Row():
|
172 |
+
with gr.Column():
|
173 |
+
with gr.Group():
|
174 |
+
prompt = gr.Textbox(label=korean_labels["Prompt"], info="μ€λͺ
ν λ΄μ©μ μ
λ ₯νμΈμ", placeholder="곡μμ μλ κ°μμ§")
|
175 |
+
with gr.Row():
|
176 |
+
concept_1 = gr.Textbox(label=korean_labels["1st direction to steer"], info="μμ μν", placeholder="겨μΈ")
|
177 |
+
concept_2 = gr.Textbox(label=korean_labels["2nd direction to steer"], info="μ’
λ£ μν", placeholder="μ¬λ¦")
|
178 |
+
x = gr.Slider(minimum=0, value=1.75, step=0.1, maximum=4.0, label=korean_labels["Strength"], info="κ° λ°©ν₯μ μ΅λ κ°λ (2.5 μ΄μμ λΆμμ )")
|
179 |
+
submit = gr.Button(korean_labels["Generate directions"])
|
180 |
+
with gr.Column():
|
181 |
+
with gr.Group(elem_id="group"):
|
182 |
+
post_generation_image = gr.Image(label=korean_labels["Generated Images"], type="filepath", elem_id="interactive")
|
183 |
+
post_generation_slider = gr.Slider(minimum=-10, maximum=10, value=0, step=1, label=korean_labels["From 1st to 2nd direction"])
|
184 |
+
with gr.Row():
|
185 |
+
with gr.Column(scale=4):
|
186 |
+
image_seq = gr.Image(label=korean_labels["Strip"], elem_id="strip", height=80)
|
187 |
+
with gr.Column(scale=2, min_width=100):
|
188 |
+
output_image = gr.Video(label=korean_labels["Looping video"], elem_id="video", loop=True, autoplay=True)
|
189 |
+
with gr.Accordion(label=korean_labels["Advanced options"], open=False):
|
190 |
+
interm_steps = gr.Slider(label=korean_labels["Num of intermediate images"], minimum=3, value=7, maximum=65, step=2)
|
191 |
+
with gr.Row():
|
192 |
+
iterations = gr.Slider(label=korean_labels["Num iterations for clip directions"], minimum=0, value=200, maximum=400, step=1)
|
193 |
+
steps = gr.Slider(label=korean_labels["Num inference steps"], minimum=1, value=3, maximum=4, step=1)
|
194 |
+
with gr.Row():
|
195 |
+
guidance_scale = gr.Slider(
|
196 |
+
label=korean_labels["Guidance scale"],
|
197 |
+
minimum=0.1,
|
198 |
+
maximum=10.0,
|
199 |
+
step=0.1,
|
200 |
+
value=3.5,
|
201 |
+
)
|
202 |
+
with gr.Column():
|
203 |
+
randomize_seed = gr.Checkbox(True, label=korean_labels["Randomize seed"])
|
204 |
+
seed = gr.Slider(minimum=0, maximum=MAX_SEED, step=1, label=korean_labels["Seed"], interactive=True, randomize=True)
|
205 |
+
|
206 |
+
examples_gradio = gr.Examples(
|
207 |
+
examples=examples,
|
208 |
+
inputs=[prompt, concept_1, concept_2, x],
|
209 |
+
fn=generate,
|
210 |
+
outputs=[x_concept_1, x_concept_2, avg_diff_x, output_image, image_seq, total_images, post_generation_image, post_generation_slider, seed],
|
211 |
+
cache_examples="lazy"
|
212 |
+
)
|
213 |
+
|
214 |
+
submit.click(
|
215 |
+
fn=generate,
|
216 |
+
inputs=[prompt, concept_1, concept_2, x, randomize_seed, seed, recalc_directions, iterations, steps, interm_steps, guidance_scale, x_concept_1, x_concept_2, avg_diff_x, total_images],
|
217 |
+
outputs=[x_concept_1, x_concept_2, avg_diff_x, output_image, image_seq, total_images, post_generation_image, post_generation_slider, seed]
|
218 |
+
)
|
219 |
+
iterations.change(
|
220 |
+
fn=reset_recalc_directions,
|
221 |
+
outputs=[recalc_directions]
|
222 |
+
)
|
223 |
+
seed.change(
|
224 |
+
fn=reset_recalc_directions,
|
225 |
+
outputs=[recalc_directions]
|
226 |
+
)
|
227 |
+
post_generation_slider.change(
|
228 |
+
fn=update_pre_generated_images,
|
229 |
+
inputs=[post_generation_slider, total_images],
|
230 |
+
outputs=[post_generation_image],
|
231 |
+
queue=False,
|
232 |
+
show_progress="hidden",
|
233 |
+
concurrency_limit=None
|
234 |
+
)
|
235 |
+
|
236 |
+
if __name__ == "__main__":
|
237 |
+
demo.launch()
|