codic commited on
Commit
0c6da48
·
verified ·
1 Parent(s): 5d5b492

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -44
app.py CHANGED
@@ -1,4 +1,3 @@
1
- import spaces
2
  import gradio as gr
3
  import diffusers
4
  import torch
@@ -14,19 +13,34 @@ import gc
14
 
15
  from scipy.ndimage import sobel
16
 
 
 
 
17
 
 
 
18
 
 
 
 
 
 
 
 
 
 
 
19
 
20
-
21
- import xformers
22
- from xformers.ops import memory_efficient_attention
23
  # Device configuration
24
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
25
  if device.type == "cpu":
26
  print("Using CPU, not GPU")
27
  else:
28
- print("Using ZeroGPU")
29
- torch.cuda.empty_cache()
 
 
 
30
 
31
  # Load the Marigold Depth Pipeline with LCM Scheduler
32
  try:
@@ -37,29 +51,35 @@ try:
37
  torch_dtype=torch.float16
38
  ).to(device)
39
  print("Pipeline loaded successfully.")
 
 
40
  print("Loading custom VAE...")
 
41
  pipe.vae = diffusers.AutoencoderTiny.from_pretrained(
42
  "madebyollin/taesd",
43
  torch_dtype=torch.float16
44
- ).cuda()
45
  print("Custom VAE loaded.")
46
  except Exception as e:
47
  print(f"Error loading depth pipeline: {type(e).__name__} - {e}")
48
  raise
49
 
50
- # Enable XFormers
51
- try:
52
- from xformers.ops import memory_efficient_attention
53
- print("xformers is installed and operational!")
54
- print("Enabling XFormers...")
55
- pipe.enable_xformers_memory_efficient_attention()
56
- print("XFormers enabled.")
57
- except AttributeError:
58
- print("XFormers is not supported in the installed version of diffusers or model.")
59
- except ImportError:
60
- print("XFormers library is not installed. Run `pip install xformers`.")
61
- except Exception as e:
62
- print(f"Unexpected error enabling XFormers: {type(e).__name__} - {e}")
 
 
 
63
 
64
  @spaces.GPU(enable_queue=True)
65
  def predict_depth(image: Image.Image):
@@ -215,35 +235,17 @@ def get_mesh(image: Image.Image, depth, image_path: str, foreground: np.ndarray)
215
  # Visualize normalized depth map for debugging
216
  Image.fromarray(depth_image_normalized.astype(np.uint8)).save("debug_depth_normalized.png")
217
 
218
- # Sharpen depth image using gradients
219
- sobel_x = sobel(depth_image_resized, axis=0)
220
- sobel_y = sobel(depth_image_resized, axis=1)
221
- gradient_magnitude = np.hypot(sobel_x, sobel_y)
222
- edge_mask = gradient_magnitude < (gradient_magnitude.max() * 0.1)
223
- depth_image_sharpened = np.where(edge_mask, depth_image_normalized, 0)
224
- print("Depth image sharpening completed.")
225
-
226
- # Visualize sharpened depth image for debugging
227
- Image.fromarray(depth_image_sharpened.astype(np.uint8)).save("debug_depth_sharpened.png")
228
-
229
- # Validate depth and foreground size before generating the point cloud
230
- if depth_image_sharpened.shape != foreground.shape[:2]:
231
- raise ValueError(
232
- f"Shape mismatch before point cloud generation: Depth map shape {depth_image_sharpened.shape} "
233
- f"and foreground shape {foreground.shape[:2]} do not align."
234
- )
235
- print("Final size check before point cloud generation passed.")
236
-
237
  # Ensure the foreground is RGB (remove alpha channel if present)
238
- if foreground.shape[2] == 4: # Check if it has an alpha channel
239
  foreground = foreground[:, :, :3]
240
-
241
  # Create Open3D RGBD image
242
- depth_o3d = o3d.geometry.Image(depth_image_sharpened)
243
- image_o3d = o3d.geometry.Image(foreground)
244
  rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
245
  image_o3d, depth_o3d, convert_rgb_to_intensity=False
246
  )
 
