Sugam7 commited on
Commit
a54551a
·
verified ·
1 Parent(s): 52e030e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -230
app.py CHANGED
@@ -1,274 +1,142 @@
1
  import gradio as gr
2
  import numpy as np
3
  import random
4
- import spaces
5
- import torch
6
- from diffusers import DiffusionPipeline
7
- from PIL import Image, ImageEnhance
8
  import io
9
  import zipfile
 
 
 
 
10
 
11
- # Initialize model and settings
12
  dtype = torch.bfloat16
13
  device = "cuda" if torch.cuda.is_available() else "cpu"
14
- pipe = DiffusionPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16).to(device)
 
 
15
 
16
  # Constants
17
  MAX_SEED = np.iinfo(np.int32).max
18
  MAX_IMAGE_SIZE = 2048
19
 
20
- # Helper function to apply image filters
21
- def apply_filters(image, brightness, contrast, saturation):
22
- enhancer = ImageEnhance.Brightness(image)
23
- image = enhancer.enhance(brightness)
24
-
25
- enhancer = ImageEnhance.Contrast(image)
26
- image = enhancer.enhance(contrast)
27
-
28
- enhancer = ImageEnhance.Color(image)
29
- image = enhancer.enhance(saturation)
30
-
31
- return image
32
-
33
- # Helper function to create a ZIP file of images
34
- def create_zip(images):
35
- zip_buffer = io.BytesIO()
36
- with zipfile.ZipFile(zip_buffer, "a", zipfile.ZIP_DEFLATED) as zip_file:
37
- for i, img in enumerate(images):
38
- img_byte_arr = io.BytesIO()
39
- img.save(img_byte_arr, format="PNG")
40
- zip_file.writestr(f"image_{i+1}.png", img_byte_arr.getvalue())
41
- return zip_buffer.getvalue()
42
-
43
- @spaces.GPU(duration=190)
44
- def infer(prompt, num_outputs=1, seed=42, randomize_seed=False, width=1024, height=1024, guidance_scale=5.0, num_inference_steps=28, output_format="png", brightness=1.0, contrast=1.0, saturation=1.0, style="None", progress=gr.Progress(track_tqdm=True)):
45
- images = []
46
- seeds = []
47
-
48
  if randomize_seed:
49
  seed = random.randint(0, MAX_SEED)
 
50
 
51
- for _ in range(num_outputs):
52
- generator = torch.Generator(device=device).manual_seed(seed)
53
  image = pipe(
54
- prompt=prompt,
55
- width=width,
56
- height=height,
57
- num_inference_steps=num_inference_steps,
58
- generator=generator,
59
  guidance_scale=guidance_scale
60
  ).images[0]
61
-
62
- # Apply filters
63
- image = apply_filters(image, brightness, contrast, saturation)
64
-
65
- # Apply preset style if selected
66
- if style != "None":
67
- # Example of applying a filter based on a selected style
68
- # You would expand this to include actual styles, e.g., cartoon, watercolor, etc.
69
- if style == "Black & White":
70
- image = image.convert("L").convert("RGB")
71
- elif style == "Sepia":
72
- sepia_filter = np.array(image)
73
- sepia_filter = np.dot(sepia_filter[...,:3], [0.393, 0.769, 0.189])
74
- sepia_filter = np.clip(sepia_filter, 0, 255)
75
- image = Image.fromarray(sepia_filter.astype('uint8'))
76
-
77
  images.append(image)
78
- seeds.append(seed)
79
- seed += 1 # Increment seed for the next image
80
-
81
- # Optionally convert image format
82
- if output_format.lower() != "png":
83
- images = [img.convert(output_format.upper()) for img in images]
84
 
85
- return images, seeds, create_zip(images)
 
 
 
86
 
87
- # Example prompts for users to try
88
- examples = [
89
- ["a tiny astronaut hatching from an egg on the moon", 1],
90
- ["a cat holding a sign that says hello world", 2],
91
- ["an anime illustration of a wiener schnitzel", 3],
92
- ]
 
 
93
 
