Spaces:
Sleeping
Sleeping
File size: 6,571 Bytes
eef8873 | 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 | import os
import uuid
import shutil
import logging
from contextlib import asynccontextmanager
from PIL import Image
from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from dotenv import load_dotenv
from scripts.gradcam import get_resnet_gradcam, get_fusion_gradcam
from scripts.yolo_predict import get_yolo_damage_boxes
from scripts.load_models import initialize_models
# ---------------- LOGGING ----------------
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"
)
logger = logging.getLogger(__name__)
# ---------------- ENV ----------------
load_dotenv()
# ---------------- DIRECTORIES ----------------
UPLOAD_DIR = "static/uploads"
RESULT_DIR = "static/results"
os.makedirs(UPLOAD_DIR, exist_ok=True)
os.makedirs(RESULT_DIR, exist_ok=True)
# ---------------- GLOBAL MODELS ----------------
resnet_predictor = None
fusion_predictor = None
yolo_model = None
CLASS_MAP = {
0: "Front Breakage",
1: "Front Crushed",
2: "Front Normal",
3: "Rear Breakage",
4: "Rear Crushed",
5: "Rear Normal"
}
# ---------------- FASTAPI STARTUP ----------------
@asynccontextmanager
async def lifespan(app: FastAPI):
global resnet_predictor, fusion_predictor, yolo_model
logger.info("Loading models at startup...")
try:
resnet_predictor, fusion_predictor, yolo_model = initialize_models(CLASS_MAP)
logger.info("All models loaded successfully.")
except Exception as e:
logger.exception("Model loading failed.")
raise RuntimeError(str(e))
yield
logger.info("Application shutdown.")
# ---------------- APP ----------------
app = FastAPI(lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # restrict this in production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.mount("/static", StaticFiles(directory="static"), name="static")
# ---------------- HELPERS ----------------
def validate_image(upload_file: UploadFile):
if not upload_file.content_type.startswith("image/"):
raise HTTPException(
status_code=400,
detail="Uploaded file must be an image."
)
def save_upload(upload_file: UploadFile):
unique_id = str(uuid.uuid4())
filename = f"{unique_id}_input.jpg"
file_path = os.path.join(UPLOAD_DIR, filename)
with open(file_path, "wb") as buffer:
shutil.copyfileobj(upload_file.file, buffer)
return unique_id, filename, file_path
# ---------------- ROUTES ----------------
@app.get("/")
def api_status():
return {"status": "API is running"}
@app.post("/predict")
async def predict_and_generate_cams(
file: UploadFile = File(...),
mode: str = "resnet"
):
validate_image(file)
mode = mode.lower()
if mode not in {"resnet", "fusion"}:
raise HTTPException(
status_code=400,
detail="mode must be 'resnet' or 'fusion'"
)
try:
unique_id, input_filename, input_path = save_upload(file)
if mode == "resnet":
output_name = f"{unique_id}_resnet.jpg"
output_path = os.path.join(RESULT_DIR, output_name)
get_resnet_gradcam(
input_path,
resnet_predictor,
output_path
)
selected_viz = f"/static/results/{output_name}"
return {
"status": "success",
"mode": mode,
"original_image": f"/static/uploads/{input_filename}",
"selected_viz": selected_viz,
"resnet_viz": selected_viz,
"fusion_viz": None
}
output_name = f"{unique_id}_fusion.jpg"
output_path = os.path.join(RESULT_DIR, output_name)
get_fusion_gradcam(
input_path,
fusion_predictor,
output_path
)
selected_viz = f"/static/results/{output_name}"
return {
"status": "success",
"mode": mode,
"original_image": f"/static/uploads/{input_filename}",
"selected_viz": selected_viz,
"resnet_viz": None,
"fusion_viz": selected_viz
}
except Exception as e:
logger.exception("GradCAM generation failed.")
raise HTTPException(status_code=500, detail=str(e))
@app.post("/predict/resnet")
async def resnet_prediction(image: UploadFile = File(...)):
validate_image(image)
try:
pil_image = Image.open(image.file).convert("RGB")
result = resnet_predictor.resnet_predict(pil_image)
return {
"status": "success",
"prediction": result
}
except Exception as e:
logger.exception("ResNet prediction failed.")
raise HTTPException(status_code=500, detail=str(e))
@app.post("/predict/fusion")
async def fusion_prediction(image: UploadFile = File(...)):
validate_image(image)
try:
pil_image = Image.open(image.file).convert("RGB")
result = fusion_predictor.predict(pil_image)
return {
"status": "success",
"prediction": result
}
except Exception as e:
logger.exception("Fusion prediction failed.")
raise HTTPException(status_code=500, detail=str(e))
@app.post("/predict/yolo")
async def yolo_detection(file: UploadFile = File(...)):
validate_image(file)
try:
unique_id, input_filename, input_path = save_upload(file)
output_name = f"{unique_id}_yolo.jpg"
output_path = os.path.join(RESULT_DIR, output_name)
result = get_yolo_damage_boxes(
input_path,
yolo_model,
output_path
)
return {
"status": "success",
"original_image": f"/static/uploads/{input_filename}",
"yolo_image": f"/static/results/{output_name}",
"detections": result["detections"],
"total_detections": result["total_detections"],
"message": result["message"]
}
except Exception as e:
logger.exception("YOLO detection failed.")
raise HTTPException(status_code=500, detail=str(e)) |