CultriX commited on
Commit
1590202
·
verified ·
1 Parent(s): f939ee2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -309
app.py CHANGED
@@ -1,335 +1,120 @@
1
- import os
2
- import gradio as gr
3
- import json
4
- import logging
5
- import torch
6
  from PIL import Image
7
- import spaces
8
- from diffusers import DiffusionPipeline, AutoencoderTiny, AutoencoderKL, AutoPipelineForImage2Image
9
- from live_preview_helpers import calculate_shift, retrieve_timesteps, flux_pipe_call_that_returns_an_iterable_of_images
10
- from diffusers.utils import load_image
11
- from huggingface_hub import hf_hub_download, HfFileSystem, ModelCard, snapshot_download
12
- import copy
13
- import random
14
- import time
15
  import base64
 
 
16
  import tempfile
17
 
18
- # Load LoRAs from JSON file
19
- with open('loras.json', 'r') as f:
20
- loras = json.load(f)
21
 
22
- # Initialize the base model
23
- dtype = torch.bfloat16
24
- device = "cuda" if torch.cuda.is_available() else "cpu"
25
- base_model = "black-forest-labs/FLUX.1-dev"
 
 
 
 
 
 
 
26
 
27
- taef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype).to(device)
28
- good_vae = AutoencoderKL.from_pretrained(base_model, subfolder="vae", torch_dtype=dtype).to(device)
29
- pipe = DiffusionPipeline.from_pretrained(base_model, torch_dtype=dtype, vae=taef1).to(device)
30
- pipe_i2i = AutoPipelineForImage2Image.from_pretrained(base_model,
31
- vae=good_vae,
32
- transformer=pipe.transformer,
33
- text_encoder=pipe.text_encoder,
34
- tokenizer=pipe.tokenizer,
35
- text_encoder_2=pipe.text_encoder_2,
36
- tokenizer_2=pipe.tokenizer_2,
37
- torch_dtype=dtype
38
- )
39
 
40
- MAX_SEED = 2**32-1
 
 
 
41
 
42
- pipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)
43
 
44
- class calculateDuration:
45
- def __init__(self, activity_name=""):
46
- self.activity_name = activity_name
47
 
48
- def __enter__(self):
49
- self.start_time = time.time()
50
- return self
 
51
 
52
- def __exit__(self, exc_type, exc_value, traceback):
53
- self.end_time = time.time()
54
- self.elapsed_time = self.end_time - self.start_time
55
- if self.activity_name:
56
- print(f"Elapsed time for {self.activity_name}: {self.elapsed_time:.6f} seconds")
57
- else:
58
- print(f"Elapsed time: {self.elapsed_time:.6f} seconds")
59
-
60
- def update_selection(evt: gr.SelectData, width, height):
61
- selected_lora = loras[evt.index]
62
- new_placeholder = f"Type a prompt for {selected_lora['title']}"
63
- lora_repo = selected_lora["repo"]
64
- updated_text = f"### Selected: [{lora_repo}](https://huggingface.co/{lora_repo}) ✨"
65
- if "aspect" in selected_lora:
66
- if selected_lora["aspect"] == "portrait":
67
- width = 768
68
- height = 1024
69
- elif selected_lora["aspect"] == "landscape":
70
- width = 1024
71
- height = 768
72
- else:
73
- width = 1024
74
- height = 1024
75
- return (
76
- gr.update(placeholder=new_placeholder),
77
- updated_text,
78
- evt.index,
79
- width,
80
- height,
81
- )
82
 
83
- @spaces.GPU(duration=30)
84
- def generate_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale, progress):
85
- pipe.to("cuda")
86
- generator = torch.Generator(device="cuda").manual_seed(seed)
87
- with calculateDuration("Generating image"):
88
- # Generate image
89
- for img in pipe.flux_pipe_call_that_returns_an_iterable_of_images(
90
- prompt=prompt_mash,
91
- num_inference_steps=steps,
92
- guidance_scale=cfg_scale,
93
- width=width,
94
- height=height,
95
- generator=generator,
96
- joint_attention_kwargs={"scale": lora_scale},
97
- output_type="pil",
98
- good_vae=good_vae,
99
- ):
100
- yield img
101
 
