Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,23 +1,25 @@
|
|
| 1 |
from fastapi import FastAPI, UploadFile, File
|
|
|
|
|
|
|
| 2 |
from ultralytics import YOLO
|
| 3 |
from PIL import Image
|
| 4 |
import io
|
| 5 |
-
import torch
|
| 6 |
|
| 7 |
app = FastAPI(title="YOLO API - Football Model")
|
| 8 |
|
| 9 |
-
# Load model
|
| 10 |
try:
|
| 11 |
model = YOLO("best.pt")
|
| 12 |
-
print("✅ Loaded best.pt
|
| 13 |
-
except
|
| 14 |
-
print("⚠️ best.pt not found, trying last.pt:", e)
|
| 15 |
model = YOLO("last.pt")
|
|
|
|
| 16 |
|
| 17 |
@app.get("/")
|
| 18 |
def home():
|
| 19 |
return {"message": "YOLO Football Model API is running!"}
|
| 20 |
|
|
|
|
| 21 |
@app.post("/predict")
|
| 22 |
async def predict(file: UploadFile = File(...)):
|
| 23 |
contents = await file.read()
|
|
@@ -26,6 +28,7 @@ async def predict(file: UploadFile = File(...)):
|
|
| 26 |
# Run inference
|
| 27 |
results = model(image)
|
| 28 |
|
|
|
|
| 29 |
detections = []
|
| 30 |
for box in results[0].boxes:
|
| 31 |
detections.append({
|
|
@@ -34,4 +37,18 @@ async def predict(file: UploadFile = File(...)):
|
|
| 34 |
"bbox": box.xyxy[0].tolist()
|
| 35 |
})
|
| 36 |
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from fastapi import FastAPI, UploadFile, File
|
| 2 |
+
from fastapi.responses import JSONResponse
|
| 3 |
+
from fastapi.responses import StreamingResponse
|
| 4 |
from ultralytics import YOLO
|
| 5 |
from PIL import Image
|
| 6 |
import io
|
|
|
|
| 7 |
|
| 8 |
app = FastAPI(title="YOLO API - Football Model")
|
| 9 |
|
| 10 |
+
# Load model
|
| 11 |
try:
|
| 12 |
model = YOLO("best.pt")
|
| 13 |
+
print("✅ Loaded best.pt")
|
| 14 |
+
except:
|
|
|
|
| 15 |
model = YOLO("last.pt")
|
| 16 |
+
print("⚠️ Loaded last.pt")
|
| 17 |
|
| 18 |
@app.get("/")
|
| 19 |
def home():
|
| 20 |
return {"message": "YOLO Football Model API is running!"}
|
| 21 |
|
| 22 |
+
|
| 23 |
@app.post("/predict")
|
| 24 |
async def predict(file: UploadFile = File(...)):
|
| 25 |
contents = await file.read()
|
|
|
|
| 28 |
# Run inference
|
| 29 |
results = model(image)
|
| 30 |
|
| 31 |
+
# Get JSON detections
|
| 32 |
detections = []
|
| 33 |
for box in results[0].boxes:
|
| 34 |
detections.append({
|
|
|
|
| 37 |
"bbox": box.xyxy[0].tolist()
|
| 38 |
})
|
| 39 |
|
| 40 |
+
# Save image with bounding boxes drawn by YOLO
|
| 41 |
+
annotated_image = results[0].plot() # numpy array (BGR)
|
| 42 |
+
annotated_image = Image.fromarray(annotated_image[..., ::-1]) # convert BGR→RGB
|
| 43 |
+
|
| 44 |
+
# Convert to bytes for response
|
| 45 |
+
img_bytes = io.BytesIO()
|
| 46 |
+
annotated_image.save(img_bytes, format="JPEG")
|
| 47 |
+
img_bytes.seek(0)
|
| 48 |
+
|
| 49 |
+
# Return both JSON and image
|
| 50 |
+
return StreamingResponse(
|
| 51 |
+
img_bytes,
|
| 52 |
+
media_type="image/jpeg",
|
| 53 |
+
headers={"detections": str(detections)}
|
| 54 |
+
)
|