Spaces:
openfree
/
Running on Zero

File size: 9,679 Bytes
6a93034
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
275b762
6a93034
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36e5c51
 
6a93034
 
 
9baf2c7
 
 
6a93034
 
9baf2c7
6a93034
 
 
36e5c51
6a93034
 
9baf2c7
 
 
 
 
 
 
 
 
 
6a93034
 
 
 
 
 
 
9baf2c7
6a93034
 
 
 
 
 
 
 
 
275b762
6a93034
 
 
 
275b762
6a93034
 
 
36e5c51
275b762
 
 
 
 
 
 
 
 
 
9baf2c7
275b762
 
 
 
 
6a93034
 
 
 
 
 
 
 
 
9baf2c7
6a93034
9baf2c7
 
 
 
 
6a93034
 
 
 
 
 
36e5c51
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
import spaces
import time
import os

import gradio as gr
import torch
from einops import rearrange
from PIL import Image

from flux.cli import SamplingOptions
from flux.sampling import denoise, get_noise, get_schedule, prepare, unpack
from flux.util import load_ae, load_clip, load_flow_model, load_t5
from pulid.pipeline_flux import PuLIDPipeline
from pulid.utils import resize_numpy_image_long


def get_models(name: str, device: torch.device, offload: bool):
    t5 = load_t5(device, max_length=128)
    clip = load_clip(device)
    model = load_flow_model(name, device="cpu" if offload else device)
    model.eval()
    ae = load_ae(name, device="cpu" if offload else device)
    return model, ae, t5, clip


class FluxGenerator:
    def __init__(self):
        self.device = torch.device('cuda')
        self.offload = False
        self.model_name = 'flux-dev'
        self.model, self.ae, self.t5, self.clip = get_models(
            self.model_name,
            device=self.device,
            offload=self.offload,
        )
        self.pulid_model = PuLIDPipeline(self.model, 'cuda', weight_dtype=torch.bfloat16)
        self.pulid_model.load_pretrain()


flux_generator = FluxGenerator()


@spaces.GPU
@torch.inference_mode()
def generate_image(
        width,
        height,
        num_steps,
        start_step,
        guidance,
        seed,
        prompt,
        id_image=None,
        id_weight=1.0,
        neg_prompt="",
        true_cfg=1.0,
        timestep_to_start_cfg=1,
        max_sequence_length=128,
):
    flux_generator.t5.max_length = max_sequence_length

    seed = int(seed)
    if seed == -1:
        seed = None

    opts = SamplingOptions(
        prompt=prompt,
        width=width,
        height=height,
        num_steps=num_steps,
        guidance=guidance,
        seed=seed,
    )

    if opts.seed is None:
        opts.seed = torch.Generator(device="cpu").seed()

    t0 = time.perf_counter()

    use_true_cfg = abs(true_cfg - 1.0) > 1e-2

    if id_image is not None:
        id_image = resize_numpy_image_long(id_image, 1024)
        id_embeddings, uncond_id_embeddings = flux_generator.pulid_model.get_id_embedding(id_image, cal_uncond=use_true_cfg)
    else:
        id_embeddings = None
        uncond_id_embeddings = None

    # prepare input
    x = get_noise(
        1,
        opts.height,
        opts.width,
        device=flux_generator.device,
        dtype=torch.bfloat16,
        seed=opts.seed,
    )
    timesteps = get_schedule(
        opts.num_steps,
        x.shape[-1] * x.shape[-2] // 4,
        shift=True,
    )

    if flux_generator.offload:
        flux_generator.t5, flux_generator.clip = flux_generator.t5.to(flux_generator.device), flux_generator.clip.to(flux_generator.device)
    inp = prepare(t5=flux_generator.t5, clip=flux_generator.clip, img=x, prompt=opts.prompt)
    inp_neg = prepare(t5=flux_generator.t5, clip=flux_generator.clip, img=x, prompt=neg_prompt) if use_true_cfg else None

    # offload TEs to CPU, load model to gpu
    if flux_generator.offload:
        flux_generator.t5, flux_generator.clip = flux_generator.t5.cpu(), flux_generator.clip.cpu()
        torch.cuda.empty_cache()
        flux_generator.model = flux_generator.model.to(flux_generator.device)

    # denoise initial noise
    x = denoise(
        flux_generator.model, **inp, timesteps=timesteps, guidance=opts.guidance, id=id_embeddings, id_weight=id_weight,
        start_step=start_step, uncond_id=uncond_id_embeddings, true_cfg=true_cfg,
        timestep_to_start_cfg=timestep_to_start_cfg,
        neg_txt=inp_neg["txt"] if use_true_cfg else None,
        neg_txt_ids=inp_neg["txt_ids"] if use_true_cfg else None,
        neg_vec=inp_neg["vec"] if use_true_cfg else None,
    )

    # offload model, load autoencoder to gpu
    if flux_generator.offload:
        flux_generator.model.cpu()
        torch.cuda.empty_cache()
        flux_generator.ae.decoder.to(x.device)

    # decode latents to pixel space
    x = unpack(x.float(), opts.height, opts.width)
    with torch.autocast(device_type=flux_generator.device.type, dtype=torch.bfloat16):
        x = flux_generator.ae.decode(x)

    if flux_generator.offload:
        flux_generator.ae.decoder.cpu()
        torch.cuda.empty_cache()

    t1 = time.perf_counter()

    # bring into PIL format
    x = x.clamp(-1, 1)
    x = rearrange(x[0], "c h w -> h w c")

    img = Image.fromarray((127.5 * (x + 1.0)).cpu().byte().numpy())
    return img, str(opts.seed), flux_generator.pulid_model.debug_img_list


