-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathapp.py
More file actions
401 lines (371 loc) · 15.5 KB
/
app.py
File metadata and controls
401 lines (371 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
import streamlit as st
from tabs.dataset_viewer import dataset_viewer_tab
from tabs.inference import inference_tab
from tabs.evaluator import evaluator_tab
from perceptionmetrics.utils.gui import browse_folder
def browse_dataset_path():
st.session_state.dataset_path = browse_folder()
st.set_page_config(page_title="PerceptionMetrics", layout="wide")
PAGES = {
"Dataset Viewer": dataset_viewer_tab,
"Inference": inference_tab,
"Evaluator": evaluator_tab,
}
# Initialize commonly used session state keys
st.session_state.setdefault("dataset_path", "")
st.session_state.setdefault("dataset_type", "YOLO")
st.session_state.setdefault("split", "test")
st.session_state.setdefault("config_option", "Manual Configuration")
st.session_state.setdefault("confidence_threshold", 0.5)
st.session_state.setdefault("nms_threshold", 0.5)
st.session_state.setdefault("max_detections", 100)
st.session_state.setdefault("device", "cuda")
st.session_state.setdefault("batch_size", 1)
st.session_state.setdefault("evaluation_step", 5)
st.session_state.setdefault("detection_model", None)
st.session_state.setdefault("detection_model_loaded", False)
# Sidebar: Dataset Inputs
with st.sidebar:
with st.expander("Dataset Inputs", expanded=True):
# First row: Type and Split
col1, col2 = st.columns(2)
with col1:
st.selectbox(
"Type",
["COCO", "YOLO"],
key="dataset_type",
)
with col2:
st.selectbox(
"Split",
["train", "val", "test"],
key="split",
)
# Second row: Path and Browse button
col1, col2 = st.columns([3, 1])
with col1:
st.text_input("Dataset Folder", key="dataset_path")
with col2:
st.markdown(
"<div style='margin-bottom: 1.75rem;'></div>", unsafe_allow_html=True
)
st.button("Browse", on_click=browse_dataset_path)
# Additional input for YOLO config file
if st.session_state.get("dataset_type", "COCO") == "YOLO":
st.file_uploader(
"Dataset Configuration (.yaml)",
type=["yaml"],
key="dataset_config_file",
help="Upload a YAML dataset configuration file.",
)
with st.expander("Model Inputs", expanded=False):
st.file_uploader(
"Model File (.pt, .onnx, .h5, .pb, .pth, .torchscript)",
type=["pt", "onnx", "h5", "pb", "pth", "torchscript"],
key="model_file",
help="Upload your trained model file.",
max_upload_size=1024, # MB
)
st.file_uploader(
"Ontology File (.json)",
type=["json"],
key="ontology_file",
help="Upload a JSON file with class labels.",
)
st.radio(
"Configuration Method:",
["Manual Configuration", "Upload Config File"],
key="config_option",
horizontal=True,
)
if (
st.session_state.get("config_option", "Manual Configuration")
== "Upload Config File"
):
st.file_uploader(
"Configuration File (.json)",
type=["json"],
key="config_file",
help="Upload a JSON configuration file.",
)
else:
col1, col2 = st.columns(2)
with col1:
st.slider(
"Confidence Threshold",
min_value=0.0,
max_value=1.0,
step=0.01,
key="confidence_threshold",
help="Minimum confidence score for detections",
)
st.slider(
"NMS Threshold",
min_value=0.0,
max_value=1.0,
step=0.01,
key="nms_threshold",
help="Non-maximum suppression threshold",
)
st.number_input(
"Max Detections/Image",
min_value=1,
max_value=1000,
step=1,
key="max_detections",
)
with col2:
st.selectbox(
"Device",
["cpu", "cuda", "mps"],
key="device",
)
st.selectbox(
"Model Format",
["torchvision", "YOLO"],
index=(
0
if st.session_state.get("model_format", "torchvision")
== "torchvision"
else 1
),
key="model_format",
)
st.number_input(
"Batch Size",
min_value=1,
max_value=256,
step=1,
key="batch_size",
)
st.number_input(
"Evaluation Step",
min_value=0,
max_value=1000,
step=1,
key="evaluation_step",
help="Update UI with intermediate metrics every N images (0 = disable intermediate updates)",
)
st.write("---")
st.write("**Image Size Configuration**")
# Resize Logic
enable_resize = st.checkbox(
"Enable Resize", value=True, key="enable_resize"
)
if enable_resize:
resize_strategy = st.radio(
"Resize Strategy",
["Fixed Dimensions", "Min Side"],
key="resize_strategy",
horizontal=True,
label_visibility="collapsed",
)
if resize_strategy == "Fixed Dimensions":
c1, c2 = st.columns(2)
with c1:
st.number_input(
"Image Resize Height",
min_value=1,
max_value=4096,
value=640,
step=1,
key="resize_height",
help="Height to resize images for inference",
)
with c2:
st.number_input(
"Image Resize Width",
min_value=1,
max_value=4096,
value=640,
step=1,
key="resize_width",
help="Width to resize images for inference",
)
else:
st.number_input(
"Min Side",
min_value=1,
max_value=4096,
value=640,
step=1,
key="min_side",
help="Minimum size of the shorter side of the image",
)
# Crop Logic
enable_crop = st.checkbox("Enable Center Crop", key="enable_crop")
if enable_crop:
c1, c2 = st.columns(2)
with c1:
st.number_input(
"Crop Height",
min_value=1,
max_value=4096,
value=640,
step=1,
key="crop_height",
help="Center crop height",
)
with c2:
st.number_input(
"Crop Width",
min_value=1,
max_value=4096,
value=640,
step=1,
key="crop_width",
help="Center crop width",
)
# Load model action in sidebar
try:
from perceptionmetrics.models.torch_detection import TorchImageDetectionModel
_torch_available = True
except (ImportError, OSError):
_torch_available = False
import json, tempfile
if not _torch_available:
st.warning(
"⚠️ PyTorch غير متاح على هذا النظام. "
"تبويب Inference لن يعمل. "
"يُرجى تثبيت PyTorch بشكل صحيح."
)
load_model_btn = st.button(
"Load Model",
type="primary",
width="stretch",
help="Load and save the model for use in the Inference tab",
key="sidebar_load_model_btn",
disabled=not _torch_available,
)
if load_model_btn:
model_file = st.session_state.get("model_file")
ontology_file = st.session_state.get("ontology_file")
config_option = st.session_state.get(
"config_option", "Manual Configuration"
)
config_file = (
st.session_state.get("config_file")
if config_option == "Upload Config File"
else None
)
# Prepare configuration
config_data = None
config_path = None
try:
if config_option == "Upload Config File":
if config_file is not None:
config_data = json.load(config_file)
with tempfile.NamedTemporaryFile(
delete=False, suffix=".json", mode="w"
) as tmp_cfg:
json.dump(config_data, tmp_cfg)
config_path = tmp_cfg.name
else:
st.error("Please upload a configuration file")
else:
confidence_threshold = float(
st.session_state.get("confidence_threshold", 0.5)
)
nms_threshold = float(st.session_state.get("nms_threshold", 0.5))
max_detections = int(st.session_state.get("max_detections", 100))
device = st.session_state.get("device", "cpu")
batch_size = int(st.session_state.get("batch_size", 1))
evaluation_step = int(st.session_state.get("evaluation_step", 5))
model_format = st.session_state.get("model_format", "torchvision")
# Resize Logic extraction
enable_resize = st.session_state.get("enable_resize", True)
resize_cfg = None
if enable_resize:
resize_strategy = st.session_state.get(
"resize_strategy", "Fixed Dimensions"
)
if resize_strategy == "Fixed Dimensions":
resize_height = int(
st.session_state.get("resize_height", 640)
)
resize_width = int(
st.session_state.get("resize_width", 640)
)
resize_cfg = {
"height": resize_height,
"width": resize_width,
}
else:
min_side = int(st.session_state.get("min_side", 640))
resize_cfg = {"min_side": min_side}
config_data = {
"confidence_threshold": confidence_threshold,
"nms_threshold": nms_threshold,
"max_detections_per_image": max_detections,
"device": device,
"batch_size": batch_size,
"evaluation_step": evaluation_step,
"model_format": model_format.lower(),
}
if resize_cfg is not None:
config_data["resize"] = resize_cfg
if enable_crop:
crop_height = int(st.session_state.get("crop_height", 640))
crop_width = int(st.session_state.get("crop_width", 640))
crop_cfg = {"height": crop_height, "width": crop_width}
config_data["crop"] = crop_cfg
with tempfile.NamedTemporaryFile(
delete=False, suffix=".json", mode="w"
) as tmp_cfg:
json.dump(config_data, tmp_cfg)
config_path = tmp_cfg.name
except Exception as e:
st.error(f"Failed to prepare configuration: {e}")
config_path = None
if model_file is None:
st.error("Please upload a model file")
elif config_path is None:
st.error("Please provide a valid model configuration")
elif ontology_file is None:
st.error("Please upload an ontology file")
else:
with st.spinner("Loading model..."):
# Persist ontology to temp file
try:
ontology_data = json.load(ontology_file)
with tempfile.NamedTemporaryFile(
delete=False, suffix=".json", mode="w"
) as tmp_ont:
json.dump(ontology_data, tmp_ont)
ontology_path = tmp_ont.name
except Exception as e:
st.error(f"Failed to load ontology: {e}")
ontology_path = None
# Persist model to temp file
try:
with tempfile.NamedTemporaryFile(
delete=False, suffix=".pt", mode="wb"
) as tmp_model:
tmp_model.write(model_file.read())
model_temp_path = tmp_model.name
except Exception as e:
st.error(f"Failed to save model file: {e}")
model_temp_path = None
if ontology_path and model_temp_path:
try:
model = TorchImageDetectionModel(
model=model_temp_path,
model_cfg=config_path,
ontology_fname=ontology_path,
device=st.session_state.get("device", "cpu"),
)
st.session_state.detection_model = model
st.session_state.detection_model_loaded = True
st.success("Model loaded and saved for inference")
except Exception as e:
st.session_state.detection_model = None
st.session_state.detection_model_loaded = False
st.error(f"Failed to load model: {e}")
# Main content area with horizontal tabs
tab1, tab2, tab3 = st.tabs(["Dataset Viewer", "Inference", "Evaluator"])
with tab1:
dataset_viewer_tab()
with tab2:
inference_tab()
with tab3:
evaluator_tab()