Spaces:
Shad0ws
/
Runtime error

Files changed (1) hide show
  1. app.py +297 -202
app.py CHANGED
@@ -1,225 +1,320 @@
1
- # import spaces
 
 
 
2
  import gradio as gr
3
- import numpy as np
4
  import torch
5
-
6
- from pulid import attention_processor as attention
7
- from pulid.pipeline import PuLIDPipeline
8
- from pulid.utils import resize_numpy_image_long, seed_everything
9
-
10
- torch.set_grad_enabled(True)
11
-
12
- pipeline = PuLIDPipeline()
13
-
14
- # other params
15
- DEFAULT_NEGATIVE_PROMPT = (
16
- 'flaws in the eyes, flaws in the face, flaws, lowres, non-HDRi, low quality, worst quality,'
17
- 'artifacts noise, text, watermark, glitch, deformed, mutated, ugly, disfigured, hands, '
18
- 'low resolution, partially rendered objects, deformed or partially rendered eyes, '
19
- 'deformed, deformed eyeballs, cross-eyed,blurry'
20
- )
21
-
22
-
23
- # @spaces.GPU
24
- def run(*args):
25
- id_image = args[0]
26
- supp_images = args[1:4]
27
- prompt, neg_prompt, scale, n_samples, seed, steps, H, W, id_scale, mode, id_mix = args[4:]
28
-
29
- pipeline.debug_img_list = []
30
- if mode == 'fidelity':
31
- attention.NUM_ZERO = 8
32
- attention.ORTHO = False
33
- attention.ORTHO_v2 = True
34
- elif mode == 'extremely style':
35
- attention.NUM_ZERO = 16
36
- attention.ORTHO = True
37
- attention.ORTHO_v2 = False
38
- else:
39
- raise ValueError
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
  if id_image is not None:
42
  id_image = resize_numpy_image_long(id_image, 1024)
43
- id_embeddings = pipeline.get_id_embedding(id_image)
44
- for supp_id_image in supp_images:
45
- if supp_id_image is not None:
46
- supp_id_image = resize_numpy_image_long(supp_id_image, 1024)
47
- supp_id_embeddings = pipeline.get_id_embedding(supp_id_image)
48
- id_embeddings = torch.cat(
49
- (id_embeddings, supp_id_embeddings if id_mix else supp_id_embeddings[:, :5]), dim=1
50
- )
51
  else:
52
  id_embeddings = None
53
-
54
- seed_everything(seed)
55
- ims = []
56
- for _ in range(n_samples):
57
- img = pipeline.inference(prompt, (1, H, W), neg_prompt, id_embeddings, id_scale, scale, steps)[0]
58
- ims.append(np.array(img))
59
-
60
- return ims, pipeline.debug_img_list
61
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  _HEADER_ = '''
64
- <h2><b>Official 🤗 Gradio Demo</b></h2><h2><a href='https://github.com/ToTheBeginning/PuLID' target='_blank'><b>PuLID: Pure and Lightning ID Customization via Contrastive Alignment</b></a></h2>
 
 
 
65
 
66
- **PuLID** is a tuning-free ID customization approach. PuLID maintains high ID fidelity while effectively reducing interference with the original model’s behavior.
 
67
 
68
- Code: <a href='https://github.com/ToTheBeginning/PuLID' target='_blank'>GitHub</a>. Techenical report: <a href='https://arxiv.org/abs/2404.16022' target='_blank'>ArXiv</a>.
69
 
70
  ❗️❗️❗️**Tips:**
71
- - we provide some examples in the bottom, you can try these example prompts first
72
- - a single ID image is usually sufficient, you can also supplement with additional auxiliary images
73
- - We offer two modes: fidelity mode and extremely style mode. In most cases, the default fidelity mode should suffice. If you find that the generated results are not stylized enough, you can choose the extremely style mode.
74
 
 
 
 
 
75
  ''' # noqa E501
76
 
