Alessio Grancini
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -19,11 +19,18 @@ img_seg = None
|
|
19 |
depth_estimator = None
|
20 |
|
21 |
def initialize_models():
|
|
|
22 |
global img_seg, depth_estimator
|
|
|
|
|
23 |
if img_seg is None:
|
24 |
-
|
|
|
|
|
25 |
if depth_estimator is None:
|
26 |
-
|
|
|
|
|
27 |
|
28 |
def safe_gpu_decorator(func):
|
29 |
"""Custom decorator to handle GPU operations safely"""
|
@@ -42,22 +49,38 @@ def safe_gpu_decorator(func):
|
|
42 |
@safe_gpu_decorator
|
43 |
def process_image(image):
|
44 |
try:
|
45 |
-
print("Starting image processing")
|
46 |
initialize_models()
|
47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
48 |
image = utils.resize(image)
|
49 |
image_segmentation, objects_data = img_seg.predict(image)
|
50 |
depthmap, depth_colormap = depth_estimator.make_prediction(image)
|
51 |
dist_image = utils.draw_depth_info(image, depthmap, objects_data)
|
52 |
objs_pcd = utils.generate_obj_pcd(depthmap, objects_data)
|
53 |
plot_fig = display_pcd(objs_pcd)
|
|
|
54 |
return image_segmentation, depth_colormap, dist_image, plot_fig
|
55 |
-
|
56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
import traceback
|
58 |
print(traceback.format_exc())
|
59 |
raise
|
60 |
|
|
|
|
|
61 |
@safe_gpu_decorator
|
62 |
def test_process_img(image):
|
63 |
initialize_models()
|
@@ -102,41 +125,43 @@ def update_confidence_threshold(thres_val):
|
|
102 |
@safe_gpu_decorator
|
103 |
def model_selector(model_type):
|
104 |
global img_seg, depth_estimator
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
|
|
|
|
|
|
117 |
|
118 |
def cancel():
|
119 |
global CANCEL_PROCESSING
|
120 |
CANCEL_PROCESSING = True
|
121 |
|
122 |
if __name__ == "__main__":
|
123 |
-
|
124 |
try:
|
125 |
if torch.cuda.is_available():
|
126 |
-
print("CUDA is available
|
127 |
-
# Test CUDA initialization
|
128 |
-
torch.cuda.init()
|
129 |
device = torch.device("cuda")
|
|
|
130 |
else:
|
131 |
-
print("
|
132 |
-
os.environ['CUDA_VISIBLE_DEVICES'] = ''
|
133 |
device = torch.device("cpu")
|
134 |
except RuntimeError as e:
|
135 |
-
print(f"CUDA initialization failed: {e}")
|
136 |
-
|
137 |
-
os.environ['CUDA_VISIBLE_DEVICES'] = ''
|
138 |
device = torch.device("cpu")
|
139 |
|
|
|
140 |
with gr.Blocks() as my_app:
|
141 |
# title
|
142 |
gr.Markdown("<h1><center>Simultaneous Segmentation and Depth Estimation</center></h1>")
|
|
|
19 |
depth_estimator = None
|
20 |
|
21 |
def initialize_models():
|
22 |
+
"""Loads models onto GPU if available, otherwise falls back to CPU."""
|
23 |
global img_seg, depth_estimator
|
24 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
25 |
+
|
26 |
if img_seg is None:
|
27 |
+
print(f"🔹 Loading ImageSegmenter model on {device}...")
|
28 |
+
img_seg = ImageSegmenter(model_type="yolov8s-seg", device=device)
|
29 |
+
|
30 |
if depth_estimator is None:
|
31 |
+
print(f"🔹 Loading Depth Estimator model on {device}...")
|
32 |
+
depth_estimator = MonocularDepthEstimator(model_type="midas_v21_small_256", device=device)
|
33 |
+
|
34 |
|
35 |
def safe_gpu_decorator(func):
|
36 |
"""Custom decorator to handle GPU operations safely"""
|
|
|
49 |
@safe_gpu_decorator
|
50 |
def process_image(image):
|
51 |
try:
|
52 |
+
print("🚀 Starting image processing...")
|
53 |
initialize_models()
|
54 |
+
|
55 |
+
if torch.cuda.is_available():
|
56 |
+
print("✅ Using GPU for processing")
|
57 |
+
torch.set_default_tensor_type(torch.cuda.FloatTensor)
|
58 |
+
else:
|
59 |
+
print("⚠️ Using CPU for processing")
|
60 |
+
|
61 |
+
# Process image
|
62 |
image = utils.resize(image)
|
63 |
image_segmentation, objects_data = img_seg.predict(image)
|
64 |
depthmap, depth_colormap = depth_estimator.make_prediction(image)
|
65 |
dist_image = utils.draw_depth_info(image, depthmap, objects_data)
|
66 |
objs_pcd = utils.generate_obj_pcd(depthmap, objects_data)
|
67 |
plot_fig = display_pcd(objs_pcd)
|
68 |
+
|
69 |
return image_segmentation, depth_colormap, dist_image, plot_fig
|
70 |
+
|
71 |
+
except RuntimeError as e:
|
72 |
+
print(f"🚨 RuntimeError in process_image: {e}")
|
73 |
+
|
74 |
+
if "cuda" in str(e).lower():
|
75 |
+
print("⚠️ CUDA error detected. Switching to CPU mode.")
|
76 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
|
77 |
+
|
78 |
import traceback
|
79 |
print(traceback.format_exc())
|
80 |
raise
|
81 |
|
82 |
+
|
83 |
+
|
84 |
@safe_gpu_decorator
|
85 |
def test_process_img(image):
|
86 |
initialize_models()
|
|
|
125 |
@safe_gpu_decorator
|
126 |
def model_selector(model_type):
|
127 |
global img_seg, depth_estimator
|
128 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
129 |
+
|
130 |
+
model_dict = {
|
131 |
+
"Small - Better performance and less accuracy": ("midas_v21_small_256", "yolov8s-seg"),
|
132 |
+
"Medium - Balanced performance and accuracy": ("dpt_hybrid_384", "yolov8m-seg"),
|
133 |
+
"Large - Slow performance and high accuracy": ("dpt_large_384", "yolov8l-seg"),
|
134 |
+
}
|
135 |
+
|
136 |
+
midas_model, yolo_model = model_dict.get(model_type, ("midas_v21_small_256", "yolov8s-seg"))
|
137 |
+
|
138 |
+
print(f"🔹 Switching to models: YOLO={yolo_model}, MiDaS={midas_model} on {device}")
|
139 |
+
|
140 |
+
img_seg = ImageSegmenter(model_type=yolo_model, device=device)
|
141 |
+
depth_estimator = MonocularDepthEstimator(model_type=midas_model, device=device)
|
142 |
+
|
143 |
|
144 |
def cancel():
|
145 |
global CANCEL_PROCESSING
|
146 |
CANCEL_PROCESSING = True
|
147 |
|
148 |
if __name__ == "__main__":
|
149 |
+
# Ensure CUDA is properly initialized
|
150 |
try:
|
151 |
if torch.cuda.is_available():
|
152 |
+
print(f"✅ CUDA is available: {torch.cuda.get_device_name(0)}")
|
|
|
|
|
153 |
device = torch.device("cuda")
|
154 |
+
torch.cuda.empty_cache() # Clear GPU cache
|
155 |
else:
|
156 |
+
print("❌ No CUDA available. Falling back to CPU.")
|
157 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
|
158 |
device = torch.device("cpu")
|
159 |
except RuntimeError as e:
|
160 |
+
print(f"🚨 CUDA initialization failed: {e}. Switching to CPU mode.")
|
161 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
|
|
|
162 |
device = torch.device("cpu")
|
163 |
|
164 |
+
|
165 |
with gr.Blocks() as my_app:
|
166 |
# title
|
167 |
gr.Markdown("<h1><center>Simultaneous Segmentation and Depth Estimation</center></h1>")
|