|
import gradio as gr |
|
import os |
|
import torch |
|
from PIL import Image |
|
|
|
from model import ResNet101 |
|
from timeit import default_timer as timer |
|
from typing import Tuple, Dict |
|
|
|
|
|
class_names = ["normal", "pneumonia"] |
|
|
|
|
|
model = ResNet101() |
|
|
|
|
|
model.load_state_dict(torch.load(f="resnet101_pneumonia.pt", |
|
map_location=torch.device("cpu"))) |
|
model_transforms = model.transforms() |
|
|
|
|
|
def predict(img) -> Tuple[Dict, float]: |
|
""" |
|
Transforms and performs a prediction on img and returns prediction and time taken. |
|
:param img: PIL image |
|
:return: prediction and time taken |
|
""" |
|
|
|
start_time = timer() |
|
|
|
|
|
img = model_transforms(img.convert("RGB")).unsqueeze(0) |
|
|
|
|
|
model.eval() |
|
with torch.no_grad(): |
|
|
|
|
|
pred_probs = torch.sigmoid(model(img)) |
|
|
|
|
|
pred_labels_and_probs = {class_names[0]: round (1 - float(pred_probs[0])), 4), |
|
class_names[1]: round(float(pred_probs[0]), 4)} |
|
|
|
|
|
pred_time = round(timer() - start_time, 5) |
|
|
|
|
|
return pred_labels_and_probs, pred_time |
|
|
|
|
|
|
|
|
|
|
|
title = "PneumoniaDetector π" |
|
description = "A ResNet101 feature extractor computer vision model to detect pneumonia" |
|
article = "Please add a chest X-Ray image" |
|
|
|
|
|
example_list = [["examples/" + example] for example in os.listdir("examples")] |
|
|
|
|
|
demo = gr.Interface(fn=predict, |
|
inputs=gr.Image(type="pil"), |
|
outputs=[gr.Label(num_top_classes=1, label="Predictions"), |
|
gr.Number(label="Prediction time (s)")], |
|
examples=example_list, |
|
title=title, |
|
description=description, |
|
article=article) |
|
|
|
demo.launch(share=True, debug=True) |
|
|
|
|