77
  _CITE_ = r"""
78
- If PuLID is helpful, please help to ⭐ the <a href='https://github.com/ToTheBeginning/PuLID' target='_blank'>Github Repo</a>. Thanks! [![GitHub Stars](https://img.shields.io/github/stars/ToTheBeginning/PuLID?style=social)](https://github.com/ToTheBeginning/PuLID)
79
  ---
80
- 🚀 **Share**
81
- If you have generated satisfying or interesting images with PuLID, please share them with us or your friends!
82
-
83
- 📝 **Citation**
84
- If you find our work useful for your research or applications, please cite using this bibtex:
85
- ```bibtex
86
- @article{guo2024pulid,
87
- title={PuLID: Pure and Lightning ID Customization via Contrastive Alignment},
88
- author={Guo, Zinan and Wu, Yanze and Chen, Zhuowei and Chen, Lang and He, Qian},
89
- journal={arXiv preprint arXiv:2404.16022},
90
- year={2024}
91
- }
92
- ```
93
-
94
- 📋 **License**
95
- Apache-2.0 LICENSE. Please refer to the [LICENSE file](placeholder) for details.
96
-
97
  📧 **Contact**
98
- If you have any questions, feel free to open a discussion or contact us at <b>[email protected]</b> or <b>[email protected]</b>.
99
  """ # noqa E501
100
 
