import gradio as gr from fastai.vision.all import * from efficientnet_pytorch import EfficientNet import torch, torchvision from torchvision import transforms from pytorch_grad_cam import GradCAM from pytorch_grad_cam.utils.image import show_cam_on_image from PIL import Image title = "COVID_19 Infection Detectation App!" head = ( "
" "" """The model is trained using COVID-QU-Ex dataset""" " that the researchers from Qatar University compiled,that consists of 33,920 chest X-ray (CXR) images including:" "
" "" "Thanks to Kaggle & KaggleX, this is the largest ever created lung mask dataset, that I am aware of publicly available as of October 2023." "
" "" ) description = head examples = [ ['covid/covid_1038.png'], ['covid/covid_1034.png'], ['covid/cd.png'], ['covid/covid_1021.png'], ['covid/covid_1027.png'], ['covid/covid_1042.png'], ['covid/covid_1031.png'] ] #learn = load_learner('model/predictcovidfastaifinal18102023.pkl') learn = load_learner('model/final_20102023_eb7_model.pkl') categories = learn.dls.vocab def predict_image(get_image): pred, idx, probs = learn.predict(get_image) return dict(zip(categories, map(float, probs))) def interpretation_function(image_path, model, target_layer, target_category=None): # Load and preprocess the image image = Image.open(image_path) preprocess = transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor(), ]) input_image = preprocess(image).unsqueeze(0) # Add a batch dimension input_image = input_image.to('cuda' if torch.cuda.is_available() else 'cpu') # Create an instance of GradCAM cam = GradCAM(model=model, target_layer=target_layer) # Compute the CAM cam_image = cam(input_tensor=input_image, target_category=target_category) # Show the CAM on the original image visualization = show_cam_on_image(input_image, cam_image) #visualization.show() with gr.Blocks() as demo: with gr.Row(): with gr.Column(): input_img = gr.Image(label="Input Image", shape=(224, 224)) with gr.Row(): interpret = gr.Button("Interpret") with gr.Column(): label = gr.Label(label="Predicted Class") with gr.Column(): interpretation = gr.components.Interpretation(input_img) interpret.click(interpretation_function(input_img,learn, learn.model[0][-1],target_category=None), input_img, interpretation) #interpretation="default" enable_queue=True gr.Interface(fn=predict_image, inputs=gr.Image(shape=(224,224)), outputs = gr.Label(num_top_classes=3),title=title,description=description,examples=examples, interpretation=interpretation,enable_queue=enable_queue).launch(share=False)