94
- # CSS styling for modern look
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  css = """
96
  #col-container {
97
  margin: 0 auto;
98
- max-width: 1000px;
99
- padding: 20px;
100
- background-color: #f9f9f9;
101
- border-radius: 10px;
102
- box-shadow: 0px 0px 20px rgba(0,0,0,0.1);
103
- }
104
-
105
- #title {
106
- font-family: 'Arial', sans-serif;
107
- color: #333;
108
- text-align: center;
109
- margin-bottom: 20px;
110
- }
111
-
112
- #advanced-settings {
113
- background-color: #f1f1f1;
114
- border-radius: 8px;
115
- padding: 10px;
116
- }
117
-
118
- #output-container {
119
- text-align: center;
120
- margin-top: 20px;
121
  }
122
  """
123
 
 
 
 
 
 
 
124
  with gr.Blocks(css=css) as demo:
125
  with gr.Column(elem_id="col-container"):
126
-
127
- # Title and Description
128
- gr.Markdown(f"""
129
- <h1 id="title">FLUX.1 [dev] - Feature-Rich Text-to-Image Generator</h1>
130
- <p style="text-align:center; color:#555;">
131
- Unleash your creativity with this advanced text-to-image generator. Customize prompts, generate multiple images, apply filters, and more!
132
- </p>
133
  """)
134
 
135
  with gr.Row():
136
- prompt = gr.Textbox(
137
- label="Prompt",
138
- show_label=False,
139
- max_lines=1,
140
- placeholder="Enter your creative prompt...",
141
- container=False,
142
- interactive=True
143
- )
144
-
145
- num_outputs = gr.Slider(
146
- label="Number of Variations",
147
- minimum=1,
148
- maximum=10,
149
- step=1,
150
- value=1,
151
- interactive=True
152
- )
153
-
154
- run_button = gr.Button("Generate", elem_id="generate-button")
155
-
156
- # Output image gallery and settings
157
- with gr.Row(elem_id="output-container"):
158
- gallery = gr.Gallery(label="Generated Images", show_label=False).style(grid=[4], height="auto")
159
- output_format = gr.Radio(
160
- label="Output Format",
161
- choices=["png", "jpeg", "bmp"],
162
- value="png",
163
- interactive=True
164
- )
165
-
166
- # Advanced settings
167
- with gr.Accordion("Advanced Settings", open=False, elem_id="advanced-settings"):
168
- seed = gr.Slider(
169
- label="Seed",
170
- minimum=0,
171
- maximum=MAX_SEED,
172
- step=1,
173
- value=0,
174
- interactive=True
175
- )
176
- randomize_seed = gr.Checkbox(label="Randomize Seed", value=True, interactive=True)
177
-
178
  with gr.Row():
179
- width = gr.Slider(
180
- label="Width",
181
- minimum=256,
182
- maximum=MAX_IMAGE_SIZE,
183
- step=32,
184
- value=1024,
185
- interactive=True
186
- )
187
- height = gr.Slider(
188
- label="Height",
189
- minimum=256,
190
- maximum=MAX_IMAGE_SIZE,
191
- step=32,
192
- value=1024,
193
- interactive=True
194
- )
195
-
196
  with gr.Row():
