Spaces:
Sleeping
Sleeping
Download app.py from taher-dev/litter-detection: direct link, hf CLI and curl.
- Browser
- Download file 1.93 kB
-
https://huggingface.co/spaces/taher-dev/litter-detection/resolve/main/app.py
- Command line
-
hf download hf://spaces/taher-dev/litter-detection/app.py
-
curl -L -o app.py https://huggingface.co/spaces/taher-dev/litter-detection/resolve/main/app.py
1.93 kB
| # 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() | |