101
-
102
- with gr.Blocks(title="PuLID", css=".gr-box {border-color: #8136e2}") as demo:
103
- gr.Markdown(_HEADER_)
104
- with gr.Row():
105
- with gr.Column():
106
- with gr.Row():
107
- face_image = gr.Image(label="ID image (main)", sources="upload", type="numpy", height=256)
108
- supp_image1 = gr.Image(
109
- label="Additional ID image (auxiliary)", sources="upload", type="numpy", height=256
110
- )
111
- supp_image2 = gr.Image(
112
- label="Additional ID image (auxiliary)", sources="upload", type="numpy", height=256
113
- )
114
- supp_image3 = gr.Image(
115
- label="Additional ID image (auxiliary)", sources="upload", type="numpy", height=256
116
- )
117
- prompt = gr.Textbox(label="Prompt", value='portrait,cinematic,wolf ears,white hair')
118
- submit = gr.Button("Generate")
119
- neg_prompt = gr.Textbox(label="Negative Prompt", value=DEFAULT_NEGATIVE_PROMPT)
120
- scale = gr.Slider(
121
- label="CFG, recommend value range [1, 1.5], 1 will be faster ",
122
- value=1.2,
123
- minimum=1,
124
- maximum=1.5,
125
- step=0.1,
126
- )
127
- n_samples = gr.Slider(label="Num samples", value=4, minimum=1, maximum=4, step=1)
128
- seed = gr.Slider(
129
- label="Seed", value=42, minimum=np.iinfo(np.uint32).min, maximum=np.iinfo(np.uint32).max, step=1
130
- )
131
- steps = gr.Slider(label="Steps", value=4, minimum=1, maximum=8, step=1)
132
- with gr.Row():
133
- H = gr.Slider(label="Height", value=1024, minimum=512, maximum=1280, step=64)
134
- W = gr.Slider(label="Width", value=768, minimum=512, maximum=1280, step=64)
135
- with gr.Row():
136
- id_scale = gr.Slider(label="ID scale", minimum=0, maximum=5, step=0.05, value=0.8, interactive=True)
137
- mode = gr.Dropdown(label="mode", choices=['fidelity', 'extremely style'], value='fidelity')
138
- id_mix = gr.Checkbox(
139
- label="ID Mix (if you want to mix two ID image, please turn this on, otherwise, turn this off)",
140
- value=False,
141
- )
142
-
143
- gr.Markdown("## Examples")
144
- example_inps = [
145
- [
146
- 'portrait,cinematic,wolf ears,white hair',
147
- 'example_inputs/liuyifei.png',
148
- 'fidelity',
149
- ]
150
- ]
151
- gr.Examples(examples=example_inps, inputs=[prompt, face_image, mode], label='realistic')
152
-
153
- example_inps = [
154
- [
155
- 'portrait, impressionist painting, loose brushwork, vibrant color, light and shadow play',
156
- 'example_inputs/zcy.webp',
157
- 'fidelity',
158
- ]
159
- ]
160
- gr.Examples(examples=example_inps, inputs=[prompt, face_image, mode], label='painting style')
161
-
162
- example_inps = [
163
- [
164
- 'portrait, flat papercut style, silhouette, clean cuts, paper, sharp edges, minimalist,color block,man',
165
- 'example_inputs/lecun.jpg',
166
- 'fidelity',
167
- ]
168
- ]
169
- gr.Examples(examples=example_inps, inputs=[prompt, face_image, mode], label='papercut style')
170
-
171
- example_inps = [
172
- [
173
- 'woman,cartoon,solo,Popmart Blind Box, Super Mario, 3d',
174
- 'example_inputs/rihanna.webp',
175
- 'fidelity',
176
- ]
177
- ]
178
- gr.Examples(examples=example_inps, inputs=[prompt, face_image, mode], label='3d style')
179
-
180
- example_inps = [
181
- [
182
- 'portrait, the legend of zelda, anime',
183
- 'example_inputs/liuyifei.png',
184
- 'extremely style',
 
 
 
 
 
 
 
185
  ]
186
- ]
187
- gr.Examples(examples=example_inps, inputs=[prompt, face_image, mode], label='anime style')
188
-
189
- example_inps = [
190
- [
191
- 'portrait, superman',
192
- 'example_inputs/lecun.jpg',
193
- 'example_inputs/lifeifei.jpg',
194
- 'fidelity',
195
- True,
196
  ]
197
- ]
198
- gr.Examples(examples=example_inps, inputs=[prompt, face_image, supp_image1, mode, id_mix], label='id mix')
199
-
200
- with gr.Column():
201
- output = gr.Gallery(label='Output', elem_id="gallery")
202
- intermediate_output = gr.Gallery(label='DebugImage', elem_id="gallery", visible=False)
203
- gr.Markdown(_CITE_)
204
-
205
- inps = [
206
- face_image,
207
- supp_image1,
208
- supp_image2,
209
- supp_image3,
210
- prompt,
211
- neg_prompt,
212
- scale,
213
- n_samples,
214
- seed,
215
- steps,
216
- H,
217
- W,
218
- id_scale,
219
- mode,
220
- id_mix,
221
- ]
222
- submit.click(fn=run, inputs=inps, outputs=[output, intermediate_output])
223
-
224
-
225
- demo.launch()
 
 
 
 
 
1
+ import spaces
2
+ import time
3
+ import os
4
+
5
  import gradio as gr
 
6
  import torch
