Spaces:
Sleeping
Sleeping
Download app.py from moniljoseph/mojo: direct link, hf CLI and curl.
- Browser
- Download file 2.03 kB
-
https://huggingface.co/spaces/moniljoseph/mojo/resolve/main/app.py
- Command line
-
hf download hf://spaces/moniljoseph/mojo/app.py
-
curl -L -o app.py https://huggingface.co/spaces/moniljoseph/mojo/resolve/main/app.py
2.03 kB
| import gradio as gr | |
| from ultralytics import YOLO | |
| from PIL import Image | |
| import numpy as np | |
| # ===================================== | |
| # LOAD MODEL | |
| # ===================================== | |
| MODEL_PATH = "best.pt" | |
| model = YOLO(MODEL_PATH) | |
| CLASS_NAMES = model.names # {0: 'paregi', 1: 'pelise'} | |
| IMG_SIZE = 640 | |
| CONF_THRESH = 0.15 | |
| print("✅ YOLOv8 model loaded") | |
| # ===================================== | |
| # PREDICTION FUNCTION | |
| # ===================================== | |
| def predict(image: Image.Image): | |
| if image is None: | |
| return {"error": "No image provided"} | |
| # Run inference | |
| results = model.predict( | |
| source=image, | |
| imgsz=IMG_SIZE, | |
| conf=CONF_THRESH, | |
| verbose=False | |
| ) | |
| r = results[0] | |
| if len(r.boxes) == 0: | |
| return { | |
| "prediction": "no_object_detected", | |
| "confidence": 0.0, | |
| "probabilities": { | |
| CLASS_NAMES[0]: 0.0, | |
| CLASS_NAMES[1]: 0.0 | |
| } | |
| } | |
| # Pick highest-confidence detection | |
| idx = r.boxes.conf.argmax() | |
| cls_id = int(r.boxes.cls[idx]) | |
| conf = float(r.boxes.conf[idx]) | |
| probs = { | |
| CLASS_NAMES[0]: 0.0, | |
| CLASS_NAMES[1]: 0.0 | |
| } | |
| probs[CLASS_NAMES[cls_id]] = conf | |
| return { | |
| "prediction": CLASS_NAMES[cls_id], | |
| "confidence": round(conf, 4), | |
| "probabilities": probs | |
| } | |
| # ===================================== | |
| # GRADIO UI | |
| # ===================================== | |
| app = gr.Interface( | |
| fn=predict, | |
| inputs=gr.Image(type="pil", label="Upload O-Ring Image"), | |
| outputs=gr.JSON(label="Prediction"), | |
| title="ann2ann – Paregi / Pelise Detection", | |
| description=( | |
| "YOLOv8 model trained to classify O-ring defects.\n\n" | |
| "Classes:\n" | |
| "- paregi\n" | |
| "- pelise\n\n" | |
| "Input images are resized to 640×640 automatically." | |
| ), | |
| examples=None | |
| ) | |
| # ===================================== | |
| # LAUNCH | |
| # ===================================== | |
| if __name__ == "__main__": | |
| app.launch() |