102
- def generate_image_to_image(prompt_mash, image_input_path, image_strength, steps, cfg_scale, width, height, lora_scale, seed):
103
- generator = torch.Generator(device="cuda").manual_seed(seed)
104
- pipe_i2i.to("cuda")
105
- image_input = load_image(image_input_path)
106
- final_image = pipe_i2i(
107
- prompt=prompt_mash,
108
- image=image_input,
109
- strength=image_strength,
110
- num_inference_steps=steps,
111
- guidance_scale=cfg_scale,
112
- width=width,
113
- height=height,
114
- generator=generator,
115
- joint_attention_kwargs={"scale": lora_scale},
116
- output_type="pil",
117
- ).images[0]
118
 
119
- # Save the image as a downloadable PNG file
120
- temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
121
- final_image.save(temp_file.name, "PNG")
122
 
123
- # Convert the image to a base64 string
124
- buffered = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
125
- final_image.save(buffered.name, format="PNG")
126
- with open(buffered.name, "rb") as f:
127
- img_base64 = base64.b64encode(f.read()).decode("utf-8")
128
 
129
- return final_image, temp_file.name, f"data:image/png;base64,{img_base64}"
 
 
 
 
130
 
131
- @spaces.GPU(duration=30)
132
- 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)):
133
- if selected_index is None:
134
- raise gr.Error("You must select a LoRA before proceeding.")
135
- selected_lora = loras[selected_index]
136
- lora_path = selected_lora["repo"]
137
- trigger_word = selected_lora["trigger_word"]
138
- if(trigger_word):
139
- if "trigger_position" in selected_lora:
140
- if selected_lora["trigger_position"] == "prepend":
141
- prompt_mash = f"{trigger_word} {prompt}"
142
- else:
143
- prompt_mash = f"{prompt} {trigger_word}"
144
- else:
145
- prompt_mash = f"{trigger_word} {prompt}"
146
- else:
147
- prompt_mash = prompt
148
 
149
- with calculateDuration("Unloading LoRA"):
150
- pipe.unload_lora_weights()
151
- pipe_i2i.unload_lora_weights()
152
-
153
- # Load LoRA weights
154
- with calculateDuration(f"Loading LoRA weights for {selected_lora['title']}"):
155
- pipe_to_use = pipe_i2i if image_input is not None else pipe
156
- weight_name = selected_lora.get("weights", None)
157
-
158
- pipe_to_use.load_lora_weights(
159
- lora_path,
160
- weight_name=weight_name,
161
- low_cpu_mem_usage=True
162
- )
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
- if(image_input is not None):
170
- final_image, file_path, base64_str = generate_image_to_image(prompt_mash, image_input, image_strength, steps, cfg_scale, width, height, lora_scale, seed)
171
- yield final_image, seed, file_path, base64_str, gr.update(visible=False)
172
- else:
173
- image_generator = generate_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale, progress)
174
-
175
- # Consume the generator to get the final image
176
- final_image = None
177
- step_counter = 0
178
- for image in image_generator:
179
- step_counter+=1
180
- final_image = image
181
- progress_bar = f'<div class="progress-container"><div class="progress-bar" style="--current: {step_counter}; --total: {steps};"></div></div>'
182
- yield image, seed, None, None, gr.update(value=progress_bar, visible=True)
183
-
184
- # Save the final image and encode to Base64
185
- temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
186
- final_image.save(temp_file.name, "PNG")
187
- with open(temp_file.name, "rb") as f:
188
- img_base64 = base64.b64encode(f.read()).decode("utf-8")
189
 