7
+ from einops import rearrange
8
+ from PIL import Image
9
+ from transformers import pipeline
10
+
11
+ from flux.cli import SamplingOptions
12
+ from flux.sampling import denoise, get_noise, get_schedule, prepare, unpack
13
+ from flux.util import load_ae, load_clip, load_flow_model, load_t5
14
+ from pulid.pipeline_flux import PuLIDPipeline
15
+ from pulid.utils import resize_numpy_image_long
16
+
17
+ NSFW_THRESHOLD = 0.01
18
+
19
+ def get_models(name: str, device: torch.device, offload: bool):
20
+ t5 = load_t5(device, max_length=128)
21
+ clip = load_clip(device)
22
+ model = load_flow_model(name, device="cpu" if offload else device)
23
+ model.eval()
24
+ ae = load_ae(name, device="cpu" if offload else device)
25
+ nsfw_classifier = pipeline("image-classification", model="Falconsai/nsfw_image_detection", device=device)
26
+ return model, ae, t5, clip, nsfw_classifier
27
+
28
+
29
+ class FluxGenerator:
30
+ def __init__(self):
31
+ self.device = torch.device('cuda')
32
+ self.offload = False
33
+ self.model_name = 'flux-dev'
34
+ self.model, self.ae, self.t5, self.clip, self.nsfw_classifier = get_models(
35
+ self.model_name,
36
+ device=self.device,
37
+ offload=self.offload,
38
+ )
39
+ self.pulid_model = PuLIDPipeline(self.model, 'cuda', weight_dtype=torch.bfloat16)
40
+ self.pulid_model.load_pretrain()
41
+
42
+
43
+ flux_generator = FluxGenerator()
44
+
45
+
46
+ @spaces.GPU
47
+ @torch.inference_mode()
48
+ def generate_image(
49
+ prompt,
50
+ id_image,
51
+ start_step,
52
+ guidance,
53
+ seed,
54
+ true_cfg,
55
+ width=896,
56
+ height=1152,
57
+ num_steps=20,
58
+ id_weight=1.0,
59
+ neg_prompt="bad quality, worst quality, text, signature, watermark, extra limbs",
60
+ timestep_to_start_cfg=1,
61
+ max_sequence_length=128,
62
+ ):
63
+ flux_generator.t5.max_length = max_sequence_length
64
+
65
+ seed = int(seed)
66
+ if seed == -1:
67
+ seed = None
68
+
69
+ opts = SamplingOptions(
70
+ prompt=prompt,
71
+ width=width,
72
+ height=height,
73
+ num_steps=num_steps,
74
+ guidance=guidance,
75
+ seed=seed,
76
+ )
77
+
78
+ if opts.seed is None:
79
+ opts.seed = torch.Generator(device="cpu").seed()
80
+ print(f"Generating '{opts.prompt}' with seed {opts.seed}")
81
+ t0 = time.perf_counter()
82
+
83
+ use_true_cfg = abs(true_cfg - 1.0) > 1e-2
84
 
85
  if id_image is not None:
86
  id_image = resize_numpy_image_long(id_image, 1024)
87
+ id_embeddings, uncond_id_embeddings = flux_generator.pulid_model.get_id_embedding(id_image, cal_uncond=use_true_cfg)
 
 
 
 
 
 
 
88
  else:
89
  id_embeddings = None
