Spaces:
Paused
Paused
Delete app (19).py
Browse files- app (19).py +0 -237
app (19).py
DELETED
|
@@ -1,237 +0,0 @@
|
|
| 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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