Nonabzbssbbsbs commited on
Commit
4cad02c
·
verified ·
1 Parent(s): 0bf5a02

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +138 -0
app.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from ultralytics import YOLO
3
+ import cv2
4
+ import numpy as np
5
+ from PIL import Image
6
+ import torch
7
+ import os
8
+
9
+ # Моделді жүктеу
10
+ model = None
11
+
12
+ def load_model(model_path="best.pt"):
13
+ """Моделді жүктеу функциясы"""
14
+ global model
15
+ try:
16
+ # Егер best.pt болмаса, pretrained модельді жүктеу
17
+ if not os.path.exists(model_path):
18
+ print(f"⚠️ {model_path} табылмады. Pretrained модельді жүктеу...")
19
+ model_path = "yolov8n-seg.pt" # Автоматты жүктеледі
20
+
21
+ model = YOLO(model_path)
22
+ return f"✅ Модель сәтті жүктелді: {model_path}"
23
+ except Exception as e:
24
+ return f"❌ Қате: {str(e)}"
25
+
26
+ def predict_image(image, conf_threshold=0.25, iou_threshold=0.45):
27
+ """Суретті талдау және сегментация жасау"""
28
+ if model is None:
29
+ return None, "❌ Модель жүктелмеген!"
30
+
31
+ if image is None:
32
+ return None, "❌ Сурет жүктелмеді!"
33
+
34
+ try:
35
+ # Болжам жасау
36
+ results = model.predict(
37
+ source=image,
38
+ conf=conf_threshold,
39
+ iou=iou_threshold,
40
+ save=False
41
+ )
42
+
43
+ # Нәтижені визуализациялау
44
+ annotated_img = results[0].plot()
45
+ annotated_img = cv2.cvtColor(annotated_img, cv2.COLOR_BGR2RGB)
46
+
47
+ # Анықталған объектілер туралы ақпарат
48
+ detections = []
49
+ if results[0].masks is not None:
50
+ for i, (box, mask) in enumerate(zip(results[0].boxes, results[0].masks)):
51
+ class_id = int(box.cls[0])
52
+ confidence = float(box.conf[0])
53
+ class_name = model.names[class_id]
54
+ detections.append(f"{i+1}. {class_name}: {confidence:.2%}")
55
+
56
+ info_text = "\n".join(detections) if detections else "ℹ️ Объектілер табылмады"
57
+
58
+ return annotated_img, info_text
59
+
60
+ except Exception as e:
61
+ return None, f"❌ Қате: {str(e)}"
62
+
63
+ # Gradio интерфейсі
64
+ def create_interface():
65
+ with gr.Blocks(title="YOLOv8 Қазақша Сегментация", theme=gr.themes.Soft()) as demo:
66
+ gr.Markdown("""
67
+ # 🎯 YOLOv8 Сегментация - Қазақша
68
+
69
+ Бұл модель объектілерді анықтап, сегментациялайды.
70
+ Суретті жүктеп, параметрлерді орнатыңыз.
71
+
72
+ > ⚠️ **Назар:** Егер өз модельіңіз болса, `best.pt` файлын жүктеңіз.
73
+ > Әйтпесе, COCO dataset pretrained моделі қолданылады.
74
+ """)
75
+
76
+ with gr.Row():
77
+ with gr.Column():
78
+ input_image = gr.Image(
79
+ label="📸 Суретті жүктеңіз",
80
+ type="numpy"
81
+ )
82
+
83
+ conf_slider = gr.Slider(
84
+ minimum=0.1,
85
+ maximum=1.0,
86
+ value=0.25,
87
+ step=0.05,
88
+ label="🎯 Сенімділік табалдырығы (Confidence)"
89
+ )
90
+
91
+ iou_slider = gr.Slider(
92
+ minimum=0.1,
93
+ maximum=1.0,
94
+ value=0.45,
95
+ step=0.05,
96
+ label="📊 IoU табалдырығы"
97
+ )
98
+
99
+ predict_btn = gr.Button("🔍 Талдау", variant="primary", size="lg")
100
+
101
+ with gr.Column():
102
+ output_image = gr.Image(
103
+ label="✨ Нәтиже"
104
+ )
105
+ output_text = gr.Textbox(
106
+ label="📋 Анықталған объектілер",
107
+ lines=10
108
+ )
109
+
110
+ gr.Markdown("""
111
+ ### 📝 Нұсқаулық:
112
+ 1. Суретті жүктеңіз
113
+ 2. Қажет болса параметрлерді өзгертіңіз
114
+ 3. "Талдау" батырмасын басыңыз
115
+
116
+ ### ⚙️ Параметрлер:
117
+ - **Сенімділік табалдырығы**: Объектіді қабылдау үшін минималды сенімділік
118
+ - **IoU табалдырығы**: Non-maximum suppression үшін қолданылады
119
+
120
+ ### 🏷️ Анықталатын объектілер:
121
+ person (адам), car (машина), dog (ит), cat (мысық), bicycle (велосипед), т.б.
122
+ """)
123
+
124
+ predict_btn.click(
125
+ fn=predict_image,
126
+ inputs=[input_image, conf_slider, iou_slider],
127
+ outputs=[output_image, output_text]
128
+ )
129
+
130
+ return demo
131
+
132
+ # Моделді жүктеу
133
+ print(load_model())
134
+
135
+ # Интерфейсті іске қосу
136
+ if __name__ == "__main__":
137
+ demo = create_interface()
138
+ demo.launch()