Spaces:
Sleeping
Sleeping
Fix: Runtime error
Browse files- app.py +124 -113
- inference.py +61 -53
app.py
CHANGED
|
@@ -53,143 +53,154 @@ def inference_wrapper(image, alpha, top_k, target_layer):
|
|
| 53 |
"""
|
| 54 |
try:
|
| 55 |
if image is None:
|
| 56 |
-
return
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
except Exception as e:
|
| 69 |
print(f"Error in inference: {str(e)}")
|
| 70 |
-
return
|
| 71 |
|
| 72 |
|
| 73 |
def main():
|
| 74 |
"""
|
| 75 |
Main function for the application.
|
| 76 |
"""
|
| 77 |
-
global model, classes
|
| 78 |
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
with gr.Blocks() as demo:
|
| 86 |
-
gr.Markdown(
|
| 87 |
-
"""
|
| 88 |
-
# ImageNet-1K trained on ResNet50v2
|
| 89 |
-
"""
|
| 90 |
-
)
|
| 91 |
|
| 92 |
-
with gr.
|
| 93 |
gr.Markdown(
|
| 94 |
"""
|
| 95 |
-
|
| 96 |
"""
|
| 97 |
)
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
height=224,
|
| 105 |
-
width=224
|
| 106 |
)
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
|
|
|
|
|
|
| 111 |
height=224,
|
| 112 |
width=224
|
| 113 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
target_layer_slider = gr.Slider(
|
| 131 |
-
minimum=1,
|
| 132 |
-
maximum=6,
|
| 133 |
-
value=4,
|
| 134 |
-
step=1,
|
| 135 |
-
label="Target Layer Number"
|
| 136 |
)
|
| 137 |
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
|
| 155 |
-
#
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
["assets/examples/horse.jpg", 0.5, 3, 4],
|
| 166 |
-
["assets/examples/plane.jpg", 0.5, 3, 4],
|
| 167 |
-
["assets/examples/ship.png", 0.5, 3, 4]
|
| 168 |
-
],
|
| 169 |
-
inputs=[
|
| 170 |
-
img_input,
|
| 171 |
-
alpha_slider,
|
| 172 |
-
top_k_slider,
|
| 173 |
-
target_layer_slider
|
| 174 |
-
],
|
| 175 |
-
outputs=[
|
| 176 |
-
label_output,
|
| 177 |
-
gradcam_output
|
| 178 |
-
],
|
| 179 |
-
fn=inference_wrapper,
|
| 180 |
-
cache_examples=True,
|
| 181 |
-
label="Click on any example to run GradCAM"
|
| 182 |
)
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
server_port=7860,
|
| 188 |
-
share=False,
|
| 189 |
-
debug=True,
|
| 190 |
-
show_error=True,
|
| 191 |
-
max_threads=4
|
| 192 |
-
)
|
| 193 |
|
| 194 |
|
| 195 |
if __name__ == "__main__":
|
|
|
|
| 53 |
"""
|
| 54 |
try:
|
| 55 |
if image is None:
|
| 56 |
+
return {"error": "No image provided"}, None
|
| 57 |
|
| 58 |
+
results = inference(
|
| 59 |
+
image,
|
| 60 |
+
alpha,
|
| 61 |
+
top_k,
|
| 62 |
+
target_layer,
|
| 63 |
+
model=model,
|
| 64 |
+
classes=classes
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
if results is None:
|
| 68 |
+
return {"error": "Processing failed"}, None
|
| 69 |
+
|
| 70 |
+
return results
|
| 71 |
+
|
| 72 |
except Exception as e:
|
| 73 |
print(f"Error in inference: {str(e)}")
|
| 74 |
+
return {"error": str(e)}, None
|
| 75 |
|
| 76 |
|
| 77 |
def main():
|
| 78 |
"""
|
| 79 |
Main function for the application.
|
| 80 |
"""
|
| 81 |
+
global model, classes
|
| 82 |
|
| 83 |
+
try:
|
| 84 |
+
# Load the model at startup
|
| 85 |
+
model = load_model("resnet50_imagenet1k.pth")
|
| 86 |
+
|
| 87 |
+
# Load the classes at startup
|
| 88 |
+
classes = load_classes()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
+
with gr.Blocks() as demo:
|
| 91 |
gr.Markdown(
|
| 92 |
"""
|
| 93 |
+
# ImageNet-1K trained on ResNet50v2
|
| 94 |
"""
|
| 95 |
)
|
| 96 |
+
|
| 97 |
+
with gr.Tab("GradCam"):
|
| 98 |
+
gr.Markdown(
|
| 99 |
+
"""
|
| 100 |
+
Visualize Class Activations Maps generated by the model's layer for the predicted class.
|
| 101 |
+
"""
|
|
|
|
|
|
|
| 102 |
)
|
| 103 |
+
|
| 104 |
+
# Define inputs
|
| 105 |
+
with gr.Row():
|
| 106 |
+
img_input = gr.Image(
|
| 107 |
+
label="Input Image",
|
| 108 |
+
type="numpy",
|
| 109 |
height=224,
|
| 110 |
width=224
|
| 111 |
)
|
| 112 |
+
with gr.Column():
|
| 113 |
+
label_output = gr.Label(label="Predictions")
|
| 114 |
+
gradcam_output = gr.Image(
|
| 115 |
+
label="GradCAM Output",
|
| 116 |
+
height=224,
|
| 117 |
+
width=224
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
with gr.Row():
|
| 121 |
+
alpha_slider = gr.Slider(
|
| 122 |
+
minimum=0,
|
| 123 |
+
maximum=1,
|
| 124 |
+
value=0.5,
|
| 125 |
+
step=0.1,
|
| 126 |
+
label="Activation Map Transparency"
|
| 127 |
+
)
|
| 128 |
+
top_k_slider = gr.Slider(
|
| 129 |
+
minimum=1,
|
| 130 |
+
maximum=10,
|
| 131 |
+
value=3,
|
| 132 |
+
step=1,
|
| 133 |
+
label="Number of Top Predictions"
|
| 134 |
+
)
|
| 135 |
+
target_layer_slider = gr.Slider(
|
| 136 |
+
minimum=1,
|
| 137 |
+
maximum=6,
|
| 138 |
+
value=4,
|
| 139 |
+
step=1,
|
| 140 |
+
label="Target Layer Number"
|
| 141 |
+
)
|
| 142 |
|
| 143 |
+
gradcam_button = gr.Button("Generate GradCAM")
|
| 144 |
+
|
| 145 |
+
# Set up the click event
|
| 146 |
+
gradcam_button.click(
|
| 147 |
+
fn=inference_wrapper,
|
| 148 |
+
inputs=[
|
| 149 |
+
img_input,
|
| 150 |
+
alpha_slider,
|
| 151 |
+
top_k_slider,
|
| 152 |
+
target_layer_slider
|
| 153 |
+
],
|
| 154 |
+
outputs=[
|
| 155 |
+
label_output,
|
| 156 |
+
gradcam_output
|
| 157 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
)
|
| 159 |
|
| 160 |
+
# Example section
|
| 161 |
+
gr.Examples(
|
| 162 |
+
examples=[
|
| 163 |
+
["assets/examples/dog.jpg", 0.5, 3, 4],
|
| 164 |
+
["assets/examples/cat.jpg", 0.5, 3, 4],
|
| 165 |
+
["assets/examples/frog.jpg", 0.5, 3, 4],
|
| 166 |
+
["assets/examples/bird.jpg", 0.5, 3, 4],
|
| 167 |
+
["assets/examples/shark-plane.jpg", 0.5, 3, 4],
|
| 168 |
+
["assets/examples/car.jpg", 0.5, 3, 4],
|
| 169 |
+
["assets/examples/truck.jpg", 0.5, 3, 4],
|
| 170 |
+
["assets/examples/horse.jpg", 0.5, 3, 4],
|
| 171 |
+
["assets/examples/plane.jpg", 0.5, 3, 4],
|
| 172 |
+
["assets/examples/ship.png", 0.5, 3, 4]
|
| 173 |
+
],
|
| 174 |
+
inputs=[
|
| 175 |
+
img_input,
|
| 176 |
+
alpha_slider,
|
| 177 |
+
top_k_slider,
|
| 178 |
+
target_layer_slider
|
| 179 |
+
],
|
| 180 |
+
outputs=[
|
| 181 |
+
label_output,
|
| 182 |
+
gradcam_output
|
| 183 |
+
],
|
| 184 |
+
fn=inference_wrapper,
|
| 185 |
+
cache_examples=True,
|
| 186 |
+
label="Click on any example to run GradCAM"
|
| 187 |
+
)
|
| 188 |
|
| 189 |
+
# Launch the demo with reduced memory usage
|
| 190 |
+
demo.launch(
|
| 191 |
+
server_name="0.0.0.0",
|
| 192 |
+
server_port=7860,
|
| 193 |
+
share=False,
|
| 194 |
+
debug=True,
|
| 195 |
+
show_error=True,
|
| 196 |
+
max_threads=1, # Reduce concurrent processing
|
| 197 |
+
enable_queue=True, # Enable queuing to prevent memory issues
|
| 198 |
+
cache_examples=False # Disable example caching
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
)
|
| 200 |
+
except Exception as e:
|
| 201 |
+
print(f"Error during startup: {str(e)}")
|
| 202 |
+
if torch.cuda.is_available():
|
| 203 |
+
torch.cuda.empty_cache()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
|
| 205 |
|
| 206 |
if __name__ == "__main__":
|
inference.py
CHANGED
|
@@ -22,31 +22,30 @@ def inference(image, alpha, top_k, target_layer, model=None, classes=None):
|
|
| 22 |
"""
|
| 23 |
Run inference with GradCAM visualization
|
| 24 |
"""
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
# Preprocess the input image and move to device
|
| 45 |
-
input_tensor = _transform(image).to(device)
|
| 46 |
-
input_tensor = input_tensor.unsqueeze(0)
|
| 47 |
-
|
| 48 |
-
# For predictions, we don't need gradients
|
| 49 |
-
with torch.no_grad():
|
| 50 |
# Get Model Predictions
|
| 51 |
outputs = model(input_tensor)
|
| 52 |
probabilities = torch.softmax(outputs, dim=1)[0]
|
|
@@ -56,37 +55,46 @@ def inference(image, alpha, top_k, target_layer, model=None, classes=None):
|
|
| 56 |
sorted_confidences = sorted(confidences.items(), key=lambda val: val[1], reverse=True)
|
| 57 |
show_confidences = OrderedDict(sorted_confidences[:top_k])
|
| 58 |
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
# Ensure valid layer selection
|
| 70 |
-
target_layer = min(max(target_layer, 1), 6)
|
| 71 |
-
target_layers = [_layers[target_layer]]
|
| 72 |
|
| 73 |
-
|
| 74 |
-
|
|
|
|
| 75 |
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
class_idx = classes.index(top_class)
|
| 79 |
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
"""
|
| 23 |
Run inference with GradCAM visualization
|
| 24 |
"""
|
| 25 |
+
try:
|
| 26 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 27 |
+
|
| 28 |
+
# Ensure model is on correct device and in eval mode
|
| 29 |
+
model = model.to(device)
|
| 30 |
+
model.eval()
|
| 31 |
+
|
| 32 |
+
# Save a copy of input img
|
| 33 |
+
org_img = image.copy()
|
| 34 |
|
| 35 |
+
# Convert img to tensor and normalize it
|
| 36 |
+
_transform = transforms.Compose([
|
| 37 |
+
transforms.ToTensor(),
|
| 38 |
+
transforms.Normalize(
|
| 39 |
+
mean=[0.485, 0.456, 0.406],
|
| 40 |
+
std=[0.229, 0.224, 0.225]
|
| 41 |
+
)
|
| 42 |
+
])
|
| 43 |
|
| 44 |
+
# Preprocess the input image and move to device
|
| 45 |
+
input_tensor = _transform(image).to(device)
|
| 46 |
+
input_tensor = input_tensor.unsqueeze(0)
|
| 47 |
+
input_tensor.requires_grad = True
|
| 48 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
# Get Model Predictions
|
| 50 |
outputs = model(input_tensor)
|
| 51 |
probabilities = torch.softmax(outputs, dim=1)[0]
|
|
|
|
| 55 |
sorted_confidences = sorted(confidences.items(), key=lambda val: val[1], reverse=True)
|
| 56 |
show_confidences = OrderedDict(sorted_confidences[:top_k])
|
| 57 |
|
| 58 |
+
# Map layer numbers to meaningful parts of the ResNet architecture
|
| 59 |
+
_layers = {
|
| 60 |
+
1: model.conv1,
|
| 61 |
+
2: model.layer1[-1],
|
| 62 |
+
3: model.layer2[-1],
|
| 63 |
+
4: model.layer3[-1],
|
| 64 |
+
5: model.layer4[-1],
|
| 65 |
+
6: model.layer4[-1]
|
| 66 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
+
# Ensure valid layer selection
|
| 69 |
+
target_layer = min(max(target_layer, 1), 6)
|
| 70 |
+
target_layers = [_layers[target_layer]]
|
| 71 |
|
| 72 |
+
# Get the class activations from the selected layer
|
| 73 |
+
cam = GradCAM(model=model, target_layers=target_layers)
|
|
|
|
| 74 |
|
| 75 |
+
# Get the most probable class index
|
| 76 |
+
top_class = max(confidences.items(), key=lambda x: x[1])[0]
|
| 77 |
+
class_idx = classes.index(top_class)
|
| 78 |
+
|
| 79 |
+
# Generate GradCAM for the top predicted class
|
| 80 |
+
grayscale_cam = cam(
|
| 81 |
+
input_tensor=input_tensor,
|
| 82 |
+
targets=[ClassifierOutputTarget(class_idx)],
|
| 83 |
+
aug_smooth=False, # Disable augmentation for memory efficiency
|
| 84 |
+
eigen_smooth=False # Disable eigen smoothing for memory efficiency
|
| 85 |
+
)
|
| 86 |
+
grayscale_cam = grayscale_cam[0, :]
|
| 87 |
|
| 88 |
+
# Overlay input image with Class activations
|
| 89 |
+
visualization = show_cam_on_image(org_img/255., grayscale_cam, use_rgb=True, image_weight=alpha)
|
| 90 |
+
|
| 91 |
+
# Clear CUDA cache
|
| 92 |
+
if torch.cuda.is_available():
|
| 93 |
+
torch.cuda.empty_cache()
|
| 94 |
+
|
| 95 |
+
return show_confidences, visualization
|
| 96 |
+
|
| 97 |
+
except Exception as e:
|
| 98 |
+
if torch.cuda.is_available():
|
| 99 |
+
torch.cuda.empty_cache()
|
| 100 |
+
raise e
|