rphrp1985 commited on
Commit
d26c235
·
verified ·
1 Parent(s): a4ff28d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +151 -98
app.py CHANGED
@@ -3,120 +3,173 @@ import numpy as np
3
  import random
4
  import spaces
5
  import torch
6
- from diffusers import DiffusionPipeline
 
 
 
7
 
8
- dtype = torch.bfloat16
9
- device = "cuda" if torch.cuda.is_available() else "cpu"
10
-
11
- pipe = DiffusionPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=dtype).to(device)
12
 
 
13
  MAX_SEED = np.iinfo(np.int32).max
14
  MAX_IMAGE_SIZE = 2048
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- @spaces.GPU()
17
- def infer(prompt, seed=42, randomize_seed=False, width=1024, height=1024, num_inference_steps=4, progress=gr.Progress(track_tqdm=True)):
 
 
 
 
18
  if randomize_seed:
19
  seed = random.randint(0, MAX_SEED)
20
- generator = torch.Generator().manual_seed(seed)
21
- image = pipe(
22
- prompt = prompt,
23
- width = width,
24
- height = height,
25
- num_inference_steps = num_inference_steps,
26
- generator = generator,
27
- guidance_scale=0.0
28
- ).images[0]
29
- return image, seed
30
-
 
 
 
 
 
 
31
  examples = [
32
  "a tiny astronaut hatching from an egg on the moon",
33
- "a cat holding a sign that says hello world",
34
- "an anime illustration of a wiener schnitzel",
 
 
 
 
35
  ]
36
 
37
- css="""
38
- #col-container {
39
- margin: 0 auto;
40
- max-width: 520px;
41
- }
42
- """
43
 
44
- with gr.Blocks(css=css) as demo:
45
-
46
- with gr.Column(elem_id="col-container"):
47
- gr.Markdown(f"""# FLUX.1 [schnell]
48
- 12B param rectified flow transformer distilled from [FLUX.1 [pro]](https://blackforestlabs.ai/) for 4 step generation
49
- [[blog](https://blackforestlabs.ai/announcing-black-forest-labs/)] [[model](https://huggingface.co/black-forest-labs/FLUX.1-schnell)]
50
- """)
51
-
52
  with gr.Row():
53
-
54
- prompt = gr.Text(
55
- label="Prompt",
56
- show_label=False,
57
- max_lines=1,
58
- placeholder="Enter your prompt",
59
- container=False,
60
- )
61
-
62
- run_button = gr.Button("Run", scale=0)
63
-
64
- result = gr.Image(label="Result", show_label=False)
65
-
66
- with gr.Accordion("Advanced Settings", open=False):
67
-
68
- seed = gr.Slider(
69
- label="Seed",
70
- minimum=0,
71
- maximum=MAX_SEED,
72
- step=1,
73
- value=0,
74
- )
75
-
76
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
77
-
78
- with gr.Row():
79
-
80
- width = gr.Slider(
81
- label="Width",
82
- minimum=256,
83
- maximum=MAX_IMAGE_SIZE,
84
- step=32,
85
- value=1024,
86
  )
87
-
88
- height = gr.Slider(
89
- label="Height",
90
- minimum=256,
91
- maximum=MAX_IMAGE_SIZE,
92
- step=32,
93
- value=1024,
94
- )
95
-
96
- with gr.Row():
97
-
98
-
99
- num_inference_steps = gr.Slider(
100
- label="Number of inference steps",
101
- minimum=1,
102
- maximum=50,
103
- step=1,
104
- value=4,
105
- )
106
-
107
- gr.Examples(
108
- examples = examples,
109
- fn = infer,
110
- inputs = [prompt],
111
- outputs = [result, seed],
112
- cache_examples="lazy"
113
- )
 
 
 
 
 
 
 
114
 
115
  gr.on(
116
- triggers=[run_button.click, prompt.submit],
117
- fn = infer,
118
- inputs = [prompt, seed, randomize_seed, width, height, num_inference_steps],
119
- outputs = [result, seed]
120
  )
121
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  demo.launch()
 
