Skip to content

Commit 67918bc

Browse files
committed
Run black
1 parent e5c897f commit 67918bc

File tree

6 files changed

+108
-73
lines changed

6 files changed

+108
-73
lines changed

src/napari_deeplabcut/_tests/conftest.py

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,15 @@ def fake_keypoints():
2222
n_animals = 2
2323
n_kpts = 3
2424
data = np.random.rand(n_rows, n_animals * n_kpts * 2)
25-
cols = pd.MultiIndex.from_product([
26-
["me"],
27-
[f"animal_{i}" for i in range(n_animals)],
28-
[f"kpt_{i}" for i in range(n_kpts)],
29-
["x", "y"]
30-
], names=["scorer", "individuals", "bodyparts", "coords"])
25+
cols = pd.MultiIndex.from_product(
26+
[
27+
["me"],
28+
[f"animal_{i}" for i in range(n_animals)],
29+
[f"kpt_{i}" for i in range(n_kpts)],
30+
["x", "y"],
31+
],
32+
names=["scorer", "individuals", "bodyparts", "coords"],
33+
)
3134
df = pd.DataFrame(data, columns=cols, index=range(n_rows))
3235
return df
3336

@@ -68,11 +71,12 @@ def config_path(tmp_path_factory):
6871
"colormap": "viridis",
6972
"video_sets": {
7073
"fake_video": [],
71-
}
74+
},
7275
}
7376
path = str(tmp_path_factory.mktemp("configs") / "config.yaml")
7477
_writer._write_config(
75-
path, params=cfg,
78+
path,
79+
params=cfg,
7680
)
7781
return path
7882

@@ -83,7 +87,7 @@ def video_path(tmp_path_factory):
8387
h = w = 50
8488
writer = cv2.VideoWriter(
8589
output_path,
86-
cv2.VideoWriter_fourcc(*'MJPG'),
90+
cv2.VideoWriter_fourcc(*"MJPG"),
8791
2,
8892
(w, h),
8993
)

src/napari_deeplabcut/_tests/test_keypoints.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def test_point_resize(viewer, points):
4646

4747

4848
def test_add_unnanotated(store):
49-
store.layer.metadata["controls"].label_mode = 'loop'
49+
store.layer.metadata["controls"].label_mode = "loop"
5050
ind_to_remove = 0
5151
data = store.layer.data
5252
store.layer.data = data[data[:, 0] != ind_to_remove]
@@ -59,10 +59,11 @@ def test_add_unnanotated(store):
5959

6060

6161
def test_add_quick(store):
62-
store.layer.metadata["controls"].label_mode = 'quick'
62+
store.layer.metadata["controls"].label_mode = "quick"
6363
store.current_keypoint = store._keypoints[0]
6464
coord = store.current_step, -1, -1
6565
keypoints._add(store, coord=coord)
6666
np.testing.assert_array_equal(
67-
store.layer.data[store.current_step], coord,
67+
store.layer.data[store.current_step],
68+
coord,
6869
)

src/napari_deeplabcut/_tests/test_misc.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,7 @@ def test_to_os_dir_sep_invalid():
6666

6767
def test_guarantee_multiindex_rows():
6868
fake_index = [
69-
f"labeled-data/subfolder_{i}/image_{j}"
70-
for i in range(3) for j in range(10)
69+
f"labeled-data/subfolder_{i}/image_{j}" for i in range(3) for j in range(10)
7170
]
7271
df = pd.DataFrame(index=fake_index)
7372
misc.guarantee_multiindex_rows(df)
@@ -94,9 +93,15 @@ def test_dlc_header():
9493
scorer = "me"
9594
animals = [f"animal_{n}" for n in range(n_animals)]
9695
keypoints = [f"kpt_{n}" for n in range(n_keypoints)]
97-
fake_columns = pd.MultiIndex.from_product([
98-
[scorer], animals, keypoints, ["x", "y", "likelihood"],
99-
], names=["scorer", "individuals", "bodyparts", "coords"])
96+
fake_columns = pd.MultiIndex.from_product(
97+
[
98+
[scorer],
99+
animals,
100+
keypoints,
101+
["x", "y", "likelihood"],
102+
],
103+
names=["scorer", "individuals", "bodyparts", "coords"],
104+
)
100105
header = misc.DLCHeader(fake_columns)
101106
assert header.scorer == scorer
102107
header.scorer = "you"

