Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -6,69 +6,20 @@ import torch
|
|
6 |
import spaces
|
7 |
import random
|
8 |
|
9 |
-
from diffusers import
|
10 |
from PIL import Image
|
11 |
|
12 |
|
13 |
MAX_SEED = np.iinfo(np.int32).max
|
14 |
MAX_IMAGE_SIZE = 2048
|
15 |
|
16 |
-
pipe =
|
17 |
-
# pipe.enable_sequential_cpu_offload()
|
18 |
-
# pipe.enable_fp16()
|
19 |
-
# pipe.vae.enable_slicing()
|
20 |
-
# pipe.vae.enable_tiling()
|
21 |
-
|
22 |
-
def calculate_optimal_dimensions(image: Image.Image):
|
23 |
-
# Extract the original dimensions
|
24 |
-
original_width, original_height = image.size
|
25 |
-
|
26 |
-
# Set constants
|
27 |
-
MIN_ASPECT_RATIO = 9 / 16
|
28 |
-
MAX_ASPECT_RATIO = 16 / 9
|
29 |
-
FIXED_DIMENSION = 1024
|
30 |
-
|
31 |
-
# Calculate the aspect ratio of the original image
|
32 |
-
original_aspect_ratio = original_width / original_height
|
33 |
-
|
34 |
-
# Determine which dimension to fix
|
35 |
-
if original_aspect_ratio > 1: # Wider than tall
|
36 |
-
width = FIXED_DIMENSION
|
37 |
-
height = round(FIXED_DIMENSION / original_aspect_ratio)
|
38 |
-
else: # Taller than wide
|
39 |
-
height = FIXED_DIMENSION
|
40 |
-
width = round(FIXED_DIMENSION * original_aspect_ratio)
|
41 |
-
|
42 |
-
# Ensure dimensions are multiples of 8
|
43 |
-
width = (width // 8) * 8
|
44 |
-
height = (height // 8) * 8
|
45 |
-
|
46 |
-
# Enforce aspect ratio limits
|
47 |
-
calculated_aspect_ratio = width / height
|
48 |
-
if calculated_aspect_ratio > MAX_ASPECT_RATIO:
|
49 |
-
width = (height * MAX_ASPECT_RATIO // 8) * 8
|
50 |
-
elif calculated_aspect_ratio < MIN_ASPECT_RATIO:
|
51 |
-
height = (width / MIN_ASPECT_RATIO // 8) * 8
|
52 |
-
|
53 |
-
# Ensure width and height remain above the minimum dimensions
|
54 |
-
width = max(width, 576) if width == FIXED_DIMENSION else width
|
55 |
-
height = max(height, 576) if height == FIXED_DIMENSION else height
|
56 |
-
|
57 |
-
return width, height
|
58 |
|
59 |
@spaces.GPU(durations=300)
|
60 |
-
def infer(
|
61 |
-
|
62 |
-
|
63 |
-
image = edit_images["background"]
|
64 |
-
width, height = calculate_optimal_dimensions(image)
|
65 |
-
mask = edit_images["layers"][0]
|
66 |
-
if randomize_seed:
|
67 |
-
seed = random.randint(0, MAX_SEED)
|
68 |
image = pipe(
|
69 |
prompt=prompt,
|
70 |
-
image=image,
|
71 |
-
mask_image=mask,
|
72 |
height=height,
|
73 |
width=width,
|
74 |
guidance_scale=guidance_scale,
|
@@ -104,15 +55,6 @@ with gr.Blocks(css=css) as demo:
|
|
104 |
""")
|
105 |
with gr.Row():
|
106 |
with gr.Column():
|
107 |
-
edit_image = gr.ImageEditor(
|
108 |
-
label='Upload and draw mask for inpainting',
|
109 |
-
type='pil',
|
110 |
-
sources=["upload", "webcam"],
|
111 |
-
image_mode='RGB',
|
112 |
-
layers=False,
|
113 |
-
brush=gr.Brush(colors=["#FFFFFF"]),
|
114 |
-
# height=600
|
115 |
-
)
|
116 |
prompt = gr.Text(
|
117 |
label="Prompt",
|
118 |
show_label=False,
|
@@ -177,270 +119,8 @@ with gr.Blocks(css=css) as demo:
|
|
177 |
gr.on(
|
178 |
triggers=[run_button.click, prompt.submit],
|
179 |
fn = infer,
|
180 |
-
inputs = [
|
181 |
outputs = [result, seed]
|
182 |
)
|
183 |
|
184 |
-
demo.launch()
|
185 |
-
|
186 |
-
|
187 |
-
# import gradio as gr
|
188 |
-
# import numpy as np
|
189 |
-
# import torch
|
190 |
-
# import random
|
191 |
-
# from PIL import Image
|
192 |
-
# import cv2
|
193 |
-
# import spaces
|
194 |
-
|
195 |
-
# # ------------------ Inpainting Pipeline Setup ------------------ #
|
196 |
-
# from diffusers import FluxFillPipeline
|
197 |
-
|
198 |
-
# MAX_SEED = np.iinfo(np.int32).max
|
199 |
-
# MAX_IMAGE_SIZE = 2048
|
200 |
-
|
201 |
-
# pipe = FluxFillPipeline.from_pretrained(
|
202 |
-
# "black-forest-labs/FLUX.1-Fill-dev", torch_dtype=torch.bfloat16
|
203 |
-
# )
|
204 |
-
# pipe.load_lora_weights("alvdansen/flux-koda")
|
205 |
-
# pipe.enable_lora()
|
206 |
-
|
207 |
-
# def calculate_optimal_dimensions(image: Image.Image):
|
208 |
-
# # Extract the original dimensions
|
209 |
-
# original_width, original_height = image.size
|
210 |
-
|
211 |
-
# # Set constants
|
212 |
-
# MIN_ASPECT_RATIO = 9 / 16
|
213 |
-
# MAX_ASPECT_RATIO = 16 / 9
|
214 |
-
# FIXED_DIMENSION = 1024
|
215 |
-
|
216 |
-
# # Calculate the aspect ratio of the original image
|
217 |
-
# original_aspect_ratio = original_width / original_height
|
218 |
-
|
219 |
-
# # Determine which dimension to fix
|
220 |
-
# if original_aspect_ratio > 1: # Wider than tall
|
221 |
-
# width = FIXED_DIMENSION
|
222 |
-
# height = round(FIXED_DIMENSION / original_aspect_ratio)
|
223 |
-
# else: # Taller than wide
|
224 |
-
# height = FIXED_DIMENSION
|
225 |
-
# width = round(FIXED_DIMENSION * original_aspect_ratio)
|
226 |
-
|
227 |
-
# # Ensure dimensions are multiples of 8
|
228 |
-
# width = (width // 8) * 8
|
229 |
-
# height = (height // 8) * 8
|
230 |
-
|
231 |
-
# # Enforce aspect ratio limits
|
232 |
-
# calculated_aspect_ratio = width / height
|
233 |
-
# if calculated_aspect_ratio > MAX_ASPECT_RATIO:
|
234 |
-
# width = (height * MAX_ASPECT_RATIO // 8) * 8
|
235 |
-
# elif calculated_aspect_ratio < MIN_ASPECT_RATIO:
|
236 |
-
# height = (width / MIN_ASPECT_RATIO // 8) * 8
|
237 |
-
|
238 |
-
# # Ensure minimum dimensions are met
|
239 |
-
# width = max(width, 576) if width == FIXED_DIMENSION else width
|
240 |
-
# height = max(height, 576) if height == FIXED_DIMENSION else height
|
241 |
-
|
242 |
-
# return width, height
|
243 |
-
|
244 |
-
# # ------------------ SAM (Transformers) Imports and Initialization ------------------ #
|
245 |
-
# from transformers import SamModel, SamProcessor
|
246 |
-
|
247 |
-
# # Load the model and processor from Hugging Face.
|
248 |
-
# sam_model = SamModel.from_pretrained("facebook/sam-vit-base")
|
249 |
-
# sam_processor = SamProcessor.from_pretrained("facebook/sam-vit-base")
|
250 |
-
|
251 |
-
# @spaces.GPU(durations=300)
|
252 |
-
# def generate_mask_with_sam(image: Image.Image, mask_prompt: str):
|
253 |
-
# """
|
254 |
-
# Generate a segmentation mask using SAM (via Hugging Face Transformers).
|
255 |
-
|
256 |
-
# The mask_prompt is expected to be a comma-separated string of two integers,
|
257 |
-
# e.g. "450,600" representing an (x,y) coordinate in the image.
|
258 |
-
|
259 |
-
# The function converts the coordinate into the proper input format for SAM and returns a binary mask.
|
260 |
-
# """
|
261 |
-
# if mask_prompt.strip() == "":
|
262 |
-
# raise ValueError("No mask prompt provided.")
|
263 |
-
|
264 |
-
# try:
|
265 |
-
# # Parse the mask_prompt into a coordinate
|
266 |
-
# coords = [int(x.strip()) for x in mask_prompt.split(",")]
|
267 |
-
# if len(coords) != 2:
|
268 |
-
# raise ValueError("Expected two comma-separated integers (x,y).")
|
269 |
-
# except Exception as e:
|
270 |
-
# raise ValueError("Invalid mask prompt. Please provide coordinates as 'x,y'. Error: " + str(e))
|
271 |
-
|
272 |
-
# # The SAM processor expects a list of input points.
|
273 |
-
# # Format the point as a list of lists; here we assume one point per image.
|
274 |
-
# # (The Transformers SAM expects the points in [x, y] order.)
|
275 |
-
# input_points = [coords] # e.g. [[450,600]]
|
276 |
-
# # Optionally, you can supply input_labels (1 for foreground, 0 for background)
|
277 |
-
# input_labels = [1]
|
278 |
-
|
279 |
-
# # Prepare the inputs for the SAM processor.
|
280 |
-
# inputs = sam_processor(images=image,
|
281 |
-
# input_points=[input_points],
|
282 |
-
# input_labels=[input_labels],
|
283 |
-
# return_tensors="pt")
|
284 |
-
|
285 |
-
# # Move tensors to the same device as the model.
|
286 |
-
# device = next(sam_model.parameters()).device
|
287 |
-
# inputs = {k: v.to(device) for k, v in inputs.items()}
|
288 |
-
|
289 |
-
# # Forward pass through SAM.
|
290 |
-
# with torch.no_grad():
|
291 |
-
# outputs = sam_model(**inputs)
|
292 |
-
|
293 |
-
# # The output contains predicted masks; we take the first mask from the first prompt.
|
294 |
-
# # (Assuming outputs.pred_masks is of shape (batch_size, num_masks, H, W))
|
295 |
-
# pred_masks = outputs.pred_masks # Tensor of shape (1, num_masks, H, W)
|
296 |
-
# mask = pred_masks[0][0].detach().cpu().numpy()
|
297 |
-
|
298 |
-
# # Convert the mask to binary (0 or 255) using a threshold.
|
299 |
-
# mask_bin = (mask > 0.5).astype(np.uint8) * 255
|
300 |
-
# mask_pil = Image.fromarray(mask_bin)
|
301 |
-
# return mask_pil
|
302 |
-
|
303 |
-
# # ------------------ Inference Function ------------------ #
|
304 |
-
# @spaces.GPU(durations=300)
|
305 |
-
# def infer(edit_images, prompt, mask_prompt,
|
306 |
-
# seed=42, randomize_seed=False, width=1024, height=1024,
|
307 |
-
# guidance_scale=3.5, num_inference_steps=28, progress=gr.Progress(track_tqdm=True)):
|
308 |
-
# # Get the base image from the "background" layer.
|
309 |
-
# image = edit_images["background"]
|
310 |
-
# width, height = calculate_optimal_dimensions(image)
|
311 |
-
|
312 |
-
# # If a mask prompt is provided, use the SAM-based mask generator.
|
313 |
-
# if mask_prompt and mask_prompt.strip() != "":
|
314 |
-
# try:
|
315 |
-
# mask = generate_mask_with_sam(image, mask_prompt)
|
316 |
-
# except Exception as e:
|
317 |
-
# raise ValueError("Error generating mask from prompt: " + str(e))
|
318 |
-
# else:
|
319 |
-
# # Fall back to using a manually drawn mask (from the first layer).
|
320 |
-
# try:
|
321 |
-
# mask = edit_images["layers"][0]
|
322 |
-
# except (TypeError, IndexError):
|
323 |
-
# raise ValueError("No mask provided. Please either draw a mask or supply a mask prompt.")
|
324 |
-
|
325 |
-
# if randomize_seed:
|
326 |
-
# seed = random.randint(0, MAX_SEED)
|
327 |
-
|
328 |
-
# # Run the inpainting diffusion pipeline with the provided prompt and mask.
|
329 |
-
# image_out = pipe(
|
330 |
-
# prompt=prompt,
|
331 |
-
# image=image,
|
332 |
-
# mask_image=mask,
|
333 |
-
# height=height,
|
334 |
-
# width=width,
|
335 |
-
# guidance_scale=guidance_scale,
|
336 |
-
# num_inference_steps=num_inference_steps,
|
337 |
-
# generator=torch.Generator(device='cuda').manual_seed(seed),
|
338 |
-
# ).images[0]
|
339 |
-
|
340 |
-
# output_image_jpg = image_out.convert("RGB")
|
341 |
-
# output_image_jpg.save("output.jpg", "JPEG")
|
342 |
-
# return output_image_jpg, seed
|
343 |
-
|
344 |
-
# # ------------------ Gradio UI ------------------ #
|
345 |
-
# css = """
|
346 |
-
# #col-container {
|
347 |
-
# margin: 0 auto;
|
348 |
-
# max-width: 1000px;
|
349 |
-
# }
|
350 |
-
# """
|
351 |
-
|
352 |
-
# with gr.Blocks(css=css) as demo:
|
353 |
-
# with gr.Column(elem_id="col-container"):
|
354 |
-
# gr.Markdown("# FLUX.1 [dev] with SAM (Transformers) Mask Generation")
|
355 |
-
# with gr.Row():
|
356 |
-
# with gr.Column():
|
357 |
-
# # The image editor now allows you to optionally draw a mask.
|
358 |
-
# edit_image = gr.ImageEditor(
|
359 |
-
# label='Upload Image (and optionally draw a mask)',
|
360 |
-
# type='pil',
|
361 |
-
# sources=["upload", "webcam"],
|
362 |
-
# image_mode='RGB',
|
363 |
-
# layers=False, # We will generate a mask automatically if needed.
|
364 |
-
# brush=gr.Brush(colors=["#FFFFFF"]),
|
365 |
-
# )
|
366 |
-
# prompt = gr.Text(
|
367 |
-
# label="Inpainting Prompt",
|
368 |
-
# show_label=False,
|
369 |
-
# max_lines=2,
|
370 |
-
# placeholder="Enter your inpainting prompt",
|
371 |
-
# container=False,
|
372 |
-
# )
|
373 |
-
# mask_prompt = gr.Text(
|
374 |
-
# label="Mask Prompt (enter a coordinate as 'x,y')",
|
375 |
-
# show_label=True,
|
376 |
-
# placeholder="E.g. 450,600",
|
377 |
-
# container=True,
|
378 |
-
# )
|
379 |
-
# generate_mask_btn = gr.Button("Generate Mask")
|
380 |
-
# mask_preview = gr.Image(label="Mask Preview", show_label=True)
|
381 |
-
# run_button = gr.Button("Run")
|
382 |
-
# result = gr.Image(label="Result", show_label=False)
|
383 |
-
|
384 |
-
# # Button to preview the generated mask.
|
385 |
-
# def on_generate_mask(image, mask_prompt):
|
386 |
-
# if image is None or mask_prompt.strip() == "":
|
387 |
-
# return None
|
388 |
-
# mask = generate_mask_with_sam(image, mask_prompt)
|
389 |
-
# return mask
|
390 |
-
|
391 |
-
# generate_mask_btn.click(
|
392 |
-
# fn=on_generate_mask,
|
393 |
-
# inputs=[edit_image, mask_prompt],
|
394 |
-
# outputs=[mask_preview]
|
395 |
-
# )
|
396 |
-
|
397 |
-
# with gr.Accordion("Advanced Settings", open=False):
|
398 |
-
# seed = gr.Slider(
|
399 |
-
# label="Seed",
|
400 |
-
# minimum=0,
|
401 |
-
# maximum=MAX_SEED,
|
402 |
-
# step=1,
|
403 |
-
# value=0,
|
404 |
-
# )
|
405 |
-
# randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
|
406 |
-
# with gr.Row():
|
407 |
-
# width = gr.Slider(
|
408 |
-
# label="Width",
|
409 |
-
# minimum=256,
|
410 |
-
# maximum=MAX_IMAGE_SIZE,
|
411 |
-
# step=32,
|
412 |
-
# value=1024,
|
413 |
-
# visible=False
|
414 |
-
# )
|
415 |
-
# height = gr.Slider(
|
416 |
-
# label="Height",
|
417 |
-
# minimum=256,
|
418 |
-
# maximum=MAX_IMAGE_SIZE,
|
419 |
-
# step=32,
|
420 |
-
# value=1024,
|
421 |
-
# visible=False
|
422 |
-
# )
|
423 |
-
# with gr.Row():
|
424 |
-
# guidance_scale = gr.Slider(
|
425 |
-
# label="Guidance Scale",
|
426 |
-
# minimum=1,
|
427 |
-
# maximum=30,
|
428 |
-
# step=0.5,
|
429 |
-
# value=3.5,
|
430 |
-
# )
|
431 |
-
# num_inference_steps = gr.Slider(
|
432 |
-
# label="Number of Inference Steps",
|
433 |
-
# minimum=1,
|
434 |
-
# maximum=50,
|
435 |
-
# step=1,
|
436 |
-
# value=28,
|
437 |
-
# )
|
438 |
-
|
439 |
-
# gr.on(
|
440 |
-
# triggers=[run_button.click, prompt.submit],
|
441 |
-
# fn=infer,
|
442 |
-
# inputs=[edit_image, prompt, mask_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
|
443 |
-
# outputs=[result, seed]
|
444 |
-
# )
|
445 |
-
|
446 |
-
# demo.launch()
|
|
|
6 |
import spaces
|
7 |
import random
|
8 |
|
9 |
+
from diffusers import FluxPipeline
|
10 |
from PIL import Image
|
11 |
|
12 |
|
13 |
MAX_SEED = np.iinfo(np.int32).max
|
14 |
MAX_IMAGE_SIZE = 2048
|
15 |
|
16 |
+
pipe = FluxPipeline.from_pretrained("Himanshu806/FluxHyperReal", torch_dtype=torch.bfloat16).to("cuda")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
|
18 |
@spaces.GPU(durations=300)
|
19 |
+
def infer(prompt, seed=42, randomize_seed=False, width=1024, height=1024, guidance_scale=3.5, num_inference_steps=28, progress=gr.Progress(track_tqdm=True)):
|
20 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
image = pipe(
|
22 |
prompt=prompt,
|
|
|
|
|
23 |
height=height,
|
24 |
width=width,
|
25 |
guidance_scale=guidance_scale,
|
|
|
55 |
""")
|
56 |
with gr.Row():
|
57 |
with gr.Column():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
58 |
prompt = gr.Text(
|
59 |
label="Prompt",
|
60 |
show_label=False,
|
|
|
119 |
gr.on(
|
120 |
triggers=[run_button.click, prompt.submit],
|
121 |
fn = infer,
|
122 |
+
inputs = [prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
|
123 |
outputs = [result, seed]
|
124 |
)
|
125 |
|
126 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|