SunderAli17 commited on
Commit
1835926
·
verified ·
1 Parent(s): 0bfe3b3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +213 -127
app.py CHANGED
@@ -1,146 +1,232 @@
1
- import gradio as gr
2
- import numpy as np
 
3
  import random
4
- from diffusers import DiffusionPipeline
 
 
5
  import torch
 
 
6
 
7
- device = "cuda" if torch.cuda.is_available() else "cpu"
8
-
9
- if torch.cuda.is_available():
10
- torch.cuda.max_memory_allocated(device=device)
11
- pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", torch_dtype=torch.float16, variant="fp16", use_safetensors=True)
12
- pipe.enable_xformers_memory_efficient_attention()
13
- pipe = pipe.to(device)
14
- else:
15
- pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", use_safetensors=True)
16
- pipe = pipe.to(device)
17
 
18
  MAX_SEED = np.iinfo(np.int32).max
19
- MAX_IMAGE_SIZE = 1024
20
-
21
- def infer(prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps):
22
-
23
- if randomize_seed:
24
- seed = random.randint(0, MAX_SEED)
25
-
26
- generator = torch.Generator().manual_seed(seed)
27
-
28
- image = pipe(
29
- prompt = prompt,
30
- negative_prompt = negative_prompt,
31
- guidance_scale = guidance_scale,
32
- num_inference_steps = num_inference_steps,
33
- width = width,
34
- height = height,
35
- generator = generator
36
- ).images[0]
37
-
38
  return image
39
 
40
- examples = [
41
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
42
- "An astronaut riding a green horse",
43
- "A delicious ceviche cheesecake slice",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  ]
45
 
