AlekseyCalvin commited on
Commit
2290e72
1 Parent(s): b040fe3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +249 -0
app.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import json
4
+ import logging
5
+ import torch
6
+ from PIL import Image
7
+ from os import path
8
+ import spaces
9
+ from diffusers import DiffusionPipeline, AutoencoderTiny, AutoencoderKL
10
+ from diffusers.models.transformers import FluxTransformer2DModel
11
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
12
+ from transformers import CLIPModel, CLIPProcessor, CLIPTextModel, CLIPTokenizer, CLIPConfig, T5EncoderModel, T5Tokenizer
13
+ import copy
14
+ import random
15
+ import time
16
+ from live_preview_helpers import calculate_shift, retrieve_timesteps, flux_pipe_call_that_returns_an_iterable_of_images
17
+ from huggingface_hub import HfFileSystem, ModelCard
18
+ from huggingface_hub import login, hf_hub_download
19
+ import safetensors.torch
20
+ from safetensors.torch import load_file
21
+ hf_token = os.environ.get("HF_TOKEN")
22
+ login(token=hf_token)
23
+
24
+ cache_path = path.join(path.dirname(path.abspath(__file__)), "models")
25
+ os.environ["TRANSFORMERS_CACHE"] = cache_path
26
+ os.environ["HF_HUB_CACHE"] = cache_path
27
+ os.environ["HF_HOME"] = cache_path
28
+
29
+ torch.set_float32_matmul_precision("medium")
30
+
31
+ #torch._inductor.config.conv_1x1_as_mm = True
32
+ #torch._inductor.config.coordinate_descent_tuning = True
33
+ #torch._inductor.config.epilogue_fusion = False
34
+ #torch._inductor.config.coordinate_descent_check_all_directions = False
35
+
36
+ # Load LoRAs from JSON file
37
+ with open('loras.json', 'r') as f:
38
+ loras = json.load(f)
39
+
40
+ # Initialize the base model
41
+ dtype = torch.bfloat16
42
+ device = "cuda" if torch.cuda.is_available() else "cpu"
43
+
44
+ taef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype).to(device)
45
+ good_vae = AutoencoderKL.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="vae", torch_dtype=dtype).to(device)
46
+
47
+ pipe = DiffusionPipeline.from_pretrained(
48
+ "AlekseyCalvin/Flux_Dedistilled_Mix_byWikeeyang_Diffusers",
49
+ custom_pipeline="jimmycarter/LibreFLUX",
50
+ use_safetensors=True,
51
+ torch_dtype=torch.bfloat16,
52
+ trust_remote_code=True,
53
+ ).to(device)
54
+
55
+ clipmodel = 'norm'
56
+ if clipmodel == "long":
57
+ model_id = "zer0int/LongCLIP-GmP-ViT-L-14"
58
+ config = CLIPConfig.from_pretrained(model_id)
59
+ maxtokens = 77
60
+ if clipmodel == "norm":
61
+ model_id = "zer0int/CLIP-GmP-ViT-L-14"
62
+ config = CLIPConfig.from_pretrained(model_id)
63
+ maxtokens = 77
64
+ clip_model = CLIPModel.from_pretrained(model_id, torch_dtype=torch.bfloat16, config=config, ignore_mismatched_sizes=True).to("cuda")
65
+ clip_processor = CLIPProcessor.from_pretrained(model_id, padding="max_length", max_length=maxtokens, ignore_mismatched_sizes=True, return_tensors="pt", truncation=True)
66
+
67
+ pipe.tokenizer = clip_processor.tokenizer
68
+ pipe.text_encoder = clip_model.text_model
69
+ pipe.tokenizer_max_length = maxtokens
70
+ pipe.text_encoder.dtype = torch.bfloat16
71
+ pipe.vae = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype).to("cuda")
72
+
73
+
74
+ #pipe.transformer.to(memory_format=torch.channels_last)
75
+ #pipe.vae.to(memory_format=torch.channels_last)
76
+
77
+ #pipe.transformer = torch.compile(pipe.transformer, mode="max-autotune", fullgraph=False)
78
+ #pipe.vae.decode = torch.compile(pipe.vae.decode, mode="max-autotune", fullgraph=False)
79
+
80
+ MAX_SEED = 2**32-1
81
+
82
+ class calculateDuration:
83
+ def __init__(self, activity_name=""):
84
+ self.activity_name = activity_name
85
+
86
+ def __enter__(self):
87
+ self.start_time = time.time()
88
+ return self
89
+
90
+ def __exit__(self, exc_type, exc_value, traceback):
91
+ self.end_time = time.time()
92
+ self.elapsed_time = self.end_time - self.start_time
93
+ if self.activity_name:
94
+ print(f"Elapsed time for {self.activity_name}: {self.elapsed_time:.6f} seconds")
95
+ else:
96
+ print(f"Elapsed time: {self.elapsed_time:.6f} seconds")
97
+
98
+
99
+ def update_selection(evt: gr.SelectData, width, height):
100
+ selected_lora = loras[evt.index]
101
+ new_placeholder = f"Type a prompt for {selected_lora['title']}"
102
+ lora_repo = selected_lora["repo"]
103
+ updated_text = f"### Selected: [{lora_repo}](https://huggingface.co/{lora_repo}) ✨"
104
+ if "aspect" in selected_lora:
105
+ if selected_lora["aspect"] == "portrait":
106
+ width = 768
107
+ height = 1024
108
+ elif selected_lora["aspect"] == "landscape":
109
+ width = 1024
110
+ height = 768
111
+ return (
112
+ gr.update(placeholder=new_placeholder),
113
+ updated_text,
114
+ evt.index,
115
+ width,
116
+ height,
117
+ )
118
+
119
+ @spaces.GPU(duration=70)
120
+ def generate_image(prompt, trigger_word, steps, seed, cfg_scale, width, height, negative_prompt, lora_scale, progress, no_cfg_until_timestep):
121
+ pipe.to("cuda")
122
+ generator = torch.Generator(device="cuda").manual_seed(seed)
123
+
124
+ with calculateDuration("Generating image"):
125
+ # Generate image
126
+ image = pipe(
127
+ prompt=f"{prompt} {trigger_word}",
128
+ num_inference_steps=steps,
129
+ guidance_scale=cfg_scale,
130
+ width=width,
131
+ height=height,
132
+ generator=generator,
133
+ negative_prompt=negative_prompt,
134
+ joint_attention_kwargs={"scale": lora_scale},
135
+ no_cfg_until_timestep=2,
136
+ ).images[0]
137
+ return image
138
+
139
+ def run_lora(prompt, cfg_scale, steps, selected_index, randomize_seed, seed, width, height, negative_prompt, lora_scale, no_cfg_until_timestep=2, progress=gr.Progress(track_tqdm=True)):
140
+ if selected_index is None:
141
+ raise gr.Error("You must select a LoRA before proceeding.")
142
+
143
+ selected_lora = loras[selected_index]
144
+ lora_path = selected_lora["repo"]
145
+ trigger_word = selected_lora["trigger_word"]
146
+ if(trigger_word):
147
+ if "trigger_position" in selected_lora:
148
+ if selected_lora["trigger_position"] == "prepend":
149
+ prompt_mash = f"{trigger_word} {prompt}"
150
+ else:
151
+ prompt_mash = f"{prompt} {trigger_word}"
152
+ else:
153
+ prompt_mash = f"{trigger_word} {prompt}"
154
+ else:
155
+ prompt_mash = prompt
156
+
157
+ # Load LoRA weights
158
+ with calculateDuration(f"Loading LoRA weights for {selected_lora['title']}"):
159
+ if "weights" in selected_lora:
160
+ pipe.load_lora_weights(lora_path, weight_name=selected_lora["weights"])
161
+ else:
162
+ pipe.load_lora_weights(lora_path)
163
+
164
+ # Set random seed for reproducibility
165
+ with calculateDuration("Randomizing seed"):
166
+ if randomize_seed:
167
+ seed = random.randint(0, MAX_SEED)
168
+
169
+ image = generate_image(prompt, trigger_word, steps, seed, cfg_scale, width, height, negative_prompt, lora_scale, progress, no_cfg_until_timestep)
170
+ pipe.to("cpu")
171
+ pipe.unload_lora_weights()
172
+ return image, seed
173
+
174
+ run_lora.zerogpu = True
175
+
176
+ css = '''
177
+ #gen_btn{height: 100%}
178
+ #title{text-align: center}
179
+ #title h1{font-size: 3em; display:inline-flex; align-items:center}
180
+ #title img{width: 100px; margin-right: 0.5em}
181
+ #gallery .grid-wrap{height: 10vh}
182
+ '''
183
+ with gr.Blocks(theme=gr.themes.Soft(), css=css) as app:
184
+ title = gr.HTML(
185
+ """<h1><img src="https://huggingface.co/AlekseyCalvin/HSTklimbimOPENfluxLora/resolve/main/acs62iv.png" alt="LoRA"> LibreFLUX SOONfactory </h1>""",
186
+ elem_id="title",
187
+ )
188
+ # Info blob stating what the app is running
189
+ info_blob = gr.HTML(
190
+ """<div id="info_blob"> SOON®'s curated LoRa Gallery & Art Manufactory Space | Over LibreFLUX (jimmycarter/LibreFLUX): a slowish, rawer, & freest Flux de-distilled from Schnell + Zer0int's fine-tuned CLIP(*'norm' 77 size for now)| Largely stocked w/our trained LoRAs: Historic Color, Silver Age Poets, Sots Art, more!|</div>"""
191
+ )
192
+
193
+ # Info blob stating what the app is running
194
+ info_blob = gr.HTML(
195
+ """<div id="info_blob"> Pre-phrase Prompts w/: 1-2. HST style |3. RCA poster |4.SOTS art |5.HST Austin Osman Spare |6. Mayakovsky |7-8. Tsvetaeva |9. Akhmatova |10. Mandelshtam |11-13. Blok |14. LEN Lenin |15. Trotsky |16. Rosa Fluxenburg |17-30. HST |31. how2draw |32. propaganda poster |33. TOK photo cartoon hybrid |34. photo |35.unexpected photo |36. flmft |37. Yearbook |38. TOK portra |39. pficonics |40. retrofuturism |41. wh3r3sw4ld0 |42. amateur photo |43. crisp photo |44-45. ADU |46. Film Photo |47. ff-collage |48. HST|49-50. AOS Austin Osman Spare art |51. cover </div>"""
196
+ )
197
+ selected_index = gr.State(None)
198
+ with gr.Row():
199
+ with gr.Column(scale=2):
200
+ prompt = gr.Textbox(label="Prompt", lines=1, placeholder="Select LoRa/Style & type prompt!")
201
+ with gr.Column(scale=2):
202
+ negative_prompt = gr.Textbox(label="Negative Prompt", lines=1, placeholder="What to exclude!")
203
+ with gr.Column(scale=1, elem_id="gen_column"):
204
+ generate_button = gr.Button("Generate", variant="primary", elem_id="gen_btn")
205
+ with gr.Row():
206
+ with gr.Column(scale=3):
207
+ selected_info = gr.Markdown("")
208
+ gallery = gr.Gallery(
209
+ [(item["image"], item["title"]) for item in loras],
210
+ label="LoRA Inventory",
211
+ allow_preview=False,
212
+ columns=3,
213
+ elem_id="gallery"
214
+ )
215
+
216
+ with gr.Column(scale=4):
217
+ result = gr.Image(label="Generated Image")
218
+
219
+ with gr.Row():
220
+ with gr.Accordion("Advanced Settings", open=True):
221
+ with gr.Column():
222
+ with gr.Row():
223
+ cfg_scale = gr.Slider(label="CFG Scale", minimum=0, maximum=20, step=0.5, value=2.5)
224
+ steps = gr.Slider(label="Steps", minimum=1, maximum=50, step=1, value=20)
225
+
226
+ with gr.Row():
227
+ width = gr.Slider(label="Width", minimum=256, maximum=1536, step=64, value=768)
228
+ height = gr.Slider(label="Height", minimum=256, maximum=1536, step=64, value=768)
229
+
230
+ with gr.Row():
231
+ randomize_seed = gr.Checkbox(True, label="Randomize seed")
232
+ seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0, randomize=True)
233
+ lora_scale = gr.Slider(label="LoRA Scale", minimum=0, maximum=2.0, step=0.01, value=0.9)
234
+
235
+ gallery.select(
236
+ update_selection,
237
+ inputs=[width, height],
238
+ outputs=[prompt, selected_info, selected_index, width, height]
239
+ )
240
+
241
+ gr.on(
242
+ triggers=[generate_button.click, prompt.submit],
243
+ fn=run_lora,
244
+ inputs=[prompt, cfg_scale, steps, selected_index, randomize_seed, seed, width, height, negative_prompt, lora_scale],
245
+ outputs=[result, seed]
246
+ )
247
+
248
+ app.queue(default_concurrency_limit=2).launch(show_error=True)
249
+ app.launch()