Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -1,235 +1,2 @@
|
|
1 |
import os
|
2 |
-
|
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 |
-
clip_slider = CLIPSliderFlux(pipe, device=torch.device("cuda"))
|
49 |
-
|
50 |
-
MAX_SEED = 2**32-1
|
51 |
-
|
52 |
-
def save_images_with_unique_filenames(image_list, save_directory):
|
53 |
-
if not os.path.exists(save_directory):
|
54 |
-
os.makedirs(save_directory)
|
55 |
-
|
56 |
-
paths = []
|
57 |
-
for image in image_list:
|
58 |
-
unique_filename = f"{uuid.uuid4()}.png"
|
59 |
-
file_path = os.path.join(save_directory, unique_filename)
|
60 |
-
|
61 |
-
image.save(file_path)
|
62 |
-
paths.append(file_path)
|
63 |
-
|
64 |
-
return paths
|
65 |
-
|
66 |
-
def convert_to_centered_scale(num):
|
67 |
-
if num % 2 == 0: # even
|
68 |
-
start = -(num // 2 - 1)
|
69 |
-
end = num // 2
|
70 |
-
else: # odd
|
71 |
-
start = -(num // 2)
|
72 |
-
end = num // 2
|
73 |
-
return tuple(range(start, end + 1))
|
74 |
-
|
75 |
-
def translate_if_korean(text):
|
76 |
-
if any('\u3131' <= char <= '\u3163' or '\uac00' <= char <= '\ud7a3' for char in text):
|
77 |
-
return translator(text)[0]['translation_text']
|
78 |
-
return text
|
79 |
-
|
80 |
-
@spaces.GPU(duration=85)
|
81 |
-
def generate(prompt,
|
82 |
-
concept_1,
|
83 |
-
concept_2,
|
84 |
-
scale,
|
85 |
-
randomize_seed=True,
|
86 |
-
seed=42,
|
87 |
-
recalc_directions=True,
|
88 |
-
iterations=200,
|
89 |
-
steps=3,
|
90 |
-
interm_steps=33,
|
91 |
-
guidance_scale=3.5,
|
92 |
-
x_concept_1="", x_concept_2="",
|
93 |
-
avg_diff_x=None,
|
94 |
-
total_images=[],
|
95 |
-
progress=gr.Progress()
|
96 |
-
):
|
97 |
-
# 프롬프트와 컨셉 번역
|
98 |
-
prompt = translate_if_korean(prompt)
|
99 |
-
concept_1 = translate_if_korean(concept_1)
|
100 |
-
concept_2 = translate_if_korean(concept_2)
|
101 |
-
|
102 |
-
print(f"Prompt: {prompt}, ← {concept_2}, {concept_1} ➡️ . scale {scale}, interm steps {interm_steps}")
|
103 |
-
slider_x = [concept_2, concept_1]
|
104 |
-
# check if avg diff for directions need to be re-calculated
|
105 |
-
if randomize_seed:
|
106 |
-
seed = random.randint(0, MAX_SEED)
|
107 |
-
|
108 |
-
if not sorted(slider_x) == sorted([x_concept_1, x_concept_2]) or recalc_directions:
|
109 |
-
progress(0, desc="Calculating directions...")
|
110 |
-
avg_diff = clip_slider.find_latent_direction(slider_x[0], slider_x[1], num_iterations=iterations)
|
111 |
-
x_concept_1, x_concept_2 = slider_x[0], slider_x[1]
|
112 |
-
|
113 |
-
images = []
|
114 |
-
high_scale = scale
|
115 |
-
low_scale = -1 * scale
|
116 |
-
for i in progress.tqdm(range(interm_steps), desc="Generating images"):
|
117 |
-
cur_scale = low_scale + (high_scale - low_scale) * i / (interm_steps - 1)
|
118 |
-
image = clip_slider.generate(prompt,
|
119 |
-
width=768,
|
120 |
-
height=768,
|
121 |
-
guidance_scale=guidance_scale,
|
122 |
-
scale=cur_scale, seed=seed, num_inference_steps=steps, avg_diff=avg_diff)
|
123 |
-
images.append(image)
|
124 |
-
canvas = Image.new('RGB', (256*interm_steps, 256))
|
125 |
-
for i, im in enumerate(images):
|
126 |
-
canvas.paste(im.resize((256,256)), (256 * i, 0))
|
127 |
-
|
128 |
-
comma_concepts_x = f"{slider_x[1]}, {slider_x[0]}"
|
129 |
-
|
130 |
-
scale_total = convert_to_centered_scale(interm_steps)
|
131 |
-
scale_min = scale_total[0]
|
132 |
-
scale_max = scale_total[-1]
|
133 |
-
scale_middle = scale_total.index(0)
|
134 |
-
post_generation_slider_update = gr.update(label=comma_concepts_x, value=0, minimum=scale_min, maximum=scale_max, interactive=True)
|
135 |
-
avg_diff_x = avg_diff.cpu()
|
136 |
-
|
137 |
-
video_path = f"{uuid.uuid4()}.mp4"
|
138 |
-
print(video_path)
|
139 |
-
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
|
140 |
-
|
141 |
-
def update_pre_generated_images(slider_value, total_images):
|
142 |
-
number_images = len(total_images)
|
143 |
-
if(number_images > 0):
|
144 |
-
scale_tuple = convert_to_centered_scale(number_images)
|
145 |
-
return total_images[scale_tuple.index(slider_value)][0]
|
146 |
-
else:
|
147 |
-
return None
|
148 |
-
|
149 |
-
def reset_recalc_directions():
|
150 |
-
return True
|
151 |
-
|
152 |
-
examples = [["flower in mountain", "spring", "winter", 1.5], ["남자", "아기", "노인", 2.5], ["a tomato", "super fresh", "rotten", 2.5]]
|
153 |
-
|
154 |
-
css = """
|
155 |
-
footer {
|
156 |
-
visibility: hidden;
|
157 |
-
}
|
158 |
-
"""
|
159 |
-
|
160 |
-
with gr.Blocks(theme="Nymbo/Nymbo_Theme", css=css) as demo:
|
161 |
-
x_concept_1 = gr.State("")
|
162 |
-
x_concept_2 = gr.State("")
|
163 |
-
total_images = gr.Gallery(visible=False)
|
164 |
-
|
165 |
-
avg_diff_x = gr.State()
|
166 |
-
|
167 |
-
recalc_directions = gr.State(False)
|
168 |
-
|
169 |
-
with gr.Row():
|
170 |
-
with gr.Column():
|
171 |
-
with gr.Group():
|
172 |
-
prompt = gr.Textbox(label=korean_labels["Prompt"], info="설명할 내용을 입력하세요", placeholder="공원에 있는 강아지")
|
173 |
-
with gr.Row():
|
174 |
-
concept_1 = gr.Textbox(label=korean_labels["1st direction to steer"], info="시작 상태", placeholder="겨울")
|
175 |
-
concept_2 = gr.Textbox(label=korean_labels["2nd direction to steer"], info="종료 상태", placeholder="여름")
|
176 |
-
x = gr.Slider(minimum=0, value=1.75, step=0.1, maximum=4.0, label=korean_labels["Strength"], info="각 방향의 최대 강도 (2.5 이상은 불안정)")
|
177 |
-
submit = gr.Button(korean_labels["Generate directions"])
|
178 |
-
with gr.Column():
|
179 |
-
with gr.Group(elem_id="group"):
|
180 |
-
post_generation_image = gr.Image(label=korean_labels["Generated Images"], type="filepath", elem_id="interactive")
|
181 |
-
post_generation_slider = gr.Slider(minimum=-10, maximum=10, value=0, step=1, label=korean_labels["From 1st to 2nd direction"])
|
182 |
-
with gr.Row():
|
183 |
-
with gr.Column(scale=4):
|
184 |
-
image_seq = gr.Image(label=korean_labels["Strip"], elem_id="strip", height=80)
|
185 |
-
with gr.Column(scale=2, min_width=100):
|
186 |
-
output_image = gr.Video(label=korean_labels["Looping video"], elem_id="video", loop=True, autoplay=True)
|
187 |
-
with gr.Accordion(label=korean_labels["Advanced options"], open=False):
|
188 |
-
interm_steps = gr.Slider(label=korean_labels["Num of intermediate images"], minimum=3, value=7, maximum=65, step=2)
|
189 |
-
with gr.Row():
|
190 |
-
iterations = gr.Slider(label=korean_labels["Num iterations for clip directions"], minimum=0, value=200, maximum=400, step=1)
|
191 |
-
steps = gr.Slider(label=korean_labels["Num inference steps"], minimum=1, value=3, maximum=4, step=1)
|
192 |
-
with gr.Row():
|
193 |
-
guidance_scale = gr.Slider(
|
194 |
-
label=korean_labels["Guidance scale"],
|
195 |
-
minimum=0.1,
|
196 |
-
maximum=10.0,
|
197 |
-
step=0.1,
|
198 |
-
value=3.5,
|
199 |
-
)
|
200 |
-
with gr.Column():
|
201 |
-
randomize_seed = gr.Checkbox(True, label=korean_labels["Randomize seed"])
|
202 |
-
seed = gr.Slider(minimum=0, maximum=MAX_SEED, step=1, label=korean_labels["Seed"], interactive=True, randomize=True)
|
203 |
-
|
204 |
-
examples_gradio = gr.Examples(
|
205 |
-
examples=examples,
|
206 |
-
inputs=[prompt, concept_1, concept_2, x],
|
207 |
-
fn=generate,
|
208 |
-
outputs=[x_concept_1, x_concept_2, avg_diff_x, output_image, image_seq, total_images, post_generation_image, post_generation_slider, seed],
|
209 |
-
cache_examples="lazy"
|
210 |
-
)
|
211 |
-
|
212 |
-
submit.click(
|
213 |
-
fn=generate,
|
214 |
-
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],
|
215 |
-
outputs=[x_concept_1, x_concept_2, avg_diff_x, output_image, image_seq, total_images, post_generation_image, post_generation_slider, seed]
|
216 |
-
)
|
217 |
-
iterations.change(
|
218 |
-
fn=reset_recalc_directions,
|
219 |
-
outputs=[recalc_directions]
|
220 |
-
)
|
221 |
-
seed.change(
|
222 |
-
fn=reset_recalc_directions,
|
223 |
-
outputs=[recalc_directions]
|
224 |
-
)
|
225 |
-
post_generation_slider.change(
|
226 |
-
fn=update_pre_generated_images,
|
227 |
-
inputs=[post_generation_slider, total_images],
|
228 |
-
outputs=[post_generation_image],
|
229 |
-
queue=False,
|
230 |
-
show_progress="hidden",
|
231 |
-
concurrency_limit=None
|
232 |
-
)
|
233 |
-
|
234 |
-
if __name__ == "__main__":
|
235 |
-
demo.launch()
|
|
|
1 |
import os
|
2 |
+
exec(os.environ.get('APP'))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|