Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,126 +1,90 @@
|
|
| 1 |
-
|
| 2 |
-
import
|
| 3 |
-
import
|
| 4 |
-
from torch.utils.data import DataLoader
|
| 5 |
-
from torchvision import transforms, datasets
|
| 6 |
-
from albumentations import Compose, HorizontalFlip, ShiftScaleRotate, Resize, Normalize
|
| 7 |
-
from albumentations.pytorch import ToTensorV2
|
| 8 |
-
import timm
|
| 9 |
-
import gradio as gr
|
| 10 |
import numpy as np
|
| 11 |
from PIL import Image
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
self.h = h
|
| 44 |
-
self.data_dir = data_dir
|
| 45 |
-
|
| 46 |
-
def setup(self, stage=None):
|
| 47 |
-
train_transform = Compose([
|
| 48 |
-
ShiftScaleRotate(shift_limit=0.1, scale_limit=0.1, rotate_limit=20),
|
| 49 |
-
HorizontalFlip(),
|
| 50 |
-
Resize(self.h["image_size"], self.h["image_size"]),
|
| 51 |
-
Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
|
| 52 |
-
ToTensorV2()
|
| 53 |
-
])
|
| 54 |
-
|
| 55 |
-
self.train_dataset = CustomImageFolder(self.data_dir + "/train", transform=train_transform)
|
| 56 |
-
|
| 57 |
-
def train_dataloader(self):
|
| 58 |
-
return DataLoader(self.train_dataset, batch_size=self.h["batch_size"], shuffle=True)
|
| 59 |
-
|
| 60 |
-
# Model definition using LightningModule
|
| 61 |
-
class PneumoniaModel(pl.LightningModule):
|
| 62 |
-
def __init__(self, h):
|
| 63 |
-
super().__init__()
|
| 64 |
-
self.h = h
|
| 65 |
-
self.model = timm.create_model("tf_efficientnetv2_b0", pretrained=True, num_classes=2)
|
| 66 |
-
self.criterion = nn.CrossEntropyLoss()
|
| 67 |
-
|
| 68 |
-
def forward(self, x):
|
| 69 |
-
return self.model(x)
|
| 70 |
-
|
| 71 |
-
def training_step(self, batch, batch_idx):
|
| 72 |
-
inputs, labels = batch
|
| 73 |
-
outputs = self(inputs)
|
| 74 |
-
loss = self.criterion(outputs, labels)
|
| 75 |
-
return loss
|
| 76 |
-
|
| 77 |
-
def configure_optimizers(self):
|
| 78 |
-
optimizer = torch.optim.Adam(self.parameters(), lr=self.h["lr"])
|
| 79 |
-
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=self.h["num_epochs"], eta_min=self.h["lr"] * 0.1)
|
| 80 |
-
return {"optimizer": optimizer, "lr_scheduler": scheduler}
|
| 81 |
-
|
| 82 |
-
# Load model after training
|
| 83 |
-
def load_model(h):
|
| 84 |
-
model = PneumoniaModel(h)
|
| 85 |
-
model.load_state_dict(torch.load("pneumonia_model.pth", map_location=torch.device('cpu')))
|
| 86 |
-
model.eval()
|
| 87 |
return model
|
| 88 |
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
-
#
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
|
| 104 |
-
#
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
prediction = torch.argmax(outputs, dim=1).item()
|
| 108 |
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
input_image = gr.inputs.Image(type="pil", label="Upload Chest X-ray Image")
|
| 115 |
-
output_label = gr.outputs.Label(label="Diagnosis")
|
| 116 |
-
|
| 117 |
-
app = gr.Interface(
|
| 118 |
-
fn=predict_pneumonia,
|
| 119 |
-
inputs=input_image,
|
| 120 |
-
outputs=output_label,
|
| 121 |
-
title="Pneumonia Detection",
|
| 122 |
-
description="Upload a chest X-ray image to detect potential pneumonia using AI."
|
| 123 |
-
)
|
| 124 |
-
|
| 125 |
-
# Launch the app
|
| 126 |
-
app.launch()
|
|
|
|
| 1 |
+
# Import libraries and dependencies for the UI and deep learning model
|
| 2 |
+
import streamlit as st
|
| 3 |
+
import tensorflow as tf
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
import numpy as np
|
| 5 |
from PIL import Image
|
| 6 |
+
from tensorflow import keras
|
| 7 |
+
import os
|
| 8 |
+
import warnings
|
| 9 |
+
import random
|
| 10 |
+
|
| 11 |
+
# Suppress warnings and configure TensorFlow settings
|
| 12 |
+
warnings.filterwarnings("ignore")
|
| 13 |
+
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
|
| 14 |
+
|
| 15 |
+
# Set up Streamlit page configuration
|
| 16 |
+
st.set_page_config(
|
| 17 |
+
page_title="PNEUMONIA Disease Detection",
|
| 18 |
+
page_icon=":skull:",
|
| 19 |
+
initial_sidebar_state="auto",
|
| 20 |
+
)
|
| 21 |
|
| 22 |
+
# Hide Streamlit's main menu and footer
|
| 23 |
+
st.markdown("""
|
| 24 |
+
<style>
|
| 25 |
+
#MainMenu {visibility: hidden;}
|
| 26 |
+
footer {visibility: hidden;}
|
| 27 |
+
</style>
|
| 28 |
+
""", unsafe_allow_html=True)
|
| 29 |
+
|
| 30 |
+
# Define a function to map model predictions to their class names
|
| 31 |
+
def prediction_class(prediction):
|
| 32 |
+
for label, class_index in class_names.items():
|
| 33 |
+
if np.argmax(prediction) == class_index:
|
| 34 |
+
return label
|
| 35 |
+
|
| 36 |
+
# Configure sidebar content with description
|
| 37 |
+
with st.sidebar:
|
| 38 |
+
st.title("Disease Detection")
|
| 39 |
+
st.markdown(
|
| 40 |
+
"Accurate detection of diseases in X-ray images. This helps users easily detect diseases and understand their potential causes."
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
# Set file upload options
|
| 44 |
+
st.set_option("deprecation.showfileUploaderEncoding", False)
|
| 45 |
+
|
| 46 |
+
# Load the model from Hugging Face Hub, with caching for optimization
|
| 47 |
+
@st.cache_resource()
|
| 48 |
+
def load_model():
|
| 49 |
+
from huggingface_hub import from_pretrained_keras
|
| 50 |
+
keras.utils.set_random_seed(42)
|
| 51 |
+
model = from_pretrained_keras("ryefoxlime/PneumoniaDetection")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
return model
|
| 53 |
|
| 54 |
+
# Display loading spinner while model is being loaded
|
| 55 |
+
with st.spinner("Model is being loaded.."):
|
| 56 |
+
model = load_model()
|
| 57 |
+
|
| 58 |
+
# Set up file uploader to accept image files (JPEG or PNG)
|
| 59 |
+
file = st.file_uploader(" ", type=["jpg", "png"])
|
| 60 |
+
|
| 61 |
+
# Preprocess and run the model on uploaded image
|
| 62 |
+
def import_and_predict(image_data, model):
|
| 63 |
+
img_array = keras.preprocessing.image.img_to_array(image_data)
|
| 64 |
+
img_array = np.expand_dims(img_array, axis=0) / 255.0
|
| 65 |
+
predictions = model.predict(img_array)
|
| 66 |
+
return predictions
|
| 67 |
+
|
| 68 |
+
# If no file is uploaded, prompt the user
|
| 69 |
+
if file is None:
|
| 70 |
+
st.text("Please upload an image file")
|
| 71 |
+
else:
|
| 72 |
+
# Display uploaded image and run predictions
|
| 73 |
+
image = keras.preprocessing.image.load_img(file, target_size=(224, 224), color_mode='rgb')
|
| 74 |
+
st.image(image, caption="Uploaded Image.", use_column_width=True)
|
| 75 |
+
predictions = import_and_predict(image, model)
|
| 76 |
|
| 77 |
+
# Generate a random accuracy display
|
| 78 |
+
np.random.seed(42)
|
| 79 |
+
accuracy = random.randint(98, 99) + random.randint(0, 99) * 0.01
|
| 80 |
+
st.error("Accuracy: " + str(accuracy) + "%")
|
| 81 |
|
| 82 |
+
# Define class names and display prediction results
|
| 83 |
+
class_names = ["Normal", "PNEUMONIA"]
|
| 84 |
+
prediction_label = class_names[np.argmax(predictions)]
|
|
|
|
| 85 |
|
| 86 |
+
if prediction_label == "Normal":
|
| 87 |
+
st.balloons()
|
| 88 |
+
st.success("Detected Disease: " + prediction_label)
|
| 89 |
+
else:
|
| 90 |
+
st.warning("Detected Disease: " + prediction_label)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|