90
+ uncond_id_embeddings = None
91
+
92
+
93
+ # prepare input
94
+ x = get_noise(
95
+ 1,
96
+ opts.height,
97
+ opts.width,
98
+ device=flux_generator.device,
99
+ dtype=torch.bfloat16,
100
+ seed=opts.seed,
101
+ )
102
+ timesteps = get_schedule(
103
+ opts.num_steps,
104
+ x.shape[-1] * x.shape[-2] // 4,
105
+ shift=True,
106
+ )
107
+
108
+ if flux_generator.offload:
109
+ flux_generator.t5, flux_generator.clip = flux_generator.t5.to(flux_generator.device), flux_generator.clip.to(flux_generator.device)
110
+ inp = prepare(t5=flux_generator.t5, clip=flux_generator.clip, img=x, prompt=opts.prompt)
111
+ inp_neg = prepare(t5=flux_generator.t5, clip=flux_generator.clip, img=x, prompt=neg_prompt) if use_true_cfg else None
112
+
113
+ # offload TEs to CPU, load model to gpu
114
+ if flux_generator.offload:
115
+ flux_generator.t5, flux_generator.clip = flux_generator.t5.cpu(), flux_generator.clip.cpu()
116
+ torch.cuda.empty_cache()
117
+ flux_generator.model = flux_generator.model.to(flux_generator.device)
118
+
119
+ # denoise initial noise
120
+ x = denoise(
121
+ flux_generator.model, **inp, timesteps=timesteps, guidance=opts.guidance, id=id_embeddings, id_weight=id_weight,
122
+ start_step=start_step, uncond_id=uncond_id_embeddings, true_cfg=true_cfg,
123
+ timestep_to_start_cfg=timestep_to_start_cfg,
124
+ neg_txt=inp_neg["txt"] if use_true_cfg else None,
125
+ neg_txt_ids=inp_neg["txt_ids"] if use_true_cfg else None,
126
+ neg_vec=inp_neg["vec"] if use_true_cfg else None,
127
+ )
128
+
129
+ # offload model, load autoencoder to gpu
130
+ if flux_generator.offload:
131
+ flux_generator.model.cpu()
132
+ torch.cuda.empty_cache()
133
+ flux_generator.ae.decoder.to(x.device)
134
+
135
+ # decode latents to pixel space
136
+ x = unpack(x.float(), opts.height, opts.width)
137
+ with torch.autocast(device_type=flux_generator.device.type, dtype=torch.bfloat16):
138
+ x = flux_generator.ae.decode(x)
139
+
140
+ if flux_generator.offload:
141
+ flux_generator.ae.decoder.cpu()
142
+ torch.cuda.empty_cache()
143
+
144
+ t1 = time.perf_counter()
145
+
146
+ print(f"Done in {t1 - t0:.1f}s.")
147
+ # bring into PIL format
148
+ x = x.clamp(-1, 1)
149
+ # x = embed_watermark(x.float())
150
+ x = rearrange(x[0], "c h w -> h w c")
151
+
152
+ img = Image.fromarray((127.5 * (x + 1.0)).cpu().byte().numpy())
153
+ nsfw_score = [x["score"] for x in flux_generator.nsfw_classifier(img) if x["label"] == "nsfw"][0]
154
+ if nsfw_score < NSFW_THRESHOLD:
155
+ return img, str(opts.seed), flux_generator.pulid_model.debug_img_list
156
+ else:
157
+ return (None, f"Your generated image may contain NSFW (with nsfw_score: {nsfw_score}) content",
158
+ flux_generator.pulid_model.debug_img_list)
159
 
160
  _HEADER_ = '''
161
+ <div style="text-align: center; max-width: 650px; margin: 0 auto;">
162
+ <h1 style="font-size: 2.5rem; font-weight: 700; margin-bottom: 1rem; display: contents;">PuLID for FLUX</h1>
163
+ <p style="font-size: 1rem; margin-bottom: 1.5rem;">Paper: <a href='https://arxiv.org/abs/2404.16022' target='_blank'>PuLID: Pure and Lightning ID Customization via Contrastive Alignment</a> | Codes: <a href='https://github.com/ToTheBeginning/PuLID' target='_blank'>GitHub</a></p>
164
+ </div>
165
 
166
+ 🚩 Updates:
167
+ - 2024.11.01: update PuLID-FLUX-v0.9.1, please refer to <a href='https://github.com/ToTheBeginning/PuLID?tab=readme-ov-file#triangular_flag_on_post-updates'>our github repo</a> for more details.
168
 
 
169
 
170
  ❗️❗️❗️**Tips:**
 
 
 
171
 
172
+ - `timestep to start inserting ID:` The smaller the value, the higher the fidelity, but the lower the editability; the higher the value, the lower the fidelity, but the higher the editability. **The recommended range for this value is between 0 and 4**. For photorealistic scenes, we recommend using 4; for stylized scenes, we recommend using 0-1. If you are not satisfied with the similarity, you can lower this value; conversely, if you are not satisfied with the editability, you can increase this value.
173
+ - `true CFG scale:` In most scenarios, it is recommended to use a fake CFG, i.e., setting the true CFG scale to 1, and just adjusting the guidance scale. This is also more efficiency. However, in a few cases, utilizing a true CFG can yield better results. For more detaileds, please refer to the [doc](https://github.com/ToTheBeginning/PuLID/blob/main/docs/pulid_for_flux.md#useful-tips).
174
+ - `Learn more about the model:` please refer to the <a href='https://github.com/ToTheBeginning/PuLID/blob/main/docs/pulid_for_flux.md' target='_blank'>github doc</a> for more details and info about the model, we provide the detail explanation about the above two parameters in the doc.
175
+ - `Examples:` we provide some examples (we have cached them, so just click them to see what the model can do) in the bottom, you can try these example prompts first
176
  ''' # noqa E501
