-
Notifications
You must be signed in to change notification settings - Fork 0
/
streamlit_app.py
348 lines (284 loc) · 12.4 KB
/
streamlit_app.py
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
import dataclasses
import sys, os, json
from dataclasses import dataclass
from glob import glob
from pathlib import Path
from typing import List, Tuple, Dict
import cv2
import numpy as np
import pandas as pd
import tensorflow as tf
import seaborn as sns
import umap
from tensorflow.python.keras.preprocessing.image_dataset import load_image
from tqdm import tqdm
import streamlit as st
from sklearn.ensemble import IsolationForest
from sklearn.covariance import EllipticEnvelope
from sklearn.svm import OneClassSVM
from sklearn.cluster import DBSCAN
from sklearn.decomposition import PCA
from streamlit_tags import st_tags, st_tags_sidebar
from utils import MetaData, MetaDataItem, CLASS_NAMES, get_feature_extractor, get_feature_map
class StreamlitApp:
def __init__(self) -> None:
self._experiment_dir = "experiments"
self._outlier_detectors = {
"IsolationForest": ("Isolation Forest", IsolationForest),
"EllipticEnvelope": ("Elliptic Envelope", EllipticEnvelope),
"OneClassSVM": ("SVM", OneClassSVM),
}
def run(self):
self._build_sidebar()
self._build_main_container()
def _build_sidebar(self) -> None:
st.sidebar.markdown("## Data Settings")
self._build_source_experiment_dropbox()
self._build_dataset_dropbox()
self._build_class_name_dropbox()
self._build_show_images_button()
st.sidebar.markdown("---\n## Outlier Detection Settings")
self._build_models_dropbox()
self._build_outlier_detector_dropbox()
self._build_find_outliers_button()
st.sidebar.markdown("---\n## Other")
st.sidebar.button("Find blank images", on_click=lambda: self._find_blank_images())
def _build_main_container(self) -> None:
st.write("# Labeller")
if "filtered_image_paths" not in st.session_state:
st.write("Please select the images to label in the side bar.")
else:
st.write(f"Found {self.n_images} images")
self._render_image_selectors()
self._render_selected_image()
self._render_tags_container()
@property
def n_images(self) -> int:
return len(self.filtered_image_paths)
@property
def class_name(self) -> np.ndarray:
return st.session_state["class_name"]
@property
def dataset(self) -> np.ndarray:
return st.session_state["dataset"]
@property
def current_image_index(self) -> int:
return st.session_state["current_image_index"]
@property
def possible_tags(self) -> List[str]:
if "possible_tags" not in st.session_state:
file_path = os.path.join(self._experiment_dir, "possible-tags.txt")
with open(file_path, "r") as file:
possible_tags = [s.strip() for s in file.readlines() if len(s.strip()) > 1]
st.session_state["possible_tags"] = possible_tags
return st.session_state["possible_tags"]
@property
def current_image_path(self) -> Path:
index = self.current_image_index - 1
image_path = self.filtered_image_paths[index]
return image_path
@current_image_index.setter
def current_image_index(self, new_val: int) -> None:
st.session_state["current_image_index"] = new_val
@property
def filtered_image_paths(self) -> np.ndarray:
return st.session_state["filtered_image_paths"]
@filtered_image_paths.setter
def filtered_image_paths(self, new_val: np.ndarray) -> None:
st.session_state["filtered_image_paths"] = new_val
@property
def meta_data_file_path(self) -> str:
source_experiment = st.session_state["source-experiment"]
data_dir = os.path.join(self._experiment_dir, source_experiment, "data", self.dataset, self.class_name)
return os.path.join(data_dir, "meta-data.json")
@property
def meta_data(self) -> MetaData:
if "meta_data" not in st.session_state:
raise Exception("Meta data is not loaded.")
meta_data: MetaData = st.session_state["meta_data"]
return meta_data
@property
def current_image_meta(self) -> MetaDataItem:
return self.meta_data.get(self.current_image_path)
def _go_next_image(self) -> None:
new_val = self.current_image_index + 1
max_val = self.n_images
if new_val >= max_val:
new_val = max_val
self.current_image_index = new_val
def _go_prev_image(self) -> None:
new_val = self.current_image_index - 1
if new_val < 1:
new_val = 1
self.current_image_index = new_val
def _render_image_selectors(self) -> None:
col1, col2, col3 = st.columns([0.1, 0.8, 0.1])
col1.button("Prev", on_click=lambda: self._go_prev_image())
col2.slider('Current Image Index', min_value=1, max_value=self.n_images, key="current_image_index")
col3.button("Next", on_click=lambda: self._go_next_image())
def _render_selected_image(self) -> None:
col1, col2 = st.columns([0.7, 0.3])
col1.header("Image")
image_path = self.current_image_path
img = cv2.imread(str(image_path), cv2.IMREAD_GRAYSCALE)
col1.image(img, use_column_width=False)
print(f"original mean: {np.mean(img):0.2f}, std: {np.std(img):0.2f}")
new_size = (32,32)
resized_img = load_image(str(image_path), image_size=new_size, num_channels=3, interpolation="bilinear")
resized_img = cv2.cvtColor(resized_img.numpy(), cv2.COLOR_BGR2GRAY)
print(f"resized mean: {np.mean(resized_img):0.2f}, std: {np.std(resized_img):0.2f}")
col1.image(resized_img, use_column_width=False, clamp=True, output_format="png")
col1.text(image_path.name)
col2.header("Label")
radio_options = ["invalid", "unsure"] + CLASS_NAMES
st.session_state["radio_val_selected_image_label"] = self._get_current_image_label()
# print(self._get_current_image_label())
col2.radio(
label='',
options=radio_options,
key="radio_val_selected_image_label",
on_change=lambda: self._on_label_change(),
)
def _render_tags_container(self) -> None:
possible_tags = self.possible_tags
image_meta = self.current_image_meta
st.session_state["selected_tags"] = image_meta.tags
st.markdown("## Tags")
st.multiselect(
label="Assignments for current image",
options=possible_tags,
default=[],
key="selected_tags",
on_change=lambda: self._update_current_image_tags()
)
st_tags(
label='### All possible tags',
text='Press enter to add more',
value=possible_tags,
suggestions=[],
maxtags=-1
)
def _update_current_image_tags(self) -> None:
self.current_image_meta.tags = st.session_state["selected_tags"]
self.meta_data.to_csv(self.meta_data_file_path)
def _on_label_change(self) -> None:
new_label = st.session_state["radio_val_selected_image_label"]
self._set_current_image_label(new_label)
def _load_or_create_meta_data_into_session(self, image_paths: List[Path]) -> None:
file_path = self.meta_data_file_path
if os.path.exists(file_path):
meta_data: MetaData = MetaData.from_csv(file_path)
else:
meta_data = MetaData()
for path in image_paths:
item = MetaDataItem(
full_path=path,
given_label=path.parent.name,
new_label=path.parent.name,
tags=[]
)
meta_data.add(item)
meta_data.to_csv(file_path)
st.session_state["meta_data"] = meta_data
def _get_current_image_label(self) -> str:
return self.meta_data.get(self.current_image_path).new_label
def _set_current_image_label(self, new_label: str) -> None:
meta_data = self.meta_data
item = meta_data.get(self.current_image_path)
item.set_new_label(new_label)
meta_data.to_csv(self.meta_data_file_path)
def _build_source_experiment_dropbox(self) -> None:
source_experiments = os.listdir(self._experiment_dir)
vals = [exp for exp in source_experiments]
st.sidebar.selectbox(
label='Source experiment',
options=vals,
index=vals.index("original"),
key="source-experiment"
)
def _build_outlier_detector_dropbox(self) -> None:
st.sidebar.selectbox(
label='Outlier detector',
options=list(self._outlier_detectors.keys()),
index=0,
key="outlier_detector"
)
def _build_models_dropbox(self) -> None:
model_names = {
"best_model": "RomanNumerals-trained model",
"imagenet-finetuned": "Fine-tuned model",
"imagenet": "ImageNet-trained model",
}
st.sidebar.selectbox(
label='Model',
options=list(model_names.keys()),
index=1,
key="model_name"
)
def _build_dataset_dropbox(self) -> None:
st.sidebar.selectbox(
label='Dataset',
options=["train", "val", "test"],
index=0,
key="dataset"
)
def _build_class_name_dropbox(self) -> None:
st.sidebar.selectbox(
label='Class name',
options=CLASS_NAMES,
index=0,
key="class_name"
)
def _build_find_outliers_button(self) -> None:
st.sidebar.button("Find outliers", on_click=lambda: self._on_find_outliers_button_click())
def _on_find_outliers_button_click(self) -> None:
source_experiment = st.session_state["source-experiment"]
model_name = st.session_state["model_name"]
class_name = st.session_state["class_name"]
outlier_detector = st.session_state["outlier_detector"]
dataset = self.dataset
if model_name == "imagenet":
model_path = "imagenet"
else:
model_path = os.path.join(self._experiment_dir, source_experiment, "checkpoints", model_name)
print(f"Model path: {model_path}")
print(f"Loading model: {model_path}")
model = get_feature_extractor(model_path)
data_dir = os.path.join(self._experiment_dir, source_experiment, "data", dataset, class_name)
image_paths = list(sorted(Path(data_dir).glob("**/*.png")))
self._load_or_create_meta_data_into_session(image_paths=image_paths)
print("Computing feature map")
feature_map = get_feature_map(model, image_paths)
print("Computing PCA features")
pca = PCA(n_components=0.9, svd_solver="full", whiten=True)
feature_map_pca = pca.fit_transform(feature_map)
od_algo = self._outlier_detectors[outlier_detector][1]()
outlier_labels = od_algo.fit_predict(feature_map_pca)
self.filtered_image_paths = np.array(image_paths)[(outlier_labels == -1)]
self.current_image_index = 1
def _build_show_images_button(self) -> None:
st.sidebar.button("Show images", on_click=lambda: self._show_images())
def _show_images(self) -> None:
source_experiment = st.session_state["source-experiment"]
class_name = st.session_state["class_name"]
dataset = self.dataset
data_dir = os.path.join(self._experiment_dir, source_experiment, "data", dataset, class_name)
image_paths = list(sorted(Path(data_dir).glob("**/*.png")))
self._load_or_create_meta_data_into_session(image_paths=image_paths)
self.filtered_image_paths = image_paths
self.current_image_index = 1
def _find_blank_images(self) -> None:
source_experiment = st.session_state["source-experiment"]
class_name = st.session_state["class_name"]
dataset = self.dataset
data_dir = os.path.join(self._experiment_dir, source_experiment, "data", dataset, class_name)
image_paths = list(sorted(Path(data_dir).glob("**/*.png")))
self._load_or_create_meta_data_into_session(image_paths=image_paths)
filtered_image_paths = []
for image_path in tqdm(image_paths):
img = cv2.imread(str(image_path), cv2.IMREAD_GRAYSCALE)
if np.mean(img) > 250 and np.std(img) < 30:
filtered_image_paths.append(image_path)
self.filtered_image_paths = filtered_image_paths
self.current_image_index = 1
StreamlitApp().run()