46
- css="""
47
- #col-container {
48
- margin: 0 auto;
49
- max-width: 520px;
50
- }
51
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
- if torch.cuda.is_available():
54
- power_device = "GPU"
55
- else:
56
- power_device = "CPU"
57
-
58
- with gr.Blocks(css=css) as demo:
59
-
60
- with gr.Column(elem_id="col-container"):
61
- gr.Markdown(f"""
62
- # Text-to-Image Gradio Template
63
- Currently running on {power_device}.
64
- """)
65
-
66
- with gr.Row():
67
-
68
- prompt = gr.Text(
69
- label="Prompt",
70
- show_label=False,
71
- max_lines=1,
72
- placeholder="Enter your prompt",
73
- container=False,
74
- )
75
-
76
- run_button = gr.Button("Run", scale=0)
77
-
78
- result = gr.Image(label="Result", show_label=False)
79
-
80
- with gr.Accordion("Advanced Settings", open=False):
81
-
82
- negative_prompt = gr.Text(
83
- label="Negative prompt",
84
- max_lines=1,
85
- placeholder="Enter a negative prompt",
86
- visible=False,
87
- )
88
-
89
- seed = gr.Slider(
90
- label="Seed",
91
- minimum=0,
92
- maximum=MAX_SEED,
93
- step=1,
94
- value=0,
95
- )
96
-
97
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
98
-
99
- with gr.Row():
100
-
101
- width = gr.Slider(
102
- label="Width",
103
- minimum=256,
104
- maximum=MAX_IMAGE_SIZE,
105
- step=32,
106
- value=512,
107
- )
108
-
109
- height = gr.Slider(
110
- label="Height",
111
- minimum=256,
112
- maximum=MAX_IMAGE_SIZE,
113
- step=32,
114
- value=512,
115
- )
116
-
117
  with gr.Row():
118
-
119
- guidance_scale = gr.Slider(
120
- label="Guidance scale",
121
- minimum=0.0,
122
- maximum=10.0,
123
- step=0.1,
124
- value=0.0,
125
  )
126
-
127
- num_inference_steps = gr.Slider(
128
- label="Number of inference steps",
129
- minimum=1,
130
- maximum=12,
 
 
 
131
  step=1,
132
- value=2,
133
  )
134
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  gr.Examples(
136
- examples = examples,
137
- inputs = [prompt]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  )
139
 
140
- run_button.click(
141
- fn = infer,
142
- inputs = [prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
143
- outputs = [result]
 
 
 
 
 
 
 
 
 
 
144
  )
145
 
146
- demo.queue().launch()
 
1
+ from typing import Tuple
2
+
3
+ import requests
4
  import random
5
+ import numpy as np
6
+ import gradio as gr
7
+ import spaces
8
  import torch
9
+ from PIL import Image
10
+ from diffusers import FluxInpaintPipeline
11
 
12
+ """
13
+ A big shoutout to [Black Forest Labs](https://huggingface.co/black-forest-labs) team for making their models available.
14
+ Also a big thanks to [Gothos](https://github.com/Gothos) for enabling inpainting with the FLUX.
15
+ """
 
 
 
 
 
 
16
 
17
  MAX_SEED = np.iinfo(np.int32).max
18
+ IMAGE_SIZE = 1024
19
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
20
+
21
+
22
+ def remove_background(image: Image.Image, threshold: int = 50) -> Image.Image:
23
+ image = image.convert("RGBA")
24
+ data = image.getdata()
25
+ new_data = []
26
+ for item in data:
27
+ avg = sum(item[:3]) / 3
28
+ if avg < threshold:
29
+ new_data.append((0, 0, 0, 0))
30
+ else:
31
+ new_data.append(item)
32
+
33
+ image.putdata(new_data)
 
 
 
34
  return image
35
 
36
+
37
+ EXAMPLES = [
38
+ [
39
+ {
40
+ "background": Image.open(requests.get("https://media.roboflow.com/spaces/doge-2-image.png", stream=True).raw),
41
+ "layers": [remove_background(Image.open(requests.get("https://media.roboflow.com/spaces/doge-2-mask-2.png", stream=True).raw))],
42
+ "composite": Image.open(requests.get("https://media.roboflow.com/spaces/doge-2-composite-2.png", stream=True).raw),
43
+ },
44
+ "little lion",
45
+ 42,
46
+ False,
47
+ 0.85,
48
+ 30
49
+ ],
50
+ [
51
+ {
52
+ "background": Image.open(requests.get("https://media.roboflow.com/spaces/doge-2-image.png", stream=True).raw),
53
+ "layers": [remove_background(Image.open(requests.get("https://media.roboflow.com/spaces/doge-2-mask-3.png", stream=True).raw))],
54
+ "composite": Image.open(requests.get("https://media.roboflow.com/spaces/doge-2-composite-3.png", stream=True).raw),
55
+ },
56
+ "tribal tattoos",
57
+ 42,
58
+ False,
59
+ 0.85,
60
+ 30
61
+ ]
62
  ]
63
 
64
+ pipe = FluxInpaintPipeline.from_pretrained(
65
+ "black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16).to(DEVICE)
66
+
67
+
68
+ def resize_image_dimensions(
69
+ original_resolution_wh: Tuple[int, int],
70
+ maximum_dimension: int = IMAGE_SIZE
71
+ ) -> Tuple[int, int]:
72
+ width, height = original_resolution_wh
73
+
74
+ if width > height:
75
+ scaling_factor = maximum_dimension / width
76
+ else:
77
+ scaling_factor = maximum_dimension / height
78
+
79
+ new_width = int(width * scaling_factor)
80
+ new_height = int(height * scaling_factor)
81
+
82
+ new_width = new_width - (new_width % 32)
83
+ new_height = new_height - (new_height % 32)
84
+
85
+ return new_width, new_height
86
+
87
+
88
+ @spaces.GPU(duration=100)
89
+ def process(
90
+ input_image_editor: dict,
91
+ input_text: str,
92
+ seed_slicer: int,
93
+ randomize_seed_checkbox: bool,
94
+ strength_slider: float,
95
+ num_inference_steps_slider: int,
96
+ progress=gr.Progress(track_tqdm=True)
97
+ ):
98
+ if not input_text:
99
+ gr.Info("Please enter a text prompt.")
100
+ return None, None
101
+
102
+ image = input_image_editor['background']
103
+ mask = input_image_editor['layers'][0]
104
+
105
+ if not image:
106
+ gr.Info("Please upload an image.")
107
+ return None, None
108
+
109
+ if not mask:
110
+ gr.Info("Please draw a mask on the image.")
111
+ return None, None
112
+
113
+ width, height = resize_image_dimensions(original_resolution_wh=image.size)
114
+ resized_image = image.resize((width, height), Image.LANCZOS)
115
+ resized_mask = mask.resize((width, height), Image.LANCZOS)
116
+
117
+ if randomize_seed_checkbox:
118
+ seed_slicer = random.randint(0, MAX_SEED)
119
+ generator = torch.Generator().manual_seed(seed_slicer)
120
+ result = pipe(
121
+ prompt=input_text,
122
+ image=resized_image,
123
+ mask_image=resized_mask,
124
+ width=width,
125
+ height=height,
126
+ strength=strength_slider,
127
+ generator=generator,
128
+ num_inference_steps=num_inference_steps_slider
129
+ ).images[0]
130
+ print('INFERENCE DONE')
131
+ return result, resized_mask
132
+
133
+
134
+ with gr.Blocks() as demo:
135
+ gr.Markdown(MARKDOWN)
136
+ with gr.Row():
137
+ with gr.Column():
138
+ input_image_editor_component = gr.ImageEditor(
139
+ label='Image',
140
+ type='pil',
141
+ sources=["upload", "webcam"],
142
+ image_mode='RGB',
143
+ layers=False,
144
+ brush=gr.Brush(colors=["#FFFFFF"], color_mode="fixed"))
145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  with gr.Row():
147
+ input_text_component = gr.Text(
148
+ label="Prompt",
149
+ show_label=False,
150
+ max_lines=1,
151
+ placeholder="Enter your prompt",
152
+ container=False,
 
153
  )
154
+ submit_button_component = gr.Button(
155
+ value='Submit', variant='primary', scale=0)
156
+
157
+ with gr.Accordion("Advanced Settings", open=False):
158
+ seed_slicer_component = gr.Slider(
159
+ label="Seed",
160
+ minimum=0,
161
+ maximum=MAX_SEED,
162
  step=1,
163
+ value=42,
164
  )
165
+
166
+ randomize_seed_checkbox_component = gr.Checkbox(
167
+ label="Randomize seed", value=True)
168
+
169
+ with gr.Row():
170
+ strength_slider_component = gr.Slider(
171
+ label="Strength",
172
+ info="Indicates extent to transform the reference `image`. "
173
+ "Must be between 0 and 1. `image` is used as a starting "
174
+ "point and more noise is added the higher the `strength`.",
175
+ minimum=0,
176
+ maximum=1,
177
+ step=0.01,
178
+ value=0.85,
179
+ )
180
+
181
+ num_inference_steps_slider_component = gr.Slider(
182
+ label="Number of inference steps",
183
+ info="The number of denoising steps. More denoising steps "
184
+ "usually lead to a higher quality image at the",
185
+ minimum=1,
186
+ maximum=50,
187
+ step=1,
188
+ value=20,
189
+ )
190
+ with gr.Column():
191
+ output_image_component = gr.Image(
192
+ type='pil', image_mode='RGB', label='Generated image', format="png")
193
+ with gr.Accordion("Debug", open=False):
194
+ output_mask_component = gr.Image(
195
+ type='pil', image_mode='RGB', label='Input mask', format="png")
196
+ with gr.Row():
197
  gr.Examples(
198
+ fn=process,
199
+ examples=EXAMPLES,
200
+ inputs=[
201
+ input_image_editor_component,
202
+ input_text_component,
203
+ seed_slicer_component,
204
+ randomize_seed_checkbox_component,
205
+ strength_slider_component,
206
+ num_inference_steps_slider_component
207
+ ],
208
+ outputs=[
209
+ output_image_component,
210
+ output_mask_component
211
+ ],
212
+ run_on_click=True,
213
+ cache_examples=True
214
  )
215
 
216
+ submit_button_component.click(
217
+ fn=process,
218
+ inputs=[
219
+ input_image_editor_component,
220
+ input_text_component,
221
+ seed_slicer_component,
222
+ randomize_seed_checkbox_component,
223
+ strength_slider_component,
224
+ num_inference_steps_slider_component
225
+ ],
226
+ outputs=[
227
+ output_image_component,
228
+ output_mask_component
229
+ ]
230
  )
231
 
232
+ demo.launch(debug=False, show_error=True)