File size: 7,778 Bytes
0b25f63
9a3f0d1
0b25f63
 
 
 
 
e4ee15c
0b25f63
 
 
 
9a3f0d1
0b25f63
9a3f0d1
adddbc4
 
0b25f63
 
 
9a3f0d1
0b25f63
 
9a3f0d1
0b25f63
 
 
 
 
f30e9ce
5ce6559
 
 
 
 
 
 
 
 
0b25f63
 
 
 
 
 
 
 
 
 
 
 
e777edc
0b25f63
 
 
 
 
 
 
 
 
adddbc4
 
0b25f63
db5708c
 
0b25f63
 
 
 
 
 
 
 
 
 
 
 
 
0f2c19b
0b25f63
 
 
eb27870
0b25f63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adddbc4
 
 
0b25f63
e777edc
adddbc4
0b25f63
 
e777edc
 
0b25f63
 
 
 
 
 
 
 
 
9a3f0d1
0b25f63
 
e777edc
0b25f63
 
f30e9ce
 
0b25f63
f30e9ce
e777edc
0b25f63
 
 
 
e777edc
885080e
f30e9ce
 
 
 
 
 
 
 
 
 
9a3f0d1
e777edc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a3f0d1
e777edc
9f8a91d
 
 
 
 
9a3f0d1
e777edc
eb27870
e777edc
9a3f0d1
0b25f63
e777edc
 
 
 
 
0b25f63
 
db5708c
e777edc
0f2c19b
0b25f63
e777edc
 
9a3f0d1
0b25f63
e777edc
 
0b25f63
e777edc
 
 
 
adddbc4
609484b
adddbc4
4a9687c
9a3f0d1
e777edc
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
import os
import gradio as gr
import json
import logging
import torch
from PIL import Image
import spaces
from diffusers import DiffusionPipeline, AutoencoderTiny, AutoencoderKL, FluxImg2ImgPipeline
from live_preview_helpers import calculate_shift, retrieve_timesteps, flux_pipe_call_that_returns_an_iterable_of_images
from diffusers.utils import load_image
from huggingface_hub import hf_hub_download, HfFileSystem, ModelCard, snapshot_download
import copy
import random
import time

selected_lora_index = None

# Load LoRAs from JSON file
with open('loras.json', 'r') as f:
    loras = json.load(f)

# Initialize the base model
dtype = torch.bfloat16
device = "cuda" if torch.cuda.is_available() else "cpu"
base_model = "black-forest-labs/FLUX.1-dev"

taef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype).to(device)
good_vae = AutoencoderKL.from_pretrained(base_model, subfolder="vae", torch_dtype=dtype).to(device)
pipe = DiffusionPipeline.from_pretrained(base_model, torch_dtype=dtype, vae=taef1).to(device)
pipe_i2i = FluxImg2ImgPipeline.from_pretrained(
    base_model,
    vae=good_vae,
    transformer=pipe.transformer,
    text_encoder=pipe.text_encoder,
    tokenizer=pipe.tokenizer,
    text_encoder_2=pipe.text_encoder_2,
    tokenizer_2=pipe.tokenizer_2,
    torch_dtype=dtype
)

MAX_SEED = 2**32-1

pipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)

class calculateDuration:
    def __init__(self, activity_name=""):
        self.activity_name = activity_name

    def __enter__(self):
        self.start_time = time.time()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.end_time = time.time()
        self.elapsed_time = self.end_time - self.start_time
        if self.activity_name:
            print(f"Elapsed time for {self.activity_name}: {self.elapsed_time:.6f} seconds")
        else:
            print(f"Elapsed time: {self.elapsed_time:.6f} seconds")

def update_selection(evt: gr.SelectData, width, height):
    global selected_lora_index
    selected_lora_index = evt.index
    selected_lora = loras[evt.index]
    default_prompt = selected_lora.get('default_prompt', '')
    new_placeholder = f"{selected_lora['trigger_word']} {default_prompt}"
    lora_repo = selected_lora["repo"]
    updated_text = f"### Selected: [{lora_repo}](https://huggingface.co/{lora_repo}) ✨"
    if "aspect" in selected_lora:
        if selected_lora["aspect"] == "portrait":
            width = 768
            height = 1024
        elif selected_lora["aspect"] == "landscape":
            width = 1024
            height = 768
        else:
            width = 1024
            height = 1024
    return (
        gr.update(value=new_placeholder),
        updated_text,
        width,
        height,
        gr.update(interactive=True)  # Enable the Generate button
    )