197
- guidance_scale = gr.Slider(
198
- label="Guidance Scale",
199
- minimum=1,
200
- maximum=15,
201
- step=0.1,
202
- value=5.0,
203
- interactive=True
204
- )
205
- num_inference_steps = gr.Slider(
206
- label="Number of Inference Steps",
207
- minimum=1,
208
- maximum=50,
209
- step=1,
210
- value=28,
211
- interactive=True
212
- )
213
-
214
- # Image filter sliders
215
- brightness = gr.Slider(
216
- label="Brightness",
217
- minimum=0.5,
218
- maximum=2.0,
219
- step=0.1,
220
- value=1.0,
221
- interactive=True
222
- )
223
- contrast = gr.Slider(
224
- label="Contrast",
225
- minimum=0.5,
226
- maximum=2.0,
227
- step=0.1,
228
- value=1.0,
229
- interactive=True
230
- )
231
- saturation = gr.Slider(
232
- label="Saturation",
233
- minimum=0.5,
234
- maximum=2.0,
235
- step=0.1,
236
- value=1.0,
237
- interactive=True
238
- )
239
-
240
- # Preset styles
241
- style = gr.Dropdown(
242
- label="Preset Styles",
243
- choices=["None", "Black & White", "Sepia", "Vivid Colors"],
244
- value="None",
245
- interactive=True
246
- )
247
-
248
- # Interactive Examples
249
  gr.Examples(
250
  examples=examples,
251
  fn=infer,
252
- inputs=[prompt, num_outputs],
253
- outputs=[gallery, seed],
254
- cache_examples="lazy",
255
- label="Try these examples:"
256
  )
257
 
258
- # Download all images as a ZIP file
259
- download_button = gr.Button("Download All Images")
260
- zip_file = gr.File(label="Download", show_label=False)
261
- download_button.click(
262
- fn=create_zip,
263
- inputs=[gallery],
264
- outputs=[zip_file]
265
- )
266
 
267
- # Link button to trigger inference
268
- run_button.click(
269
- fn=infer,
270
- inputs=[prompt, num_outputs, seed, randomize_seed, width, height, guidance_scale, num_inference_steps, output_format, brightness, contrast, saturation, style],
271
- outputs=[gallery, seed, zip_file]
272
- )
 
 
 
 
 
273
 
274
  demo.launch()
 
1
  import gradio as gr
2
  import numpy as np
3
  import random
 
 
 
 
4
  import io
5
  import zipfile
6
+ from PIL import Image, ImageEnhance
7
+ import torch
8
+ from diffusers import DiffusionPipeline
9
+ from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
10
 
11
+ # Configuration
12
  dtype = torch.bfloat16
13
  device = "cuda" if torch.cuda.is_available() else "cpu"
14
+
15
+ # Load the model
16
+ pipe = DiffusionPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=dtype).to(device)
17
 
18
  # Constants
19
  MAX_SEED = np.iinfo(np.int32).max
20
  MAX_IMAGE_SIZE = 2048
21
 
22
+ # Define the inference function
23
+ def infer(prompt, seed=42, randomize_seed=False, width=1024, height=1024, guidance_scale=5.0, num_inference_steps=28, num_variations=1, brightness=1.0, contrast=1.0, saturation=1.0, style="Style1"):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  if randomize_seed:
25
  seed = random.randint(0, MAX_SEED)
26
+ generator = torch.Generator().manual_seed(seed)
27
 
28
+ images = []
29
+ for _ in range(num_variations):
30
  image = pipe(
31
+ prompt=prompt,
32
+ width=width,
33
+ height=height,
34
+ num_inference_steps=num_inference_steps,
35
+ generator=generator,
36
  guidance_scale=guidance_scale
37
  ).images[0]
38
+ # Apply image adjustments
39
+ image = adjust_image(image, brightness, contrast, saturation)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  images.append(image)
 
 
 
 
 
 
41
 
42
+ # Apply style (dummy implementation, replace with actual style application)
43
+ images = [apply_style(img, style) for img in images]
44
+
45
+ return images, seed
46
 
47
+ def adjust_image(image, brightness, contrast, saturation):
48
+ enhancer = ImageEnhance.Brightness(image)
49
+ image = enhancer.enhance(brightness)
50
+ enhancer = ImageEnhance.Contrast(image)
51
+ image = enhancer.enhance(contrast)
52
+ enhancer = ImageEnhance.Color(image)
53
+ image = enhancer.enhance(saturation)
54
+ return image
55
 
