File size: 13,561 Bytes
86be4e6
 
2b8b77d
 
1eb5467
e1fcf74
2b8b77d
 
 
 
e2371c5
f1c3cc1
3c2c999
e6d3f1b
cb42b1e
b365a93
8570e29
e6d3f1b
b365a93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6d3f1b
003a054
cb42b1e
815fecf
 
cb42b1e
 
 
 
 
815fecf
 
cb42b1e
815fecf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158bf4e
815fecf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158bf4e
 
 
815fecf
158bf4e
 
815fecf
cb42b1e
815fecf
 
 
 
 
 
 
3b53d1c
815fecf
df2f72d
815fecf
 
3b53d1c
 
815fecf
 
 
df2f72d
815fecf
cb42b1e
 
 
 
 
 
 
 
 
 
815fecf
cb42b1e
815fecf
cb42b1e
815fecf
 
 
 
 
 
 
 
 
3b53d1c
815fecf
 
cb42b1e
3b53d1c
815fecf
 
 
 
158bf4e
815fecf
 
 
a821008
815fecf
cb42b1e
 
 
 
 
815fecf
9d731d3
cb42b1e
ed049a0
cb42b1e
3b53d1c
 
 
 
 
 
ed049a0
 
 
7bddc43
 
3b53d1c
 
7bddc43
 
3b53d1c
7bddc43
 
 
3b53d1c
7bddc43
 
3b53d1c
7bddc43
 
3b53d1c
7bddc43
 
 
 
 
 
 
 
 
 
 
 
3b53d1c
7bddc43
 
 
b365a93
9fc9078
 
cb42b1e
f217e4d
 
df2f72d
7b9e6e4
718ba97
7bddc43
 
 
518583e
7bddc43
 
 
 
 
 
 
 
 
 
 
 
 
 
cb42b1e
7bddc43
 
 
 
 
cb42b1e
7bddc43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb42b1e
7bddc43
 
a821008
 
 
7bddc43
a821008
 
 
 
 
 
 
 
 
 
 
 
 
479e0d8
 
7bddc43
7c696fc
479e0d8
10c555d
479e0d8
7bddc43
815fecf
 
cb42b1e
 
 
 
 
 
 
9fc9078
 
cb42b1e
 
 
 
 
815fecf
479e0d8
7bddc43
 
815fecf
 
 
 
 
 
 
 
7bddc43
cd2465c
3b53d1c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import os
import uuid
import gradio as gr
import spaces
from clip_slider_pipeline import CLIPSliderFlux
from diffusers import FluxPipeline, AutoencoderTiny
import torch
import numpy as np
import cv2
from PIL import Image
from diffusers.utils import load_image
from diffusers.utils import export_to_video
import random
from transformers import pipeline

# Translation model load
translator = pipeline("translation", model="Helsinki-NLP/opus-mt-ko-en")

# English menu labels
english_labels = {
    "Prompt": "Prompt",
    "1st direction to steer": "1st Direction",
    "2nd direction to steer": "2nd Direction",
    "Strength": "Strength",
    "Generate directions": "Generate Directions",
    "Generated Images": "Generated Images",
    "From 1st to 2nd direction": "From 1st to 2nd Direction",
    "Strip": "Image Strip",
    "Looping video": "Looping Video",
    "Advanced options": "Advanced Options",
    "Num of intermediate images": "Number of Intermediate Images",
    "Num iterations for clip directions": "Number of CLIP Direction Iterations",
    "Num inference steps": "Number of Inference Steps",
    "Guidance scale": "Guidance Scale",
    "Randomize seed": "Randomize Seed",
    "Seed": "Seed"
}

# Load pipelines
base_model = "black-forest-labs/FLUX.1-schnell"
taef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=torch.bfloat16).to("cuda")
pipe = FluxPipeline.from_pretrained(
    base_model,
    vae=taef1,
    torch_dtype=torch.bfloat16
)
pipe.transformer.to(memory_format=torch.channels_last)
clip_slider = CLIPSliderFlux(pipe, device=torch.device("cuda"))
MAX_SEED = 2**32 - 1

def save_images_with_unique_filenames(image_list, save_directory):
    if not os.path.exists(save_directory):
        os.makedirs(save_directory)
    paths = []
    for image in image_list:
        unique_filename = f"{uuid.uuid4()}.png"
        file_path = os.path.join(save_directory, unique_filename)
        image.save(file_path)
        paths.append(file_path)
    return paths

