Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,103 +1,141 @@
|
|
| 1 |
-
from fastapi import FastAPI, Request
|
| 2 |
import torch
|
| 3 |
import torch.nn as nn
|
| 4 |
import torch.optim as optim
|
| 5 |
from torchvision import transforms
|
| 6 |
from torch.utils.data import Dataset, DataLoader
|
| 7 |
from PIL import Image
|
|
|
|
|
|
|
|
|
|
| 8 |
from sklearn.model_selection import train_test_split
|
| 9 |
from sklearn.metrics import accuracy_score, f1_score
|
| 10 |
import segmentation_models_pytorch as smp
|
| 11 |
-
from torchvision.models import densenet121
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
app = FastAPI()
|
| 15 |
|
| 16 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
).
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
self.
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
mask = (mask > 0.5).float()
|
| 46 |
-
masked = image_tensor * mask
|
| 47 |
|
| 48 |
-
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
|
|
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
|
|
|
| 55 |
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
|
|
|
| 60 |
|
| 61 |
-
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
-
|
| 65 |
-
def load_model():
|
| 66 |
-
model = densenet121(weights=DenseNet121_Weights.IMAGENET1K_V1)
|
| 67 |
-
model.classifier = nn.Linear(1024, 4)
|
| 68 |
-
model.load_state_dict(torch.load("Classification_Model.pth", map_location=device))
|
| 69 |
-
return model.to(device)
|
| 70 |
|
| 71 |
-
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
transform = transforms.Compose([
|
| 75 |
transforms.Resize((224, 224)),
|
| 76 |
-
transforms.
|
| 77 |
-
transforms.Normalize(mean=[0.41]*3, std=[0.16]*3)
|
| 78 |
])
|
| 79 |
|
| 80 |
train_entries, val_entries = train_test_split(
|
| 81 |
samples, test_size=0.2, stratify=[s["true_label"] for s in samples], random_state=42
|
| 82 |
)
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
| 86 |
|
| 87 |
criterion = nn.CrossEntropyLoss()
|
| 88 |
-
optimizer = optim.Adam(
|
| 89 |
|
| 90 |
for epoch in range(5):
|
| 91 |
-
|
|
|
|
| 92 |
for imgs, labels in train_loader:
|
| 93 |
imgs, labels = imgs.to(device), labels.to(device)
|
| 94 |
-
out =
|
| 95 |
loss = criterion(out, labels)
|
| 96 |
optimizer.zero_grad()
|
| 97 |
loss.backward()
|
| 98 |
optimizer.step()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
-
def evaluate(model, loader):
|
| 101 |
model.eval()
|
| 102 |
y_true, y_pred = [], []
|
| 103 |
with torch.no_grad():
|
|
@@ -107,20 +145,26 @@ async def trigger_train(request: Request):
|
|
| 107 |
y_pred.extend(outputs.argmax(1).cpu().numpy())
|
| 108 |
y_true.extend(labels.numpy())
|
| 109 |
return {
|
|
|
|
| 110 |
"accuracy": round(accuracy_score(y_true, y_pred), 4),
|
| 111 |
"f1_macro": round(f1_score(y_true, y_pred, average="macro"), 4),
|
| 112 |
}
|
| 113 |
|
| 114 |
-
eval_old = evaluate(m2_old, val_loader)
|
| 115 |
-
eval_new = evaluate(
|
| 116 |
|
| 117 |
-
|
| 118 |
-
if model_used == "new":
|
| 119 |
-
torch.save(m2_new.state_dict(), "Classification_Model.pth")
|
| 120 |
|
| 121 |
return {
|
| 122 |
"old_model": eval_old,
|
| 123 |
-
"new_model": eval_new
|
| 124 |
-
"model_used": model_used,
|
| 125 |
-
"updated_model_path": "Classification_Model.pth" if model_used == "new" else "unchanged"
|
| 126 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import torch
|
| 2 |
import torch.nn as nn
|
| 3 |
import torch.optim as optim
|
| 4 |
from torchvision import transforms
|
| 5 |
from torch.utils.data import Dataset, DataLoader
|
| 6 |
from PIL import Image
|
| 7 |
+
import requests
|
| 8 |
+
from io import BytesIO
|
| 9 |
+
from pymongo import MongoClient
|
| 10 |
from sklearn.model_selection import train_test_split
|
| 11 |
from sklearn.metrics import accuracy_score, f1_score
|
| 12 |
import segmentation_models_pytorch as smp
|
| 13 |
+
from torchvision.models import densenet121
|
| 14 |
+
import gradio as gr
|
| 15 |
+
import json
|
|
|
|
| 16 |
|
| 17 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 18 |
|
| 19 |
+
client = MongoClient("mongodb+srv://xcovidinsight:FYP25S108@cluster0.vqesy.mongodb.net/")
|
| 20 |
+
db = client["covid_system"]
|
| 21 |
+
collection = db["validated_xrays"]
|
| 22 |
+
|
| 23 |
+
class UNet(nn.Module):
|
| 24 |
+
def __init__(self):
|
| 25 |
+
super().__init__()
|
| 26 |
+
self.model = smp.Unet(
|
| 27 |
+
encoder_name="resnet34",
|
| 28 |
+
encoder_weights="imagenet",
|
| 29 |
+
in_channels=1,
|
| 30 |
+
classes=1
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
def forward(self, x):
|
| 34 |
+
return self.model(x)
|
| 35 |
+
|
| 36 |
+
class MyClassifier(nn.Module):
|
| 37 |
+
def __init__(self, num_classes=4):
|
| 38 |
+
super().__init__()
|
| 39 |
+
from torchvision.models import DenseNet121_Weights
|
| 40 |
+
base_model = densenet121(weights=DenseNet121_Weights.IMAGENET1K_V1)
|
| 41 |
+
in_features = base_model.classifier.in_features
|
| 42 |
+
base_model.classifier = nn.Linear(in_features, num_classes)
|
| 43 |
+
self.model = base_model
|
| 44 |
+
|
| 45 |
+
def forward(self, x):
|
| 46 |
+
return self.model(x)
|
| 47 |
+
|
| 48 |
+
def fetch_image(url):
|
| 49 |
+
try:
|
| 50 |
+
response = requests.get(url)
|
| 51 |
+
image = Image.open(BytesIO(response.content)).convert("L").resize((256, 256))
|
| 52 |
+
return image
|
| 53 |
+
except Exception as e:
|
| 54 |
+
print(f"Failed to fetch image from {url}: {e}")
|
| 55 |
+
return None
|
| 56 |
+
|
| 57 |
+
def trigger_incremental_train():
|
| 58 |
+
samples = list(collection.find())
|
| 59 |
+
samples = [s for s in samples if "image_path" in s and "true_label" in s]
|
| 60 |
|
| 61 |
+
if not samples or len(samples) < 100:
|
| 62 |
+
return {"error": "Not enough validated samples (minimum 100 required)."}
|
|
|
|
|
|
|
| 63 |
|
| 64 |
+
m1 = UNet()
|
| 65 |
+
m1.model.load_state_dict(torch.load("Segmentation Model.pth"))
|
| 66 |
+
m1.to(device).eval()
|
| 67 |
|
| 68 |
+
m2_old = MyClassifier()
|
| 69 |
+
m2_old.load_state_dict(torch.load("Classification Model.pth", map_location=device))
|
| 70 |
+
m2_old.to(device).eval()
|
| 71 |
|
| 72 |
+
m2 = MyClassifier()
|
| 73 |
+
m2.load_state_dict(torch.load("Classification Model.pth", map_location=device))
|
| 74 |
+
m2.to(device)
|
| 75 |
|
| 76 |
+
class LungXrayDataset(Dataset):
|
| 77 |
+
def __init__(self, entries, transform):
|
| 78 |
+
self.entries = entries
|
| 79 |
+
self.transform = transform
|
| 80 |
+
self.label_map = {label: i for i, label in enumerate(sorted(set(s["true_label"] for s in entries)))}
|
| 81 |
|
| 82 |
+
def __len__(self):
|
| 83 |
+
return len(self.entries)
|
| 84 |
+
|
| 85 |
+
def __getitem__(self, idx):
|
| 86 |
+
entry = self.entries[idx]
|
| 87 |
+
image = fetch_image(entry["image_path"])
|
| 88 |
+
if image is None:
|
| 89 |
+
raise RuntimeError(f"Image at {entry['image_path']} could not be loaded.")
|
| 90 |
|
| 91 |
+
image_tensor = transforms.ToTensor()(image).unsqueeze(0).to(device)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
+
with torch.no_grad():
|
| 94 |
+
mask = m1(image_tensor).sigmoid()
|
| 95 |
+
mask = (mask > 0.5).float()
|
| 96 |
+
masked = image_tensor * mask
|
| 97 |
+
|
| 98 |
+
masked_rgb = masked.squeeze(0).repeat(3, 1, 1).cpu()
|
| 99 |
+
|
| 100 |
+
if self.transform:
|
| 101 |
+
masked_rgb = self.transform(masked_rgb)
|
| 102 |
+
|
| 103 |
+
label = self.label_map[entry["true_label"]]
|
| 104 |
+
return masked_rgb, label
|
| 105 |
|
| 106 |
transform = transforms.Compose([
|
| 107 |
transforms.Resize((224, 224)),
|
| 108 |
+
transforms.Normalize(mean=[0.5]*3, std=[0.5]*3)
|
|
|
|
| 109 |
])
|
| 110 |
|
| 111 |
train_entries, val_entries = train_test_split(
|
| 112 |
samples, test_size=0.2, stratify=[s["true_label"] for s in samples], random_state=42
|
| 113 |
)
|
| 114 |
|
| 115 |
+
train_ds = LungXrayDataset(train_entries, transform)
|
| 116 |
+
val_ds = LungXrayDataset(val_entries, transform)
|
| 117 |
+
train_loader = DataLoader(train_ds, batch_size=16, shuffle=True)
|
| 118 |
+
val_loader = DataLoader(val_ds, batch_size=16)
|
| 119 |
|
| 120 |
criterion = nn.CrossEntropyLoss()
|
| 121 |
+
optimizer = optim.Adam(m2.parameters(), lr=1e-4)
|
| 122 |
|
| 123 |
for epoch in range(5):
|
| 124 |
+
m2.train()
|
| 125 |
+
total_loss, correct = 0, 0
|
| 126 |
for imgs, labels in train_loader:
|
| 127 |
imgs, labels = imgs.to(device), labels.to(device)
|
| 128 |
+
out = m2(imgs)
|
| 129 |
loss = criterion(out, labels)
|
| 130 |
optimizer.zero_grad()
|
| 131 |
loss.backward()
|
| 132 |
optimizer.step()
|
| 133 |
+
total_loss += loss.item()
|
| 134 |
+
correct += (out.argmax(1) == labels).sum().item()
|
| 135 |
+
acc = correct / len(train_ds)
|
| 136 |
+
print(f"Epoch {epoch+1} ➤ Loss: {total_loss:.4f} | Accuracy: {acc:.4f}")
|
| 137 |
|
| 138 |
+
def evaluate(model, loader, version):
|
| 139 |
model.eval()
|
| 140 |
y_true, y_pred = [], []
|
| 141 |
with torch.no_grad():
|
|
|
|
| 145 |
y_pred.extend(outputs.argmax(1).cpu().numpy())
|
| 146 |
y_true.extend(labels.numpy())
|
| 147 |
return {
|
| 148 |
+
"version": version,
|
| 149 |
"accuracy": round(accuracy_score(y_true, y_pred), 4),
|
| 150 |
"f1_macro": round(f1_score(y_true, y_pred, average="macro"), 4),
|
| 151 |
}
|
| 152 |
|
| 153 |
+
eval_old = evaluate(m2_old, val_loader, "Old")
|
| 154 |
+
eval_new = evaluate(m2, val_loader, "New")
|
| 155 |
|
| 156 |
+
torch.save(m2.state_dict(), "New Classification Model.pth")
|
|
|
|
|
|
|
| 157 |
|
| 158 |
return {
|
| 159 |
"old_model": eval_old,
|
| 160 |
+
"new_model": eval_new
|
|
|
|
|
|
|
| 161 |
}
|
| 162 |
+
|
| 163 |
+
with gr.Blocks() as demo:
|
| 164 |
+
with gr.Row():
|
| 165 |
+
train_button = gr.Button("Start Incremental Training")
|
| 166 |
+
output_json = gr.JSON(label="Training Result")
|
| 167 |
+
|
| 168 |
+
train_button.click(fn=trigger_incremental_train, inputs=[], outputs=output_json)
|
| 169 |
+
|
| 170 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|