Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,22 +1,38 @@
|
|
1 |
-
from fastapi import FastAPI,
|
2 |
-
from
|
3 |
-
from PIL import Image
|
4 |
import torch
|
5 |
-
import
|
|
|
|
|
|
|
6 |
|
7 |
app = FastAPI()
|
8 |
|
9 |
-
# Load the YOLOv5 model and processor from Hugging Face
|
10 |
-
model = YolosForObjectDetection.from_pretrained('ultralytics/yolov5')
|
11 |
-
processor = YolosImageProcessor.from_pretrained('ultralytics/yolov5')
|
12 |
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
13 |
-
model.to(device)
|
14 |
model.eval()
|
15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
@app.post("/predict/")
|
17 |
async def predict(file: UploadFile = File(...)):
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
outputs =
|
22 |
-
|
|
|
|
1 |
+
from fastapi import FastAPI, File, UploadFile
|
2 |
+
from fastapi.responses import JSONResponse
|
|
|
3 |
import torch
|
4 |
+
from PIL import Image
|
5 |
+
from torchvision.transforms import functional as F
|
6 |
+
from yolov5.models.yolo import Model
|
7 |
+
from yolov5.utils.general import non_max_suppression
|
8 |
|
9 |
app = FastAPI()
|
10 |
|
|
|
|
|
|
|
11 |
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
12 |
+
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True).to(device)
|
13 |
model.eval()
|
14 |
|
15 |
+
def preprocess_image(image):
|
16 |
+
image_tensor = F.to_tensor(image)
|
17 |
+
return image_tensor.unsqueeze(0).to(device)
|
18 |
+
|
19 |
+
def draw_boxes(outputs, threshold=0.3):
|
20 |
+
boxes = []
|
21 |
+
for box in outputs:
|
22 |
+
score, label, x1, y1, x2, y2 = box[4].item(), int(box[5].item()), box[0].item(), box[1].item(), box[2].item(), box[3].item()
|
23 |
+
if score > threshold:
|
24 |
+
boxes.append({
|
25 |
+
"label": model.names[label],
|
26 |
+
"score": score,
|
27 |
+
"box": [x1, y1, x2, y2]
|
28 |
+
})
|
29 |
+
return boxes
|
30 |
+
|
31 |
@app.post("/predict/")
|
32 |
async def predict(file: UploadFile = File(...)):
|
33 |
+
image = Image.open(file.file)
|
34 |
+
image_tensor = preprocess_image(image)
|
35 |
+
outputs = model(image_tensor)
|
36 |
+
outputs = non_max_suppression(outputs)[0]
|
37 |
+
boxes = draw_boxes(outputs)
|
38 |
+
return JSONResponse(content={"boxes": boxes})
|