Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,27 +6,27 @@ model = YOLO("best.pt")
|
|
| 6 |
|
| 7 |
def predict(img):
|
| 8 |
results = model(img)
|
| 9 |
-
# This draws the boxes and labels on the image
|
| 10 |
annotated_img = results[0].plot()
|
| 11 |
|
| 12 |
-
# Extract the labels and confidences to send back as data
|
| 13 |
detections = []
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
-
# We now return BOTH the image and a JSON string containing the detection data
|
| 24 |
return annotated_img, json.dumps(detections)
|
| 25 |
|
| 26 |
demo = gr.Interface(
|
| 27 |
fn=predict,
|
| 28 |
inputs=gr.Image(type="pil"),
|
| 29 |
-
# Update the outputs to expect both an Image and a Textbox (for our JSON)
|
| 30 |
outputs=[
|
| 31 |
gr.Image(type="pil"),
|
| 32 |
gr.Textbox(label="Detections")
|
|
|
|
| 6 |
|
| 7 |
def predict(img):
|
| 8 |
results = model(img)
|
|
|
|
| 9 |
annotated_img = results[0].plot()
|
| 10 |
|
|
|
|
| 11 |
detections = []
|
| 12 |
+
# Safely extract boxes if they exist
|
| 13 |
+
if len(results) > 0 and len(results[0].boxes) > 0:
|
| 14 |
+
for box in results[0].boxes:
|
| 15 |
+
# Use .item() to safely convert PyTorch tensors to standard Python numbers
|
| 16 |
+
class_id = int(box.cls.item())
|
| 17 |
+
label = model.names[class_id]
|
| 18 |
+
conf = float(box.conf.item())
|
| 19 |
+
|
| 20 |
+
detections.append({
|
| 21 |
+
"label": label,
|
| 22 |
+
"confidence": conf
|
| 23 |
+
})
|
| 24 |
|
|
|
|
| 25 |
return annotated_img, json.dumps(detections)
|
| 26 |
|
| 27 |
demo = gr.Interface(
|
| 28 |
fn=predict,
|
| 29 |
inputs=gr.Image(type="pil"),
|
|
|
|
| 30 |
outputs=[
|
| 31 |
gr.Image(type="pil"),
|
| 32 |
gr.Textbox(label="Detections")
|