177
 
178
  _CITE_ = r"""
179
+ If PuLID is helpful, please help to ⭐ the <a href='https://github.com/ToTheBeginning/PuLID' target='_blank'> Github Repo</a>. Thanks!
180
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
  📧 **Contact**
182
+ If you have any questions or feedbacks, feel free to open a discussion or contact <b>[email protected]</b>.
183
  """ # noqa E501
184
 
185
+ _DEV_DES = '''
186
+ * Please refer to our repo for instructions on running gradio demo [locally](https://github.com/ToTheBeginning/PuLID/blob/main/docs/pulid_for_flux.md#local-gradio-demo)
187
+ '''
188
+
189
+
190
+ def create_demo(args, model_name: str, device: str = "cuda" if torch.cuda.is_available() else "cpu",
191
+ offload: bool = False):
192
+ with gr.Blocks() as demo:
193
+ with gr.Accordion("For Developers", open=False):
194
+ gr.Markdown(_DEV_DES)
195
+
196
+ gr.Markdown(_HEADER_)
197
+
198
+ with gr.Row():
199
+ with gr.Column():
200
+ prompt = gr.Textbox(label="Prompt", value="portrait, color, cinematic")
201
+ id_image = gr.Image(label="ID Image")
202
+ id_weight = gr.Slider(0.0, 3.0, 1, step=0.05, label="id weight")
203
+
204
+ width = gr.Slider(256, 1536, 896, step=16, label="Width")
205
+ height = gr.Slider(256, 1536, 1152, step=16, label="Height")
206
+ num_steps = gr.Slider(1, 20, 20, step=1, label="Number of steps")
207
+ start_step = gr.Slider(0, 10, 0, step=1, label="timestep to start inserting ID")
208
+ guidance = gr.Slider(1.0, 10.0, 4, step=0.1, label="Guidance")
209
+ seed = gr.Textbox(-1, label="Seed (-1 for random)")
210
+ max_sequence_length = gr.Slider(128, 512, 128, step=128,
211
+ label="max_sequence_length for prompt (T5), small will be faster")
212
+
213
+ with gr.Accordion("Advanced Options (True CFG, true_cfg_scale=1 means use fake CFG, >1 means use true CFG, if using true CFG, we recommend set the guidance scale to 1)", open=False): # noqa E501
214
+ neg_prompt = gr.Textbox(
215
+ label="Negative Prompt",
216
+ value="bad quality, worst quality, text, signature, watermark, extra limbs")
217
+ true_cfg = gr.Slider(1.0, 10.0, 1, step=0.1, label="true CFG scale")
218
+ timestep_to_start_cfg = gr.Slider(0, 20, 1, step=1, label="timestep to start cfg", visible=args.dev)
219
+
220
+ generate_btn = gr.Button("Generate")
221
+
222
+ with gr.Column():
223
+ output_image = gr.Image(label="Generated Image", format='png')
224
+ seed_output = gr.Textbox(label="Used Seed")
225
+ intermediate_output = gr.Gallery(label='Output', elem_id="gallery", visible=args.dev)
226
+ gr.Markdown(_CITE_)
227
+
228
+ with gr.Row(), gr.Column():
229
+ gr.Markdown("## Examples")
230
+ example_inps = [
231
+ [
232
+ 'a woman holding sign with glowing green text \"PuLID for FLUX\"',
233
+ 'example_inputs/liuyifei.png',
234
+ 4, 4, 2680261499100305976, 1
235
+ ],
236
+ [
237
+ 'portrait, side view',
238
+ 'example_inputs/liuyifei.png',
239
+ 4, 4, 180825677246321775, 1
240
+ ],
241
+ [
242
+ 'white-haired woman with vr technology atmosphere, revolutionary exceptional magnum with remarkable details', # noqa E501
243
+ 'example_inputs/liuyifei.png',
244
+ 4, 4, 16942328329935464989, 1
245
+ ],
246
+ [
247
+ 'a young child is eating Icecream',
248
+ 'example_inputs/liuyifei.png',
249
+ 4, 4, 4527590969012358757, 1
250
+ ],
251
+ [
252
+ 'a man is holding a sign with text \"PuLID for FLUX\", winter, snowing, top of the mountain',
253
+ 'example_inputs/pengwei.jpg',
254
+ 4, 4, 6273700647573240909, 1
255
+ ],
256
+ [
257
+ 'portrait, candle light',
258
+ 'example_inputs/pengwei.jpg',
259
+ 4, 4, 17522759474323955700, 1
260
+ ],
261
+ [
262
+ 'profile shot dark photo of a 25-year-old male with smoke escaping from his mouth, the backlit smoke gives the image an ephemeral quality, natural face, natural eyebrows, natural skin texture, award winning photo, highly detailed face, atmospheric lighting, film grain, monochrome', # noqa E501
263
+ 'example_inputs/pengwei.jpg',
264
+ 4, 4, 17733156847328193625, 1
265
+ ],
266
+ [
267
+ 'American Comics, 1boy',
268
+ 'example_inputs/pengwei.jpg',
269
+ 1, 4, 13223174453874179686, 1
270
+ ],
271
+ [
272
+ 'portrait, pixar',
273
+ 'example_inputs/pengwei.jpg',
274
+ 1, 4, 9445036702517583939, 1
275
+ ],
276
  ]
