Spaces:
Sleeping
Sleeping
Deploy latest YOLO model and app (version 20250422.7)
Browse files
app.py
CHANGED
@@ -2,11 +2,9 @@ import gradio as gr
|
|
2 |
from PIL import Image
|
3 |
from pathlib import Path
|
4 |
import numpy as np
|
5 |
-
import torch
|
6 |
from ultralytics import YOLO
|
7 |
-
import os
|
8 |
|
9 |
-
MODEL_WEIGHTS_PATH = Path("weights/best.pt")
|
10 |
VERSION_PATH = Path("VERSION")
|
11 |
|
12 |
# Read version string from VERSION file
|
@@ -15,9 +13,11 @@ try:
|
|
15 |
except Exception:
|
16 |
VERSION = "unknown"
|
17 |
|
18 |
-
# Lazy-load model (singleton)
|
19 |
model = None
|
20 |
-
def get_model():
|
|
|
|
|
|
|
21 |
global model
|
22 |
if model is None:
|
23 |
if not MODEL_WEIGHTS_PATH.exists():
|
@@ -25,19 +25,20 @@ def get_model():
|
|
25 |
model = YOLO(str(MODEL_WEIGHTS_PATH))
|
26 |
return model
|
27 |
|
28 |
-
def segment(image: Image.Image):
|
|
|
|
|
|
|
29 |
model = get_model()
|
30 |
img_np = np.array(image)
|
31 |
-
# Run prediction
|
32 |
results = model(img_np)
|
33 |
if not results or not hasattr(results[0], "masks") or results[0].masks is None:
|
34 |
-
mask_img = Image.new("L", image.size, 0)
|
35 |
else:
|
36 |
-
mask = results[0].masks.data[0].cpu().numpy()
|
37 |
mask_img = Image.fromarray((mask * 255).astype(np.uint8))
|
38 |
-
mask_img = mask_img.resize(image.size)
|
39 |
-
|
40 |
-
return mask_img, VERSION # Return as tuple for Gradio
|
41 |
|
42 |
iface = gr.Interface(
|
43 |
fn=segment,
|
|
|
2 |
from PIL import Image
|
3 |
from pathlib import Path
|
4 |
import numpy as np
|
|
|
5 |
from ultralytics import YOLO
|
|
|
6 |
|
7 |
+
MODEL_WEIGHTS_PATH = Path("weights/best.pt")
|
8 |
VERSION_PATH = Path("VERSION")
|
9 |
|
10 |
# Read version string from VERSION file
|
|
|
13 |
except Exception:
|
14 |
VERSION = "unknown"
|
15 |
|
|
|
16 |
model = None
|
17 |
+
def get_model() -> YOLO:
|
18 |
+
"""
|
19 |
+
Returns the YOLO model instance.
|
20 |
+
"""
|
21 |
global model
|
22 |
if model is None:
|
23 |
if not MODEL_WEIGHTS_PATH.exists():
|
|
|
25 |
model = YOLO(str(MODEL_WEIGHTS_PATH))
|
26 |
return model
|
27 |
|
28 |
+
def segment(image: Image.Image) -> tuple[Image.Image, str]:
|
29 |
+
"""
|
30 |
+
Returns a tuple: (segmentation mask PIL.Image, model version string)
|
31 |
+
"""
|
32 |
model = get_model()
|
33 |
img_np = np.array(image)
|
|
|
34 |
results = model(img_np)
|
35 |
if not results or not hasattr(results[0], "masks") or results[0].masks is None:
|
36 |
+
mask_img = Image.new("L", image.size, 0)
|
37 |
else:
|
38 |
+
mask = results[0].masks.data[0].cpu().numpy()
|
39 |
mask_img = Image.fromarray((mask * 255).astype(np.uint8))
|
40 |
+
mask_img = mask_img.resize(image.size)
|
41 |
+
return mask_img, str(VERSION)
|
|
|
42 |
|
43 |
iface = gr.Interface(
|
44 |
fn=segment,
|