src/napari_deeplabcut/_tests/test_reader.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,7 @@ def test_read_config(config_path):
6464
def test_read_hdf_old_index(tmp_path_factory, fake_keypoints):
6565
path = str(tmp_path_factory.mktemp("folder") / "data.h5")
6666
old_index = [
67-
f"labeled-data/video/img{i}.png"
68-
for i in range(fake_keypoints.shape[0])
67+
f"labeled-data/video/img{i}.png" for i in range(fake_keypoints.shape[0])
6968
]
7069
fake_keypoints.index = old_index
7170
fake_keypoints.to_hdf(path, key="data")
@@ -79,11 +78,13 @@ def test_read_hdf_old_index(tmp_path_factory, fake_keypoints):
7978

8079
def test_read_hdf_new_index(tmp_path_factory, fake_keypoints):
8180
path = str(tmp_path_factory.mktemp("folder") / "data.h5")
82-
new_index = pd.MultiIndex.from_product([
83-
["labeled-data"],
84-
["video"],
85-
[f"img{i}.png" for i in range(fake_keypoints.shape[0])]
86-
])
81+
new_index = pd.MultiIndex.from_product(
82+
[
83+
["labeled-data"],
84+
["video"],
85+
[f"img{i}.png" for i in range(fake_keypoints.shape[0])],
86+
]
87+
)
8788
fake_keypoints.index = new_index
8889
fake_keypoints.to_hdf(path, key="data")
8990
layers = _reader.read_hdf(path)

src/napari_deeplabcut/_tests/test_widgets.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66

77
def test_guess_continuous():
8-
assert _widgets.guess_continuous(np.array([0.]))
8+
assert _widgets.guess_continuous(np.array([0.0]))
99
assert not _widgets.guess_continuous(np.array(list("abc")))
1010

1111

@@ -40,7 +40,7 @@ def test_store_crop_coordinates(viewer, images, config_path):
4040
viewer.layers.selection.add(images)
4141
_ = viewer.add_shapes(
4242
np.random.random((4, 3)),
43-
shape_type='rectangle',
43+
shape_type="rectangle",
4444
)
4545
controls = _widgets.KeypointControls(viewer)
4646
controls._images_meta = {
@@ -55,17 +55,17 @@ def test_toggle_face_color(viewer, points):
5555
view = viewer.window._qt_viewer
5656
# By default, points are colored by individual with multi-animal data
5757
assert points._face.color_properties.name == "id"
58-
view.canvas.events.key_press(key=keys.Key('F'))
58+
view.canvas.events.key_press(key=keys.Key("F"))
5959
assert points._face.color_properties.name == "label"
60-
view.canvas.events.key_press(key=keys.Key('F'))
60+
view.canvas.events.key_press(key=keys.Key("F"))
6161
assert points._face.color_properties.name == "id"
6262

6363

6464
def test_toggle_edge_color(viewer, points):
6565
viewer.layers.selection.add(points)
6666
view = viewer.window._qt_viewer
6767
np.testing.assert_array_equal(points.edge_width, 0)
68-
view.canvas.events.key_press(key=keys.Key('E'))
68+
view.canvas.events.key_press(key=keys.Key("E"))
6969
np.testing.assert_array_equal(points.edge_width, 2)
7070

7171

@@ -82,7 +82,7 @@ def test_keypoints_dropdown_menu(store):
8282
widget = _widgets.KeypointsDropdownMenu(store)
8383
assert "id" in widget.menus
8484
assert "label" in widget.menus
85-
label_menu = widget.menus['label']
85+
label_menu = widget.menus["label"]
8686
label_menu.currentText() == "kpt_0"
8787
widget.update_menus(event=None)
8888
label_menu.currentText() == "kpt_2"
@@ -92,7 +92,7 @@ def test_keypoints_dropdown_menu(store):
9292

9393
def test_keypoints_dropdown_menu_smart_reset(store):
9494
widget = _widgets.KeypointsDropdownMenu(store)
95-
label_menu = widget.menus['label']
95+
label_menu = widget.menus["label"]
9696
label_menu.update_to("kpt_2")
9797
widget._locked = True
9898
widget.smart_reset(event=None)
@@ -119,4 +119,4 @@ def test_color_scheme_display(qtbot):
119119
widget.add_entry("keypoint", "red")
120120
assert widget.scheme_dict["keypoint"] == "red"
121121
assert widget._container.layout().count() == 1
122-
qtbot.add_widget(widget)
122+
qtbot.add_widget(widget)

src/napari_deeplabcut/_widgets.py

Lines changed: 65 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@
5252
)
5353

5454

55-
Tip = namedtuple('Tip', ['msg', 'pos'])
55+
Tip = namedtuple("Tip", ["msg", "pos"])
5656

5757

5858
class Tutorial(QDialog):
@@ -67,15 +67,35 @@ def __init__(self, parent):
6767