css = """
footer {
    visibility: hidden;
}
"""

def create_demo(args, model_name: str, device: str = "cuda" if torch.cuda.is_available() else "cpu",
                offload: bool = False):
    
    with gr.Blocks(theme="Nymbo/Nymbo_Theme", css=css) as demo:
        gr.Markdown("## AI ํฌํ†  ์ง€๋‹ˆ: ์šฐ์ฃผ")
        gr.Markdown("### ์ด์šฉ ์•ˆ๋‚ด: 1) ์˜ˆ์‹œ์ค‘ ํ•˜๋‚˜๋ฅผ ์„ ํƒ. 2) ์นด๋ฉ”๋ผ ๋ฒ„ํŠผ์„ ํด๋ฆญํ•˜๊ณ  ์–ผ๊ตด์ด ๋ณด์ด๋ฉด ์นด๋ฉ”๋ผ ๋ฒ„ํŠผ ํด๋ฆญ. 3) '์ƒ์„ฑ' ๋ฒ„ํŠผ์„ ํด๋ฆญํ•˜๊ณ  ๊ธฐ๋‹ค๋ฆฌ๋ฉด ๋ฉ๋‹ˆ๋‹ค.")
        
        with gr.Row():
            with gr.Column():
                prompt = gr.Textbox(label="ํ”„๋กฌํ”„ํŠธ", value="์ดˆ์ƒํ™”, ์ƒ‰๊ฐ, ์˜ํ™”์ ")
                id_image = gr.Image(label="ID ์ด๋ฏธ์ง€", sources=["webcam", "upload"], type="numpy")
                generate_btn = gr.Button("์ƒ์„ฑ")
                
            with gr.Column():
                output_image = gr.Image(label="์ƒ์„ฑ๋œ ์ด๋ฏธ์ง€")

        with gr.Row():
            with gr.Column():
                gr.Markdown("### ์˜ˆ์‹œ")
                
                all_examples = [
                    ['์—ฌ์ž๊ฐ€ "PuLID for FLUX"๋ผ๊ณ  ์“ฐ์ธ ๋น›๋‚˜๋Š” ๋…น์ƒ‰ ํ‘œ์ง€ํŒ์„ ๋“ค๊ณ  ์žˆ๋‹ค', 'example_inputs/liuyifei.png'],
                    ['์˜†๋ชจ์Šต ์ดˆ์ƒํ™”', 'example_inputs/liuyifei.png'],
                    ['VR ๊ธฐ์ˆ  ๋ถ„์œ„๊ธฐ์˜ ํฐ ๋จธ๋ฆฌ ์—ฌ์„ฑ', 'example_inputs/liuyifei.png'],
                    ['์–ด๋ฆฐ ์•„์ด๊ฐ€ ์•„์ด์Šคํฌ๋ฆผ์„ ๋จน๊ณ  ์žˆ๋‹ค', 'example_inputs/liuyifei.png'],
                    ['๋‚จ์ž๊ฐ€ "PuLID for FLUX"๋ผ๊ณ  ์“ฐ์ธ ํ‘œ์ง€ํŒ์„ ๋“ค๊ณ  ์žˆ๋‹ค, ๊ฒจ์šธ, ๋ˆˆ ๋‚ด๋ฆผ', 'example_inputs/pengwei.jpg'],
                    ['์ดˆ์ƒํ™”, ์ด›๋ถˆ ์กฐ๋ช…', 'example_inputs/pengwei.jpg'],
                    ['25์„ธ ๋‚จ์„ฑ์˜ ์–ด๋‘์šด ํ”„๋กœํ•„ ์‚ฌ์ง„, ์ž…์—์„œ ์—ฐ๊ธฐ๊ฐ€ ๋‚˜์˜ค๊ณ  ์žˆ์Œ', 'example_inputs/pengwei.jpg'],
                    ['๋ฏธ๊ตญ ๋งŒํ™” ์Šคํƒ€์ผ, ์†Œ๋…„ 1๋ช…', 'example_inputs/pengwei.jpg'],
                    ['์ดˆ์ƒํ™”, ํ”ฝ์‚ฌ ์Šคํƒ€์ผ', 'example_inputs/pengwei.jpg'],
                    ['์ดˆ์ƒํ™”, ์–ผ์Œ ์กฐ๊ฐ์ƒ', 'example_inputs/lecun.jpg'],
                ]

                example_images = [example[1] for example in all_examples]
                example_captions = [example[0] for example in all_examples]

                gallery = gr.Gallery(
                    value=list(zip(example_images, example_captions)),
                    label="์˜ˆ์‹œ ๊ฐค๋Ÿฌ๋ฆฌ",
                    show_label=False,
                    elem_id="gallery",
                    columns=5,
                    rows=2,
                    object_fit="contain",
                    height="auto"
                )

                def fill_example(evt: gr.SelectData):
                    return [all_examples[evt.index][i] for i in [0, 1]]

                gallery.select(
                    fill_example,
                    None,
                    [prompt, id_image],
                )

        generate_btn.click(
            fn=lambda *args: generate_image(*args)[0],  # Only return the first item (the image)
            inputs=[
                gr.Slider(256, 1536, 896, step=16, visible=False),  # width
                gr.Slider(256, 1536, 1152, step=16, visible=False),  # height
                gr.Slider(1, 20, 20, step=1, visible=False),  # num_steps
                gr.Slider(0, 10, 0, step=1, visible=False),  # start_step
                gr.Slider(1.0, 10.0, 4, step=0.1, visible=False),  # guidance
                gr.Textbox(-1, visible=False),  # seed
                prompt, 
                id_image, 
                gr.Slider(0.0, 3.0, 1, step=0.05, visible=False),  # id_weight
                gr.Textbox("์ €ํ’ˆ์งˆ, ์ตœ์•…์˜ ํ’ˆ์งˆ, ํ…์ŠคํŠธ, ์„œ๋ช…, ์›Œํ„ฐ๋งˆํฌ, ์—ฌ๋ถ„์˜ ํŒ”๋‹ค๋ฆฌ", visible=False),  # neg_prompt
                gr.Slider(1.0, 10.0, 1, step=0.1, visible=False),  # true_cfg
                gr.Slider(0, 20, 1, step=1, visible=False),  # timestep_to_start_cfg
                gr.Slider(128, 512, 128, step=128, visible=False),  # max_sequence_length
            ],
            outputs=[output_image],
        )

    return demo

if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="PuLID for FLUX.1-dev")
    parser.add_argument("--name", type=str, default="flux-dev", choices=list('flux-dev'),
                        help="ํ˜„์žฌ๋Š” flux-dev๋งŒ ์ง€์›ํ•ฉ๋‹ˆ๋‹ค")
    parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu",
                        help="์‚ฌ์šฉํ•  ๋””๋ฐ”์ด์Šค")
    parser.add_argument("--offload", action="store_true", help="์‚ฌ์šฉํ•˜์ง€ ์•Š์„ ๋•Œ ๋ชจ๋ธ์„ CPU๋กœ ์˜ฎ๊น๋‹ˆ๋‹ค")
    parser.add_argument("--port", type=int, default=8080, help="์‚ฌ์šฉํ•  ํฌํŠธ")
    parser.add_argument("--dev", action='store_true', help="๊ฐœ๋ฐœ ๋ชจ๋“œ")
    parser.add_argument("--pretrained_model", type=str, help='๊ฐœ๋ฐœ์šฉ')
    args = parser.parse_args()

    import huggingface_hub
    huggingface_hub.login(os.getenv('HF_TOKEN'))

    demo = create_demo(args, args.name, args.device, args.offload)
    demo.launch(share=True)