forked from smarsland/AviaNZ
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AviaNZ_batch_GUI.py
1975 lines (1698 loc) · 85.4 KB
/
AviaNZ_batch_GUI.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
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Version 3.0 14/09/20
# Authors: Stephen Marsland, Nirosha Priyadarshani, Julius Juodakis, Virginia Listanti
# This contains all the GUI parts for batch running of AviaNZ.
# AviaNZ bioacoustic analysis program
# Copyright (C) 2017--2020
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from PyQt5 import QtGui
from PyQt5.QtGui import QIcon, QPixmap, QColor
from PyQt5.QtWidgets import QMessageBox, QMainWindow, QLabel, QPlainTextEdit, QPushButton, QRadioButton, QTimeEdit, QSpinBox, QDesktopWidget, QApplication, QComboBox, QLineEdit, QSlider, QListWidgetItem, QCheckBox, QGroupBox, QGridLayout, QHBoxLayout, QVBoxLayout, QProgressDialog, QFileDialog, QDoubleSpinBox, QFormLayout
from PyQt5.QtCore import Qt, QDir, QSize, QThread, QWaitCondition, QObject, QMutex, pyqtSignal, pyqtSlot
import fnmatch, gc, sys, os, json, re
import numpy as np
import wavio
import traceback
from pyqtgraph.dockarea import Dock, DockArea
import pyqtgraph as pg
from AviaNZ_batch import AviaNZ_batchProcess, GentleExitException
import SignalProc
import Segment
import SupportClasses, SupportClasses_GUI
import Dialogs
import colourMaps
import webbrowser, copy
class AviaNZ_batchWindow(QMainWindow):
def __init__(self, configdir=''):
# Allow the user to browse a folder and push a button to process that folder to find a target species
# and sets up the window.
QMainWindow.__init__(self)
self.msgClosed = QWaitCondition()
# read config and filters from user location
# recogniser - filter file name without ".txt"
# (Duplicated w/ the worker, but is needed here as well)
self.configdir = configdir
self.configfile = os.path.join(configdir, "AviaNZconfig.txt")
self.ConfigLoader = SupportClasses.ConfigLoader()
self.config = self.ConfigLoader.config(self.configfile)
filtersDir = os.path.join(configdir, self.config['FiltersDir'])
self.FilterDicts = self.ConfigLoader.filters(filtersDir)
self.dirName=''
self.statusBar().showMessage("Select a directory to process")
self.setWindowTitle('AviaNZ - Batch Processing')
self.setWindowIcon(QIcon('img/Avianz.ico'))
self.createMenu()
self.createFrame()
self.center()
def createFrame(self):
# Make the window and set its size
self.area = DockArea()
self.setCentralWidget(self.area)
self.setMinimumSize(850, 720)
# Make the docks
self.d_detection = Dock("Automatic Detection",size=(550, 700))
self.d_files = Dock("File list", size=(300, 700))
self.area.addDock(self.d_detection, 'right')
self.area.addDock(self.d_files, 'left')
self.w_browse = QPushButton(" Browse Folder")
self.w_browse.setToolTip("Select a folder to process (may contain sub folders)")
self.w_browse.setFixedSize(165, 50)
self.w_browse.setIcon(self.style().standardIcon(QtGui.QStyle.SP_DialogOpenButton))
self.w_browse.setStyleSheet('QPushButton {font-weight: bold; padding: 3px 3px 3px 3px}')
self.w_dir = QPlainTextEdit()
self.w_dir.setFixedHeight(50)
self.w_dir.setReadOnly(True)
self.w_dir.setPlainText('')
self.w_dir.setToolTip("The folder being processed")
self.w_dir.setStyleSheet("color : #808080;")
w_speLabel1 = QLabel("Select one or more recognisers to use:")
self.w_spe1 = QComboBox()
self.speCombos = [self.w_spe1]
# populate this box (always show all filters here)
spp = sorted(list(self.FilterDicts.keys()))
self.w_spe1.addItem("Any sound")
self.w_spe1.addItem("Any sound (Intermittent sampling)")
self.w_spe1.addItems(spp)
self.w_spe1.currentTextChanged.connect(self.fillSpeciesBoxes)
self.addSp = QPushButton("Add another recogniser")
self.addSp.clicked.connect(self.addSpeciesBox)
w_timeLabel = QLabel("Want to process a subset of recordings only e.g. dawn or dusk?\nThen select the time window, otherwise skip")
self.w_timeStart = QTimeEdit()
self.w_timeStart.setDisplayFormat('hh:mm:ss')
self.w_timeEnd = QTimeEdit()
self.w_timeEnd.setDisplayFormat('hh:mm:ss')
self.w_wind = QComboBox()
self.w_wind.addItems(["OLS wind filter (recommended)", "Robust wind filter (experimental, slow)", "No wind filter"])
# Spinboxes in second scale
self.minlen = QDoubleSpinBox()
self.minlen.setRange(0.02, 20.0)
self.minlen.setSingleStep(1.0)
self.minlen.setValue(0.5)
self.minlenlbl = QLabel("Minimum segment length (s)")
self.maxlen = QDoubleSpinBox()
self.maxlen.setRange(0.05, 120.0)
self.maxlen.setSingleStep(2.0)
self.maxlen.setValue(10.0)
self.maxlenlbl = QLabel("Maximum segment length (s)")
self.maxgap = QDoubleSpinBox()
self.maxgap.setRange(0.05, 10.0)
self.maxgap.setSingleStep(0.5)
self.maxgap.setValue(1.0)
self.maxgaplbl = QLabel("Maximum gap between syllables (s)")
# Intermittent Sampling controls
self.protocolSize = QSpinBox()
self.protocolSize.setRange(1, 180)
self.protocolSize.setValue(self.config['protocolSize'])
self.protocolInterval = QSpinBox()
self.protocolInterval.setRange(5, 3600)
self.protocolInterval.setValue(self.config['protocolInterval'])
self.w_processButton = SupportClasses_GUI.MainPushButton(" Process Folder")
self.w_processButton.setIcon(QIcon(QPixmap('img/process.png')))
self.w_processButton.clicked.connect(self.detect)
self.w_processButton.setFixedWidth(165)
self.w_processButton.setEnabled(False)
self.w_browse.clicked.connect(self.browse)
self.d_detection.addWidget(self.w_dir, row=0, col=0, colspan=2)
self.d_detection.addWidget(self.w_browse, row=0, col=2)
self.d_detection.addWidget(w_speLabel1, row=1, col=0)
self.warning = QLabel("Warning!\nThe chosen \"Any sound\" mode will delete ALL the existing annotations\nin the above selected folder")
self.warning.setStyleSheet('QLabel {font-size:14px; color:red;}')
# Filter selection group
self.boxSp = QGroupBox("")
self.formSp = QVBoxLayout()
self.formSp.addWidget(w_speLabel1)
self.formSp.addWidget(self.w_spe1)
self.formSp.addWidget(self.addSp)
self.formSp.addWidget(self.warning)
self.boxSp.setLayout(self.formSp)
self.d_detection.addWidget(self.boxSp, row=1, col=0, colspan=3)
# Time Settings group
self.boxTime = QGroupBox()
formTime = QGridLayout()
formTime.addWidget(w_timeLabel, 0, 0, 1, 2)
formTime.addWidget(QLabel("Start time (hh:mm:ss)"), 1, 0)
formTime.addWidget(self.w_timeStart, 1, 1)
formTime.addWidget(QLabel("End time (hh:mm:ss)"), 2, 0)
formTime.addWidget(self.w_timeEnd, 2, 1)
self.boxTime.setLayout(formTime)
self.d_detection.addWidget(self.boxTime, row=2, col=0, colspan=3)
# intermittent sampling group, layout
self.boxIntermit = QGroupBox("Intermittent sampling")
formIntermit = QFormLayout()
formIntermit.addRow("Protocol size", self.protocolSize)
formIntermit.addRow("Protocol interval", self.protocolInterval)
self.boxIntermit.setLayout(formIntermit)
self.d_detection.addWidget(self.boxIntermit, row=4, col=0, colspan=3)
# Post Proc checkbox group
self.boxPost = QGroupBox("Post processing")
formPost = QGridLayout()
formPost.addWidget(self.w_wind, 0, 1)
formPost.addWidget(self.maxgaplbl, 2, 0)
formPost.addWidget(self.maxgap, 2, 1)
formPost.addWidget(self.minlenlbl, 3, 0)
formPost.addWidget(self.minlen, 3, 1)
formPost.addWidget(self.maxlenlbl, 4, 0)
formPost.addWidget(self.maxlen, 4, 1)
self.boxPost.setLayout(formPost)
self.d_detection.addWidget(self.boxPost, row=5, col=0, colspan=3)
self.d_detection.addWidget(self.w_processButton, row=6, col=2)
self.w_files = pg.LayoutWidget()
self.d_files.addWidget(self.w_files)
# List to hold the list of files
colourNone = QColor(self.config['ColourNone'][0], self.config['ColourNone'][1], self.config['ColourNone'][2], self.config['ColourNone'][3])
colourPossibleDark = QColor(self.config['ColourPossible'][0], self.config['ColourPossible'][1], self.config['ColourPossible'][2], 255)
colourNamed = QColor(self.config['ColourNamed'][0], self.config['ColourNamed'][1], self.config['ColourNamed'][2], self.config['ColourNamed'][3])
self.listFiles = SupportClasses_GUI.LightedFileList(colourNone, colourPossibleDark, colourNamed)
self.listFiles.itemDoubleClicked.connect(self.listLoadFile)
self.w_files.addWidget(QLabel('Double click to select a folder'), row=0, col=0)
self.w_files.addWidget(self.listFiles, row=2, col=0)
self.d_detection.layout.setContentsMargins(20, 20, 20, 20)
self.d_detection.layout.setSpacing(20)
self.d_files.layout.setContentsMargins(10, 10, 10, 10)
self.d_files.layout.setSpacing(10)
self.fillSpeciesBoxes() # update the boxes to match the initial position
self.show()
def createMenu(self):
""" Create the basic menu.
"""
helpMenu = self.menuBar().addMenu("&Help")
helpMenu.addAction("Help", self.showHelp,"Ctrl+H")
aboutMenu = self.menuBar().addMenu("&About")
aboutMenu.addAction("About", self.showAbout,"Ctrl+A")
quitMenu = self.menuBar().addMenu("&Quit")
quitMenu.addAction("Restart program", self.restart)
quitMenu.addAction("Quit", QApplication.quit, "Ctrl+Q")
def showAbout(self):
""" Create the About Message Box. Text is set in SupportClasses_GUI.MessagePopup"""
msg = SupportClasses_GUI.MessagePopup("a", "About", ".")
msg.exec_()
return
def showHelp(self):
""" Show the user manual (a pdf file)"""
webbrowser.open_new(r'file://' + os.path.realpath('./Docs/AviaNZManual.pdf'))
# webbrowser.open_new(r'http://avianz.net/docs/AviaNZManual.pdf')
def restart(self):
print("Restarting")
QApplication.exit(1)
def detect(self):
# 1. Parses GUI
# 2. Creates and starts the batch worker
if not self.dirName:
msg = SupportClasses_GUI.MessagePopup("w", "Select Folder", "Please select a folder to process!")
msg.exec_()
return(1)
# retrieve selected filter(s)
species = set()
for box in self.speCombos:
if box.currentText() != "":
species.add(box.currentText())
species = list(species)
print("Recognisers:", species)
# Parse wind box:
# a bit wacky but maps: 0 (default option, OLS) -> 1
# 1 (robust) -> 2
# 2 (none) -> 0
wind = (self.w_wind.currentIndex()+1)%3
print("Wind set to", wind)
# Update config file based on provided settings, for reading
# by the worker
# (particularly to store protocol settings for Intermittent,
# but could pass any other changes this way as well)
self.config['protocolSize'] = self.protocolSize.value()
self.config['protocolInterval'] = self.protocolInterval.value()
self.ConfigLoader.configwrite(self.config, self.configfile)
# Create the worker and move it to its thread
# NOTE: any communication w/ batchProc from this thread
# must be via signals, if at all necessary
self.batchProc = BatchProcessWorker(self, mode="GUI", configdir=self.configdir, sdir=self.dirName, recogniser=species, wind=wind, maxgap=self.maxgap.value(), minlen=self.minlen.value(), maxlen=self.maxlen.value())
# NOTE: must be on self. to maintain the reference
self.batchThread = QThread()
self.batchProc.moveToThread(self.batchThread)
# NOTE: any connections should be done after moveToThread
self.batchProc.finished.connect(self.batchThread.quit)
self.batchProc.completed.connect(self.completed_fileproc)
self.batchProc.stopped.connect(self.stopped_fileproc)
self.batchProc.failed.connect(self.error_fileproc)
self.batchProc.need_msg.connect(self.check_msg)
self.batchProc.need_clean_UI.connect(self.clean_UI)
self.batchProc.need_update.connect(self.update_progress)
self.batchProc.need_bat_info.connect(self.bat_survey_form)
self.batchThread.started.connect(self.batchProc.detect)
self.batchThread.start() # a signal connected to batchProc.detect()
def check_msg(self,title,text):
msg = SupportClasses_GUI.MessagePopup("t", title, text)
msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
response = msg.exec_()
if response == QMessageBox.Cancel:
# a fall back basically
self.msg_response = 2
elif response == QMessageBox.No:
# catches Esc as well
self.msg_response = 1
else:
self.msg_response = 0
# to utilize Esc, need to add another standard button, and then do:
# msg.setEscapeButton(QMessageBox.Cancel)
self.msgClosed.wakeAll()
def bat_survey_form(self,operator,easting,northing,recorder):
exportForm = Dialogs.ExportBats(os.path.join(self.dirName, "BatDB.csv"),operator,easting,northing,recorder)
response = exportForm.exec_()
if response==1:
self.batFormResults = exportForm.getValues()
else:
self.batFormResults = None
# ping the batch worker that form was accepted or rejected
self.msgClosed.wakeAll()
def clean_UI(self,total,cnt):
self.w_processButton.setEnabled(False)
self.update()
self.repaint()
self.dlg = QProgressDialog("Analysing file %d / %d. Time remaining: ? h ?? min" % (cnt+1, total), "Cancel run", 0, total+1, self)
self.dlg.setFixedSize(350, 100)
self.dlg.setWindowIcon(QIcon('img/Avianz.ico'))
self.dlg.setWindowTitle("AviaNZ - running Batch Analysis")
self.dlg.setWindowFlags(self.dlg.windowFlags() ^ Qt.WindowContextHelpButtonHint ^ Qt.WindowCloseButtonHint)
self.dlg.canceled.connect(self.stopping_fileproc)
# should be the default, but to make sure:
self.dlg.setWindowModality(Qt.ApplicationModal)
self.dlg.open()
self.dlg.setValue(cnt)
self.dlg.update()
self.dlg.repaint()
QApplication.processEvents()
# ping the batch worker that dlg is ready
self.msgClosed.wakeAll()
def error_fileproc(self,e):
# Pops an error message with string e
self.statusBar().showMessage("Analysis stopped due to error")
if hasattr(self, 'dlg'):
self.dlg.setValue(self.dlg.maximum())
msg = SupportClasses_GUI.MessagePopup("w", "Analysis error!", e)
msg.setStyleSheet("QMessageBox QLabel{color: #cc0000}")
msg.exec_()
self.w_processButton.setEnabled(True)
def completed_fileproc(self):
# All files successfully processed
self.statusBar().showMessage("Processed all %d files" % (self.dlg.maximum()-1))
self.dlg.setValue(self.dlg.maximum())
self.w_processButton.setEnabled(True)
text = "Finished processing.\nWould you like to return to the start screen?"
msg = SupportClasses_GUI.MessagePopup("t", "Finished", text)
msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
reply = msg.exec_()
if reply==QMessageBox.Yes:
QApplication.exit(1)
else:
return(0)
def stopping_fileproc(self):
# When "cancel" is pressed on the progress dialog, it hides,
# but it may take a while for the worker thread to do the check and stop.
# This function fills this period with Busy cursor.
self.dlg.show()
self.dlg.setLabelText("Stopping...")
self.statusBar().showMessage("Stopping...")
QApplication.setOverrideCursor(Qt.WaitCursor)
def stopped_fileproc(self):
# Processing gently stopped (worker thread has now halted, and UI can continue).
# Process any earlier requests, in particular the "stopping" signal:
# NOTE: this might still lead to race condition as the "stopping" and "stopped" are
# emitted by two different threads. Might need to re-emit self.dlg.canceled, or bloody sleep here.
QApplication.processEvents()
self.statusBar().showMessage("Analysis cancelled")
if hasattr(self, 'dlg'):
self.dlg.hide()
self.w_processButton.setEnabled(True)
# in case there was a busy cursor
try:
QApplication.restoreOverrideCursor()
except Exception:
pass
def update_progress(self,cnt,progrtext):
self.dlg.setValue(cnt)
self.dlg.setLabelText(progrtext)
self.statusBar().showMessage(progrtext)
self.dlg.update()
# Refresh GUI after each file (only the ProgressDialog which is modal)
# TODO see if it repaints properly without this
# QApplication.processEvents()
def center(self):
# geometry of the main window
qr = self.frameGeometry()
# center point of screen
cp = QDesktopWidget().availableGeometry().center()
# move rectangle's center point to screen's center point
qr.moveCenter(cp)
# top left of rectangle becomes top left of window centering it
self.move(qr.topLeft())
def browse(self):
if self.dirName:
self.dirName = QFileDialog.getExistingDirectory(self,'Choose Folder to Process',str(self.dirName))
else:
self.dirName = QFileDialog.getExistingDirectory(self,'Choose Folder to Process')
self.w_dir.setPlainText(self.dirName)
self.w_dir.setReadOnly(True)
# populate file list and update rest of interface:
if self.fillFileList()==0:
self.statusBar().showMessage("Ready for processing")
self.w_processButton.setEnabled(True)
else:
self.statusBar().showMessage("Select a directory to process")
self.w_processButton.setEnabled(False)
def addSpeciesBox(self):
""" Deals with adding and moving species comboboxes """
# create a new combobox
newSpBox = QComboBox()
self.speCombos.append(newSpBox)
# populate it with possible species (that have same Fs)
self.fillSpeciesBoxes()
# create a "delete" button for it
delSpBtn = QPushButton("X")
delSpBtn.speciesbox = newSpBox
delSpBtn.setFixedWidth(30)
# connect the listener for deleting
delSpBtn.clicked.connect(self.removeSpeciesBox)
# insert those just above Add button
btncombo = QHBoxLayout()
delSpBtn.layout = btncombo
btncombo.addWidget(newSpBox)
btncombo.addWidget(delSpBtn)
self.formSp.insertLayout(len(self.speCombos), btncombo)
self.boxSp.setMinimumHeight(30*len(self.speCombos)+90)
self.setMinimumHeight(610+30*len(self.speCombos))
self.boxSp.updateGeometry()
def removeSpeciesBox(self):
""" Deals with removing and moving species comboboxes """
# identify the clicked button
called = self.sender()
lay = called.layout
# delete the corresponding combobox and button from their HBox
self.speCombos.remove(called.speciesbox)
lay.removeWidget(called.speciesbox)
called.speciesbox.deleteLater()
lay.removeWidget(called)
called.deleteLater()
# remove the empty HBox
self.formSp.removeItem(lay)
lay.deleteLater()
self.boxSp.setMinimumHeight(30*len(self.speCombos)+90)
self.setMinimumHeight(610+30*len(self.speCombos))
self.boxSp.updateGeometry()
def fillSpeciesBoxes(self):
# select filters with Fs matching box 1 selection
# and show/hide any other UI elements specific to bird filters or AnySound methods
spp = []
currname = self.w_spe1.currentText()
if currname not in ["Any sound", "Any sound (Intermittent sampling)"]:
currfilt = self.FilterDicts[currname]
currmethod = currfilt.get("method", "wv")
# (can't use AllSp with any other filter)
# Don't add different methods, samplerates, or the same name again
# (providing that missing method equals "wv")
for name, filt in self.FilterDicts.items():
if filt["SampleRate"]==currfilt["SampleRate"] and name!=currname and filt.get("method", "wv")==currmethod:
spp.append(name)
self.minlen.hide()
self.minlenlbl.hide()
self.maxlen.hide()
self.maxlenlbl.hide()
self.maxgap.hide()
self.maxgaplbl.hide()
self.boxIntermit.hide()
self.boxPost.show()
self.addSp.show()
self.warning.hide()
if currmethod=="chp":
self.w_wind.show()
else:
self.w_wind.hide()
elif currname == "Any sound":
self.minlen.show()
self.minlenlbl.show()
self.maxlen.show()
self.maxlenlbl.show()
self.maxgap.show()
self.maxgaplbl.show()
self.boxIntermit.hide()
self.boxPost.show()
self.addSp.hide()
self.warning.show()
self.w_wind.hide()
elif currname == "Any sound (Intermittent sampling)":
self.boxPost.hide()
self.boxIntermit.show()
self.addSp.hide()
self.warning.show()
self.boxTime.show()
if currname == "NZ Bats" or currname == "NZ Bats_NP":
self.addSp.setEnabled(False)
self.addSp.setToolTip("Bat recognisers cannot be combined with others")
self.w_wind.setCurrentIndex(0)
self.w_wind.setEnabled(False)
self.w_wind.setToolTip("Filter not applicable to bats")
else:
self.addSp.setEnabled(True)
self.addSp.setToolTip("")
self.w_wind.setEnabled(True)
self.w_wind.setToolTip("")
# (skip first box which is fixed)
for box in self.speCombos[1:]:
# clear old items:
for i in reversed(range(box.count())):
box.removeItem(i)
box.setCurrentIndex(-1)
box.setCurrentText("")
box.addItems(sorted(spp))
def fillFileList(self, fileName=None):
""" Populates the list of files for the file listbox.
Returns an error code if the specified directory is bad.
"""
if not os.path.isdir(self.dirName):
print("ERROR: directory %s doesn't exist" % self.dirName)
self.listFiles.clear()
return(1)
self.listFiles.fill(self.dirName, fileName)
# update the "Browse" field text
self.w_dir.setPlainText(self.dirName)
return(0)
def listLoadFile(self,current):
""" Listener for when the user clicks on an item in filelist """
# Need name of file
if type(current) is QListWidgetItem:
current = current.text()
current = re.sub(r'\/.*', '', current)
self.previousFile = current
# Update the file list to show the right one
i=0
lof = self.listFiles.listOfFiles
while i<len(lof)-1 and lof[i].fileName() != current:
i+=1
if lof[i].isDir() or (i == len(lof)-1 and lof[i].fileName() != current):
dir = QDir(self.dirName)
dir.cd(lof[i].fileName())
# Now repopulate the listbox
self.dirName=str(dir.absolutePath())
self.previousFile = None
self.fillFileList(current)
# Show the selected file
index = self.listFiles.findItems(os.path.basename(current), Qt.MatchExactly)
if len(index) > 0:
self.listFiles.setCurrentItem(index[0])
return(0)
class BatchProcessWorker(AviaNZ_batchProcess, QObject):
# adds QObject functionality to standard batchProc,
# so that it could be moved to a separate thread when multithreading.
finished = pyqtSignal()
completed = pyqtSignal()
stopped = pyqtSignal()
failed = pyqtSignal(str)
need_msg = pyqtSignal(str, str)
need_clean_UI = pyqtSignal(int, int)
need_update = pyqtSignal(int, str)
need_bat_info = pyqtSignal(str, str, str, str)
def __init__(self, *args, **kwargs):
# this is supposedly not OK if somebody was to ever
# further multiply-inherit this class.
AviaNZ_batchProcess.__init__(self, *args, **kwargs)
QObject.__init__(self)
self.mutex = QMutex()
@pyqtSlot()
def detect(self):
try:
AviaNZ_batchProcess.detect(self)
self.completed.emit()
except GentleExitException:
# for clean exits, such as stops via progress dialog
self.stopped.emit()
except Exception as e:
# we have UI, so just cleanly present the error;
# in other modes this will CTD
e = "Encountered error:\n" + traceback.format_exc()
self.failed.emit(e)
self.finished.emit() # this is to prompt generic actions like stopping the event loop
class AviaNZ_reviewAll(QMainWindow):
# Main class for reviewing batch processing results
# Should call HumanClassify1 somehow
def __init__(self,root=None,configdir=''):
# Allow the user to browse a folder and push a button to process that folder to find a target species
# and sets up the window.
super(AviaNZ_reviewAll, self).__init__()
self.root = root
self.dirName=''
self.configdir = configdir
# At this point, the main config file should already be ensured to exist.
self.configfile = os.path.join(configdir, "AviaNZconfig.txt")
self.ConfigLoader = SupportClasses.ConfigLoader()
self.config = self.ConfigLoader.config(self.configfile)
# For some calltype functionality, a list of current filters is needed
filtersDir = os.path.join(configdir, self.config['FiltersDir'])
self.FilterDicts = self.ConfigLoader.filters(filtersDir)
# Make the window and associated widgets
QMainWindow.__init__(self, root)
#self.statusBar().showMessage("Ready to review")
self.setWindowTitle('AviaNZ - Review Batch Results')
self.createFrame()
self.createMenu()
self.center()
def createFrame(self):
# Make the window and set its size
self.area = DockArea()
self.setCentralWidget(self.area)
self.setMinimumSize(1000, 750)
self.setWindowIcon(QIcon('img/Avianz.ico'))
# Make the docks
self.d_detection = Dock("Review",size=(600, 250), autoOrientation=False)
self.d_files = Dock("File list", size=(300, 750))
self.d_excel = Dock("Excel", size=(600, 150))
self.d_settings = Dock("Advanced settings", size=(600, 350))
self.d_excel.hideTitleBar()
self.d_settings.hideTitleBar()
self.area.addDock(self.d_files, 'left')
self.area.addDock(self.d_detection, 'right')
self.area.addDock(self.d_excel, 'bottom', self.d_detection)
self.area.addDock(self.d_settings, 'bottom', self.d_excel)
self.w_revLabel = QLabel("Reviewer")
self.w_reviewer = QLineEdit()
self.w_reviewer.textChanged.connect(self.validateInputs)
self.w_browse = QPushButton(" Browse Folder")
self.w_browse.setToolTip("Select a folder to review (may contain sub folders)")
self.w_browse.setFixedHeight(50)
self.w_browse.setStyleSheet('QPushButton {font-weight: bold}')
self.w_browse.setIcon(self.style().standardIcon(QtGui.QStyle.SP_DialogOpenButton))
self.w_dir = QPlainTextEdit()
self.w_dir.setFixedHeight(50)
self.w_dir.setPlainText('')
self.w_dir.setToolTip("The folder being processed")
self.w_processButton = SupportClasses_GUI.MainPushButton(" Review One-By-One")
self.w_processButton.setIcon(QIcon(QPixmap('img/review.png')))
self.w_processButton.clicked.connect(self.reviewClickedAll)
self.w_processButton.setEnabled(False)
self.w_processButton1 = SupportClasses_GUI.MainPushButton(" Review Quick")
self.w_processButton1.setIcon(QIcon(QPixmap('img/tile1.png')))
self.w_processButton1.clicked.connect(self.reviewClickedSingle)
self.w_processButton1.setEnabled(False)
self.w_processButton.setMinimumWidth(200)
self.w_processButton1.setMinimumWidth(200)
self.w_speLabel1 = QLabel("Species to review")
self.w_spe1 = QComboBox()
self.w_spe1.currentIndexChanged.connect(self.speChanged)
self.spList = []
self.w_spe1.addItem('All species')
self.w_spe1.addItems(self.spList)
self.w_spe1.setEnabled(False)
# Simple certainty selector:
self.certCombo = QComboBox()
self.certCombo.addItems(["Show all (even previously reviewed)", "Show only auto/unknown", "Custom certainty bounds"])
self.certCombo.setCurrentIndex(1)
self.certCombo.activated.connect(self.changedCertSimple)
# add controls to dock
self.d_detection.addWidget(self.w_dir, row=0,col=1, colspan=2)
self.d_detection.addWidget(self.w_browse, row=0,col=0)
self.d_detection.addWidget(self.w_revLabel, row=1, col=0)
self.d_detection.addWidget(self.w_reviewer, row=1, col=1, colspan=2)
self.d_detection.addWidget(self.w_speLabel1,row=2,col=0)
self.d_detection.addWidget(self.w_spe1,row=2, col=1, colspan=2)
self.d_detection.addWidget(QLabel("Minimum certainty to show"), row=3, col=0)
self.d_detection.addWidget(self.certCombo, row=3, col=1, colspan=2)
# self.d_detection.addWidget(self.w_processButton1, row=4, col=1)
# self.d_detection.addWidget(self.w_processButton, row=4, col=2)
procBox = QHBoxLayout()
procBox.addStretch(5)
procBox.addWidget(self.w_processButton1)
procBox.addStretch(1)
procBox.addWidget(self.w_processButton)
procBox.addStretch(5)
self.d_detection.layout.addLayout(procBox, 4, 0, 1, 3)
# Excel export section
self.w_resLabel = QLabel("Size(s) of presence/absence windows\nin the output")
self.w_res = QSpinBox()
self.w_res.setRange(1,600)
self.w_res.setSingleStep(5)
self.w_res.setValue(60)
timePrecisionLabel = QLabel("Output timestamp precision")
self.timePrecisionBox = QComboBox()
self.timePrecisionBox.addItems(["Down to seconds", "Down to milliseconds"])
self.d_excel.addWidget(self.w_resLabel, row=6, col=0)
self.d_excel.addWidget(self.w_res, row=6, col=1, colspan=2)
self.d_excel.addWidget(timePrecisionLabel, row=7, col=0)
self.d_excel.addWidget(self.timePrecisionBox, row=7, col=1, colspan=2)
self.w_excelButton = QPushButton(" Generate Excel ")
self.w_excelButton.setStyleSheet('QPushButton {font-weight: bold; font-size:14px; padding: 2px 2px 2px 8px}')
self.w_excelButton.setFixedHeight(45)
self.w_excelButton.setIcon(QIcon(QPixmap('img/excel.png')))
self.w_excelButton.clicked.connect(self.exportExcel)
self.w_excelButton.setEnabled(False)
self.d_excel.addWidget(self.w_excelButton, row=8, col=2)
self.toggleSettingsBtn = QPushButton(" Advanced settings ")
self.toggleSettingsBtn.setStyleSheet('QPushButton {font-weight: bold; padding: 2px 2px 2px 4px}')
self.toggleSettingsBtn.setFixedHeight(32)
self.toggleSettingsBtn.setIcon(QIcon(QPixmap('img/settingsmore.png')))
self.toggleSettingsBtn.setIconSize(QSize(25, 17))
self.toggleSettingsBtn.clicked.connect(self.toggleSettings)
# linesep = QFrame()
# linesep.setFrameShape(QFrame.HLine)
# linesep.setFrameShadow(QFrame.Sunken)
# ADVANCED SETTINGS:
# precise certainty bounds
self.certBox = QSpinBox()
self.certBox.setRange(0,100)
self.certBox.setSingleStep(10)
self.certBox.setValue(90)
self.certBox.valueChanged.connect(self.changedCert)
# sliders to select min/max frequencies for ALL SPECIES only
self.fLow = QSlider(Qt.Horizontal)
self.fLow.setTickPosition(QSlider.TicksBelow)
self.fLow.setTickInterval(500)
self.fLow.setRange(0, 5000)
self.fLow.setSingleStep(100)
self.fLowcheck = QCheckBox()
self.fLowtext = QLabel('Show only freq. above (Hz)')
self.fLowvalue = QLabel('0')
self.fLow.valueChanged.connect(self.fLowChanged)
self.fHigh = QSlider(Qt.Horizontal)
self.fHigh.setTickPosition(QSlider.TicksBelow)
self.fHigh.setTickInterval(1000)
self.fHigh.setRange(4000, 32000)
self.fHigh.setSingleStep(250)
self.fHigh.setValue(32000)
self.fHighcheck = QCheckBox()
self.fHightext = QLabel('Show only freq. below (Hz)')
self.fHighvalue = QLabel('32000')
self.fHigh.valueChanged.connect(self.fHighChanged)
# disable freq sliders until they are toggled on:
self.fLowcheck.stateChanged.connect(self.toggleFreqLow)
self.fHighcheck.stateChanged.connect(self.toggleFreqHigh)
for widg in [self.fLow, self.fLowtext, self.fLowvalue, self.fHigh, self.fHightext, self.fHighvalue]:
widg.setEnabled(False)
# FFT parameters
self.winwidthBox = QSpinBox()
self.incrBox = QSpinBox()
self.winwidthBox.setRange(2, 1000000)
self.incrBox.setRange(1, 1000000)
self.winwidthBox.setValue(self.config['window_width'])
self.incrBox.setValue(self.config['incr'])
# Single Sp review parameters
self.chunksizeAuto = QRadioButton("Auto-pick view size")
self.chunksizeAuto.setChecked(True)
self.chunksizeManual = QRadioButton("View segments in chunks of (s):")
self.chunksizeManual.toggled.connect(self.chunkChanged)
self.chunksizeBox = QSpinBox()
self.chunksizeBox.setRange(1, 60)
self.chunksizeBox.setValue(10)
self.chunksizeBox.setEnabled(False)
# playback settings - TODO find a better place maybe?
self.loopBox = QCheckBox("Loop playback")
self.autoplayBox = QCheckBox("Autoplay (One-by-One only)")
# Advanced Settings Layout
self.d_settings.addWidget(self.toggleSettingsBtn, row=0, col=2, colspan=2, rowspan=1)
self.d_settings.addWidget(QLabel("Skip if certainty above:"), row=1, col=0, colspan=2, rowspan=1)
self.d_settings.addWidget(self.certBox, row=1, col=2, colspan=2, rowspan=1)
self.d_settings.addWidget(self.fLowcheck, row=2, col=0)
self.d_settings.addWidget(self.fLowtext, row=2, col=1)
self.d_settings.addWidget(self.fLow, row=2, col=2, colspan=2, rowspan=1)
self.d_settings.addWidget(self.fLowvalue, row=2, col=4)
self.d_settings.addWidget(self.fHighcheck, row=3, col=0)
self.d_settings.addWidget(self.fHightext, row=3, col=1)
self.d_settings.addWidget(self.fHigh, row=3, col=2, colspan=2, rowspan=1)
self.d_settings.addWidget(self.fHighvalue, row=3, col=4)
self.d_settings.addWidget(QLabel("FFT window size"), row=4, col=1)
self.d_settings.addWidget(self.winwidthBox, row=4, col=2)
self.d_settings.addWidget(QLabel("FFT hop size"), row=4, col=3)
self.d_settings.addWidget(self.incrBox, row=4, col=4)
self.d_settings.addWidget(self.chunksizeAuto, row=5, col=0, colspan=2, rowspan=1)
self.d_settings.addWidget(self.chunksizeManual, row=6, col=0, colspan=2, rowspan=1)
self.d_settings.addWidget(self.chunksizeBox, row=6, col=2)
self.d_settings.addWidget(self.loopBox, row=7, col=0, colspan=2, rowspan=1)
self.d_settings.addWidget(self.autoplayBox, row=8, col=0, colspan=2, rowspan=1)
self.w_browse.clicked.connect(self.browse)
# print("spList after browse: ", self.spList)
self.w_files = pg.LayoutWidget()
self.d_files.addWidget(self.w_files)
self.w_files.addWidget(QLabel('Double click to select a folder'), row=0, col=0)
# List to hold the list of files
colourNone = QColor(self.config['ColourNone'][0], self.config['ColourNone'][1], self.config['ColourNone'][2], self.config['ColourNone'][3])
colourPossibleDark = QColor(self.config['ColourPossible'][0], self.config['ColourPossible'][1], self.config['ColourPossible'][2], 255)
colourNamed = QColor(self.config['ColourNamed'][0], self.config['ColourNamed'][1], self.config['ColourNamed'][2], self.config['ColourNamed'][3])
self.listFiles = SupportClasses_GUI.LightedFileList(colourNone, colourPossibleDark, colourNamed)
self.listFiles.itemDoubleClicked.connect(self.listLoadFile)
self.w_files.addWidget(self.listFiles, row=2, col=0)
self.d_detection.layout.setContentsMargins(20, 20, 20, 20)
self.d_detection.layout.setSpacing(20)
self.d_excel.layout.setContentsMargins(20, 20, 20, 20)
self.d_excel.layout.setSpacing(20)
self.d_settings.layout.setContentsMargins(20, 20, 20, 20)
self.d_settings.layout.setSpacing(20)
self.d_files.layout.setContentsMargins(10, 10, 10, 10)
self.d_files.layout.setSpacing(10)
for item in self.d_settings.widgets:
if item!=self.toggleSettingsBtn:
item.hide()
self.d_settings.layout.setColumnMinimumWidth(1, 80)
self.d_settings.layout.setColumnMinimumWidth(4, 80)
self.d_settings.layout.setColumnStretch(2, 5)
self.show()
self.validateInputs() # initial trigger to determine status
def changedCertSimple(self, cert):
# update certainty spinbox (adv setting) when dropdown changed
if cert==0:
# Will show all annotations
self.certBox.setValue(100)
elif cert==1:
# Will show yellow, red annotations
self.certBox.setValue(90)
else:
# Will show a custom range
# Make sure the advanced settings dock is visible, to make it obvious
# where to change this parameter
self.toggleSettings(None, forceOn=True)
self.certBox.setFocus()
def changedCert(self, cert):
# update certainty dropdown when advanced setting changed
if cert==100:
# "Show all"
self.certCombo.setCurrentIndex(0)
elif cert==90:
# "Show yellow + red"
self.certCombo.setCurrentIndex(1)
else:
# "custom"
self.certCombo.setCurrentIndex(2)
def toggleSettings(self, clicked, forceOn=None):
""" forceOn can be None to toggle, or True/False to force Visible/Hidden. """
if forceOn is None:
forceOn = not self.d_settings.widgets[1].isVisible()
if forceOn:
for item in self.d_settings.widgets:
if item!=self.toggleSettingsBtn:
item.show()
# self.d_settings.setVisible(True)
self.d_excel.hide()
self.toggleSettingsBtn.setText(" Hide settings ")
self.toggleSettingsBtn.setIcon(QIcon(QPixmap('img/settingsless.png')))
else:
# self.d_settings.setVisible(False)
for item in self.d_settings.widgets:
if item!=self.toggleSettingsBtn:
item.hide()
self.d_excel.show()
self.toggleSettingsBtn.setText(" Advanced settings ")
self.toggleSettingsBtn.setIcon(QIcon(QPixmap('img/settingsmore.png')))
self.repaint()
QApplication.processEvents()
def toggleFreqHigh(self,state):
# state=0 for unchecked, state=2 for checked
for widg in [self.fHigh, self.fHightext, self.fHighvalue]:
widg.setEnabled(state==2)
if state==0:
self.fHigh.setValue(self.fHigh.maximum())
def toggleFreqLow(self, state):
for widg in [self.fLow, self.fLowtext, self.fLowvalue]:
widg.setEnabled(state==2)
if state==0:
self.fLow.setValue(self.fLow.minimum())
def fHighChanged(self, value):
self.fHighvalue.setText(str(int(value)))
self.validateInputs()
def speChanged(self, value):
if self.w_spe1.currentText() == "All species":
self.w_processButton1.setEnabled(False)
self.w_processButton1.setToolTip("Only one species at a time can be reviewed in quick mode")
else:
self.w_processButton1.setEnabled(True)
self.w_processButton1.setToolTip("")
def fLowChanged(self, value):
self.fLowvalue.setText(str(int(value)))
self.validateInputs()
def chunkChanged(self):
self.chunksizeBox.setEnabled(self.chunksizeManual.isChecked())
def validateInputs(self):
""" Checks if review should be allowed based on current settings.
Use similarly to QWizardPage's isComplete, i.e. after any changes in GUI.
"""
ready = True
problemMsg = ""
if self.listFiles.count()==0 or self.dirName=='':
ready = False
problemMsg = "Select a directory to review"
elif self.w_reviewer.text()=='':
ready = False
problemMsg = "Enter reviewer name"
elif self.fHigh.value()<self.fLow.value():
ready = False
problemMsg = "Bad frequency bands set"
else:
problemMsg = "Ready to review"
# show explanations
self.statusBar().showMessage(problemMsg)
if ready:
self.w_processButton.setToolTip("")
self.w_processButton1.setToolTip("")
else:
self.w_processButton.setToolTip(problemMsg)
self.w_processButton1.setToolTip(problemMsg)