3
  import random
4
  import spaces
5
  import torch
6
+ import time
7
+ from diffusers import DiffusionPipeline, AutoencoderTiny
8
+ from diffusers.models.attention_processor import AttnProcessor2_0
9
+ from custom_pipeline import FluxWithCFGPipeline
10
 
11
+ torch.backends.cuda.matmul.allow_tf32 = True
 
 
 
12
 
13
+ # Constants
14
  MAX_SEED = np.iinfo(np.int32).max
15
  MAX_IMAGE_SIZE = 2048
16
+ DEFAULT_WIDTH = 1024
17
+ DEFAULT_HEIGHT = 1024
18
+ DEFAULT_INFERENCE_STEPS = 1
19
+
20
+ # Device and model setup
21
+ dtype = torch.float16
22
+ pipe = FluxWithCFGPipeline.from_pretrained(
23
+ "black-forest-labs/FLUX.1-schnell", torch_dtype=dtype
24
+ )
25
+ pipe.vae = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype)
26
+ pipe.to("cuda")
27
+ pipe.load_lora_weights('hugovntr/flux-schnell-realism', weight_name='schnell-realism_v2.3.safetensors', adapter_name="better")
28
+ pipe.set_adapters(["better"], adapter_weights=[1.0])
29
+ pipe.fuse_lora(adapter_name=["better"], lora_scale=1.0)
30
+ pipe.unload_lora_weights()
31
 
32
+ torch.cuda.empty_cache()
33
+ from io import BytesIO
34
+ from PIL import Image
35
+ # Inference function
36
+ @spaces.GPU(duration=25)
37
+ def generate_image(prompt, seed=24, width=DEFAULT_WIDTH, height=DEFAULT_HEIGHT, randomize_seed=False, num_inference_steps=2, progress=gr.Progress(track_tqdm=True)):
38
  if randomize_seed:
39
  seed = random.randint(0, MAX_SEED)
40
+ generator = torch.Generator().manual_seed(int(float(seed)))
41
+
42
+ start_time = time.time()
43
+
44
+ # Only generate the last image in the sequence
45
+ img = pipe.generate_images(
46
+ prompt=prompt,
47
+ width=width,
48
+ height=height,
49
+ num_inference_steps=num_inference_steps,
50
+ generator=generator
51
+ )
52
+ latency = f"Latency: {(time.time()-start_time):.2f} seconds"
53
+
54
+ return img, seed, latency
55
+
56
+ # Example prompts
57
  examples = [
58
  "a tiny astronaut hatching from an egg on the moon",
59
+ "a cute white cat holding a sign that says hello world",
60
+ "an anime illustration of Steve Jobs",
61
+ "Create image of Modern house in minecraft style",
62
+ "photo of a woman on the beach, shot from above. She is facing the sea, while wearing a white dress. She has long blonde hair",
63
+ "Selfie photo of a wizard with long beard and purple robes, he is apparently in the middle of Tokyo. Probably taken from a phone.",
64
+ "Photo of a young woman with long, wavy brown hair tied in a bun and glasses. She has a fair complexion and is wearing subtle makeup, emphasizing her eyes and lips. She is dressed in a black top. The background appears to be an urban setting with a building facade, and the sunlight casts a warm glow on her face.",
65
  ]
66
 
67
+ # --- Gradio UI ---
68
+ with gr.Blocks() as demo:
69
+ with gr.Column(elem_id="app-container"):
70
+ gr.Markdown("# 🎨 Realtime FLUX Image Generator")
71
+ gr.Markdown("Generate stunning images in real-time with Modified Flux.Schnell pipeline.")
72
+ gr.Markdown("<span style='color: red;'>Note: Sometimes it stucks or stops generating images (I don't know why). In that situation just refresh the site.</span>")
73
 
 
 
 
 
 
 
 
 
74
  with gr.Row():