56
+ def apply_style(image, style):
57
+ # Dummy style application
58
+ return image
59
+
60
+ def download_all(images):
61
+ with io.BytesIO() as buffer:
62
+ with zipfile.ZipFile(buffer, 'w') as zipf:
63
+ for i, img in enumerate(images):
64
+ img_byte_arr = io.BytesIO()
65
+ img.save(img_byte_arr, format="PNG")
66
+ zipf.writestr(f'image_{i}.png', img_byte_arr.getvalue())
67
+ buffer.seek(0)
68
+ return buffer.getvalue()
69
+
70
+ # Gradio interface
71
  css = """
72
  #col-container {
73
  margin: 0 auto;
74
+ max-width: 720px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  }
76
  """
77
 
78
+ examples = [
79
+ "a tiny astronaut hatching from an egg on the moon",
80
+ "a cat holding a sign that says hello world",
81
+ "an anime illustration of a wiener schnitzel",
82
+ ]
83
+
84
  with gr.Blocks(css=css) as demo:
85
  with gr.Column(elem_id="col-container"):
86
+ gr.Markdown(f"""# FLUX.1 [dev]
87
+ 12B param rectified flow transformer guidance-distilled from [FLUX.1 [pro]](https://blackforestlabs.ai/)
88
+ [[non-commercial license](https://huggingface.co/black-forest-labs/FLUX.1-dev/blob/main/LICENSE.md)] [[blog](https://blackforestlabs.ai/announcing-black-forest-labs/)] [[model](https://huggingface.co/black-forest-labs/FLUX.1-dev)]
 
 
 
 
89
  """)
90
 
91
  with gr.Row():
92
+ prompt = gr.Textbox(label="Prompts (comma-separated)", placeholder="Enter multiple prompts separated by commas", lines=2)
93
+ run_button = gr.Button("Run", scale=0)
94
+
95
+ result = gr.Gallery(label="Image Gallery").style(height=400)
96
+
97
+ with gr.Accordion("Advanced Settings", open=False):
98
+ seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)
99
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
100
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  with gr.Row():
102
+ width = gr.Slider(label="Width", minimum=256, maximum=MAX_IMAGE_SIZE, step=32, value=1024)
103
+ height = gr.Slider(label="Height", minimum=256, maximum=MAX_IMAGE_SIZE, step=32, value=1024)
104
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  with gr.Row():
106
+ guidance_scale = gr.Slider(label="Guidance Scale", minimum=1, maximum=15, step=0.1, value=3.5)
107
+ num_inference_steps = gr.Slider(label="Number of inference steps", minimum=1, maximum=50, step=1, value=28)
108
+
109
+ with gr.Row():
110
+ num_variations = gr.Slider(label="Number of Variations", minimum=1, maximum=10, step=1, value=1)
111
+ brightness = gr.Slider(label="Brightness", minimum=0.0, maximum=2.0, step=0.1, value=1.0)
112
+ contrast = gr.Slider(label="Contrast", minimum=0.0, maximum=2.0, step=0.1, value=1.0)
113
+ saturation = gr.Slider(label="Saturation", minimum=0.0, maximum=2.0, step=0.1, value=1.0)
114
+
115
+ style = gr.Dropdown(label="Select Style", choices=["Style1", "Style2", "Style3"], value="Style1")
116
+ download_all_button = gr.Button("Download All")
117
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  gr.Examples(
119
  examples=examples,
120
  fn=infer,
121
+ inputs=[prompt],
122
+ outputs=[result, seed],
123
+ cache_examples="lazy"
 
124
  )
125
 
126
+ def run_inference(prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps, num_variations, brightness, contrast, saturation, style):
127
+ images, seed = infer(prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps, num_variations, brightness, contrast, saturation, style)
128
+ return images, seed
 
 
 
 
 
129
 
130
+ gr.on(
131
+ triggers=[run_button.click, prompt.submit],
132
+ fn=run_inference,
133
+ inputs=[prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps, num_variations, brightness, contrast, saturation, style],
134
+ outputs=[result, seed]
135
+ )
136
+
137
+ def download_all_callback(images):
138
+ return download_all(images)
139
+
140
+ download_all_button.click(fn=download_all_callback, inputs=[result], outputs=[gr.File(label="Download All Images")])
141
 
142
  demo.launch()