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