190
- yield final_image, seed, temp_file.name, f"data:image/png;base64,{img_base64}", gr.update(value=progress_bar, visible=False)
191
-
192
- def get_huggingface_safetensors(link):
193
- split_link = link.split("/")
194
- if(len(split_link) == 2):
195
- model_card = ModelCard.load(link)
196
- base_model = model_card.data.get("base_model")
197
- print(base_model)
198
- if((base_model != "black-forest-labs/FLUX.1-dev") and (base_model != "black-forest-labs/FLUX.1-schnell")):
199
- raise Exception("Not a FLUX LoRA!")
200
- image_path = model_card.data.get("widget", [{}])[0].get("output", {}).get("url", None)
201
- trigger_word = model_card.data.get("instance_prompt", "")
202
- image_url = f"https://huggingface.co/{link}/resolve/main/{image_path}" if image_path else None
203
- fs = HfFileSystem()
204
- try:
205
- list_of_files = fs.ls(link, detail=False)
206
- for file in list_of_files:
207
- if(file.endswith(".safetensors")):
208
- safetensors_name = file.split("/")[-1]
209
- if (not image_url and file.lower().endswith((".jpg", ".jpeg", ".png", ".webp"))):
210
- image_elements = file.split("/")
211
- image_url = f"https://huggingface.co/{link}/resolve/main/{image_elements[-1]}"
212
- except Exception as e:
213
- print(e)
214
- gr.Warning(f"You didn't include a link neither a valid Hugging Face repository with a *.safetensors LoRA")
215
- raise Exception(f"You didn't include a link neither a valid Hugging Face repository with a *.safetensors LoRA")
216
- return split_link[1], link, safetensors_name, trigger_word, image_url
217
 
218
- def check_custom_model(link):
219
- if(link.startswith("https://")):
220
- if(link.startswith("https://huggingface.co") or link.startswith("https://www.huggingface.co")):
221
- link_split = link.split("huggingface.co/")
222
- return get_huggingface_safetensors(link_split[1])
223
- else:
224
- return get_huggingface_safetensors(link)
225
 
226
- def add_custom_lora(custom_lora):
227
- global loras
228
- if(custom_lora):
229
- try:
230
- title, repo, path, trigger_word, image = check_custom_model(custom_lora)
231
- print(f"Loaded custom LoRA: {repo}")
232
- card = f'''
233
- <div class="custom_lora_card">
234
- <span>Loaded custom LoRA:</span>
235
- <div class="card_internal">
236
- <img src="{image}" />
237
- <div>
238
- <h3>{title}</h3>
239
- <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>
240
- </div>
241
- </div>
242
  </div>
243
- '''
244
- existing_item_index = next((index for (index, item) in enumerate(loras) if item['repo'] == repo), None)
245
- if(not existing_item_index):
246
- new_item = {
247
- "image": image,
248
- "title": title,
249
- "repo": repo,
250
- "weights": path,
251
- "trigger_word": trigger_word
252
- }
253
- print(new_item)
254
- existing_item_index = len(loras)
255
- loras.append(new_item)
256
-
257
- return gr.update(visible=True, value=card), gr.update(visible=True), gr.Gallery(selected_index=None), f"Custom: {path}", existing_item_index, trigger_word
258
- except Exception as e:
259
- gr.Warning(f"Invalid LoRA: either you entered an invalid link, or a non-FLUX LoRA")
260
- return gr.update(visible=True, value=f"Invalid LoRA: either you entered an invalid link, a non-FLUX LoRA"), gr.update(visible=True), gr.update(), "", None, ""
261
- else:
262
- return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""
263
 
264
- def remove_custom_lora():
265
- return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""
266
 
267
- run_lora.zerogpu = True
268
 
