Spaces:
Runtime error
Runtime error
Commit
•
c541fae
1
Parent(s):
eef2251
Added object detection model
Browse files- app.py +37 -1
- models.py +0 -0
- requirements.txt +5 -0
app.py
CHANGED
@@ -1,8 +1,44 @@
|
|
1 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
app = FastAPI(docs_url='/', title='Test PyTorch COCO Object Detection')
|
4 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
@app.get('/healthcheck')
|
7 |
async def healthcheck():
|
8 |
return Response(status_code=status.HTTP_200_OK)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from io import BytesIO
|
2 |
+
|
3 |
+
from fastapi import FastAPI, Response, status, UploadFile
|
4 |
+
from torchvision.io import read_image
|
5 |
+
from torchvision.models.detection import (FasterRCNN_ResNet50_FPN_V2_Weights,
|
6 |
+
fasterrcnn_resnet50_fpn_v2)
|
7 |
+
from torchvision.transforms.v2.functional import to_pil_image
|
8 |
+
from torchvision.utils import draw_bounding_boxes
|
9 |
+
from PIL import Image
|
10 |
|
11 |
app = FastAPI(docs_url='/', title='Test PyTorch COCO Object Detection')
|
12 |
|
13 |
+
# Step 1: Initialize model with the best available weights
|
14 |
+
weights = FasterRCNN_ResNet50_FPN_V2_Weights.DEFAULT
|
15 |
+
model = fasterrcnn_resnet50_fpn_v2(weights=weights, box_score_thresh=0.9)
|
16 |
+
model.eval()
|
17 |
+
|
18 |
+
# Step 2: Initialize the inference transforms
|
19 |
+
preprocess = weights.transforms()
|
20 |
+
|
21 |
|
22 |
@app.get('/healthcheck')
|
23 |
async def healthcheck():
|
24 |
return Response(status_code=status.HTTP_200_OK)
|
25 |
+
|
26 |
+
|
27 |
+
@app.post('/detectObjectsFromURL')
|
28 |
+
async def infer(image: UploadFile):
|
29 |
+
img = read_image(image.filename)
|
30 |
+
|
31 |
+
batch = [preprocess(img)]
|
32 |
+
|
33 |
+
# Step 4: Use the model and visualize the prediction
|
34 |
+
prediction = model(batch)[0]
|
35 |
+
labels = [weights.meta["categories"][i] for i in prediction["labels"]]
|
36 |
+
box = draw_bounding_boxes(img, boxes=prediction["boxes"],
|
37 |
+
labels=labels,
|
38 |
+
colors="red",
|
39 |
+
width=4, font_size=30)
|
40 |
+
im: Image.Image
|
41 |
+
im = to_pil_image(box.detach())
|
42 |
+
with BytesIO() as bio:
|
43 |
+
im.save(bio, format='PNG')
|
44 |
+
return Response(content=bio.getvalue(), media_type='image/png')
|
models.py
ADDED
File without changes
|
requirements.txt
CHANGED
@@ -1,2 +1,7 @@
|
|
1 |
fastapi
|
2 |
uvicorn
|
|
|
|
|
|
|
|
|
|
|
|
1 |
fastapi
|
2 |
uvicorn
|
3 |
+
torch
|
4 |
+
torchvision
|
5 |
+
python-multipart
|
6 |
+
pydantic
|
7 |
+
pillow
|