Spaces:
Sleeping
Sleeping
File size: 1,925 Bytes
8025f62 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | # app.py
import os
import cv2
import gradio as gr
import numpy as np
from ultralytics import YOLO
from huggingface_hub import hf_hub_download
os.environ.setdefault("YOLO_CONFIG_DIR", "/tmp/Ultralytics")
# ---------------- CONFIG ----------------
MODEL_REPO = "taher-dev/litter-detection"
MODEL_FILENAME = "best.pt"
LOCAL_MODEL = MODEL_FILENAME
# ----------------------------------------
def download_model_if_missing():
if os.path.exists(LOCAL_MODEL):
return LOCAL_MODEL
return hf_hub_download(
repo_id=MODEL_REPO,
filename=MODEL_FILENAME,
repo_type="model",
token=os.environ.get("HF_TOKEN")
)
MODEL_PATH = download_model_if_missing()
model = YOLO(MODEL_PATH)
def detect(image, conf=0.25):
if image is None:
return None
results = model.predict(image, conf=conf, verbose=False)[0]
img = image.copy()
if results.boxes is not None:
boxes = results.boxes.xyxy.cpu().numpy()
scores = results.boxes.conf.cpu().numpy()
classes = results.boxes.cls.cpu().numpy().astype(int)
for (x1, y1, x2, y2), s, c in zip(boxes, scores, classes):
x1, y1, x2, y2 = map(int, [x1, y1, x2, y2])
label = f"{model.names[c]} {s:.2f}"
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(img, label, (x1, y1 - 8),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
return img
demo = gr.Interface(
fn=detect,
inputs=[
gr.Image(type="numpy", label="Upload Image"),
gr.Slider(0.05, 0.9, value=0.25, step=0.01, label="Confidence Threshold")
],
outputs=gr.Image(type="numpy", label="Detected Litter"),
title="Litter Detection (YOLOv8)",
description="Detect roadside litter using a custom YOLOv8 model."
)
if __name__ == "__main__":
demo.launch()
|