shubham5524 commited on
Commit
1560e05
·
verified ·
1 Parent(s): 8e8d783

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +133 -120
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
- 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)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)