75
+ with gr.Column(scale=2.5):
76
+ result = gr.Image(label="Generated Image", show_label=False, interactive=False)
77
+ with gr.Column(scale=1):
78
+ prompt = gr.Text(
79
+ label="Prompt",
80
+ placeholder="Describe the image you want to generate...",
81
+ lines=3,
82
+ show_label=False,
83
+ container=False,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  )
85
+ generateBtn = gr.Button("🖼️ Generate Image")
86
+ # enhanceBtn = gr.Button("🚀 Enhance Image")
87
+
88
+ with gr.Column("Advanced Options"):
89
+ with gr.Row():
90
+ realtime = gr.Checkbox(label="Realtime Toggler", info="If TRUE then uses more GPU but create image in realtime.", value=False)
91
+ latency = gr.Text(label="Latency")
92
+ with gr.Row():
93
+ seed = gr.Number(label="Seed", value=42)
94
+ randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
95
+ with gr.Row():
96
+ width = gr.Slider(label="Width", minimum=256, maximum=MAX_IMAGE_SIZE, step=32, value=DEFAULT_WIDTH)
97
+ height = gr.Slider(label="Height", minimum=256, maximum=MAX_IMAGE_SIZE, step=32, value=DEFAULT_HEIGHT)
98
+ num_inference_steps = gr.Slider(label="Inference Steps", minimum=1, maximum=4, step=1, value=DEFAULT_INFERENCE_STEPS)
99
+
100
+ with gr.Row():
101
+ gr.Markdown("### 🌟 Inspiration Gallery")
102
+ with gr.Row():
103
+ gr.Examples(
104
+ examples=examples,
105
+ fn=generate_image,
106
+ inputs=[prompt],
107
+ outputs=[result, seed, latency],
108
+ cache_examples="lazy"
109
+ )
110
+
111
+ # enhanceBtn.click(
112
+ # fn=generate_image,
113
+ # inputs=[prompt, seed, width, height],
114
+ # outputs=[result, seed, latency],
115
+ # show_progress="full",
116
+ # queue=False,
117
+ # concurrency_limit=None
118
+ # )
119
 
120
  gr.on(
121
+ triggers=[generateBtn.click, prompt.submit],
122
+ fn=generate_image,
123
+ inputs=[prompt, seed, width, height, randomize_seed, num_inference_steps],
124
+ outputs=[result, seed, latency],
125
  )
126
 
127
+ # generateBtn.click(
128
+ # fn=generate_image,
129
+ # inputs=[prompt, seed, width, height, randomize_seed, num_inference_steps],
130
+ # outputs=[result, seed, latency],
131
+ # show_progress="full",
132
+ # api_name="RealtimeFlux",
133
+ # queue=False
134
+ # )
135
+
136
+ # def update_ui(realtime_enabled):
137
+ # return {
138
+ # prompt: gr.update(interactive=True),
139
+ # generateBtn: gr.update(visible=not realtime_enabled)
140
+ # }
141
+
142
+ # realtime.change(
143
+ # fn=update_ui,
144
+ # inputs=[realtime],
145
+ # outputs=[prompt, generateBtn],
146
+ # queue=False,
147
+ # concurrency_limit=None
148
+ # )
149
+
150
+ # def realtime_generation(*args):
151
+ # if args[0]: # If realtime is enabled
152
+ # return next(generate_image(*args[1:]))
153
+
154
+ # prompt.submit(
155
+ # fn=generate_image,
156
+ # inputs=[prompt, seed, width, height, randomize_seed, num_inference_steps],
157
+ # outputs=[result, seed, latency],
158
+ # show_progress="full",
159
+ # queue=False,
160
+ # concurrency_limit=None
161
+ # )
162
+
163
+ # for component in [prompt, width, height, num_inference_steps]:
164
+ # component.input(
165
+ # fn=realtime_generation,
166
+ # inputs=[realtime, prompt, seed, width, height, randomize_seed, num_inference_steps],
167
+ # outputs=[result, seed, latency],
168
+ # show_progress="hidden",
169
+ # trigger_mode="always_last",
170
+ # queue=False,
171
+ # concurrency_limit=None
172
+ # )
173
+
174
+ # Launch the app
175
  demo.launch()