6868
self._current_tip = 0
6969
self._tips = [
70-
Tip("Load a folder of annotated data\n(and optionally a config file if labeling from scratch)\nfrom the menu File > Open File or Open Folder.\nAlternatively, files and folders of images can be dragged\nand dropped onto the main window.", (0.35, 0.15)),
71-
Tip("Data layers will be listed at the bottom left;\ntheir visibility can be toggled by clicking on the small eye icon.", (0.1, 0.65)),
72-
Tip("Corresponding layer controls can be found at the top left.\nSwitch between labeling and selection mode using the numeric keys 2 and 3,\nor clicking on the + or -> icons.", (0.1, 0.2)),
73-
Tip("There are three keypoint labeling modes:\nthe key M can be used to cycle between them.", (0.65, 0.05)),
74-
Tip("When done labeling, save your data by selecting the Points layer\nand hitting Ctrl+S (or File > Save Selected Layer(s)...).", (0.1, 0.65)),
75-
Tip("Read more at <a href='https://github.com/DeepLabCut/napari-deeplabcut#usage'>napari-deeplabcut</a>", (0.4, 0.4)),
70+
Tip(
71+
"Load a folder of annotated data\n(and optionally a config file if labeling from scratch)\nfrom the menu File > Open File or Open Folder.\nAlternatively, files and folders of images can be dragged\nand dropped onto the main window.",
72+
(0.35, 0.15),
73+
),
74+
Tip(
75+
"Data layers will be listed at the bottom left;\ntheir visibility can be toggled by clicking on the small eye icon.",
76+
(0.1, 0.65),
77+
),
78+
Tip(
79+
"Corresponding layer controls can be found at the top left.\nSwitch between labeling and selection mode using the numeric keys 2 and 3,\nor clicking on the + or -> icons.",
80+
(0.1, 0.2),
81+
),
82+
Tip(
83+
"There are three keypoint labeling modes:\nthe key M can be used to cycle between them.",
84+
(0.65, 0.05),
85+
),
86+
Tip(
87+
"When done labeling, save your data by selecting the Points layer\nand hitting Ctrl+S (or File > Save Selected Layer(s)...).",
88+
(0.1, 0.65),
89+
),
90+
Tip(
91+
"Read more at <a href='https://github.com/DeepLabCut/napari-deeplabcut#usage'>napari-deeplabcut</a>",
92+
(0.4, 0.4),
93+
),
7694
]
7795

78-
buttons = QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Abort
96+
buttons = (
97+
QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Abort
98+
)
7999
self.button_box = QDialogButtonBox(buttons)
80100
self.button_box.accepted.connect(self.accept)
81101
self.button_box.rejected.connect(self.reject)
@@ -97,7 +117,9 @@ def accept(self):
97117
self.reject()
98118
tip = self._tips[self._current_tip]
99119
msg = tip.msg
100-
if self._current_tip < 5: # No emoji in the last tip otherwise the hyperlink breaks
120+
if (
121+
self._current_tip < 5
122+
): # No emoji in the last tip otherwise the hyperlink breaks
101123
msg = "💡\n\n" + msg
102124
self.message.setText(msg)
103125
self.count.setText(f"Tip {self._current_tip + 1}|{len(self._tips)}")
@@ -173,50 +195,41 @@ def _paste_data(self, store):
173195

174196
if len(self._clipboard.keys()) > 0:
175197
not_disp = self._slice_input.not_displayed
176-
data = deepcopy(self._clipboard['data'])
198+
data = deepcopy(self._clipboard["data"])
177199
offset = [
178-
self._slice_indices[i] - self._clipboard['indices'][i]
179-
for i in not_disp
200+
self._slice_indices[i] - self._clipboard["indices"][i] for i in not_disp
180201
]
181202
data[:, not_disp] = data[:, not_disp] + np.array(offset)
182203
self._data = np.append(self.data, data, axis=0)
183-
self._shown = np.append(
184-
self.shown, deepcopy(self._clipboard['shown']), axis=0
185-
)
186-
self._size = np.append(
187-
self.size, deepcopy(self._clipboard['size']), axis=0
188-
)
204+
self._shown = np.append(self.shown, deepcopy(self._clipboard["shown"]), axis=0)
205+
self._size = np.append(self.size, deepcopy(self._clipboard["size"]), axis=0)
189206
self._symbol = np.append(
190-
self.symbol, deepcopy(self._clipboard['symbol']), axis=0
207+
self.symbol, deepcopy(self._clipboard["symbol"]), axis=0
191208
)
192209

193-
self._feature_table.append(self._clipboard['features'])
210+
self._feature_table.append(self._clipboard["features"])
194211

