AlekseyCalvin commited on
Commit
fb103c9
1 Parent(s): 0459549

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +213 -0
app.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import json
3
+ import logging
4
+ import argparse
5
+ import torch
6
+ import os
7
+ from os import path
8
+ from PIL import Image
9
+ import numpy as np
10
+ import spaces
11
+ import copy
12
+ import random
13
+ import time
14
+ from typing import Any, Dict, List, Optional, Union
15
+ from huggingface_hub import hf_hub_download
16
+ from diffusers import DiffusionPipeline, FluxTransformer2DModel, FluxPipeline, AutoencoderTiny
17
+ import safetensors.torch
18
+ from safetensors.torch import load_file
19
+ from custom_pipeline import FluxWithCFGPipeline
20
+ import gc
21
+
22
+ cache_path = path.join(path.dirname(path.abspath(__file__)), "models")
23
+ os.environ["TRANSFORMERS_CACHE"] = cache_path
24
+ os.environ["HF_HUB_CACHE"] = cache_path
25
+ os.environ["HF_HOME"] = cache_path
26
+
27
+ torch.backends.cuda.matmul.allow_tf32 = True
28
+
29
+ dtype = torch.float16
30
+ pipe = FluxWithCFGPipeline.from_pretrained(
31
+ "ostris/OpenFLUX.1", torch_dtype=dtype
32
+ )
33
+ # pipe.vae = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype)
34
+ # pipe.load_lora_weights("ostris/OpenFLUX.1", weight_name="openflux1-v0.1.0-fast-lora.safetensors", adapter_name="fast")
35
+ # pipe.set_adapters("fast")
36
+ # pipe.fuse_lora(adapter_names=["fast"], lora_scale=1.0)
37
+ pipe.to("cuda")
38
+ pipe.transformer.to(memory_format=torch.channels_last)
39
+ pipe.transformer = torch.compile(
40
+ pipe.transformer, mode="max-autotune", fullgraph=True
41
+ )
42
+ torch.cuda.empty_cache()
43
+
44
+ # Load LoRAs from JSON file
45
+ with open('loras.json', 'r') as f:
46
+ loras = json.load(f)
47
+
48
+ MAX_SEED = 2**32-1
49
+
50
+ class calculateDuration:
51
+ def __init__(self, activity_name=""):
52
+ self.activity_name = activity_name
53
+
54
+ def __enter__(self):
55
+ self.start_time = time.time()
56
+ return self
57
+
58
+ def __exit__(self, exc_type, exc_value, traceback):
59
+ self.end_time = time.time()
60
+ self.elapsed_time = self.end_time - self.start_time
61
+ if self.activity_name:
62
+ print(f"Elapsed time for {self.activity_name}: {self.elapsed_time:.6f} seconds")
63
+ else:
64
+ print(f"Elapsed time: {self.elapsed_time:.6f} seconds")
65
+
66
+
67
+ def update_selection(evt: gr.SelectData, width, height):
68
+ selected_lora = loras[evt.index]
69
+ new_placeholder = f"Type a prompt for {selected_lora['title']}"
70
+ lora_repo = selected_lora["repo"]
71
+ updated_text = f"### Selected: [{lora_repo}](https://huggingface.co/{lora_repo}) ✨"
72
+ if "aspect" in selected_lora:
73
+ if selected_lora["aspect"] == "portrait":
74
+ width = 768
75
+ height = 1024
76
+ elif selected_lora["aspect"] == "landscape":
77
+ width = 1024
78
+ height = 768
79
+ return (
80
+ gr.update(placeholder=new_placeholder),
81
+ updated_text,
82
+ evt.index,
83
+ width,
84
+ height,
85
+ )
86
+
87
+ @spaces.GPU(duration=70)
88
+ def generate_image(prompt, trigger_word, steps, seed, cfg_scale, width, height, lora_scale, progress):
89
+ pipe.to("cuda")
90
+ generator = torch.Generator(device="cuda").manual_seed(seed)
91
+
92
+ with calculateDuration("Generating image"):
93
+ # Generate image
94
+ image = pipe(
95
+ prompt=f"{prompt} {trigger_word}",
96
+ num_inference_steps=steps,
97
+ guidance_scale=cfg_scale,
98
+ width=width,
99
+ height=height,
100
+ generator=generator,
101
+ joint_attention_kwargs={"scale": lora_scale},
102
+ ).images[0]
103
+ return image
104
+
105
+ def run_lora(prompt, cfg_scale, steps, selected_index, randomize_seed, seed, width, height, lora_scale, progress=gr.Progress(track_tqdm=True)):
106
+ if selected_index is None:
107
+ raise gr.Error("You must select a LoRA before proceeding.")
108
+
109
+ selected_lora = loras[selected_index]
110
+ lora_path = selected_lora["repo"]
111
+ trigger_word = selected_lora["trigger_word"]
112
+ if(trigger_word):
113
+ if "trigger_position" in selected_lora:
114
+ if selected_lora["trigger_position"] == "prepend":
115
+ prompt_mash = f"{trigger_word} {prompt}"
116
+ else:
117
+ prompt_mash = f"{prompt} {trigger_word}"
118
+ else:
119
+ prompt_mash = f"{trigger_word} {prompt}"
120
+ else:
121
+ prompt_mash = prompt
122
+
123
+ # Load LoRA weights
124
+ with calculateDuration(f"Loading LoRA weights for {selected_lora['title']}"):
125
+ if "weights" in selected_lora:
126
+ pipe.load_lora_weights(lora_path, weight_name=selected_lora["weights"])
127
+ else:
128
+ pipe.load_lora_weights(lora_path)
129
+
130
+ # Set random seed for reproducibility
131
+ with calculateDuration("Randomizing seed"):
132
+ if randomize_seed:
133
+ seed = random.randint(0, MAX_SEED)
134
+
135
+ image = generate_image(prompt, trigger_word, steps, seed, cfg_scale, width, height, lora_scale, progress)
136
+ pipe.to("cpu")
137
+ pipe.unload_lora_weights()
138
+ return image, seed
139
+
140
+ run_lora.zerogpu = True
141
+
142
+ css = '''
143
+ #gen_btn{height: 100%}
144
+ #title{text-align: center}
145
+ #title h1{font-size: 3em; display:inline-flex; align-items:center}
146
+ #title img{width: 100px; margin-right: 0.5em}
147
+ #gallery .grid-wrap{height: 10vh}
148
+ '''
149
+ with gr.Blocks(theme=gr.themes.Soft(), css=css) as app:
150
+ title = gr.HTML(
151
+ """<h1><img src="https://huggingface.co/spaces/multimodalart/flux-lora-the-explorer/resolve/main/flux_lora.png" alt="LoRA"> SOONfactory </h1>""",
152
+ elem_id="title",
153
+ )
154
+ # Info blob stating what the app is running
155
+ info_blob = gr.HTML(
156
+ """<div id="info_blob"> Activist & Futurealist LoRa-stocked Img Manufactory (currently on the Acorn is Spinning Schnell V1 model checkpoint, 4-step, by Seeker70) )</div>"""
157
+ )
158
+
159
+ # Info blob stating what the app is running
160
+ info_blob = gr.HTML(
161
+ """<div id="info_blob">Prephrase prompts w/: 1.RCA style 2. HST style autochrome 3. HST style 4.TOK hybrid 5.2004 photo 6.HST style 7.LEN Vladimir Lenin 8.TOK portra 9.HST portrait 10.flmft 11.HST in Peterhof 12.HST Soviet kodachrome 13. SOTS art 14.HST 15.photo 16.pficonics 17.wh3r3sw4ld0 18.retrofuturism 19-24.HST style photo 25.vintage cover </div>"""
162
+ )
163
+ selected_index = gr.State(None)
164
+ with gr.Row():
165
+ with gr.Column(scale=3):
166
+ prompt = gr.Textbox(label="Prompt", lines=1, placeholder="Select LoRa/Style & type prompt!")
167
+ with gr.Column(scale=1, elem_id="gen_column"):
168
+ generate_button = gr.Button("Generate", variant="primary", elem_id="gen_btn")
169
+ with gr.Row():
170
+ with gr.Column(scale=3):
171
+ selected_info = gr.Markdown("")
172
+ gallery = gr.Gallery(
173
+ [(item["image"], item["title"]) for item in loras],
174
+ label="LoRA Inventory",
175
+ allow_preview=False,
176
+ columns=3,
177
+ elem_id="gallery"
178
+ )
179
+
180
+ with gr.Column(scale=4):
181
+ result = gr.Image(label="Generated Image")
182
+
183
+ with gr.Row():
184
+ with gr.Accordion("Advanced Settings", open=True):
185
+ with gr.Column():
186
+ with gr.Row():
187
+ cfg_scale = gr.Slider(label="CFG Scale", minimum=1, maximum=20, step=0.5, value=1.0)
188
+ steps = gr.Slider(label="Steps", minimum=1, maximum=50, step=1, value=5)
189
+
190
+ with gr.Row():
191
+ width = gr.Slider(label="Width", minimum=256, maximum=1536, step=64, value=768)
192
+ height = gr.Slider(label="Height", minimum=256, maximum=1536, step=64, value=1024)
193
+
194
+ with gr.Row():
195
+ randomize_seed = gr.Checkbox(True, label="Randomize seed")
196
+ seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0, randomize=True)
197
+ lora_scale = gr.Slider(label="LoRA Scale", minimum=0, maximum=2.0, step=0.01, value=0.6)
198
+
199
+ gallery.select(
200
+ update_selection,
201
+ inputs=[width, height],
202
+ outputs=[prompt, selected_info, selected_index, width, height]
203
+ )
204
+
205
+ gr.on(
206
+ triggers=[generate_button.click, prompt.submit],
207
+ fn=run_lora,
208
+ inputs=[prompt, cfg_scale, steps, selected_index, randomize_seed, seed, width, height, lora_scale],
209
+ outputs=[result, seed]
210
+ )
211
+
212
+ app.queue(default_concurrency_limit=None).launch(show_error=True)
213
+ app.launch()