diff --git a/server.py b/server.py index 905266e..4104f5c 100644 --- a/server.py +++ b/server.py @@ -6,6 +6,7 @@ import os import io import torch +import torch.nn.functional as F from torchvision import transforms from PIL import Image @@ -46,8 +47,9 @@ def get_prediction(model, image_bytes, device): with torch.no_grad(): output = model(input_tensor) - _, pred_idx = torch.max(output, 1) - return CLASS_NAMES[pred_idx.item()] + probabilities = F.softmax(output, dim=1) + confidence, pred_idx = torch.max(probabilities, 1) + return CLASS_NAMES[pred_idx.item()], confidence.item() # --- Background Task --- async def monitor_garage_door(app): @@ -65,9 +67,10 @@ async def monitor_garage_door(app): async with session.get(CAMERA_URL, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS) as response: if response.status == 200: image_bytes = await response.read() - prediction = get_prediction(model, image_bytes, device) - if prediction: - logging.debug(f"Garage door status: {prediction}") + result = get_prediction(model, image_bytes, device) + if result: + prediction, confidence = result + logging.debug(f"Garage door status: {prediction} (confidence: {confidence:.4f})") else: logging.error(f"Failed to fetch image. Status: {response.status}, Reason: {response.reason}")