269
- css = '''
270
- #gen_btn{height: 100%}
271
- #gen_column{align-self: stretch}
272
- #title{text-align: center}
273
- #title h1{font-size: 3em; display:inline-flex; align-items:center}
274
- #title img{width: 100px; margin-right: 0.5em}
275
- #gallery .grid-wrap{height: 10vh}
276
- #lora_list{background: var(--block-background-fill);padding: 0 1em .3em; font-size: 90%}
277
- .card_internal{display: flex;height: 100px;margin-top: .5em}
278
- .card_internal img{margin-right: 1em}
279
- .styler{--form-gap-width: 0px !important}
280
- #progress{height:30px}
281
- #progress .generating{display:none}
282
- .progress-container {width: 100%;height: 30px;background-color: #f0f0f0;border-radius: 15px;overflow: hidden;margin-bottom: 20px}
283
- .progress-bar {height: 100%;background-color: #4f46e5;width: calc(var(--current) / var(--total) * 100%);transition: width 0.5s ease-in-out}
284
- '''
285
- font=[gr.themes.GoogleFont("Source Sans Pro"), "Arial", "sans-serif"]
286
- with gr.Blocks(theme=gr.themes.Soft(font=font), css=css, delete_cache=(60, 60)) as app:
287
- title = gr.HTML(
288
- """<h1><img src="https://huggingface.co/spaces/multimodalart/flux-lora-the-explorer/resolve/main/flux_lora.png" alt="LoRA"> FLUX LoRA the Explorer</h1>""",
289
- elem_id="title",
290
- )
291
- selected_index = gr.State(None)
292
- with gr.Row():
293
- with gr.Column(scale=3):
294
- prompt = gr.Textbox(label="Prompt", lines=1, placeholder="Type a prompt after selecting a LoRA")
295
- with gr.Column(scale=1, elem_id="gen_column"):
296
- generate_button = gr.Button("Generate", variant="primary", elem_id="gen_btn")
297
- with gr.Row():
298
- with gr.Column():
299
- selected_info = gr.Markdown("")
300
- gallery = gr.Gallery(
301
- [(item["image"], item["title"]) for item in loras],
302
- label="LoRA Gallery",
303
- allow_preview=False,
304
- columns=3,
305
- elem_id="gallery",
306
- show_share_button=False
307
- )
308
- with gr.Group():
309
- custom_lora = gr.Textbox(label="Custom LoRA", info="LoRA Hugging Face path", placeholder="multimodalart/vintage-ads-flux")
310
- gr.Markdown("[Check the list of FLUX LoRas](https://huggingface.co/models?other=base_model:adapter:black-forest-labs/FLUX.1-dev)", elem_id="lora_list")
311
- custom_lora_info = gr.HTML(visible=False)
312
- custom_lora_button = gr.Button("Remove custom LoRA", visible=False)
313
- with gr.Column():
314
- progress_bar = gr.Markdown(elem_id="progress",visible=False)
315
- result = gr.Image(label="Generated Image")
316
- download_link = gr.File(label="Download Image")
317
- base64_output = gr.Textbox(label="Base64 Encoded Image")
318
-
319
- with gr.Row():
320
- with gr.Accordion("Advanced Settings", open=False):
321
- with gr.Row():
322
- input_image = gr.Image(label="Input image", type="filepath")
323
- 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)
324
- with gr.Column():
325
- with gr.Row():
326
- cfg_scale = gr.Slider(label="CFG Scale", minimum=1, maximum=20, step=0.5, value=3.5)
327
- steps = gr.Slider(label="Steps", minimum=1, maximum=50, step=1, value=28)
328
-
329
- with gr.Row():
330
- width = gr.Slider(label="Width", minimum=256, maximum=1536, step=64, value=1024)
331
- height = gr.Slider(label="Height", minimum=256, maximum=1536, step=64, value=1024)
332
-
333
- with gr.Row():
334
- randomize_seed = gr.Checkbox(True, label="Randomize seed")
335
- seed = gr.Slider(label="Seed", minimum=0, maximum
 
1
+ import qrcode
 
 
 
 
2
  from PIL import Image
3
+ import gradio as gr
4
+ import io
 
 
 
 
 
 
5
  import base64
6
+ import numpy as np
7
+ import cv2
8
  import tempfile
9
 
 
 
 
10
 
11
+ # Function to generate a QR code and return Base64 and PNG file
12
+ def generate_qr(data):
13
+ qr = qrcode.QRCode(
14
+ version=1,
15
+ error_correction=qrcode.constants.ERROR_CORRECT_L,
16
+ box_size=10,
17
+ border=4,
18
+ )
19
+ qr.add_data(data)
20
+ qr.make(fit=True)
21
+ img = qr.make_image(fill="black", back_color="white")
22
 
23
+ # Encode the image as a base64 string
24
+ buffered = io.BytesIO()
25
+ img.save(buffered, format="PNG")
26
+ img_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
 
 
 
 
 
 
 
 
27
 
28
+ # Save the image temporarily as a PNG file
29
+ temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
30
+ img.save(temp_file.name, format="PNG")
31
+ temp_file.close()
32
 
33
+ return f"data:image/png;base64,{img_base64}", temp_file.name, img_base64
34
 
 
 
 
35
 
36
+ # Function to decode a QR code from an uploaded image
37
+ def decode_qr(img):
38
+ if img is None:
39
+ return "No image uploaded."
40
 
41
+ # Convert PIL image to a NumPy array
42
+ img_array = np.array(img)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
+ # Convert RGB to BGR as OpenCV expects
45
+ if img_array.ndim == 3:
46
+ img_array = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
+ # Initialize OpenCV QR code detector
49
+ detector = cv2.QRCodeDetector()
50
+ data, _, _ = detector.detectAndDecode(img_array)
51
+ return data if data else "No QR code found."
 
 
 
 
 
 
 
 
 
 
 
 
52
 
 
 
 
53
 
54
+ # Gradio Interface
55
+ def create_gradio_interface():
56
+ with gr.Blocks() as demo:
57
+ gr.Markdown("## QR Code Generator and Decoder")
 
58
 
59
+ # Tab for generating QR codes
60
+ with gr.Tab("Generate QR Code"):
61
+ with gr.Row():
62
+ data_input = gr.Textbox(placeholder="Enter text or URL to encode", label="Input Data")
63
+ generate_button = gr.Button("Generate QR Code")
64
 
65
+ qr_code_html = gr.HTML(label="Generated QR Code (Base64 Embedded)")
66
+ qr_png_file = gr.File(label="Download QR Code (PNG)")
67
+ qr_base64_file = gr.File(label="Download Base64 (TXT)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
+ def generate_qr_interface(data):
70
+ if not data.strip():
71
+ raise ValueError("Input text cannot be empty!")
72
+ img_base64, png_path, base64_str = generate_qr(data)
 
 
 
 
 
 
 
 
 
 
73
 
74
+ # Save Base64 string as a .txt file
75
+ base64_txt_path = tempfile.NamedTemporaryFile(delete=False, suffix=".txt")
76
+ with open(base64_txt_path.name, "w") as f:
77
+ f.write(base64_str)
78
+
79
+ # Wrap the base64 string in an <img> tag for display
80
+ html_content = f'<img src="{img_base64}" alt="QR Code" style="max-width:300px;">'
81
+ return html_content, png_path, base64_txt_path.name
82
+
83
+ generate_button.click(
84
+ generate_qr_interface,
85
+ inputs=data_input,
86
+ outputs=[qr_code_html, qr_png_file, qr_base64_file],
87
+ )
 
 
 
 
 
 
 
 
 
 
 
88
 
89
+ # Tab for decoding QR codes
90
+ with gr.Tab("Decode QR Code"):
91
+ with gr.Row():
92
+ image_input = gr.Image(type="pil", label="Upload QR Code Image")
93
+ decode_button = gr.Button("Decode QR Code")
94
+
95
+ decoded_text = gr.Textbox(label="Decoded Text", interactive=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
+ decode_button.click(
98
+ decode_qr,
99
+ inputs=image_input,
100
+ outputs=decoded_text,
101
+ )
 
 
102
 
103
+ # Add the logo at the bottom center using gr.HTML
104
+ gr.HTML("""
105
+ <div style="
106
+ position: fixed;
107
+ bottom: 20px;
108
+ left: 50%;
109
+ transform: translateX(-50%);
110
+ z-index: 1000;
111
+ ">
112
+ <img src="file=space-logo.png" alt="Space Logo" style="width: 150px; height: auto;">
 
 
 
 
 
 
113
  </div>
114
+ """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
 
116
+ demo.launch(share=True)
 
117
 
 
118
 
119
+ # Run the Gradio interface
120
+ create_gradio_interface()