195-
self.text._paste(**self._clipboard['text'])
212+
self.text._paste(**self._clipboard["text"])
196213

197214
self._edge_width = np.append(
198215
self.edge_width,
199-
deepcopy(self._clipboard['edge_width']),
216+
deepcopy(self._clipboard["edge_width"]),
200217
axis=0,
201218
)
202219
self._edge._paste(
203-
colors=self._clipboard['edge_color'],
204-
properties=_features_to_properties(
205-
self._clipboard['features']
206-
),
220+
colors=self._clipboard["edge_color"],
221+
properties=_features_to_properties(self._clipboard["features"]),
207222
)
208223
self._face._paste(
209-
colors=self._clipboard['face_color'],
210-
properties=_features_to_properties(
211-
self._clipboard['features']
212-
),
224+
colors=self._clipboard["face_color"],
225+
properties=_features_to_properties(self._clipboard["features"]),
213226
)
214227

215228
self._selected_view = list(
216-
range(npoints, npoints + len(self._clipboard['data']))
229+
range(npoints, npoints + len(self._clipboard["data"]))
217230
)
218231
self._selected_data = set(
219-
range(totpoints, totpoints + len(self._clipboard['data']))
232+
range(totpoints, totpoints + len(self._clipboard["data"]))
220233
)
221234
self.refresh()
222235

@@ -449,17 +462,18 @@ def _extract_single_frame(self, *args):
449462
"properties": points_layer.properties,
450463
},
451464
)
452-
df = df.iloc[ind:ind + 1]
465+
df = df.iloc[ind : ind + 1]
453466
df.index = pd.MultiIndex.from_tuples([Path(output_path).parts[-3:]])
454-
filepath = os.path.join(image_layer.metadata["root"], "machinelabels-iter0.h5")
467+
filepath = os.path.join(
468+
image_layer.metadata["root"], "machinelabels-iter0.h5"
469+
)
455470
if Path(filepath).is_file():
456471
df_prev = pd.read_hdf(filepath)
457472
guarantee_multiindex_rows(df_prev)
458473
df = pd.concat([df_prev, df])
459474
df = df[~df.index.duplicated(keep="first")]
460475
df.to_hdf(filepath, key="machinelabels")
461476

462-
463477
def _store_crop_coordinates(self, *args):
464478
if not (project_path := self._images_meta.get("project")):
465479
return
@@ -605,8 +619,10 @@ def on_insert(self, event):
605619
new_keypoint_set = set(layer.metadata["header"].bodyparts)
606620
diff = new_keypoint_set.difference(current_keypoint_set)
607621
if diff:
608-
answer = QMessageBox.question(self, "", "Do you want to display the new keypoints only?")
609-
if answer == QMessageBox.Yes:
622+
answer = QMessageBox.question(
623+
self, "", "Do you want to display the new keypoints only?"
624+
)
625+
if answer == QMessageBox.Yes:
610626
self.viewer.layers[-2].shown = False
611627

612628
self.viewer.status = f"New keypoint{'s' if len(diff) > 1 else ''} {', '.join(diff)} found."
@@ -620,9 +636,13 @@ def on_insert(self, event):
620636

621637
# Always update the colormap to reflect the one in the config.yaml file
622638
for _layer, store in self._stores.items():
623-
_layer.metadata["face_color_cycles"] = layer.metadata["face_color_cycles"]
639+
_layer.metadata["face_color_cycles"] = layer.metadata[
640+
"face_color_cycles"
641+
]
624642
_layer.face_color = "label"
625-
_layer.face_color_cycle = layer.metadata["face_color_cycles"]["label"]
643+
_layer.face_color_cycle = layer.metadata["face_color_cycles"][
644+
"label"
645+
]
626646
_layer.events.face_color()
627647
store.layer = _layer
628648
self._update_color_scheme()
@@ -795,7 +815,9 @@ def _populate_menus(self):
795815
menu.currentTextChanged.connect(self.refresh_label_menu)
796816
self.menus["id"] = menu
797817
self.menus["label"] = create_dropdown_menu(
798-
self.store, self.id2label[id_], "label",
818+
self.store,
819+
self.id2label[id_],
820+
"label",
799821
)
800822

801823
def _update_items(self):
@@ -837,7 +859,9 @@ def smart_reset(self, event):
837859
if keypoint not in already_annotated:
838860
unannotated = keypoint
839861
break
840-
self.store.current_keypoint = unannotated if unannotated else self.store._keypoints[0]
862+
self.store.current_keypoint = (
863+
unannotated if unannotated else self.store._keypoints[0]
864+
)
841865

842866

843867
def create_dropdown_menu(store, items, attr):

0 commit comments

Comments
 (0)