@spaces.GPU(duration=70)
def generate_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale, progress):
    pipe.to("cuda")
    generator = torch.Generator(device="cuda").manual_seed(seed)
    with calculateDuration("Generating image"):
        # Generate image
        for img in pipe.flux_pipe_call_that_returns_an_iterable_of_images(
            prompt=prompt_mash,
            num_inference_steps=steps,
            guidance_scale=cfg_scale,
            width=width,
            height=height,
            generator=generator,
            joint_attention_kwargs={"scale": lora_scale},
            output_type="pil",
            good_vae=good_vae,
        ):
            yield img

def run_lora(prompt, cfg_scale, steps, randomize_seed, seed, width, height, lora_scale, progress=gr.Progress(track_tqdm=True)):
    global selected_lora_index
    if selected_lora_index is None:
        raise gr.Error("You must select a LoRA before proceeding.")
    
    selected_lora = loras[selected_lora_index]
    lora_path = selected_lora["repo"]
    trigger_word = selected_lora["trigger_word"]
    
    if trigger_word:
        if "trigger_position" in selected_lora:
            if selected_lora["trigger_position"] == "prepend":
                prompt_mash = f"{trigger_word} {prompt}"
            else:
                prompt_mash = f"{prompt} {trigger_word}"
        else:
            prompt_mash = f"{trigger_word} {prompt}"
    else:
        prompt_mash = prompt

    with calculateDuration("Unloading LoRA"):
        pipe.unload_lora_weights()

    # Load LoRA weights
    with calculateDuration(f"Loading LoRA weights for {selected_lora['title']}"):
        if "weights" in selected_lora:
            pipe.load_lora_weights(lora_path, weight_name=selected_lora["weights"])
        else:
            pipe.load_lora_weights(lora_path)

    # Set random seed for reproducibility
    with calculateDuration("Randomizing seed"):
        if randomize_seed:
            seed = random.randint(0, MAX_SEED)

    image_generator = generate_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale, progress)
    # Consume the generator to get the final image
    final_image = None
    step_counter = 0
    for image in image_generator:
        step_counter += 1
        final_image = image
        progress_bar = f'Generating image... Step {step_counter}/{steps}'
        yield image, seed, gr.update(visible=True, value=progress_bar)
    
    yield final_image, seed, gr.update(visible=False)

# Gradio interface
with gr.Blocks() as demo:
    gr.Markdown("# Awaken Ones' Lora Previews")
    gr.Markdown("Select a LoRA model from the gallery below to get started!")
    
    with gr.Row():
        gallery = gr.Gallery(
            value=[lora["image"] for lora in loras],
            label="LoRA Gallery",
            show_label=False,
            elem_id="gallery",
            columns=[5],
            rows=[3],
            object_fit="contain",
            height="auto",
        )

    with gr.Row():
        prompt = gr.Textbox(
            label="Prompt",
            placeholder="Type your prompt here...",
            show_label=True,
        )

    with gr.Row():
        generate = gr.Button("Generate", variant="primary", interactive=False)
        cancel = gr.Button("Cancel")

    with gr.Row():
        with gr.Column(scale=4):
            result = gr.Image(label="Result", show_label=False, elem_id="result")
        with gr.Column(scale=1):
            seed_output = gr.Number(label="Seed", interactive=False)

    with gr.Row():
        with gr.Column():
            steps = gr.Slider(minimum=1, maximum=100, value=25, step=1, label="Steps")
            cfg_scale = gr.Slider(minimum=1, maximum=20, value=3.5, step=0.1, label="CFG Scale")
            lora_scale = gr.Slider(minimum=0, maximum=2, value=1, step=0.1, label="LoRA Scale")
        with gr.Column():
            width = gr.Slider(minimum=256, maximum=1024, value=512, step=64, label="Width")
            height = gr.Slider(minimum=256, maximum=1024, value=512, step=64, label="Height")

    with gr.Row():
        randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
        seed_input = gr.Number(label="Seed", value=0, interactive=True, visible=False)

    selected_lora = gr.Markdown("### No LoRA selected")
    progress_bar = gr.Markdown(visible=False)

    # Event handlers
    gallery.select(update_selection, [width, height], [prompt, selected_lora, width, height, generate])
    randomize_seed.change(lambda x: gr.update(visible=not x), randomize_seed, seed_input)
    generate_event = generate.click(run_lora, inputs=[prompt, cfg_scale, steps, randomize_seed, seed_input, width, height, lora_scale], outputs=[result, seed_output, progress_bar])
    cancel.click(lambda: None, None, None, cancels=[generate_event])

demo.queue().launch()