Spaces:
Sleeping
Sleeping
File size: 13,598 Bytes
535f4a6 8a62694 535f4a6 8a62694 535f4a6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 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 62 63 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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 | from fastapi import FastAPI, File, UploadFile, Query
from fastapi.responses import StreamingResponse, JSONResponse
from PIL import Image
import io
import cv2
from ultralytics import YOLO
from llm import analyze_detections
from typing import Dict, List, Any
from collections import Counter
import base64
app = FastAPI()
model = None
model_cache = {}
@app.on_event("startup")
def load_model():
global model
try:
model = YOLO("models/anemia_detection_yolov8.onnx")
model_cache["anemia_detection_yolov8"] = model
print("Default model (anemia_detection_yolov8) successfully loaded")
except Exception as e:
print(f"Failed to load default model: {e}")
# Map model_name to model file path
MODEL_PATHS = {
"generic_detection_yolov8": "models/PixCellv1.pt",
"parasite_detection_yolov8": "models/parasite_detection_yolov8.onnx",
"anemia_detection_yolov8": "models/anemia_detection_yolov8.onnx",
"malaria_detection_yolov8": "models/malaria_detection_yolov8.onnx",
}
@app.post("/predict")
async def predict(file: UploadFile = File(...), model_name: str = Query("anemia_detection_yolov8")):
# full_model_name = model_name + ".onnx"
image_bytes = await file.read()
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
# model = load_model(full_model_name)
# Use proper YOLO predict method
results = model.predict(image, save=False, save_txt=False)
# Extract results from the first result object
result = results[0]
class_names = []
if result.boxes is not None:
for box in result.boxes:
cls = int(box.cls[0])
conf = float(box.conf[0])
xyxy = box.xyxy[0].tolist() # bounding box [x1, y1, x2, y2]
class_name = model.names[cls]
class_names.append(class_name)
print(f"Class: {class_name}, Confidence: {conf:.2f}, BBox: {xyxy}")
# Use Counter for accurate counting
class_counts = Counter(class_names)
img_with_boxes = result.plot()
img_with_boxes = cv2.cvtColor(img_with_boxes, cv2.COLOR_BGR2RGB)
img_pil = Image.fromarray(img_with_boxes)
img_bytes = io.BytesIO()
img_pil.save(img_bytes, format="JPEG")
img_bytes.seek(0)
# Return the processed image as before
return StreamingResponse(img_bytes, media_type="image/jpeg")
@app.post("/predict-with-data")
async def predict_with_data(file: UploadFile = File(...), model_name: str = Query("anemia_detection_yolov8")):
"""
Predict endpoint that returns both the processed image and detection data.
"""
image_bytes = await file.read()
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
# Use proper YOLO predict method
results = model.predict(image, save=False, save_txt=False)
# Extract results from the first result object
result = results[0]
class_names = []
if result.boxes is not None:
for box in result.boxes:
cls = int(box.cls[0])
conf = float(box.conf[0])
xyxy = box.xyxy[0].tolist()
class_name = model.names[cls]
class_names.append(class_name)
print(f"Class: {class_name}, Confidence: {conf:.2f}, BBox: {xyxy}")
# Use Counter for accurate counting
class_counts = Counter(class_names)
return JSONResponse({
"detections": dict(class_counts),
"total_detections": sum(class_counts.values()),
"success": True
})
@app.post("/ai-analysis")
async def ai_analysis(
file: UploadFile = File(...),
sample_type: str = Query("Blood smear"),
stain: str = Query("Giemsa"),
magnification: str = Query("1000x")
):
"""
Perform AI analysis on an image using the detection model and LLM.
"""
try:
# First, get detections from the image
image_bytes = await file.read()
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
# Use proper YOLO predict method
results = model.predict(image, save=False, save_txt=False)
# Extract results from the first result object
result = results[0]
class_names = []
if result.boxes is not None:
for box in result.boxes:
cls = int(box.cls[0])
class_name = model.names[cls]
class_names.append(class_name)
# Use Counter for accurate counting
class_counts = Counter(class_names)
# If no detections found, return early
if not class_counts:
return JSONResponse({
"success": False,
"error": "No detections found in the image",
"detection_summary": {}
})
# Perform AI analysis
analysis_result = analyze_detections(dict(class_counts), sample_type, stain, magnification)
return JSONResponse(analysis_result)
except Exception as e:
return JSONResponse({
"success": False,
"error": f"Analysis failed: {str(e)}",
"detection_summary": {}
})
# New endpoint that combines detection and AI analysis in one call
@app.post("/detect-and-analyze")
async def detect_and_analyze(
file: UploadFile = File(...),
model_name: str = Query("anemia_detection_yolov8"),
sample_type: str = Query("Blood smear"),
stain: str = Query("Giemsa"),
magnification: str = Query("1000x")
):
"""
Combined endpoint that runs detection once and returns both detection results and AI analysis.
"""
try:
# Model selection logic
global model_cache
if model_name not in MODEL_PATHS:
return JSONResponse({
"success": False,
"error": f"Unknown model_name: {model_name}",
"detections": {},
"total_detections": 0,
"detection_details": [],
"ai_analysis": None
}, status_code=400)
if model_name not in model_cache:
try:
model_cache[model_name] = YOLO(MODEL_PATHS[model_name])
print(f"Model {model_name} loaded from {MODEL_PATHS[model_name]}")
except Exception as e:
return JSONResponse({
"success": False,
"error": f"Failed to load model {model_name}: {e}",
"detections": {},
"total_detections": 0,
"detection_details": [],
"ai_analysis": None
}, status_code=500)
yolo_model = model_cache[model_name]
image_bytes = await file.read()
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
# Run model prediction only once
results = yolo_model.predict(image, save=False, save_txt=False)
result = results[0]
class_names = []
detection_details = []
if result.boxes is not None:
for box in result.boxes:
cls = int(box.cls[0])
conf = float(box.conf[0])
xyxy = box.xyxy[0].tolist()
class_name = yolo_model.names[cls]
class_names.append(class_name)
detection_details.append({
"class": class_name,
"confidence": conf,
"bbox": xyxy
})
print(f"Class: {class_name}, Confidence: {conf:.2f}, BBox: {xyxy}")
# Use Counter for accurate counting
class_counts = Counter(class_names)
# Generate processed image
img_with_boxes = result.plot()
img_with_boxes = cv2.cvtColor(img_with_boxes, cv2.COLOR_BGR2RGB)
img_pil = Image.fromarray(img_with_boxes)
img_bytes = io.BytesIO()
img_pil.save(img_bytes, format="JPEG")
img_bytes.seek(0)
# Encode processed image as base64
processed_image_base64 = base64.b64encode(img_bytes.getvalue()).decode("utf-8")
# Perform AI analysis if detections found
ai_analysis_result = None
if class_counts:
ai_analysis_result = analyze_detections(dict(class_counts), sample_type, stain, magnification)
else:
ai_analysis_result = {
"success": False,
"error": "No detections found in the image",
"detection_summary": {}
}
return JSONResponse({
"detections": dict(class_counts),
"total_detections": sum(class_counts.values()),
"detection_details": detection_details,
"ai_analysis": ai_analysis_result,
"processed_image_base64": processed_image_base64,
"success": True
})
except Exception as e:
return JSONResponse({
"success": False,
"error": f"Detection and analysis failed: {str(e)}",
"detections": {},
"total_detections": 0,
"detection_details": [],
"ai_analysis": None,
"processed_image_base64": None
})
@app.post("/detect-and-analyze-batch")
async def detect_and_analyze_batch(
files: list[UploadFile] = File(...),
model_name: str = Query("anemia_detection_yolov8"),
sample_type: str = Query("Blood smear"),
stain: str = Query("Giemsa"),
magnification: str = Query("1000x")
):
"""
Batch endpoint that runs detection and analysis on multiple images.
Returns total counts, per-image results, and batch AI analysis.
"""
try:
global model_cache
if model_name not in MODEL_PATHS:
return JSONResponse({
"success": False,
"error": f"Unknown model_name: {model_name}",
"total_counts": {},
"total_detections": 0,
"results": [],
"ai_analysis": None
}, status_code=400)
if model_name not in model_cache:
try:
model_cache[model_name] = YOLO(MODEL_PATHS[model_name])
print(f"Model {model_name} loaded from {MODEL_PATHS[model_name]}")
except Exception as e:
return JSONResponse({
"success": False,
"error": f"Failed to load model {model_name}: {e}",
"total_counts": {},
"total_detections": 0,
"results": [],
"ai_analysis": None
}, status_code=500)
yolo_model = model_cache[model_name]
total_class_counts = Counter()
per_image_results = []
processed_images = []
total_detections = 0
for file in files:
image_bytes = await file.read()
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
results = yolo_model.predict(image, save=False, save_txt=False)
result = results[0]
class_names = []
detection_details = []
if result.boxes is not None:
for box in result.boxes:
cls = int(box.cls[0])
conf = float(box.conf[0])
xyxy = box.xyxy[0].tolist()
class_name = yolo_model.names[cls]
class_names.append(class_name)
detection_details.append({
"class": class_name,
"confidence": conf,
"bbox": xyxy
})
class_counts = Counter(class_names)
total_class_counts.update(class_counts)
total_detections += sum(class_counts.values())
# Generate processed image with boxes
img_with_boxes = result.plot()
img_with_boxes = cv2.cvtColor(img_with_boxes, cv2.COLOR_BGR2RGB)
img_pil = Image.fromarray(img_with_boxes)
img_bytes = io.BytesIO()
img_pil.save(img_bytes, format="JPEG")
img_bytes.seek(0)
processed_image_base64 = base64.b64encode(img_bytes.getvalue()).decode("utf-8")
processed_images.append(processed_image_base64)
per_image_results.append({
"detections": dict(class_counts),
"total_detections": sum(class_counts.values()),
"detection_details": detection_details,
"processed_image_base64": processed_image_base64
})
# Perform batch AI analysis on total counts
if total_class_counts:
ai_analysis_result = analyze_detections(dict(total_class_counts), sample_type, stain, magnification)
else:
ai_analysis_result = {
"success": False,
"error": "No detections found in any image",
"detection_summary": {}
}
return JSONResponse({
"success": True,
"total_counts": dict(total_class_counts),
"total_detections": total_detections,
"results": per_image_results,
"ai_analysis": ai_analysis_result,
"processed_images": processed_images
})
except Exception as e:
return JSONResponse({
"success": False,
"error": f"Batch detection and analysis failed: {str(e)}",
"total_counts": {},
"total_detections": 0,
"results": [],
"ai_analysis": None
})
|