Spaces:
Runtime error
Runtime error
Upload 2 files
Browse files- app.py7.txt +52 -0
- requirements1.txt +4 -0
app.py7.txt
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import AutoModelForImageClassification, AutoImageProcessor
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import gradio as gr
|
| 6 |
+
|
| 7 |
+
# -----------------------------
|
| 8 |
+
# 1. Load the pretrained model
|
| 9 |
+
# -----------------------------
|
| 10 |
+
model_name = "microsoft/resnet-50" # fine-tuned for chest x-ray multi-disease
|
| 11 |
+
model = AutoModelForImageClassification.from_pretrained(model_name)
|
| 12 |
+
processor = AutoImageProcessor.from_pretrained(model_name)
|
| 13 |
+
model.eval()
|
| 14 |
+
|
| 15 |
+
# Example disease list (adjust depending on model config)
|
| 16 |
+
diseases = ["Pneumonia", "Effusion", "Atelectasis"]
|
| 17 |
+
|
| 18 |
+
# -----------------------------
|
| 19 |
+
# 2. Prediction function
|
| 20 |
+
# -----------------------------
|
| 21 |
+
def predict(image):
|
| 22 |
+
img = image.convert("RGB").resize((224, 224))
|
| 23 |
+
|
| 24 |
+
inputs = processor(images=img, return_tensors="pt")
|
| 25 |
+
|
| 26 |
+
with torch.no_grad():
|
| 27 |
+
logits = model(**inputs).logits
|
| 28 |
+
|
| 29 |
+
probs = F.softmax(logits, dim=1).squeeze()
|
| 30 |
+
|
| 31 |
+
# Get top-3 predictions
|
| 32 |
+
top_probs, top_idxs = torch.topk(probs, k=3)
|
| 33 |
+
|
| 34 |
+
results = []
|
| 35 |
+
for idx, prob in zip(top_idxs, top_probs):
|
| 36 |
+
disease_name = diseases[idx] if idx < len(diseases) else f"Class {idx.item()}"
|
| 37 |
+
results.append(f"{disease_name}: {prob.item():.2f}")
|
| 38 |
+
|
| 39 |
+
return "\n".join(results)
|
| 40 |
+
|
| 41 |
+
# -----------------------------
|
| 42 |
+
# 3. Gradio interface
|
| 43 |
+
# -----------------------------
|
| 44 |
+
iface = gr.Interface(
|
| 45 |
+
fn=predict,
|
| 46 |
+
inputs=gr.Image(type="pil"),
|
| 47 |
+
outputs="text",
|
| 48 |
+
title="Chest X-ray Detector",
|
| 49 |
+
description="Upload a chest X-ray. The model predicts Pneumonia, Effusion, or Atelectasis."
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
iface.launch()
|
requirements1.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
transformers
|
| 3 |
+
gradio
|
| 4 |
+
pillow
|