File size: 19,766 Bytes
e9d75d6 db2f76f e9d75d6 db2f76f e9d75d6 db2f76f e9d75d6 db2f76f e9d75d6 db2f76f e9d75d6 db2f76f e9d75d6 db2f76f e9d75d6 db2f76f e9d75d6 db2f76f e9d75d6 db2f76f e9d75d6 db2f76f e9d75d6 db2f76f e9d75d6 db2f76f e9d75d6 db2f76f e9d75d6 db2f76f e9d75d6 db2f76f e9d75d6 db2f76f e9d75d6 | 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 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 | mport torch
import torch.nn as nn
from torchvision import transforms, models
import numpy as np
import cv2
from PIL import Image
import io
import json
from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.responses import JSONResponse
import base64
from typing import List, Dict
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Agg')
# ============================================================================
# CONSTANTS
# ============================================================================
IMG_SIZE = 224
NUM_CLASSES = 4
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
UNHYGIENIC_CLASSES = [1, 2, 3] # Adjust based on your class indices
# ============================================================================
# BOUNDING BOX DETECTION MODULE
# ============================================================================
class BoundingBoxDetector:
"""Detects and localizes problem regions using attention maps"""
def __init__(self, threshold=0.2, min_area=15, max_boxes=15):
self.threshold = threshold
self.min_area = min_area
self.max_boxes = max_boxes
def get_bboxes_from_heatmap(self, heatmap, orig_width, orig_height):
"""Extract bounding boxes from attention heatmap"""
heatmap = cv2.resize(heatmap, (orig_width, orig_height))
# Normalize heatmap
heatmap = (heatmap - heatmap.min()) / (heatmap.max() - heatmap.min() + 1e-8)
# Threshold
threshold = np.percentile(heatmap, 85)
binary = (heatmap > threshold).astype(np.uint8) * 255
# Find contours
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
bboxes = []
for contour in contours:
area = cv2.contourArea(contour)
if area < 100: # increase threshold
continue
x, y, w, h = cv2.boundingRect(contour)
# Reject giant boxes
if w > 0.9 * orig_width and h > 0.9 * orig_height:
continue
confidence = heatmap[y:y+h, x:x+w].mean()
bboxes.append({
'x': int(x),
'y': int(y),
'width': int(w),
'height': int(h),
'confidence': float(confidence),
'area': int(area)
})
# Sort by confidence and keep top N
bboxes = sorted(bboxes, key=lambda b: b['confidence'], reverse=True)[:self.max_boxes]
return bboxes
# ============================================================================
# INFERENCE RESULT CONTAINER
# ============================================================================
class InferenceResult:
"""Container for all inference outputs"""
def __init__(self):
self.prediction = None # Class index
self.confidence = None # Confidence score
self.probabilities = None # All class probabilities
self.gradcam = None # GradCAM heatmap (numpy)
self.gradcam_image = None # GradCAM overlay (PIL Image)
self.bbox_list = None # List of bounding boxes
self.original_image = None # Input image (PIL Image)
# ============================================================================
# MODEL DEFINITION
# ============================================================================
class KitchenHygieneModelWithBBox(nn.Module):
"""EfficientNet with attention-based bbox localization AND integrated GradCAM"""
def __init__(self, num_classes=NUM_CLASSES):
super().__init__()
# Base model
base_model = models.efficientnet_b0(weights=None)
# Freeze early layers
for param in list(base_model.parameters())[:-35]:
param.requires_grad = False
self.features = base_model.features
self.avgpool = base_model.avgpool
# Classification head
self.classifier = nn.Sequential(
nn.Dropout(0.3),
nn.Linear(base_model.classifier[1].in_features, 256),
nn.ReLU(),
nn.Dropout(0.3),
nn.Linear(256, num_classes)
)
# Attention head for bbox localization
self.attention_head = nn.Sequential(
nn.Conv2d(base_model.classifier[1].in_features, 128, kernel_size=1),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.Conv2d(128, 64, kernel_size=1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.Conv2d(64, 1, kernel_size=1),
nn.Sigmoid()
)
# Gradients for GradCAM
self.gradients = None
self.activations = None
# Register hooks for GradCAM
self.features[-1].register_forward_hook(self._save_activations)
self.features[-1].register_full_backward_hook(self._save_gradients)
self.num_classes = num_classes
def _save_activations(self, module, input, output):
self.activations = output.detach()
def _save_gradients(self, module, grad_input, grad_output):
self.gradients = grad_output[0].detach()
def forward(self, x):
# Feature extraction
features = self.features(x)
# Classification
pool = self.avgpool(features)
pool = torch.flatten(pool, 1)
logits = self.classifier(pool)
# Attention map for bbox
attention_map = self.attention_head(features)
# Return both
return logits, attention_map
def generate_gradcam(self, input_tensor, class_idx):
"""Generate GradCAM for specified class"""
# Forward pass
outputs, _ = self(input_tensor)
# Backward pass
self.zero_grad()
one_hot = torch.zeros_like(outputs)
one_hot[0][class_idx] = 1
outputs.backward(gradient=one_hot)
# Calculate CAM
if self.gradients is None or self.activations is None:
return None
gradients = self.gradients[0]
activations = self.activations[0]
# Weights: average gradients across spatial dimensions
weights = gradients.mean(dim=(1, 2), keepdim=True)
# Weighted activation maps
cam = (weights * activations).sum(dim=0)
# ReLU to keep only positive activations
cam = torch.clamp(cam, min=0)
# Normalize to 0-1
cam = cam - cam.min()
cam = cam / (cam.max() + 1e-8)
return cam.cpu().numpy()
# ============================================================================
# UTILITY FUNCTIONS
# ============================================================================
def overlay_gradcam_on_image(image, cam, alpha=0.5):
"""Overlay GradCAM heatmap on original image"""
cam_resized = Image.fromarray((cam * 255).astype(np.uint8)).resize(
(image.width, image.height), Image.BILINEAR
)
cam_array = np.array(cam_resized)
heatmap = plt.cm.hot(cam_array / 255.0)
heatmap_rgb = Image.fromarray((heatmap[:, :, :3] * 255).astype(np.uint8))
blended = Image.blend(image.convert('RGB'), heatmap_rgb, alpha)
return blended
def image_to_base64(image):
"""Convert PIL Image to base64 string"""
buffered = io.BytesIO()
image.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue()).decode()
return img_str
def draw_bboxes_on_image(image, bboxes, class_idx, class_names):
"""Draw bounding boxes on image and return as PIL Image"""
img_cv = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
colors = {
1: (0, 0, 180),
2: (0, 0, 220),
3: (0, 0, 255)
}
color = colors.get(class_idx, (0, 0, 200))
for bbox in bboxes:
x, y, w, h = int(bbox['x']), int(bbox['y']), int(bbox['width']), int(bbox['height'])
conf = bbox['confidence']
# skip useless tiny boxes
if w < 20 or h < 20:
continue
# Draw thick rectangle
cv2.rectangle(img_cv, (x, y), (x + w, y + h), color, 6)
# Label text
label = f"{conf:.0%}"
# Get text size
(tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.8, 2)
# Draw filled background
cv2.rectangle(img_cv, (x, y - th - 10), (x + tw + 5, y), color, -1)
# Put white text
cv2.putText(img_cv, label, (x + 2, y - 5),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2)
return Image.fromarray(cv2.cvtColor(img_cv, cv2.COLOR_BGR2RGB))
# ============================================================================
# FASTAPI APP INITIALIZATION
# ============================================================================
app = FastAPI(
title="Kitchen Hygiene Classification API",
description="Complete inference with GradCAM, Bounding Box Detection, and Prediction",
version="1.0.0"
)
from fastapi.responses import HTMLResponse
@app.get("/", response_class=HTMLResponse)
async def home():
return """
<h2>🍽️ Kitchen Hygiene API is running!</h2>
<p>Go to <a href="/docs">/docs</a> to test the API.</p>
"""
# Global variables
model = None
class_names = None
@app.on_event("startup")
async def load_model():
"""Load model on startup"""
global model, class_names
try:
# Load the full model
model = KitchenHygieneModelWithBBox(num_classes=NUM_CLASSES)
model.load_state_dict(torch.load("kitchen_model_new.pth", map_location=DEVICE))
model.to(DEVICE)
model.eval()
# Load class names from model info
with open("model_info.json", "r") as f:
model_info = json.load(f)
class_names = model_info["classes"]
print(f"✓ Model loaded successfully")
print(f" Classes: {class_names}")
print(f" Device: {DEVICE}")
except Exception as e:
print(f"ERROR loading model: {str(e)}")
raise
# ============================================================================
# API ENDPOINTS
# ============================================================================
@app.get("/health")
async def health_check():
"""Health check endpoint"""
return {
"status": "healthy",
"model_loaded": model is not None,
"device": str(DEVICE),
"num_classes": NUM_CLASSES,
"classes": class_names
}
@app.post("/predict")
async def predict(file: UploadFile = File(...)):
"""
Complete inference endpoint
Returns:
- prediction: predicted class name
- confidence: confidence score
- probabilities: all class probabilities
- bounding_boxes: list of detected problem regions
- gradcam_image: base64 encoded GradCAM overlay
- bbox_image: base64 encoded image with bounding boxes
"""
if model is None:
raise HTTPException(status_code=500, detail="Model not loaded")
try:
# Read uploaded image
contents = await file.read()
image = Image.open(io.BytesIO(contents)).convert('RGB')
original_image = image.copy()
orig_width, orig_height = image.size
# Preprocess image
transform = transforms.Compose([
transforms.Resize((IMG_SIZE, IMG_SIZE)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
image_tensor = transform(image).unsqueeze(0).to(DEVICE)
# Step 1: Get prediction
with torch.no_grad():
outputs, attention_maps = model(image_tensor)
probabilities = torch.softmax(outputs[0], dim=0).detach().cpu().numpy()
predicted_class_idx = int(np.argmax(probabilities))
confidence = float(probabilities[predicted_class_idx])
# Step 2: Generate GradCAM
gradcam = model.generate_gradcam(image_tensor, predicted_class_idx)
if gradcam is None:
gradcam = np.zeros((IMG_SIZE, IMG_SIZE))
gradcam_image = overlay_gradcam_on_image(original_image, gradcam, alpha=0.4)
# Step 3: Detect bounding boxes
attention_np = gradcam
if attention_np.max() > 0:
attention_np = (attention_np - attention_np.min()) / (attention_np.max() - attention_np.min() + 1e-8)
detector = BoundingBoxDetector(threshold=0.15, min_area=10, max_boxes=10)
bboxes = detector.get_bboxes_from_heatmap(attention_np, orig_width, orig_height)
# Only show bboxes for unhygienic classes
filtered_bboxes = bboxes if predicted_class_idx in UNHYGIENIC_CLASSES else []
# Draw bboxes
bbox_image = draw_bboxes_on_image(original_image, filtered_bboxes,
predicted_class_idx, class_names)
# Prepare response
response = {
"prediction": class_names[predicted_class_idx],
"confidence": confidence,
"probabilities": {
class_names[i]: float(probabilities[i])
for i in range(len(class_names))
},
"bounding_boxes": filtered_bboxes,
"num_problems_detected": len(filtered_bboxes),
"gradcam_image": f"data:image/png;base64,{image_to_base64(gradcam_image)}",
"bbox_image": f"data:image/png;base64,{image_to_base64(bbox_image)}"
}
return JSONResponse(content=response)
except Exception as e:
raise HTTPException(status_code=400, detail=f"Error processing image: {str(e)}")
@app.post("/predict-simple")
async def predict_simple(file: UploadFile = File(...)):
"""
Simplified prediction endpoint (returns only prediction and probabilities, no images)
"""
if model is None:
raise HTTPException(status_code=500, detail="Model not loaded")
try:
# Read uploaded image
contents = await file.read()
image = Image.open(io.BytesIO(contents)).convert('RGB')
# Preprocess image
transform = transforms.Compose([
transforms.Resize((IMG_SIZE, IMG_SIZE)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
image_tensor = transform(image).unsqueeze(0).to(DEVICE)
# Get prediction
with torch.no_grad():
outputs, _ = model(image_tensor)
probabilities = torch.softmax(outputs[0], dim=0).detach().cpu().numpy()
predicted_class_idx = int(np.argmax(probabilities))
confidence = float(probabilities[predicted_class_idx])
response = {
"prediction": class_names[predicted_class_idx],
"confidence": confidence,
"probabilities": {
class_names[i]: float(probabilities[i])
for i in range(len(class_names))
}
}
return JSONResponse(content=response)
except Exception as e:
raise HTTPException(status_code=400, detail=f"Error processing image: {str(e)}")
@app.post("/gradcam-only")
async def gradcam_only(file: UploadFile = File(...)):
"""
GradCAM only endpoint (returns GradCAM heatmap and prediction)
"""
if model is None:
raise HTTPException(status_code=500, detail="Model not loaded")
try:
contents = await file.read()
image = Image.open(io.BytesIO(contents)).convert('RGB')
original_image = image.copy()
transform = transforms.Compose([
transforms.Resize((IMG_SIZE, IMG_SIZE)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
image_tensor = transform(image).unsqueeze(0).to(DEVICE)
# Get prediction
with torch.no_grad():
outputs, _ = model(image_tensor)
probabilities = torch.softmax(outputs[0], dim=0).detach().cpu().numpy()
predicted_class_idx = int(np.argmax(probabilities))
confidence = float(probabilities[predicted_class_idx])
# Generate GradCAM
gradcam = model.generate_gradcam(image_tensor, predicted_class_idx)
if gradcam is None:
gradcam = np.zeros((IMG_SIZE, IMG_SIZE))
gradcam_image = overlay_gradcam_on_image(original_image, gradcam, alpha=0.4)
response = {
"prediction": class_names[predicted_class_idx],
"confidence": confidence,
"probabilities": {
class_names[i]: float(probabilities[i])
for i in range(len(class_names))
},
"gradcam_image": f"data:image/png;base64,{image_to_base64(gradcam_image)}"
}
return JSONResponse(content=response)
except Exception as e:
raise HTTPException(status_code=400, detail=f"Error processing image: {str(e)}")
@app.post("/bbox-detection")
async def bbox_detection(file: UploadFile = File(...)):
"""
Bounding box detection only endpoint
"""
if model is None:
raise HTTPException(status_code=500, detail="Model not loaded")
try:
contents = await file.read()
image = Image.open(io.BytesIO(contents)).convert('RGB')
original_image = image.copy()
orig_width, orig_height = image.size
transform = transforms.Compose([
transforms.Resize((IMG_SIZE, IMG_SIZE)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
image_tensor = transform(image).unsqueeze(0).to(DEVICE)
# Get prediction and attention
with torch.no_grad():
outputs, _ = model(image_tensor)
probabilities = torch.softmax(outputs[0], dim=0).detach().cpu().numpy()
predicted_class_idx = int(np.argmax(probabilities))
confidence = float(probabilities[predicted_class_idx])
# Generate GradCAM for attention
gradcam = model.generate_gradcam(image_tensor, predicted_class_idx)
if gradcam is None:
gradcam = np.zeros((IMG_SIZE, IMG_SIZE))
attention_np = gradcam
if attention_np.max() > 0:
attention_np = (attention_np - attention_np.min()) / (attention_np.max() - attention_np.min() + 1e-8)
# Detect boxes
detector = BoundingBoxDetector(threshold=0.15, min_area=10, max_boxes=10)
bboxes = detector.get_bboxes_from_heatmap(attention_np, orig_width, orig_height)
filtered_bboxes = bboxes if predicted_class_idx in UNHYGIENIC_CLASSES else []
bbox_image = draw_bboxes_on_image(original_image, filtered_bboxes,
predicted_class_idx, class_names)
response = {
"prediction": class_names[predicted_class_idx],
"confidence": confidence,
"bounding_boxes": filtered_bboxes,
"num_problems_detected": len(filtered_bboxes),
"bbox_image": f"data:image/png;base64,{image_to_base64(bbox_image)}"
}
return JSONResponse(content=response)
except Exception as e:
raise HTTPException(status_code=400, detail=f"Error processing image: {str(e)}")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860) |