Spaces:
Sleeping
Sleeping
File size: 6,907 Bytes
d0ef04f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 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 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 |
import gradio as gr
import numpy as np
from PIL import Image
import torch
import os
import shutil
import config
from models.yolo import YOLOv3
from utils.data import PascalDataModule
from utils.loss import YoloLoss
from utils.gradcam import generate_gradcam
from utils.utils import generate_result
from markdown import model_stats, data_stats
datamodule = PascalDataModule(
train_csv_path=f"{config.DATASET}/train.csv",
test_csv_path=f"{config.DATASET}/test.csv",
batch_size=config.BATCH_SIZE,
shuffle=config.SHUFFLE,
num_workers=os.cpu_count() - 1,
)
datamodule.setup()
class FilterModel(torch.nn.Module):
def __init__(self):
super().__init__()
self.yolo = YOLOv3.load_from_checkpoint(
"model.ckpt",
in_channels=3,
num_classes=config.NUM_CLASSES,
epochs=config.NUM_EPOCHS,
loss_fn=YoloLoss,
datamodule=datamodule,
learning_rate=config.LEARNING_RATE,
maxlr=config.LEARNING_RATE,
scheduler_steps=len(datamodule.train_dataloader()),
device_count=config.NUM_WORKERS,
)
self.yolo = self.yolo.to("cpu")
def forward(self, x):
x = self.yolo(x)
return x[-1]
model = FilterModel()
prediction_image = None
def upload_file(files):
file_paths = [file.name for file in files]
return file_paths
def read_image(path):
img = Image.open(path)
img.load()
data = np.asarray(img, dtype="uint8")
return data
def sample_images():
all_imgs = os.listdir(config.IMG_DIR)
rand_inds = np.random.random_integers(0, len(all_imgs), 10).tolist()
images = [f"{config.IMG_DIR}/{all_imgs[ind]}" for ind in rand_inds]
return images
def get_gradcam_images(gradcam_layer, images, gradcam_opacity):
gradcam_images = []
target_layers = [model.yolo.layers[int(gradcam_layer)]]
gradcam_images = generate_gradcam(
model=model,
target_layers=target_layers,
images=images,
use_cuda=False,
transparency=gradcam_opacity,
)
return gradcam_images
def show_hide_gradcam(status):
if not status:
return [gr.update(visible=False) for i in range(3)]
return [gr.update(visible=True) for i in range(3)]
def set_prediction_image(evt: gr.SelectData, gallery):
global prediction_image
if isinstance(gallery[evt.index], dict):
prediction_image = gallery[evt.index]["name"]
else:
prediction_image = gallery[evt.index][0]["name"]
def predict(is_gradcam, gradcam_layer, gradcam_opacity):
gradcam_images = None
img = read_image(prediction_image)
image_transformed = config.test_transforms(image=img, bboxes=[])["image"]
if is_gradcam:
images = [image_transformed]
gradcam_images = get_gradcam_images(gradcam_layer, images, gradcam_opacity)
data = image_transformed.unsqueeze(0)
if not os.path.exists("output"):
os.mkdir("output")
else:
shutil.rmtree("output")
os.mkdir("output")
generate_result(
model=model.yolo,
data=data,
thresh=0.6,
iou_thresh=0.5,
anchors=model.yolo.scaled_anchors,
)
result_images = os.listdir("output")
result_images = [
f"output/{file}" for file in result_images if file.endswith(".png")
]
return {
output: gr.update(value=result_images[0]),
gradcam_output: gr.update(value=gradcam_images[0]),
}
with gr.Blocks() as app:
gr.Markdown("## ERA Session13 - PASCAL-VOC Object Detection with YoloV3")
with gr.Row():
with gr.Column():
with gr.Box():
is_gradcam = gr.Checkbox(
label="GradCAM Images",
info="Display GradCAM images?",
)
gradcam_layer = gr.Dropdown(
choices=list(range(len(model.yolo.layers))),
label="Select the layer",
info="Please select the layer for which the GradCAM is required",
interactive=True,
visible=False,
)
gradcam_opacity = gr.Slider(
minimum=0,
maximum=1,
value=0.6,
label="Opacity",
info="Opacity of GradCAM output",
interactive=True,
visible=False,
)
is_gradcam.input(
show_hide_gradcam,
inputs=[is_gradcam],
outputs=[gradcam_layer, gradcam_opacity],
)
with gr.Box():
# file_output = gr.File(file_types=["image"])
with gr.Group():
upload_gallery = gr.Gallery(
value=None,
label="Uploaded images",
show_label=False,
elem_id="gallery_upload",
columns=5,
rows=2,
height="auto",
object_fit="contain",
)
upload_button = gr.UploadButton(
"Click to Upload images",
file_types=["image"],
file_count="multiple",
)
upload_button.upload(upload_file, upload_button, upload_gallery)
with gr.Group():
sample_gallery = gr.Gallery(
value=sample_images,
label="Sample images",
show_label=True,
elem_id="gallery_sample",
columns=5,
rows=2,
height="auto",
object_fit="contain",
)
upload_gallery.select(set_prediction_image, inputs=[upload_gallery])
sample_gallery.select(set_prediction_image, inputs=[sample_gallery])
run_btn = gr.Button()
with gr.Column():
with gr.Box():
output = gr.Image(value=None, label="Model Result")
with gr.Box():
gradcam_output = gr.Image(value=None, label="GradCAM Image")
run_btn.click(
predict,
inputs=[
is_gradcam,
gradcam_layer,
gradcam_opacity,
],
outputs=[output, gradcam_output],
)
with gr.Row():
with gr.Box():
with gr.Row():
with gr.Column():
with gr.Box():
gr.Markdown(model_stats)
with gr.Column():
with gr.Box():
gr.Markdown(data_stats)
app.launch()
|