prithivMLmods commited on
Commit
865dbe3
·
verified ·
1 Parent(s): 9a81f91

update app [.]

Browse files
Files changed (1) hide show
  1. app.py +437 -0
app.py ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import copy
4
+ import time
5
+ import requests
6
+ import random
7
+ import logging
8
+ import numpy as np
9
+ import spaces
10
+ from typing import Any, Dict, List, Optional, Union
11
+
12
+ import torch
13
+ from PIL import Image
14
+ import gradio as gr
15
+
16
+ from diffusers import (
17
+ DiffusionPipeline,
18
+ AutoPipelineForImage2Image,
19
+ FlowMatchEulerDiscreteScheduler
20
+ )
21
+
22
+ from huggingface_hub import (
23
+ hf_hub_download,
24
+ HfFileSystem,
25
+ ModelCard,
26
+ snapshot_download)
27
+
28
+ from diffusers.utils import load_image
29
+ from typing import Iterable
30
+ from gradio.themes import Soft
31
+ from gradio.themes.utils import colors, fonts, sizes
32
+
33
+ # --- THEME DEFINITION ---
34
+ colors.steel_blue = colors.Color(
35
+ name="steel_blue",
36
+ c50="#EBF3F8",
37
+ c100="#D3E5F0",
38
+ c200="#A8CCE1",
39
+ c300="#7DB3D2",
40
+ c400="#529AC3",
41
+ c500="#4682B4",
42
+ c600="#3E72A0",
43
+ c700="#36638C",
44
+ c800="#2E5378",
45
+ c900="#264364",
46
+ c950="#1E3450",
47
+ )
48
+
49
+ class SteelBlueTheme(Soft):
50
+ def __init__(
51
+ self,
52
+ *,
53
+ primary_hue: colors.Color | str = colors.gray,
54
+ secondary_hue: colors.Color | str = colors.steel_blue,
55
+ neutral_hue: colors.Color | str = colors.slate,
56
+ text_size: sizes.Size | str = sizes.text_lg,
57
+ font: fonts.Font | str | Iterable[fonts.Font | str] = (
58
+ fonts.GoogleFont("Outfit"), "Arial", "sans-serif",
59
+ ),
60
+ font_mono: fonts.Font | str | Iterable[fonts.Font | str] = (
61
+ fonts.GoogleFont("IBM Plex Mono"), "ui-monospace", "monospace",
62
+ ),
63
+ ):
64
+ super().__init__(
65
+ primary_hue=primary_hue,
66
+ secondary_hue=secondary_hue,
67
+ neutral_hue=neutral_hue,
68
+ text_size=text_size,
69
+ font=font,
70
+ font_mono=font_mono,
71
+ )
72
+ super().set(
73
+ background_fill_primary="*primary_50",
74
+ background_fill_primary_dark="*primary_900",
75
+ body_background_fill="linear-gradient(135deg, *primary_200, *primary_100)",
76
+ body_background_fill_dark="linear-gradient(135deg, *primary_900, *primary_800)",
77
+ button_primary_text_color="white",
78
+ button_primary_text_color_hover="white",
79
+ button_primary_background_fill="linear-gradient(90deg, *secondary_500, *secondary_600)",
80
+ button_primary_background_fill_hover="linear-gradient(90deg, *secondary_600, *secondary_700)",
81
+ button_primary_background_fill_dark="linear-gradient(90deg, *secondary_600, *secondary_800)",
82
+ button_primary_background_fill_hover_dark="linear-gradient(90deg, *secondary_500, *secondary_500)",
83
+ button_secondary_text_color="black",
84
+ button_secondary_text_color_hover="white",
85
+ button_secondary_background_fill="linear-gradient(90deg, *primary_300, *primary_300)",
86
+ button_secondary_background_fill_hover="linear-gradient(90deg, *primary_400, *primary_400)",
87
+ button_secondary_background_fill_dark="linear-gradient(90deg, *primary_500, *primary_600)",
88
+ button_secondary_background_fill_hover_dark="linear-gradient(90deg, *primary_500, *primary_500)",
89
+ slider_color="*secondary_500",
90
+ slider_color_dark="*secondary_600",
91
+ block_title_text_weight="600",
92
+ block_border_width="3px",
93
+ block_shadow="*shadow_drop_lg",
94
+ button_primary_shadow="*shadow_drop_lg",
95
+ button_large_padding="11px",
96
+ color_accent_soft="*primary_100",
97
+ block_label_background_fill="*primary_200",
98
+ )
99
+
100
+ steel_blue_theme = SteelBlueTheme()
101
+
102
+ # --- LORA DEFINITIONS ---
103
+ loras = [
104
+ {
105
+ "image": "https://huggingface.co/Shakker-Labs/AWPortrait-Z/resolve/main/images/example.png",
106
+ "title": "AWPortrait-Z",
107
+ "repo": "Shakker-Labs/AWPortrait-Z",
108
+ "weights": "AWPortrait-Z.safetensors",
109
+ "trigger_word": "Portrait"
110
+ },
111
+ {
112
+ "image": "https://huggingface.co/ostris/z_image_turbo_childrens_drawings/resolve/main/images/1764433591828__000003000_2.jpg",
113
+ "title": "Childrens Drawings",
114
+ "repo": "ostris/z_image_turbo_childrens_drawings",
115
+ "weights": "z_image_turbo_childrens_drawings.safetensors",
116
+ "trigger_word": "Children Drawings"
117
+ },
118
+ ]
119
+
120
+ # --- MODEL LOADING ---
121
+ dtype = torch.bfloat16
122
+ device = "cuda" if torch.cuda.is_available() else "cpu"
123
+ base_model = "Tongyi-MAI/Z-Image-Turbo"
124
+
125
+ print(f"Loading {base_model}...")
126
+
127
+ pipe = DiffusionPipeline.from_pretrained(
128
+ base_model,
129
+ torch_dtype=dtype,
130
+ )
131
+ pipe.to(device)
132
+
133
+ # Initialize Image-to-Image pipeline sharing components with the main pipeline
134
+ pipe_i2i = AutoPipelineForImage2Image.from_pipe(pipe)
135
+
136
+ MAX_SEED = 2**32-1
137
+
138
+ class calculateDuration:
139
+ def __init__(self, activity_name=""):
140
+ self.activity_name = activity_name
141
+
142
+ def __enter__(self):
143
+ self.start_time = time.time()
144
+ return self
145
+
146
+ def __exit__(self, exc_type, exc_value, traceback):
147
+ self.end_time = time.time()
148
+ self.elapsed_time = self.end_time - self.start_time
149
+ if self.activity_name:
150
+ print(f"Elapsed time for {self.activity_name}: {self.elapsed_time:.6f} seconds")
151
+ else:
152
+ print(f"Elapsed time: {self.elapsed_time:.6f} seconds")
153
+
154
+ def update_selection(evt: gr.SelectData, width, height):
155
+ selected_lora = loras[evt.index]
156
+ new_placeholder = f"Type a prompt for {selected_lora['title']}"
157
+ lora_repo = selected_lora["repo"]
158
+ updated_text = f"### Selected: [{lora_repo}](https://huggingface.co/{lora_repo}) ✅"
159
+ if "aspect" in selected_lora:
160
+ if selected_lora["aspect"] == "portrait":
161
+ width = 768
162
+ height = 1024
163
+ elif selected_lora["aspect"] == "landscape":
164
+ width = 1024
165
+ height = 768
166
+ else:
167
+ width = 1024
168
+ height = 1024
169
+ return (
170
+ gr.update(placeholder=new_placeholder),
171
+ updated_text,
172
+ evt.index,
173
+ width,
174
+ height,
175
+ )
176
+
177
+ @spaces.GPU
178
+ def generate_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale, progress):
179
+ pipe.to("cuda")
180
+ generator = torch.Generator(device="cuda").manual_seed(seed)
181
+
182
+ with calculateDuration("Generating image"):
183
+ image = pipe(
184
+ prompt=prompt_mash,
185
+ num_inference_steps=steps,
186
+ guidance_scale=cfg_scale,
187
+ width=width,
188
+ height=height,
189
+ generator=generator,
190
+ joint_attention_kwargs={"scale": lora_scale},
191
+ output_type="pil",
192
+ ).images[0]
193
+ yield image
194
+
195
+ def generate_image_to_image(prompt_mash, image_input_path, image_strength, steps, cfg_scale, width, height, lora_scale, seed):
196
+ generator = torch.Generator(device="cuda").manual_seed(seed)
197
+ pipe_i2i.to("cuda")
198
+ image_input = load_image(image_input_path)
199
+ final_image = pipe_i2i(
200
+ prompt=prompt_mash,
201
+ image=image_input,
202
+ strength=image_strength,
203
+ num_inference_steps=steps,
204
+ guidance_scale=cfg_scale,
205
+ width=width,
206
+ height=height,
207
+ generator=generator,
208
+ joint_attention_kwargs={"scale": lora_scale},
209
+ output_type="pil",
210
+ ).images[0]
211
+ return final_image
212
+
213
+ @spaces.GPU
214
+ def run_lora(prompt, image_input, image_strength, cfg_scale, steps, selected_index, randomize_seed, seed, width, height, lora_scale, progress=gr.Progress(track_tqdm=True)):
215
+ if selected_index is None:
216
+ raise gr.Error("You must select a LoRA before proceeding.🧨")
217
+
218
+ selected_lora = loras[selected_index]
219
+ lora_path = selected_lora["repo"]
220
+ trigger_word = selected_lora["trigger_word"]
221
+
222
+ if(trigger_word):
223
+ if "trigger_position" in selected_lora:
224
+ if selected_lora["trigger_position"] == "prepend":
225
+ prompt_mash = f"{trigger_word} {prompt}"
226
+ else:
227
+ prompt_mash = f"{prompt} {trigger_word}"
228
+ else:
229
+ prompt_mash = f"{trigger_word} {prompt}"
230
+ else:
231
+ prompt_mash = prompt
232
+
233
+ with calculateDuration("Unloading LoRA"):
234
+ pipe.unload_lora_weights()
235
+ pipe_i2i.unload_lora_weights()
236
+
237
+ # LoRA weights flow
238
+ with calculateDuration(f"Loading LoRA weights for {selected_lora['title']}"):
239
+ pipe_to_use = pipe_i2i if image_input is not None else pipe
240
+ weight_name = selected_lora.get("weights", None)
241
+
242
+ try:
243
+ pipe_to_use.load_lora_weights(
244
+ lora_path,
245
+ weight_name=weight_name,
246
+ low_cpu_mem_usage=True
247
+ )
248
+ except Exception as e:
249
+ print(f"Error loading LoRA: {e}")
250
+ raise gr.Error(f"Failed to load LoRA: {str(e)}")
251
+
252
+ with calculateDuration("Randomizing seed"):
253
+ if randomize_seed:
254
+ seed = random.randint(0, MAX_SEED)
255
+
256
+ if(image_input is not None):
257
+ final_image = generate_image_to_image(prompt_mash, image_input, image_strength, steps, cfg_scale, width, height, lora_scale, seed)
258
+ yield final_image, seed, gr.update(visible=False)
259
+ else:
260
+ # Standard generation
261
+ image_generator = generate_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale, progress)
262
+
263
+ final_image = None
264
+ # We process the generator (even if it yields once)
265
+ for image in image_generator:
266
+ final_image = image
267
+ yield image, seed, gr.update(visible=False)
268
+
269
+ def get_huggingface_safetensors(link):
270
+ split_link = link.split("/")
271
+ if(len(split_link) == 2):
272
+ model_card = ModelCard.load(link)
273
+ base_model_meta = model_card.data.get("base_model")
274
+ print(f"Base model metadata: {base_model_meta}")
275
+
276
+ # Note: We relax the check here slightly to allow models compatible with Turbo/Flux
277
+ # or we just rely on try/catch during loading.
278
+
279
+ image_path = model_card.data.get("widget", [{}])[0].get("output", {}).get("url", None)
280
+ trigger_word = model_card.data.get("instance_prompt", "")
281
+ image_url = f"https://huggingface.co/{link}/resolve/main/{image_path}" if image_path else None
282
+ fs = HfFileSystem()
283
+ safetensors_name = None
284
+ try:
285
+ list_of_files = fs.ls(link, detail=False)
286
+ for file in list_of_files:
287
+ if(file.endswith(".safetensors")):
288
+ safetensors_name = file.split("/")[-1]
289
+ if (not image_url and file.lower().endswith((".jpg", ".jpeg", ".png", ".webp"))):
290
+ image_elements = file.split("/")
291
+ image_url = f"https://huggingface.co/{link}/resolve/main/{image_elements[-1]}"
292
+ except Exception as e:
293
+ print(e)
294
+ gr.Warning(f"You didn't include a link neither a valid Hugging Face repository with a *.safetensors LoRA")
295
+ raise Exception(f"You didn't include a link neither a valid Hugging Face repository with a *.safetensors LoRA")
296
+ return split_link[1], link, safetensors_name, trigger_word, image_url
297
+
298
+ def check_custom_model(link):
299
+ if(link.startswith("https://")):
300
+ if(link.startswith("https://huggingface.co") or link.startswith("https://www.huggingface.co")):
301
+ link_split = link.split("huggingface.co/")
302
+ return get_huggingface_safetensors(link_split[1])
303
+ else:
304
+ return get_huggingface_safetensors(link)
305
+
306
+ def add_custom_lora(custom_lora):
307
+ global loras
308
+ if(custom_lora):
309
+ try:
310
+ title, repo, path, trigger_word, image = check_custom_model(custom_lora)
311
+ print(f"Loaded custom LoRA: {repo}")
312
+ card = f'''
313
+ <div class="custom_lora_card">
314
+ <span>Loaded custom LoRA:</span>
315
+ <div class="card_internal">
316
+ <img src="{image}" />
317
+ <div>
318
+ <h3>{title}</h3>
319
+ <small>{"Using: <code><b>"+trigger_word+"</code></b> as the trigger word" if trigger_word else "No trigger word found. If there's a trigger word, include it in your prompt"}<br></small>
320
+ </div>
321
+ </div>
322
+ </div>
323
+ '''
324
+ existing_item_index = next((index for (index, item) in enumerate(loras) if item['repo'] == repo), None)
325
+ if(not existing_item_index):
326
+ new_item = {
327
+ "image": image,
328
+ "title": title,
329
+ "repo": repo,
330
+ "weights": path,
331
+ "trigger_word": trigger_word
332
+ }
333
+ print(new_item)
334
+ existing_item_index = len(loras)
335
+ loras.append(new_item)
336
+
337
+ return gr.update(visible=True, value=card), gr.update(visible=True), gr.Gallery(selected_index=None), f"Custom: {path}", existing_item_index, trigger_word
338
+ except Exception as e:
339
+ gr.Warning(f"Invalid LoRA: either you entered an invalid link, or incompatible LoRA")
340
+ return gr.update(visible=True, value=f"Invalid LoRA: {str(e)}"), gr.update(visible=False), gr.update(), "", None, ""
341
+ else:
342
+ return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""
343
+
344
+ def remove_custom_lora():
345
+ return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""
346
+
347
+ run_lora.zerogpu = True
348
+
349
+ css = '''
350
+ #gen_btn{height: 100%}
351
+ #gen_column{align-self: stretch}
352
+ #title{text-align: center}
353
+ #title h1{font-size: 3em; display:inline-flex; align-items:center}
354
+ #title img{width: 100px; margin-right: 0.5em}
355
+ #gallery .grid-wrap{height: 10vh}
356
+ #lora_list{background: var(--block-background-fill);padding: 0 1em .3em; font-size: 90%}
357
+ .card_internal{display: flex;height: 100px;margin-top: .5em}
358
+ .card_internal img{margin-right: 1em}
359
+ .styler{--form-gap-width: 0px !important}
360
+ #progress{height:30px}
361
+ #progress .generating{display:none}
362
+ .progress-container {width: 100%;height: 30px;background-color: #f0f0f0;border-radius: 15px;overflow: hidden;margin-bottom: 20px}
363
+ .progress-bar {height: 100%;background-color: #4f46e5;width: calc(var(--current) / var(--total) * 100%);transition: width 0.5s ease-in-out}
364
+ '''
365
+
366
+ with gr.Blocks(delete_cache=(60, 60)) as demo:
367
+ title = gr.HTML(
368
+ """<h1>Z-Image-Turbo LoRA Studio ⚡</h1>""",
369
+ elem_id="title",
370
+ )
371
+ selected_index = gr.State(None)
372
+ with gr.Row():
373
+ with gr.Column(scale=3):
374
+ prompt = gr.Textbox(label="Prompt", lines=1, placeholder="✦︎ Choose the LoRA and type the prompt ")
375
+ with gr.Column(scale=1, elem_id="gen_column"):
376
+ generate_button = gr.Button("Generate", variant="primary", elem_id="gen_btn")
377
+ with gr.Row():
378
+ with gr.Column():
379
+ selected_info = gr.Markdown("")
380
+ gallery = gr.Gallery(
381
+ [(item["image"], item["title"]) for item in loras],
382
+ label="Z-Image-Turbo LoRAs",
383
+ allow_preview=False,
384
+ columns=3,
385
+ elem_id="gallery",
386
+ )
387
+ with gr.Group():
388
+ custom_lora = gr.Textbox(label="Enter Custom LoRA", placeholder="Shakker-Labs/AWPortrait-Z")
389
+ gr.Markdown("[Check the list of Z-Image-Turbo LoRA's](https://huggingface.co/models?other=base_model:adapter:Tongyi-MAI/Z-Image-Turbo)", elem_id="lora_list")
390
+ custom_lora_info = gr.HTML(visible=False)
391
+ custom_lora_button = gr.Button("Remove custom LoRA", visible=False)
392
+ with gr.Column():
393
+ progress_bar = gr.Markdown(elem_id="progress",visible=False)
394
+ result = gr.Image(label="Generated Image", format="png")
395
+
396
+ with gr.Row():
397
+ with gr.Accordion("Advanced Settings", open=False):
398
+ with gr.Row():
399
+ input_image = gr.Image(label="Input image", type="filepath")
400
+ image_strength = gr.Slider(label="Denoise Strength", info="Lower means more image influence", minimum=0.1, maximum=1.0, step=0.01, value=0.75)
401
+ with gr.Column():
402
+ with gr.Row():
403
+ cfg_scale = gr.Slider(label="CFG Scale", minimum=1, maximum=20, step=0.5, value=3.5)
404
+ steps = gr.Slider(label="Steps", minimum=1, maximum=50, step=1, value=9)
405
+
406
+ with gr.Row():
407
+ width = gr.Slider(label="Width", minimum=256, maximum=1536, step=64, value=1024)
408
+ height = gr.Slider(label="Height", minimum=256, maximum=1536, step=64, value=1024)
409
+
410
+ with gr.Row():
411
+ randomize_seed = gr.Checkbox(True, label="Randomize seed")
412
+ seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0, randomize=True)
413
+ lora_scale = gr.Slider(label="LoRA Scale", minimum=0, maximum=3, step=0.01, value=0.95)
414
+
415
+ gallery.select(
416
+ update_selection,
417
+ inputs=[width, height],
418
+ outputs=[prompt, selected_info, selected_index, width, height]
419
+ )
420
+ custom_lora.input(
421
+ add_custom_lora,
422
+ inputs=[custom_lora],
423
+ outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, prompt]
424
+ )
425
+ custom_lora_button.click(
426
+ remove_custom_lora,
427
+ outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, custom_lora]
428
+ )
429
+ gr.on(
430
+ triggers=[generate_button.click, prompt.submit],
431
+ fn=run_lora,
432
+ inputs=[prompt, input_image, image_strength, cfg_scale, steps, selected_index, randomize_seed, seed, width, height, lora_scale],
433
+ outputs=[result, seed, progress_bar]
434
+ )
435
+
436
+ demo.queue()
437
+ demo.launch(theme=steel_blue_theme, css=css, mcp_server=True, ssr_mode=False, show_error=True)