Spaces:
Sleeping
Sleeping
Commit ·
b872f48
1
Parent(s): 3ccf4cc
FastAPI backend for AMSI-Net LULC recognition with multipart and base64 inference endpoints
Browse files- backend/app.py +57 -37
backend/app.py
CHANGED
|
@@ -2,11 +2,12 @@
|
|
| 2 |
|
| 3 |
import torch
|
| 4 |
import time
|
|
|
|
|
|
|
| 5 |
from fastapi import FastAPI, UploadFile, File, HTTPException
|
| 6 |
from fastapi.middleware.cors import CORSMiddleware
|
| 7 |
from pydantic import BaseModel
|
| 8 |
from typing import List, Dict, Any
|
| 9 |
-
import io
|
| 10 |
|
| 11 |
from model_loader import get_model_loader
|
| 12 |
from preprocessing import get_preprocessor
|
|
@@ -28,7 +29,7 @@ app.add_middleware(
|
|
| 28 |
allow_headers=["*"],
|
| 29 |
)
|
| 30 |
|
| 31 |
-
# Response models
|
| 32 |
class ClassPrediction(BaseModel):
|
| 33 |
class_index: int
|
| 34 |
class_label: str
|
|
@@ -42,45 +43,16 @@ class PredictionResponse(BaseModel):
|
|
| 42 |
inference_time_ms: float
|
| 43 |
image_info: Dict[str, Any]
|
| 44 |
|
|
|
|
|
|
|
|
|
|
| 45 |
# Constants
|
| 46 |
VALID_IMAGE_FORMATS = {"image/jpeg", "image/png", "image/jpg"}
|
| 47 |
MAX_IMAGE_SIZE = 10 * 1024 * 1024 # 10MB
|
| 48 |
CONFIDENCE_THRESHOLD = 0.5
|
| 49 |
|
| 50 |
-
def
|
| 51 |
-
"""
|
| 52 |
-
if file.content_type not in VALID_IMAGE_FORMATS:
|
| 53 |
-
raise HTTPException(
|
| 54 |
-
status_code=400,
|
| 55 |
-
detail=f"Invalid image format. Supported: JPEG, PNG. Got: {file.content_type}"
|
| 56 |
-
)
|
| 57 |
-
|
| 58 |
-
content = file.file.read()
|
| 59 |
-
if len(content) > MAX_IMAGE_SIZE:
|
| 60 |
-
raise HTTPException(
|
| 61 |
-
status_code=413,
|
| 62 |
-
detail=f"Image too large. Max size: {MAX_IMAGE_SIZE / 1024 / 1024}MB"
|
| 63 |
-
)
|
| 64 |
-
return content
|
| 65 |
-
|
| 66 |
-
@app.get("/")
|
| 67 |
-
async def root():
|
| 68 |
-
return {"status": "ok", "message": "AMSI-Net API is running"}
|
| 69 |
-
|
| 70 |
-
@app.get("/health")
|
| 71 |
-
async def health():
|
| 72 |
-
loader = get_model_loader()
|
| 73 |
-
return {
|
| 74 |
-
"status": "healthy",
|
| 75 |
-
"device": str(loader.get_device()),
|
| 76 |
-
"model_loaded": loader.model is not None
|
| 77 |
-
}
|
| 78 |
-
|
| 79 |
-
@app.post("/predict", response_model=PredictionResponse)
|
| 80 |
-
async def predict(file: UploadFile = File(...)):
|
| 81 |
-
"""Predict LULC classes for uploaded image."""
|
| 82 |
-
image_bytes = validate_image(file)
|
| 83 |
-
|
| 84 |
try:
|
| 85 |
preprocessor = get_preprocessor()
|
| 86 |
loader = get_model_loader()
|
|
@@ -138,12 +110,60 @@ async def predict(file: UploadFile = File(...)):
|
|
| 138 |
inference_time_ms=inference_time,
|
| 139 |
image_info=image_info
|
| 140 |
)
|
| 141 |
-
|
| 142 |
except Exception as e:
|
| 143 |
import traceback
|
| 144 |
traceback.print_exc()
|
| 145 |
raise HTTPException(status_code=500, detail=str(e))
|
| 146 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
@app.get("/info")
|
| 148 |
async def info():
|
| 149 |
return {
|
|
|
|
| 2 |
|
| 3 |
import torch
|
| 4 |
import time
|
| 5 |
+
import base64
|
| 6 |
+
import io
|
| 7 |
from fastapi import FastAPI, UploadFile, File, HTTPException
|
| 8 |
from fastapi.middleware.cors import CORSMiddleware
|
| 9 |
from pydantic import BaseModel
|
| 10 |
from typing import List, Dict, Any
|
|
|
|
| 11 |
|
| 12 |
from model_loader import get_model_loader
|
| 13 |
from preprocessing import get_preprocessor
|
|
|
|
| 29 |
allow_headers=["*"],
|
| 30 |
)
|
| 31 |
|
| 32 |
+
# Request/Response models
|
| 33 |
class ClassPrediction(BaseModel):
|
| 34 |
class_index: int
|
| 35 |
class_label: str
|
|
|
|
| 43 |
inference_time_ms: float
|
| 44 |
image_info: Dict[str, Any]
|
| 45 |
|
| 46 |
+
class MobileRequest(BaseModel):
|
| 47 |
+
image: str # Base64 string
|
| 48 |
+
|
| 49 |
# Constants
|
| 50 |
VALID_IMAGE_FORMATS = {"image/jpeg", "image/png", "image/jpg"}
|
| 51 |
MAX_IMAGE_SIZE = 10 * 1024 * 1024 # 10MB
|
| 52 |
CONFIDENCE_THRESHOLD = 0.5
|
| 53 |
|
| 54 |
+
def run_inference(image_bytes: bytes) -> PredictionResponse:
|
| 55 |
+
"""Core inference logic reused across endpoints."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
try:
|
| 57 |
preprocessor = get_preprocessor()
|
| 58 |
loader = get_model_loader()
|
|
|
|
| 110 |
inference_time_ms=inference_time,
|
| 111 |
image_info=image_info
|
| 112 |
)
|
|
|
|
| 113 |
except Exception as e:
|
| 114 |
import traceback
|
| 115 |
traceback.print_exc()
|
| 116 |
raise HTTPException(status_code=500, detail=str(e))
|
| 117 |
|
| 118 |
+
def validate_image(file: UploadFile) -> bytes:
|
| 119 |
+
"""Validate and read image file."""
|
| 120 |
+
if file.content_type not in VALID_IMAGE_FORMATS:
|
| 121 |
+
raise HTTPException(
|
| 122 |
+
status_code=400,
|
| 123 |
+
detail=f"Invalid image format. Supported: JPEG, PNG. Got: {file.content_type}"
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
content = file.file.read()
|
| 127 |
+
if len(content) > MAX_IMAGE_SIZE:
|
| 128 |
+
raise HTTPException(
|
| 129 |
+
status_code=413,
|
| 130 |
+
detail=f"Image too large. Max size: {MAX_IMAGE_SIZE / 1024 / 1024}MB"
|
| 131 |
+
)
|
| 132 |
+
return content
|
| 133 |
+
|
| 134 |
+
@app.get("/")
|
| 135 |
+
async def root():
|
| 136 |
+
return {"status": "ok", "message": "AMSI-Net API is running"}
|
| 137 |
+
|
| 138 |
+
@app.get("/health")
|
| 139 |
+
async def health():
|
| 140 |
+
loader = get_model_loader()
|
| 141 |
+
return {
|
| 142 |
+
"status": "healthy",
|
| 143 |
+
"device": str(loader.get_device()),
|
| 144 |
+
"model_loaded": loader.model is not None
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
@app.post("/predict", response_model=PredictionResponse)
|
| 148 |
+
async def predict(file: UploadFile = File(...)):
|
| 149 |
+
"""Standard multipart prediction (Web)."""
|
| 150 |
+
image_bytes = validate_image(file)
|
| 151 |
+
return run_inference(image_bytes)
|
| 152 |
+
|
| 153 |
+
@app.post("/predict_mobile", response_model=PredictionResponse)
|
| 154 |
+
async def predict_mobile(request: MobileRequest):
|
| 155 |
+
"""Base64 prediction (Mobile)."""
|
| 156 |
+
try:
|
| 157 |
+
# Strip potential base64 prefix (e.g. "data:image/jpeg;base64,")
|
| 158 |
+
base64_str = request.image
|
| 159 |
+
if "," in base64_str:
|
| 160 |
+
base64_str = base64_str.split(",")[1]
|
| 161 |
+
|
| 162 |
+
image_bytes = base64.b64decode(base64_str)
|
| 163 |
+
return run_inference(image_bytes)
|
| 164 |
+
except Exception as e:
|
| 165 |
+
raise HTTPException(status_code=400, detail=f"Invalid base64 image data: {str(e)}")
|
| 166 |
+
|
| 167 |
@app.get("/info")
|
| 168 |
async def info():
|
| 169 |
return {
|