Spaces:
Sleeping
Sleeping
Delete app.py
Browse files
app.py
DELETED
@@ -1,120 +0,0 @@
|
|
1 |
-
from fastapi import FastAPI, Query
|
2 |
-
from fastapi.responses import JSONResponse
|
3 |
-
import torch
|
4 |
-
import torchvision
|
5 |
-
import numpy as np
|
6 |
-
import requests
|
7 |
-
import skimage.io
|
8 |
-
import cv2
|
9 |
-
import tempfile
|
10 |
-
import os
|
11 |
-
from PIL import Image
|
12 |
-
from transformers import AutoImageProcessor, AutoModel
|
13 |
-
import joblib
|
14 |
-
from pytorch_grad_cam import GradCAM
|
15 |
-
from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
|
16 |
-
import torchxrayvision as xrv
|
17 |
-
import requests
|
18 |
-
from io import BytesIO
|
19 |
-
|
20 |
-
import logging
|
21 |
-
logging.getLogger("uvicorn").setLevel(logging.WARNING)
|
22 |
-
|
23 |
-
|
24 |
-
app = FastAPI()
|
25 |
-
|
26 |
-
cxr_model = xrv.models.DenseNet(weights="densenet121-res224-all")
|
27 |
-
cxr_model.eval()
|
28 |
-
|
29 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
30 |
-
tb_processor = AutoImageProcessor.from_pretrained("StanfordAIMI/dinov2-base-xray-224")
|
31 |
-
tb_model = AutoModel.from_pretrained("StanfordAIMI/dinov2-base-xray-224").to(device)
|
32 |
-
logreg = joblib.load("logreg_model.joblib")
|
33 |
-
|
34 |
-
def preprocess_image(image_path):
|
35 |
-
img = skimage.io.imread(image_path)
|
36 |
-
img = xrv.datasets.normalize(img, 255)
|
37 |
-
|
38 |
-
if img.ndim == 3:
|
39 |
-
img = img.mean(2)[None, ...]
|
40 |
-
elif img.ndim == 2:
|
41 |
-
img = img[None, ...]
|
42 |
-
|
43 |
-
transform = torchvision.transforms.Compose([
|
44 |
-
xrv.datasets.XRayCenterCrop(),
|
45 |
-
xrv.datasets.XRayResizer(224)
|
46 |
-
])
|
47 |
-
img = transform(img)
|
48 |
-
return torch.from_numpy(img)
|
49 |
-
|
50 |
-
def get_predictions(img_tensor, model):
|
51 |
-
with torch.no_grad():
|
52 |
-
outputs = model(img_tensor[None, ...])
|
53 |
-
preds = dict(zip(model.pathologies, outputs[0].detach().numpy()))
|
54 |
-
return preds, outputs
|
55 |
-
|
56 |
-
def get_top_preds(preds, tolerance=0.01, topk=5):
|
57 |
-
sorted_preds = sorted(preds.items(), key=lambda x: -x[1])
|
58 |
-
top_conf = sorted_preds[0][1]
|
59 |
-
similar_preds = [(i, p, conf) for i, (p, conf) in enumerate(sorted_preds)
|
60 |
-
if abs(conf - top_conf) <= tolerance][:topk]
|
61 |
-
return sorted_preds, similar_preds
|
62 |
-
|
63 |
-
def get_bounding_boxes(img_tensor, model, similar_preds):
|
64 |
-
boxes = {}
|
65 |
-
target_layer = model.features[-1]
|
66 |
-
for idx, pathology, conf in similar_preds:
|
67 |
-
cam = GradCAM(model=model, target_layers=[target_layer])
|
68 |
-
pred_index = list(model.pathologies).index(pathology)
|
69 |
-
grayscale_cam = cam(input_tensor=img_tensor[None, ...],
|
70 |
-
targets=[ClassifierOutputTarget(pred_index)])[0]
|
71 |
-
cam_resized = cv2.resize(grayscale_cam, (224, 224))
|
72 |
-
cam_uint8 = (cam_resized * 255).astype(np.uint8)
|
73 |
-
_, thresh = cv2.threshold(cam_uint8, 100, 255, cv2.THRESH_BINARY)
|
74 |
-
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
75 |
-
if contours:
|
76 |
-
x, y, w, h = cv2.boundingRect(contours[0])
|
77 |
-
boxes[pathology] = [[x, y], [x + w, y + h]]
|
78 |
-
return boxes
|
79 |
-
|
80 |
-
def predict_tb(image_path):
|
81 |
-
image = Image.open(image_path)
|
82 |
-
inputs = tb_processor(images=image, return_tensors="pt").to(device)
|
83 |
-
with torch.no_grad():
|
84 |
-
outputs = tb_model(**inputs)
|
85 |
-
embeddings = outputs.pooler_output.cpu().numpy()
|
86 |
-
prediction = logreg.predict(embeddings)
|
87 |
-
return int(prediction[0] == "tb")
|
88 |
-
|
89 |
-
@app.get("/predict")
|
90 |
-
async def predict_cxr(image_url: str = Query(..., description="URL to a chest X-ray image")):
|
91 |
-
try:
|
92 |
-
response = requests.get(image_url)
|
93 |
-
if response.status_code != 200:
|
94 |
-
return JSONResponse(content={"error": "Failed to download image"}, status_code=400)
|
95 |
-
|
96 |
-
with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as tmp:
|
97 |
-
tmp.write(response.content)
|
98 |
-
tmp_path = tmp.name
|
99 |
-
|
100 |
-
img_tensor = preprocess_image(tmp_path)
|
101 |
-
|
102 |
-
preds, _ = get_predictions(img_tensor, cxr_model)
|
103 |
-
sorted_preds, similar_preds = get_top_preds(preds)
|
104 |
-
|
105 |
-
prediction_result = {k: float(f"{v:.2f}") for k, v in preds.items()}
|
106 |
-
|
107 |
-
bounding_boxes = get_bounding_boxes(img_tensor, cxr_model, similar_preds)
|
108 |
-
|
109 |
-
tb_result = predict_tb(tmp_path)
|
110 |
-
|
111 |
-
os.remove(tmp_path)
|
112 |
-
|
113 |
-
return JSONResponse(content={
|
114 |
-
"prediction_result": prediction_result,
|
115 |
-
"bounding_box": bounding_boxes, # top-left , bottom-right coordinates
|
116 |
-
"tb_finding": tb_result
|
117 |
-
})
|
118 |
-
|
119 |
-
except Exception as e:
|
120 |
-
return JSONResponse(content={"error": str(e)}, status_code=500)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|