Spaces:
Runtime error
Runtime error
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118import streamlit as stimport torchimport torch.nn as nnimport torchvision.transforms as transformsfrom efficientnet_pytorch import EfficientNetfrom PIL import Imagefrom datetime import datetime
# Define HardSwish activationclass HardSwish(nn.Module): def __init__(self): super(HardSwish, self).__init__()
def forward(self, x): return x * (torch.clamp(x + 3, 0, 6) / 6)
# Define custom EfficientNet modelclass CustomEfficientNet(nn.Module): def __init__(self, num_classes): super(CustomEfficientNet, self).__init__() self.model = EfficientNet.from_name('efficientnet-b3') num_ftrs = self.model._fc.in_features self.model._fc = nn.Sequential( nn.Linear(num_ftrs, 512), HardSwish(), nn.Dropout(p=0.4), nn.Linear(512, num_classes) )
def forward(self, x): return self.model(x)
# Class namesclass_names = [ 'No Finding', 'Enlarged Cardiomediastinum', 'Cardiomegaly', 'Lung Opacity', 'Lung Lesion', 'Edema', 'Consolidation', 'Pneumonia', 'Atelectasis', 'Pneumothorax', 'Pleural Effusion', 'Pleural Other', 'Fracture', 'Support Devices']
# Device configurationdevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Load model@st.cache_resourcedef load_model(): model = CustomEfficientNet(num_classes=14) checkpoint = torch.load('Final_global_model.pth.tar', map_location=device) if 'state_dict' in checkpoint: model.load_state_dict(checkpoint['state_dict']) else: model.load_state_dict(checkpoint) model = model.to(device) model.eval() return model
model = load_model()
# Transformationstransform = transforms.Compose([ transforms.Resize((300, 300)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
# Prediction functiondef predict(image): if image.mode != 'RGB': image = image.convert('RGB') img = transform(image).unsqueeze(0).to(device)
with torch.no_grad(): outputs = model(img) probs = torch.sigmoid(outputs).cpu().numpy()[0]
results = {class_names[i]: float(probs[i]) for i in range(len(class_names))} sorted_results = dict(sorted(results.items(), key=lambda item: item[1], reverse=True)) top5 = {k: f"{v*100:.2f}%" for k, v in list(sorted_results.items())[:5]}
return top5
# ---------------- Streamlit App -----------------
st.set_page_config(page_title="Chest X-ray Disease Classifier", page_icon="๐ฉบ", layout="centered")
st.markdown( """ <h1 style="text-align:center;">๐ฉบ Chest X-ray Disease Classifier</h1> <p style="text-align:center;">Upload a chest X-ray image to get disease predictions.</p> """, unsafe_allow_html=True)
# Input formwith st.form("input_form"): patient_name = st.text_input("Patient Name", placeholder="Enter full name...") scan_date = st.date_input("Scan Date", value=datetime.today()) uploaded_file = st.file_uploader("Upload Chest X-ray Image", type=["png", "jpg", "jpeg", "bmp", "tiff"]) submitted = st.form_submit_button("๐ Predict")
if submitted: if uploaded_file is not None and patient_name: image = Image.open(uploaded_file)
with st.spinner('Analyzing the X-ray...'): top5_predictions = predict(image)
st.success('โ
Prediction completed!')
st.markdown("---") st.markdown(f"**๐ Patient Name:** {patient_name}") st.markdown(f"**๐
Scan Date:** {scan_date.strftime('%Y-%m-%d')}") st.markdown("### ๐งช Top 5 Predictions:") for disease, probability in top5_predictions.items(): st.write(f"๐น **{disease}**: {probability}")
st.image(image, caption="Uploaded Chest X-ray", use_column_width=True) else: st.error("โ ๏ธ Please fill all fields and upload an image.")app.pyAdded+118