lulc-backend / src /app.py
numanabubakar's picture
Add separate /predict_mobile endpoint while keeping /predict original
56fae07
Raw History Blame Contribute Delete
11.2 kB
"""FastAPI backend for LULC Recognition System."""
import torch
import time
import base64
from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Optional
import io
import logging
from model_loader import get_model_loader
from preprocessing import get_preprocessor
from class_mappings import get_class_label
from src.explainers import generate_all_explanations
app = FastAPI(
title="LULC Recognition API",
description="Deep Learning Land Use & Land Cover Recognition System",
version="1.0.0"
)
# CORS configuration for frontend integration
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("lulc-api")
@app.middleware("http")
async def log_requests(request: Request, call_next):
"""Log incoming request details for debugging non-browser clients."""
client_host = request.client.host if request.client else "unknown"
user_agent = request.headers.get("user-agent", "unknown")
logger.info(f"Incoming request: {request.method} {request.url.path} | Client: {client_host} | UA: {user_agent}")
# Check for Hugging Face specific headers
hf_headers = {k: v for k, v in request.headers.items() if k.lower().startswith("x-")}
if hf_headers:
logger.info(f"HF Headers: {hf_headers}")
response = await call_next(request)
return response
# Response models
class ClassPrediction(BaseModel):
class_index: int
class_label: str
confidence: float
class PredictionResponse(BaseModel):
"""Response model for prediction endpoint."""
predicted_class: str
class_index: int
confidence: float
all_predictions: list[ClassPrediction]
explainability_maps: dict
inference_time_ms: float
model_type: str
image_info: dict
class MobilePredictRequest(BaseModel):
"""Request model for mobile Base64 prediction."""
image_b64: str
model_type: str
class HealthResponse(BaseModel):
"""Response model for health check."""
status: str
device: str
models_available: list[str]
# Validation utilities
VALID_IMAGE_FORMATS = {"image/jpeg", "image/png", "image/jpg", "image/webp"}
VALID_MODEL_TYPES = {"eurosat", "mlrsnet", "patternnet"}
MAX_IMAGE_SIZE = 10 * 1024 * 1024 # 10MB
def validate_image(file: UploadFile) -> bytes:
"""Validate and read image file with robustness for various clients."""
logger.info(f"[predict] validate_image: filename={file.filename}, content_type={file.content_type}")
# Logic to handle mobile clients that might not send proper mime types
is_valid_type = file.content_type in VALID_IMAGE_FORMATS
# If content type is generic or missing, check the filename extension
if not is_valid_type and file.filename:
ext = file.filename.split(".")[-1].lower()
if ext in ["jpg", "jpeg", "png", "webp"]:
is_valid_type = True
logger.info(f"[predict] Image type verified by extension: .{ext}")
if not is_valid_type and file.content_type != "application/octet-stream":
logger.warning(f"Suspicious content type: {file.content_type}. Proceeding with best-effort.")
try:
content = file.file.read()
logger.info(f"[predict] validate_image: bytes_read={len(content)}")
if len(content) == 0:
raise HTTPException(status_code=400, detail="Empty image file.")
if len(content) > MAX_IMAGE_SIZE:
raise HTTPException(
status_code=413,
detail=f"Image too large. Max size: {MAX_IMAGE_SIZE / 1024 / 1024}MB"
)
return content
except HTTPException:
raise
except Exception as e:
logger.error(f"Error reading image: {str(e)}")
raise HTTPException(status_code=400, detail=f"Error reading image: {str(e)}")
def calculate_flops(input_shape: tuple = (1, 3, 224, 224)) -> int:
return 106_000_000
# Helper function to avoid repeating core logic while keeping endpoints separate
def _run_prediction_logic(image_bytes: bytes, model_type: str):
# Validate model type
model_type = model_type.lower().strip()
if model_type not in VALID_MODEL_TYPES:
raise HTTPException(
status_code=400,
detail=f"Invalid model type: {model_type}. Valid types: {', '.join(VALID_MODEL_TYPES)}"
)
try:
preprocessor = get_preprocessor()
loader = get_model_loader()
image_info = preprocessor.get_image_info(image_bytes)
image_tensor = preprocessor.preprocess(image_bytes, model_type)
image_tensor = image_tensor.to(loader.get_device())
start_time = time.time()
with torch.no_grad():
model = loader.load_model(model_type)
logits = model(image_tensor)
probabilities = torch.softmax(logits, dim=1)
all_probs, all_indices = torch.sort(probabilities, descending=True, dim=1)
all_predictions = []
for i in range(all_probs.shape[1]):
idx = all_indices[0, i].item()
prob = float(all_probs[0, i].item())
label = get_class_label(model_type, idx)
all_predictions.append(ClassPrediction(
class_index=idx,
class_label=label,
confidence=prob
))
inference_time = (time.time() - start_time) * 1000
explain_maps = generate_all_explanations(model, preprocessor, image_tensor, image_bytes, model_type)
return PredictionResponse(
predicted_class=all_predictions[0].class_label,
class_index=all_predictions[0].class_index,
confidence=all_predictions[0].confidence,
all_predictions=all_predictions,
explainability_maps=explain_maps,
inference_time_ms=float(inference_time),
model_type=model_type,
image_info=image_info
)
except Exception as e:
logger.error(f"Inference error: {str(e)}")
if isinstance(e, HTTPException): raise e
raise HTTPException(status_code=500, detail=f"Inference error: {str(e)}")
# Routes
@app.get("/")
async def root():
return {"status": "ok", "message": "LULC Recognition API is running"}
@app.get("/health", response_model=HealthResponse)
async def health_check():
loader = get_model_loader()
return HealthResponse(
status="healthy",
device=str(loader.get_device()),
models_available=list(VALID_MODEL_TYPES)
)
@app.post("/predict", response_model=PredictionResponse)
async def predict(
file: UploadFile = File(...),
model_type: str = Form(...)
):
"""
Original multipart/form-data prediction endpoint.
Keeping the full body logic as requested.
"""
logger.info(f"[predict] request received: model_type_raw={model_type}, file={file.filename}")
# Validate model type
model_type = model_type.lower().strip()
if model_type not in VALID_MODEL_TYPES:
raise HTTPException(
status_code=400,
detail=f"Invalid model type: {model_type}. Valid types: {', '.join(VALID_MODEL_TYPES)}"
)
# Validate and read image
image_bytes = validate_image(file)
try:
# Get preprocessor and model
preprocessor = get_preprocessor()
loader = get_model_loader()
logger.info(f"[predict] device={loader.get_device()}")
# Get image info for response
image_info = preprocessor.get_image_info(image_bytes)
# Preprocess image
image_tensor = preprocessor.preprocess(image_bytes, model_type)
image_tensor = image_tensor.to(loader.get_device())
# Run inference with timing
start_time = time.time()
with torch.no_grad():
model = loader.load_model(model_type)
logits = model(image_tensor)
probabilities = torch.softmax(logits, dim=1)
all_probs, all_indices = torch.sort(probabilities, descending=True, dim=1)
all_predictions = []
for i in range(all_probs.shape[1]):
idx = all_indices[0, i].item()
prob = float(all_probs[0, i].item())
label = get_class_label(model_type, idx)
all_predictions.append(ClassPrediction(
class_index=idx,
class_label=label,
confidence=prob
))
inference_time = (time.time() - start_time) * 1000
# Generate explanations
explain_maps = generate_all_explanations(model, preprocessor, image_tensor, image_bytes, model_type)
return PredictionResponse(
predicted_class=all_predictions[0].class_label,
class_index=all_predictions[0].class_index,
confidence=all_predictions[0].confidence,
all_predictions=all_predictions,
explainability_maps=explain_maps,
inference_time_ms=float(inference_time),
model_type=model_type,
image_info=image_info
)
except Exception as e:
logger.error(f"[predict] error: {str(e)}")
if isinstance(e, HTTPException): raise e
raise HTTPException(status_code=500, detail=f"Inference error: {str(e)}")
@app.post("/predict_mobile", response_model=PredictionResponse)
async def predict_mobile(request: MobilePredictRequest):
"""
Separate endpoint for mobile Base64 prediction.
"""
logger.info(f"[predict_mobile] Base64 request for model: {request.model_type}")
try:
# Decode base64
b64_data = request.image_b64
if "," in b64_data:
b64_data = b64_data.split(",")[1]
image_bytes = base64.b64decode(b64_data)
if len(image_bytes) > MAX_IMAGE_SIZE:
raise HTTPException(status_code=413, detail="Image too large")
except Exception as e:
logger.error(f"[predict_mobile] decoding error: {str(e)}")
raise HTTPException(status_code=400, detail="Invalid Base64 image data")
# We call the logic here separately
return _run_prediction_logic(image_bytes, request.model_type)
@app.get("/info")
async def get_info():
"""Get system information."""
flops = calculate_flops()
return {
"system": "Deep Learning LULC Recognition",
"version": "1.0.0",
"models": list(VALID_MODEL_TYPES),
"architecture": "Explainable CNN",
"parameters_approx": 400_000,
"flops_approx": flops,
"device": str(get_model_loader().get_device()),
}
if __name__ == "__main__":
import uvicorn
import os
port = int(os.environ.get("PORT", 7860))
uvicorn.run(app, host="0.0.0.0", port=port)