not0w4i5 commited on
Commit
bfe3904
·
verified ·
1 Parent(s): c3c004d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -0
app.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from ultralytics import YOLO
3
+ from PIL import Image
4
+ import tempfile
5
+ import os
6
+
7
+ def detect(weights_file, image_file, conf_threshold):
8
+ if weights_file is None or image_file is None:
9
+ return None, "Please upload both a .pt weights file and an image."
10
+
11
+ # Save uploaded weights to a temp path
12
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pt") as tmp_w:
13
+ tmp_w.write(weights_file.read())
14
+ weights_path = tmp_w.name
15
+
16
+ # Load model from uploaded weights
17
+ model = YOLO(weights_path)
18
+
19
+ # Load input image as PIL
20
+ if isinstance(image_file, str):
21
+ img = Image.open(image_file).convert("RGB")
22
+ else:
23
+ img = Image.open(image_file).convert("RGB")
24
+
25
+ # Run prediction; return annotated image
26
+ results = model.predict(
27
+ source=img,
28
+ conf=conf_threshold,
29
+ imgsz=640,
30
+ verbose=False,
31
+ )
32
+ r = results[0]
33
+ annotated = r.plot() # numpy array BGR
34
+ annotated_pil = Image.fromarray(annotated[:, :, ::-1]) # BGR -> RGB
35
+
36
+ return (img, annotated_pil), f"Detections done with {os.path.basename(weights_file.name)}"
37
+
38
+ # Gradio UI
39
+ with gr.Blocks() as demo:
40
+ gr.Markdown("# YOLOv8 Viewer\nUpload a YOLO `.pt` weights file and an image. The app will show original and detections side by side.")
41
+
42
+ with gr.Row():
43
+ weights_input = gr.File(
44
+ label="YOLO weights (.pt)",
45
+ file_types=[".pt"],
46
+ type="binary",
47
+ )
48
+ conf_slider = gr.Slider(
49
+ minimum=0.1,
50
+ maximum=0.9,
51
+ value=0.25,
52
+ step=0.05,
53
+ label="Confidence threshold",
54
+ )
55
+
56
+ image_input = gr.Image(type="filepath", label="Input image")
57
+
58
+ gallery = gr.Gallery(
59
+ label="Original (left) vs Detections (right)",
60
+ columns=2,
61
+ height=512,
62
+ )
63
+ status = gr.Textbox(label="Status / Info", interactive=False)
64
+
65
+ run_btn = gr.Button("Run detection")
66
+
67
+ run_btn.click(
68
+ fn=detect,
69
+ inputs=[weights_input, image_input, conf_slider],
70
+ outputs=[gallery, status],
71
+ )
72
+
73
+ if __name__ == "__main__":
74
+ demo.launch()