Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,31 +1,38 @@
|
|
1 |
from fastapi import FastAPI, Query
|
2 |
-
from
|
3 |
-
from typing import List, Tuple
|
4 |
-
from fastapi import Body
|
5 |
-
|
6 |
import torch
|
7 |
-
import torchxrayvision as xrv
|
8 |
import torchvision
|
9 |
-
import skimage.io
|
10 |
import numpy as np
|
11 |
import requests
|
|
|
12 |
import cv2
|
13 |
-
|
14 |
-
|
15 |
-
|
|
|
|
|
16 |
from pytorch_grad_cam import GradCAM
|
17 |
from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
|
18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
|
20 |
app = FastAPI()
|
21 |
|
22 |
-
|
23 |
-
|
24 |
|
|
|
|
|
|
|
|
|
25 |
|
26 |
-
def
|
27 |
-
|
28 |
-
img = skimage.io.imread(BytesIO(response.content))
|
29 |
img = xrv.datasets.normalize(img, 255)
|
30 |
|
31 |
if img.ndim == 3:
|
@@ -38,83 +45,76 @@ def preprocess_image_from_url(image_url: str) -> torch.Tensor:
|
|
38 |
xrv.datasets.XRayResizer(224)
|
39 |
])
|
40 |
img = transform(img)
|
41 |
-
|
42 |
-
return img_tensor
|
43 |
-
|
44 |
|
45 |
-
def
|
46 |
with torch.no_grad():
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
|
|
|
|
|
|
|
|
|
|
55 |
target_layer = model.features[-1]
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
|
|
|
|
73 |
|
74 |
-
|
|
|
|
|
75 |
|
|
|
76 |
|
77 |
-
|
78 |
-
|
79 |
-
confidence: float
|
80 |
|
|
|
81 |
|
82 |
-
|
83 |
-
predictions: List[Prediction]
|
84 |
-
top_prediction_bounding_boxes: List[Tuple[int, int, int, int]]
|
85 |
|
|
|
86 |
|
87 |
-
|
88 |
-
def predict(image_url: str = Query(..., description="URL of chest X-ray image")):
|
89 |
-
try:
|
90 |
-
img_tensor = preprocess_image_from_url(image_url)
|
91 |
-
preds, bboxes = get_predictions_and_bounding_box(img_tensor)
|
92 |
-
prediction_list = [Prediction(label=label, confidence=float(conf)) for label, conf in preds]
|
93 |
-
|
94 |
-
return PredictionResponse(
|
95 |
-
predictions=prediction_list,
|
96 |
-
top_prediction_bounding_boxes=bboxes
|
97 |
-
)
|
98 |
-
except Exception as e:
|
99 |
-
return {"error": str(e)}
|
100 |
|
101 |
-
|
102 |
-
|
|
|
|
|
|
|
103 |
|
104 |
-
@app.post("/predict", response_model=PredictionResponse)
|
105 |
-
def predict_from_url(body: URLRequest):
|
106 |
-
try:
|
107 |
-
img_tensor = preprocess_image_from_url(body.url)
|
108 |
-
preds, bboxes = get_predictions_and_bounding_box(img_tensor)
|
109 |
-
prediction_list = [Prediction(label=label, confidence=float(conf)) for label, conf in preds]
|
110 |
-
|
111 |
-
return PredictionResponse(
|
112 |
-
predictions=prediction_list,
|
113 |
-
top_prediction_bounding_boxes=bboxes
|
114 |
-
)
|
115 |
except Exception as e:
|
116 |
-
return {"error": str(e)}
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
# uvicorn app:app --reload
|
|
|
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:
|
|
|
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)
|
|
|
|
|
|
|
|