def convert_to_centered_scale(num):
    if num % 2 == 0:  # even
        start = -(num // 2 - 1)
        end = num // 2
    else:  # odd
        start = -(num // 2)
        end = num // 2
    return tuple(range(start, end + 1))

def translate_if_korean(text):
    if any('\u3131' <= char <= '\u3163' or '\uac00' <= char <= '\ud7a3' for char in text):
        return translator(text)[0]['translation_text']
    return text

@spaces.GPU(duration=85)
def generate(prompt,
             concept_1,
             concept_2,
             scale,
             randomize_seed=True,
             seed=42,
             recalc_directions=True,
             iterations=200,
             steps=3,
             interm_steps=33,
             guidance_scale=3.5,
             x_concept_1="", x_concept_2="",
             avg_diff_x=None,
             total_images=[],
             gradio_progress=gr.Progress()):
    # Translate prompt and concepts if Korean
    prompt = translate_if_korean(prompt)
    concept_1 = translate_if_korean(concept_1)
    concept_2 = translate_if_korean(concept_2)
    print(f"Prompt: {prompt}, โ† {concept_2}, {concept_1} โžก๏ธ . scale {scale}, interm steps {interm_steps}")
    slider_x = [concept_2, concept_1]
    if randomize_seed:
        seed = random.randint(0, MAX_SEED)
    if not sorted(slider_x) == sorted([x_concept_1, x_concept_2]) or recalc_directions:
        gradio_progress(0, desc="Calculating directions...")
        avg_diff = clip_slider.find_latent_direction(slider_x[0], slider_x[1], num_iterations=iterations)
        x_concept_1, x_concept_2 = slider_x[0], slider_x[1]
    else:
        avg_diff = avg_diff_x
    images = []
    high_scale = scale
    low_scale = -1 * scale
    for i in gradio_progress.tqdm(range(interm_steps), desc="Generating images"):
        cur_scale = low_scale + (high_scale - low_scale) * i / (interm_steps - 1)
        image = clip_slider.generate(
            prompt,
            width=768,
            height=768,
            guidance_scale=guidance_scale,
            scale=cur_scale,
            seed=seed,
            num_inference_steps=steps,
            avg_diff=avg_diff
        )
        images.append(image)
    canvas = Image.new('RGB', (256 * interm_steps, 256))
    for i, im in enumerate(images):
        canvas.paste(im.resize((256, 256)), (256 * i, 0))
    comma_concepts_x = f"{slider_x[1]}, {slider_x[0]}"
    scale_total = convert_to_centered_scale(interm_steps)
    scale_min = scale_total[0]
    scale_max = scale_total[-1]
    scale_middle = scale_total.index(0)
    post_generation_slider_update = gr.update(label=comma_concepts_x, value=0, minimum=scale_min, maximum=scale_max, interactive=True)
    avg_diff_x = avg_diff.cpu()
    video_path = f"{uuid.uuid4()}.mp4"
    print(video_path)
    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

def update_pre_generated_images(slider_value, total_images):
    number_images = len(total_images) if total_images else 0
    if number_images > 0:
        scale_tuple = convert_to_centered_scale(number_images)
        return total_images[scale_tuple.index(slider_value)][0]
    else:
        return None

def reset_recalc_directions():
    return True

# Five "Time Stream" themed examples (one Korean example included)
examples = [
    ["์‹ ์„ ํ•œ ํ† ๋งˆํ† ๊ฐ€ ๋ถ€ํŒจํ•œ ํ† ๋งˆํ† ๋กœ ๋ณ€ํ•ด๊ฐ€๋Š” ๊ณผ์ •", "Fresh", "Rotten", 2.0],
    ["A blooming flower gradually withers into decay", "Bloom", "Wither", 1.5],
    ["A vibrant cityscape transforms into a derelict ruin over time", "Modern", "Ruined", 2.5],
    ["A lively forest slowly changes into an autumnal landscape", "Spring", "Autumn", 2.0],
    ["A calm ocean evolves into a stormy seascape as time passes", "Calm", "Stormy", 3.0]
]

# CSS for a bright and modern UI with a background image
css = """
/* Bright and modern UI with background image */
body {
    background: #ffffff url('https://images.unsplash.com/photo-1506748686214-e9df14d4d9d0?ixlib=rb-1.2.1&auto=format&fit=crop&w=1600&q=80') no-repeat center center fixed;
    background-size: cover;
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    color: #333;
}
footer {
    visibility: hidden;
}
.container {
    max-width: 1200px;
    margin: 20px auto;
    padding: 0 10px;
}
.main-panel {
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.controls-panel {
    background-color: rgba(255, 255, 255, 0.85);
    border-radius: 8px;
    padding: 16px;
    box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.05);
}
.image-display {
    min-height: 400px;
    display: flex;
    flex-direction: column;
    justify-content: center;
}
.slider-container {
    padding: 10px 0;
}
.advanced-panel {
    margin-top: 20px;
    border-top: 1px solid #eaeaea;
    padding-top: 20px;
}
"""

with gr.Blocks(css=css, title="Time Stream") as demo:
    gr.Markdown("# Time Stream")
    
    x_concept_1 = gr.State("")
    x_concept_2 = gr.State("")
    total_images = gr.State([])
    avg_diff_x = gr.State()
    recalc_directions = gr.State(False)

    with gr.Row(elem_classes="container"):
        # Left Column - Controls
        with gr.Column(scale=4):
            with gr.Group(elem_classes="main-panel"):
                gr.Markdown("### Image Generation Controls")
                with gr.Group(elem_classes="controls-panel"):
                    prompt = gr.Textbox(
                        label=english_labels["Prompt"],
                        info="Enter the description",
                        placeholder="A dog in the park",
                        lines=2
                    )
                    with gr.Row():
                        with gr.Column(scale=1):
                            concept_1 = gr.Textbox(
                                label=english_labels["1st direction to steer"],
                                info="Initial state",
                                placeholder="Fresh"
                            )
                        with gr.Column(scale=1):
                            concept_2 = gr.Textbox(
                                label=english_labels["2nd direction to steer"],
                                info="Final state",
                                placeholder="Rotten"
                            )
                    with gr.Row(elem_classes="slider-container"):
                        x = gr.Slider(
                            minimum=0,
                            value=1.75,
                            step=0.1,
                            maximum=4.0,
                            label=english_labels["Strength"],
                            info="Maximum strength for each direction (above 2.5 may be unstable)"
                        )
                    submit = gr.Button(english_labels["Generate directions"], size="lg", variant="primary")
            with gr.Accordion(label=english_labels["Advanced options"], open=False, elem_classes="advanced-panel"):
                with gr.Row():
                    with gr.Column(scale=1):
                        interm_steps = gr.Slider(
                            label=english_labels["Num of intermediate images"],
                            minimum=3,
                            value=7,
                            maximum=65,
                            step=2
                        )
                    with gr.Column(scale=1):
                        guidance_scale = gr.Slider(
                            label=english_labels["Guidance scale"],
                            minimum=0.1,
                            maximum=10.0,
                            step=0.1,
                            value=3.5
                        )
                with gr.Row():
                    with gr.Column(scale=1):
                        iterations = gr.Slider(
                            label=english_labels["Num iterations for clip directions"],
                            minimum=0,
                            value=200,
                            maximum=400,
                            step=1
                        )
                    with gr.Column(scale=1):
                        steps = gr.Slider(
                            label=english_labels["Num inference steps"],
                            minimum=1,
                            value=3,
                            maximum=4,
                            step=1
                        )
                with gr.Row():
                    with gr.Column(scale=1):
                        randomize_seed = gr.Checkbox(
                            True,
                            label=english_labels["Randomize seed"]
                        )
                    with gr.Column(scale=1):
                        seed = gr.Slider(
                            minimum=0,
                            maximum=MAX_SEED,
                            step=1,
                            label=english_labels["Seed"],
                            interactive=True,
                            randomize=True
                        )
        # Right Column - Output
        with gr.Column(scale=8):
            with gr.Group(elem_classes="main-panel"):
                gr.Markdown("### Generated Results")
                # Swapped order: Image strip on top, video below (video is larger)
                image_strip = gr.Image(label="Image Strip", type="filepath", elem_id="strip", height=200)
                output_video = gr.Video(label=english_labels["Looping video"], elem_id="video", loop=True, autoplay=True, height=600)
                with gr.Row():
                    post_generation_image = gr.Image(
                        label=english_labels["Generated Images"],
                        type="filepath",
                        elem_id="interactive",
                        elem_classes="image-display"
                    )
                    post_generation_slider = gr.Slider(
                        minimum=-10,
                        maximum=10,
                        value=0,
                        step=1,
                        label=english_labels["From 1st to 2nd direction"]
                    )
    
    # Examples: ์˜ˆ์ œ ํด๋ฆญ ์‹œ ์ž…๋ ฅ๋ž€์— ๊ฐ’์ด ๋ฐ”๋กœ ์‚ฝ์ž…๋จ
    gr.Examples(
        examples=examples,
        inputs=[prompt, concept_1, concept_2, x]
    )
    
    # Event Handlers
    submit.click(
        fn=generate,
        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
        ],
        outputs=[
            x_concept_1, x_concept_2, avg_diff_x,
            output_video,      # video output
            image_strip,       # canvas (image strip)
            total_images,
            post_generation_image,
            post_generation_slider,
            seed
        ]
    )
    
    iterations.change(fn=reset_recalc_directions, outputs=[recalc_directions])
    seed.change(fn=reset_recalc_directions, outputs=[recalc_directions])
    post_generation_slider.change(
        fn=update_pre_generated_images,
        inputs=[post_generation_slider, total_images],
        outputs=[post_generation_image],
        queue=False,
        show_progress="hidden",
        concurrency_limit=None
    )

if __name__ == "__main__":
    demo.launch()