codic commited on
Commit
cce69df
·
verified ·
1 Parent(s): 8c7cb7d

back testing the old one

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