Hassan73's picture
Upload 4 files
f954b8c verified
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import HTMLResponse
from ultralytics import YOLO
import uvicorn
import io
from PIL import Image
import numpy as np
app = FastAPI(title="Fire Detection API", description="API for detecting fire and smoke using YOLOv26")
# Load model
model = YOLO("best.pt")
@app.get("/", response_class=HTMLResponse)
def read_root():
return """
<!DOCTYPE html>
<html>
<head>
<title>Fire Detection API</title>
<style>
body { font-family: sans-serif; text-align: center; padding: 50px; background: #f4f4f9; }
.container { background: white; padding: 20px; border-radius: 10px; display: inline-block; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
h1 { color: #d9534f; }
input { margin: 20px 0; }
button { background: #d9534f; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer; }
#result { margin-top: 20px; text-align: left; }
</style>
</head>
<body>
<div class="container">
<h1>🔥 Fire Detection API</h1>
<p>Upload an image to detect fire or smoke</p>
<input type="file" id="imageInput" accept="image/*">
<br>
<button onclick="uploadImage()">Detect</button>
<div id="result"></div>
</div>
<script>
async function uploadImage() {
const input = document.getElementById('imageInput');
if (!input.files[0]) return alert('Please select an image');
const formData = new FormData();
formData.append('file', input.files[0]);
const resultDiv = document.getElementById('result');
resultDiv.innerHTML = 'Detecting...';
try {
const response = await fetch('/predict', { method: 'POST', body: formData });
const data = await response.json();
resultDiv.innerHTML = '<pre>' + JSON.stringify(data, null, 2) + '</pre>';
} catch (e) {
resultDiv.innerHTML = 'Error: ' + e.message;
}
}
</script>
</body>
</html>
"""
@app.post("/predict")
async def predict(file: UploadFile = File(...)):
# Read image
contents = await file.read()
image = Image.open(io.BytesIO(contents)).convert("RGB")
# Run inference
results = model.predict(image, conf=0.25)
detections = []
for result in results:
for box in result.boxes:
detection = {
"class": model.names[int(box.cls[0])],
"confidence": float(box.conf[0]),
"bbox": [float(x) for x in box.xyxy[0]] # [x1, y1, x2, y2]
}
detections.append(detection)
return {"detections": detections}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860)