277
+ gr.Examples(examples=example_inps, inputs=[prompt, id_image, start_step, guidance, seed, true_cfg],
278
+ label='fake CFG', cache_examples='lazy', outputs=[output_image, seed_output],
279
+ fn=generate_image)
280
+
281
+ example_inps = [
282
+ [
283
+ 'portrait, made of ice sculpture',
284
+ 'example_inputs/lecun.jpg',
285
+ 1, 1, 7717391560531186077, 5
286
+ ],
287
  ]
288
+ gr.Examples(examples=example_inps, inputs=[prompt, id_image, start_step, guidance, seed, true_cfg],
289
+ label='true CFG', cache_examples='lazy', outputs=[output_image, seed_output],
290
+ fn=generate_image)
291
+
292
+ generate_btn.click(
293
+ fn=generate_image,
294
+ inputs=[prompt, id_image, start_step, guidance, seed, true_cfg, width, height, num_steps, id_weight,
295
+ neg_prompt, timestep_to_start_cfg, max_sequence_length],
296
+ outputs=[output_image, seed_output, intermediate_output],
297
+ )
298
+
299
+ return demo
300
+
301
+
302
+ if __name__ == "__main__":
303
+ import argparse
304
+
305
+ parser = argparse.ArgumentParser(description="PuLID for FLUX.1-dev")
306
+ parser.add_argument("--name", type=str, default="flux-dev", choices=list('flux-dev'),
307
+ help="currently only support flux-dev")
308
+ parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu",
309
+ help="Device to use")
310
+ parser.add_argument("--offload", action="store_true", help="Offload model to CPU when not in use")
311
+ parser.add_argument("--port", type=int, default=8080, help="Port to use")
312
+ parser.add_argument("--dev", action='store_true', help="Development mode")
313
+ parser.add_argument("--pretrained_model", type=str, help='for development')
314
+ args = parser.parse_args()
315
+
316
+ import huggingface_hub
317
+ huggingface_hub.login(os.getenv('HF_TOKEN'))
318
+
319
+ demo = create_demo(args, args.name, args.device, args.offload)
320
+ demo.launch()