247
  print("RGBD image creation completed.")
248
  # Camera intrinsics
249
  w, h = foreground.shape[1], foreground.shape[0]
@@ -362,6 +364,7 @@ iface = gr.Interface(
362
  ],
363
  title=title,
364
  description=description,
365
- allow_flagging="never"
 
366
  )
367
  iface.launch(debug=True, share=True)
 
 
1
  import gradio as gr
2
  import diffusers
3
  import torch
 
13
 
14
  from scipy.ndimage import sobel
15
 
16
+ import os
17
+ import torch
18
+ import diffusers
19
 
20
+ # Disable GPU if explicitly required
21
+ os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
22
 
23
+ # Handle GPU availability in Hugging Face Spaces with ZeroGPU
24
+ if os.environ.get("SPACES_ZERO_GPU") is not None:
25
+ import spaces
26
+ else:
27
+ class spaces:
28
+ @staticmethod
29
+ def GPU(func):
30
+ def wrapper(*args, **kwargs):
31
+ return func(*args, **kwargs)
32
+ return wrapper
33
 
 
 
 
34
  # Device configuration
35
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
36
  if device.type == "cpu":
37
  print("Using CPU, not GPU")
38
  else:
39
+ print(f"Using GPU: {torch.cuda.get_device_name(0)}")
40
+
41
+ # Clear GPU cache if applicable
42
+ if device.type == "cuda":
43
+ torch.cuda.empty_cache()
44
 
45
  # Load the Marigold Depth Pipeline with LCM Scheduler
46
  try:
 
51
  torch_dtype=torch.float16
52
  ).to(device)
53
  print("Pipeline loaded successfully.")
54
+
55
+ # Load the custom VAE
56
  print("Loading custom VAE...")
57
+ vae_device = "cuda" if device.type == "cuda" else "cpu"
58
  pipe.vae = diffusers.AutoencoderTiny.from_pretrained(
59
  "madebyollin/taesd",
60
  torch_dtype=torch.float16
61
+ ).to(vae_device)
62
  print("Custom VAE loaded.")
63
  except Exception as e:
64
  print(f"Error loading depth pipeline: {type(e).__name__} - {e}")
65
  raise
66
 
67
+ # Enable XFormers if using GPU
68
+ if device.type == "cuda":
69
+ try:
70
+ from xformers.ops import memory_efficient_attention
71
+ print("xformers is installed and operational!")
72
+ print("Enabling XFormers...")
73
+ pipe.enable_xformers_memory_efficient_attention()
74
+ print("XFormers enabled.")
75
+ except AttributeError:
76
+ print("XFormers is not supported in the installed version of diffusers or model.")
77
+ except ImportError:
78
+ print("XFormers library is not installed. Run `pip install xformers`.")
79
+ except Exception as e:
80
+ print(f"Unexpected error enabling XFormers: {type(e).__name__} - {e}")
81
+ else:
82
+ print("XFormers not enabled as the device is CPU.")
83
 
84
  @spaces.GPU(enable_queue=True)
85
  def predict_depth(image: Image.Image):
 
235
  # Visualize normalized depth map for debugging
236
  Image.fromarray(depth_image_normalized.astype(np.uint8)).save("debug_depth_normalized.png")
237
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
238
  # Ensure the foreground is RGB (remove alpha channel if present)
239
+ if foreground.shape[2] == 4:
240
  foreground = foreground[:, :, :3]
241
+
242
  # Create Open3D RGBD image
243
+ depth_o3d = o3d.geometry.Image(np.ascontiguousarray(depth_image_normalized))
244
+ image_o3d = o3d.geometry.Image(np.ascontiguousarray(foreground))
245
  rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
246
  image_o3d, depth_o3d, convert_rgb_to_intensity=False
247
  )
248
+
249
  print("RGBD image creation completed.")
250
  # Camera intrinsics
251
  w, h = foreground.shape[1], foreground.shape[0]
 
364
  ],
365
  title=title,
366
  description=description,
367
+ allow_flagging="never",
368
+ flagging_mode="manual"
369
  )
370
  iface.launch(debug=True, share=True)