-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathSupportClasses_GUI.py
1549 lines (1311 loc) · 58.9 KB
/
SupportClasses_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
# coding=latin-1
# SupportClasses_GUI.py
# Support classes for the AviaNZ program
# Mostly subclassed from pyqtgraph
# Version 3.0 14/09/20
# Authors: Stephen Marsland, Nirosha Priyadarshani, Julius Juodakis, Virginia Listanti
# 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 QtCore, QtGui
from PyQt5.QtWidgets import QMessageBox, QAbstractButton, QListWidget, QListWidgetItem, QPushButton, QSlider, QLabel, QHBoxLayout, QGridLayout, QWidget
from PyQt5.QtCore import Qt, QTime, QIODevice, QBuffer, QByteArray, QMimeData, QLineF, QLine, QPoint, QSize, QDir, pyqtSignal
from PyQt5.QtMultimedia import QAudio, QAudioOutput
from PyQt5.QtGui import QIcon, QPixmap, QPainter, QPen, QColor, QFont, QDrag
import pyqtgraph as pg
import pyqtgraph.functions as fn
import Segment
import wavio
from time import sleep
import time
import math
import numpy as np
import os
import io
class TimeAxisHour(pg.AxisItem):
# Time axis (at bottom of spectrogram)
# Writes the time as hh:mm:ss, and can add an offset
def __init__(self, *args, **kwargs):
super(TimeAxisHour, self).__init__(*args, **kwargs)
self.offset = 0
self.setLabel('Time', units='hh:mm:ss')
self.showMS = False
def setShowMS(self,value):
self.showMS = value
def tickStrings(self, values, scale, spacing):
# Overwrite the axis tick code
if self.showMS:
self.setLabel('Time', units='hh:mm:ss.ms')
return [QTime(0,0,0).addMSecs((value+self.offset)*1000).toString('hh:mm:ss.z') for value in values]
else:
self.setLabel('Time', units='hh:mm:ss')
return [QTime(0,0,0).addSecs(value+self.offset).toString('hh:mm:ss') for value in values]
def setOffset(self,offset):
self.offset = offset
#self.update()
class TimeAxisMin(pg.AxisItem):
# Time axis (at bottom of spectrogram)
# Writes the time as mm:ss, and can add an offset
def __init__(self, *args, **kwargs):
super(TimeAxisMin, self).__init__(*args, **kwargs)
self.offset = 0
self.setLabel('Time', units='mm:ss.z')
self.showMS = False
def setShowMS(self,value):
self.showMS = value
def tickStrings(self, values, scale, spacing):
# Overwrite the axis tick code
# First, get absolute time ('values' are relative to page start)
if len(values)==0:
return []
vs = [value + self.offset for value in values]
if self.showMS:
self.setLabel('Time', units='mm:ss.ms')
vstr1 = [QTime(0,0,0).addMSecs(value*1000).toString('mm:ss.z') for value in vs]
# check if we need to add hours:
if vs[-1]>=3600:
self.setLabel('Time', units='h:mm:ss.ms')
for i in range(len(vs)):
if vs[i]>=3600:
vstr1[i] = QTime(0,0,0).addMSecs(vs[i]*1000).toString('h:mm:ss.z')
return vstr1
else:
self.setLabel('Time', units='mm:ss')
vstr1 = [QTime(0,0,0).addSecs(value).toString('mm:ss') for value in vs]
# check if we need to add hours:
if vs[-1]>=3600:
self.setLabel('Time', units='h:mm:ss')
for i in range(len(vs)):
if vs[i]>=3600:
vstr1[i] = QTime(0,0,0).addSecs(vs[i]).toString('h:mm:ss')
return vstr1
def setOffset(self,offset):
self.offset = offset
self.update()
class AxisWidget(QAbstractButton):
# Axis shown along the side of Single Sp buttons
def __init__(self, sgsize, minFreq, maxFreq, parent=None):
super(AxisWidget, self).__init__(parent)
self.minFreq = minFreq
self.maxFreq = maxFreq
self.sgsize = sgsize
# fixed size
self.setSizePolicy(0,0)
self.setMinimumSize(70, sgsize)
self.fontsize = min(max(int(math.sqrt(sgsize-30)*0.8), 9), 13)
def paintEvent(self, event):
if type(event) is not bool:
painter = QPainter(self)
# actual axis line painting
bottomR = event.rect().bottomRight()
bottomR.setX(bottomR.x()-12)
topR = event.rect().topRight()
topR.setX(topR.x()-12)
painter.setPen(QPen(QColor(20,20,20), 1))
painter.drawLine(bottomR, topR)
painter.setFont(QFont("Helvetica", self.fontsize))
# draw tickmarks and numbers
currFrq = self.minFreq
fontOffset = 5 + 2.6*self.fontsize
tickmark = QLine(bottomR, QPoint(bottomR.x()+6, bottomR.y()))
painter.drawLine(tickmark)
painter.drawText(tickmark.x2()-fontOffset, tickmark.y2()+1, "%.1f" % currFrq)
for ticknum in range(3):
currFrq += (self.maxFreq - self.minFreq)/4
tickmark.translate(0, -event.rect().height()//4)
painter.drawLine(tickmark)
painter.drawText(tickmark.x2()-fontOffset, tickmark.y2()+self.fontsize//2, "%.1f" % currFrq)
tickmark.translate(0, -tickmark.y2())
painter.drawLine(tickmark)
painter.drawText(tickmark.x2()-fontOffset, tickmark.y2()+self.fontsize+1, "%.1f" % self.maxFreq)
painter.save()
painter.translate(self.fontsize//2, event.rect().height()//2)
painter.rotate(-90)
painter.drawText(-12, 8, "kHz")
painter.restore()
def sizeHint(self):
return QSize(60, self.sgsize)
def minimumSizeHint(self):
return QSize(60, self.sgsize)
class TimeAxisWidget(QAbstractButton):
# Class for HumanClassify dialogs to put spectrograms on buttons
# Also includes playback capability.
def __init__(self, sgsize, maxTime, parent=None):
super(TimeAxisWidget, self).__init__(parent)
self.sgsize = sgsize
self.maxTime = maxTime
# fixed size
self.setSizePolicy(0,0)
self.setMinimumSize(sgsize, 40)
self.setMaximumSize(sgsize, 50)
self.fontsize = min(max(int(math.sqrt(sgsize)*0.55), 9), 13)
def paintEvent(self, event):
if type(event) is not bool:
painter = QPainter(self)
# actual axis line painting
bottomL = event.rect().bottomLeft()
bottomR = event.rect().bottomRight()
top = event.rect().top()
painter.setPen(QPen(QColor(20,20,20), 1))
painter.setFont(QFont("Helvetica", self.fontsize))
# draw tickmarks and numbers
currTime = 0
fontOffset = 5+1.5*self.fontsize
if self.maxTime>=10:
timeFormat = "%d"
else:
timeFormat = "%.1f"
painter.drawLine(bottomL.x(), top+6, bottomR.x(), top+6)
tickmark = QLine(bottomL.x(), top+6, bottomL.x(), top)
painter.drawLine(tickmark)
painter.drawText(tickmark.x1(), tickmark.y1()+fontOffset, timeFormat % currTime)
for ticknum in range(4):
currTime += self.maxTime/5
tickmark.translate(event.rect().width()//5,0)
painter.drawLine(tickmark)
painter.drawText(tickmark.x1()-fontOffset//4, tickmark.y1()+fontOffset, timeFormat % currTime)
tickmark.translate(event.rect().width()//5-2,0)
painter.drawLine(tickmark)
painter.drawText(tickmark.x2()-fontOffset*0.7, tickmark.y1()+fontOffset, timeFormat % self.maxTime)
painter.save()
painter.drawText((bottomR.x() - bottomL.x())//2, bottomL.y(), "s")
painter.restore()
def sizeHint(self):
return QSize(self.sgsize,60)
def minimumSizeHint(self):
return QSize(self.sgsize,60)
class ShadedROI(pg.ROI):
# A region of interest that is shaded, for marking segments
def paint(self, p, opt, widget):
#brush = QtGui.QBrush(QtGui.QColor(0, 0, 255, 50))
if not hasattr(self, 'currentBrush'):
self.setBrush(QtGui.QBrush(QtGui.QColor(0, 0, 255, 50)))
if not hasattr(self, 'currentPen'):
self.setPen(QtGui.QPen(QtGui.QColor(255, 0, 0, 255)))
p.save()
r = self.boundingRect()
p.setRenderHint(QtGui.QPainter.Antialiasing)
p.setPen(self.currentPen)
p.setBrush(self.currentBrush)
p.translate(r.left(), r.top())
p.scale(r.width(), r.height())
p.drawRect(0, 0, 1, 1)
p.restore()
def setBrush(self, *br, **kargs):
"""Set the brush that fills the region. Can have any arguments that are valid
for :func:`mkBrush <pyqtgraph.mkBrush>`.
"""
self.brush = fn.mkBrush(*br, **kargs)
self.currentBrush = self.brush
# this allows compatibility with LinearRegions:
def setHoverBrush(self, *br, **kargs):
self.hoverBrush = fn.mkBrush(*br, **kargs)
def setPen(self, *br, **kargs):
self.pen = fn.mkPen(*br, **kargs)
self.currentPen = self.pen
def hoverEvent(self, ev):
if self.transparent:
return
if not ev.isExit():
self.setMouseHover(True)
else:
self.setMouseHover(False)
def setMouseHover(self, hover):
# for ignoring when ReadOnly enabled:
if not self.translatable:
return
# don't waste time if state isn't changing:
if self.mouseHovering == hover:
return
self.mouseHovering = hover
if hover:
self.currentBrush = self.hoverBrush
else:
self.currentBrush = self.brush
self.update()
def mouseDragEventFlexible(self, ev):
if ev.button() == self.rois[0].parent.MouseDrawingButton:
return
ev.accept()
## Inform ROIs that a drag is happening
## note: the ROI is informed that the handle has moved using ROI.movePoint
## this is for other (more nefarious) purposes.
#for r in self.roi:
#r[0].pointDragEvent(r[1], ev)
if ev.isFinish():
if self.isMoving:
for r in self.rois:
r.stateChangeFinished()
self.isMoving = False
elif ev.isStart():
for r in self.rois:
r.handleMoveStarted()
self.isMoving = True
self.startPos = self.scenePos()
self.cursorOffset = self.scenePos() - ev.buttonDownScenePos()
if self.isMoving: ## note: isMoving may become False in mid-drag due to right-click.
pos = ev.scenePos() + self.cursorOffset
self.movePoint(pos, ev.modifiers(), finish=False)
def mouseDragEventFlexibleLine(self, ev):
if self.movable and ev.button() != self.btn:
if ev.isStart():
self.moving = True
self.cursorOffset = self.pos() - self.mapToParent(ev.buttonDownPos())
self.startPosition = self.pos()
ev.accept()
if not self.moving:
return
self.setPos(self.cursorOffset + self.mapToParent(ev.pos()))
self.sigDragged.emit(self)
if ev.isFinish():
self.moving = False
self.sigPositionChangeFinished.emit(self)
class ShadedRectROI(ShadedROI):
# A rectangular ROI that it shaded, for marking segments
def __init__(self, pos, size, centered=False, movable=True, sideScalers=True, parent=None, **args):
#QtGui.QGraphicsRectItem.__init__(self, 0, 0, size[0], size[1])
pg.ROI.__init__(self, pos, size, movable=movable, **args)
self.parent = parent
self.mouseHovering = False
self.setBrush(QtGui.QBrush(QtGui.QColor(0, 0, 255, 50)))
self.setHoverBrush(QtGui.QBrush(QtGui.QColor(0, 0, 255, 100)))
self.transparent = True
#self.addTranslateHandle(center)
if self.translatable:
self.addScaleHandle([1, 1], [0, 0]) # top right
self.addScaleHandle([1, 0], [0, 1]) # bottom right
self.addScaleHandle([0, 1], [1, 0]) # top left
self.addScaleHandle([0, 0], [1, 1]) # bottom left
def setMovable(self,value):
self.resizable = value
self.translatable = value
def mouseDragEvent(self, ev):
if ev.isStart():
if ev.button() != self.parent.MouseDrawingButton:
self.setSelected(True)
if self.translatable:
self.isMoving = True
self.preMoveState = self.getState()
self.cursorOffset = self.pos() - self.mapToParent(ev.buttonDownPos())
self.sigRegionChangeStarted.emit(self)
ev.accept()
else:
ev.ignore()
elif ev.isFinish():
if self.translatable:
if self.isMoving:
self.stateChangeFinished()
self.isMoving = False
return
if self.translatable and self.isMoving and ev.buttons() != self.parent.MouseDrawingButton:
snap = True if (ev.modifiers() & QtCore.Qt.ControlModifier) else None
newPos = self.mapToParent(ev.pos()) + self.cursorOffset
self.translate(newPos - self.pos(), snap=snap, finish=False)
pg.graphicsItems.ROI.Handle.mouseDragEvent = mouseDragEventFlexible
pg.graphicsItems.InfiniteLine.InfiniteLine.mouseDragEvent = mouseDragEventFlexibleLine
class DemousedViewBox(pg.ViewBox):
# A version of ViewBox with no mouse events.
# Dramatically reduces CPU usage when such events are not needed.
def mouseDragEvent(self, ev, axis=None):
return
def mouseClickEvent(self, ev):
return
def mouseMoveEvent(self, ev):
return
def wheelEvent(self, ev, axis=None):
return
# Two subclasses of LinearRegionItem, that account for spectrogram bounds when resizing
# and use boundary caching to reduce CPU load e.g. when detecting mouse hover
class LinearRegionItem2(pg.LinearRegionItem):
def __init__(self, parent, bounds=None, *args, **kwds):
pg.LinearRegionItem.__init__(self, bounds, *args, **kwds)
self.parent = parent
self.bounds = bounds
self.useCachedView = None
# we don't provide parent, and therefore don't switch buttons,
# when using this for overview
if self.parent is not None:
self.lines[0].btn = self.parent.MouseDrawingButton
self.lines[1].btn = self.parent.MouseDrawingButton
self.setHoverBrush(QtGui.QBrush(QtGui.QColor(0, 0, 255, 100)))
def setHoverBrush(self, *br, **kargs):
self.hoverBrush = fn.mkBrush(*br, **kargs)
def setPen(self, *pen, **kargs):
self.lines[0].setPen(*pen, **kargs)
self.lines[1].setPen(*pen, **kargs)
def viewRect(self):
""" Return the visible bounds of this item's ViewBox or GraphicsWidget,
in the local coordinate system of the item.
Overwritten to use caching. """
if self.useCachedView is not None:
return self.useCachedView
view = self.getViewBox()
if view is None:
return None
bounds = view.viewRect()
bounds = self.mapRectFromView(bounds)
if bounds is None:
return None
bounds = bounds.normalized()
# For debugging cache misses:
# if self.useCachedView is not None:
# if self.useCachedView.top()!=bounds.top() or self.useCachedView.bottom()!=bounds.bottom():
# import traceback
# traceback.print_stack()
# print("cached:", self.useCachedView)
# print(bounds)
self.useCachedView = bounds
return bounds
def viewTransformChanged(self):
# Clear cache
self.useCachedView = None
# def boundingRect(self):
# # because we react to hover, this is called frequently
# # ORIGINAL:
# br = self.viewRect() # bounds of containing ViewBox mapped to local coords.
# rng = self.getRegion()
# br.setLeft(rng[0])
# br.setRight(rng[1])
# length = br.height()
# br.setBottom(br.top() + length * self.span[1])
# br.setTop(br.top() + length * self.span[0])
# br = br.normalized()
# if self._bounds != br:
# print("Preparing geom")
# self._bounds = br
# self.prepareGeometryChange()
# return br
def mouseDragEvent(self, ev):
if not self.movable or (self.parent is not None and ev.button()==self.parent.MouseDrawingButton):
return
ev.accept()
if ev.isStart():
bdp = ev.buttonDownPos()
self.cursorOffsets = [l.pos() - bdp for l in self.lines]
self.startPositions = [l.pos() for l in self.lines]
self.moving = True
if not self.moving:
return
self.lines[0].blockSignals(True) # only want to update once
newcenter = ev.pos()
# added this to bound its dragging, as in ROI.
# first, adjust center position to avoid dragging too far:
for i, l in enumerate(self.lines):
tomove = self.cursorOffsets[i] + newcenter
if self.bounds is not None:
# stop center from moving too far left
if tomove.x() < self.bounds[0]:
newcenter.setX(-self.cursorOffsets[i].x() + self.bounds[0])
# stop center from moving too far right
if tomove.x() > self.bounds[1]:
newcenter.setX(-self.cursorOffsets[i].x() + self.bounds[1])
# update lines based on adjusted center
for i, l in enumerate(self.lines):
tomove = self.cursorOffsets[i] + newcenter
l.setPos(tomove)
self.lines[0].blockSignals(False)
self.prepareGeometryChange()
if ev.isFinish():
self.moving = False
self.sigRegionChangeFinished.emit(self)
else:
self.sigRegionChanged.emit(self)
# Just another slight optimization - immediately dropping unneeded mouse events
class LinearRegionItemO(LinearRegionItem2):
def __init__(self, *args, **kwds):
LinearRegionItem2.__init__(self, parent=None, bounds=[0,100], *args, **kwds)
def setRegion(self, rgn):
"""Set the values for the edges of the region.
============== ==============================================
**Arguments:**
rgn A list or tuple of the lower and upper values.
bounds A tuple indicating allowed x range
============== ==============================================
"""
if self.lines[0].value() == rgn[0] and self.lines[1].value() == rgn[1]:
return
# shift the requested length to fit within bounds:
if self.bounds[0] is not None:
if rgn[0]<self.bounds[0]:
ll = rgn[1]-rgn[0]
rgn[0] = self.bounds[0]
rgn[1] = rgn[0]+ll
if self.bounds[1] is not None:
if rgn[1]>self.bounds[1]:
ll = rgn[1]-rgn[0]
rgn[1] = self.bounds[1]
rgn[0] = max(0, rgn[1]-ll)
self.blockLineSignal = True
self.lines[0].setValue(rgn[0])
self.lines[1].setValue(rgn[1])
self.blockLineSignal = False
# self.lineMoved(0)
# self.lineMoved(1)
self.lineMoveFinished()
def setBounds(self, bounds):
self.bounds = bounds
super(LinearRegionItemO, self).setBounds(bounds)
# identical to original, just w/o debugger
def paint(self, p, *args):
p.setBrush(self.currentBrush)
p.setPen(fn.mkPen(None))
p.drawRect(self.boundingRect())
# Immediate rejects on all unneeded events:
def mouseClickEvent(self, ev):
ev.accept()
return
def wheelEvent(self, ev):
ev.accept()
return
# Other events could be dropped too:
# def lineMoved(self, i):
# return
# def lineMoveFinished(self):
# return
# def setMouseHover(self, hover):
# return
# def hoverEvent(self, ev):
# return
class DragViewBox(pg.ViewBox):
# A normal ViewBox, but with the ability to capture drag.
# Effectively, if "dragging" is enabled, it captures press & release signals.
# Otherwise it ignores the event, which then goes to the scene(),
# which only captures click events.
sigMouseDragged = QtCore.Signal(object,object,object)
keyPressed = QtCore.Signal(int)
def __init__(self, parent, enableDrag, thisIsAmpl, *args, **kwds):
pg.ViewBox.__init__(self, *args, **kwds)
self.enableDrag = enableDrag
self.parent = parent
self.thisIsAmpl = thisIsAmpl
def mouseDragEvent(self, ev):
print("Uncaptured drag event")
# if self.enableDrag:
# ## if axis is specified, event will only affect that axis.
# ev.accept()
# if self.state['mouseMode'] != pg.ViewBox.RectMode or ev.button() == QtCore.Qt.RightButton:
# ev.ignore()
# if ev.isFinish(): ## This is the final move in the drag; draw the actual box
# print("dragging done")
# self.rbScaleBox.hide()
# self.sigMouseDragged.emit(ev.buttonDownScenePos(ev.button()),ev.scenePos(),ev.screenPos())
# else:
# ## update shape of scale box
# self.updateScaleBox(ev.buttonDownPos(), ev.pos())
# else:
# pass
def mousePressEvent(self, ev):
if self.enableDrag and ev.button() == self.parent.MouseDrawingButton:
if self.thisIsAmpl:
self.parent.mouseClicked_ampl(ev)
else:
self.parent.mouseClicked_spec(ev)
ev.accept()
else:
ev.ignore()
def mouseReleaseEvent(self, ev):
if self.enableDrag and ev.button() == self.parent.MouseDrawingButton:
if self.thisIsAmpl:
self.parent.mouseClicked_ampl(ev)
else:
self.parent.mouseClicked_spec(ev)
ev.accept()
else:
ev.ignore()
def keyPressEvent(self,ev):
# This catches the keypresses and sends out a signal
#self.emit(SIGNAL("keyPressed"),ev)
super(DragViewBox, self).keyPressEvent(ev)
self.keyPressed.emit(ev.key())
class ChildInfoViewBox(pg.ViewBox):
# Normal ViewBox, but with ability to pass a message back from a child
sigChildMessage = QtCore.Signal(object)
def __init__(self, *args, **kwds):
pg.ViewBox.__init__(self, *args, **kwds)
def resend(self,x):
self.sigChildMessage.emit(x)
class ClickableRectItem(QtGui.QGraphicsRectItem):
# QGraphicsItem doesn't include signals, hence this mess
def __init__(self, *args, **kwds):
QtGui.QGraphicsRectItem.__init__(self, *args, **kwds)
def mousePressEvent(self, ev):
super(ClickableRectItem, self).mousePressEvent(ev)
# send the position of this rectangle in ViewBox coords
# left corner:
# x = self.mapRectToParent(self.boundingRect()).x()
# or center:
x = self.mapRectToParent(self.boundingRect()).center().x()
self.parentWidget().resend(x)
class PartlyResizableGLW(pg.GraphicsLayoutWidget):
# a widget which has a fixed aspect ratio, set by height.
# useful for horizontal scroll areas.
def __init__(self):
self.plotAspect = 5
# to prevent infinite loops:
self.alreadyResizing = False
super(PartlyResizableGLW, self).__init__()
def forceResize(self):
# this should be doable by postEvent(QResizeEvent),
# but somehow doesn't always work.
self.alreadyResizing = False
self.setMinimumWidth(self.height()*self.plotAspect-10)
self.setMaximumWidth(self.height()*self.plotAspect+10)
self.adjustSize()
def resizeEvent(self, e):
if e is not None:
# break any infinite loops,
# and also processes every second event:
if self.alreadyResizing:
self.alreadyResizing = False
return
self.alreadyResizing = True
# Some buffer for flexibility, so that it could adjust itself
# and avoid infinite loops
self.setMinimumWidth(e.size().height()*self.plotAspect-10)
self.setMaximumWidth(e.size().height()*self.plotAspect+10)
pg.GraphicsLayoutWidget.resizeEvent(self, e)
class ControllableAudio(QAudioOutput):
# This links all the PyQt5 audio playback things -
# QAudioOutput, QFile, and input from main interfaces
def __init__(self, format, loop=False):
super(ControllableAudio, self).__init__(format)
# on this notify, move slider (connected in main file)
self.setNotifyInterval(30)
self.stateChanged.connect(self.endListener)
self.tempin = QBuffer()
self.timeoffset = 0 # start t of the played audio, in ms, relative to page start
self.keepSlider = False
self.loop = loop
#self.format = format
# set small buffer (10 ms) and use processed time
self.setBufferSize(int(self.format().sampleSize() * self.format().sampleRate()/100 * self.format().channelCount()))
def isPlaying(self):
return(self.state() == QAudio.ActiveState)
def endListener(self):
# this should only be called if there's some misalignment between GUI and Audio
if self.state() == QAudio.IdleState:
if self.loop:
self.restart()
return
# give some time for GUI to catch up and stop
sleepCycles = 0
while(self.state() != QAudio.StoppedState and sleepCycles < 30):
sleep(0.03)
sleepCycles += 1
# This loop stops when timeoffset+processedtime > designated stop position.
# By adding this offset, we ensure the loop stops even if
# processed audio timer breaks somehow.
self.timeoffset += 30
self.notify.emit()
self.pressedStop()
def pressedPlay(self, start=0, stop=0, audiodata=None):
# If playback bar is not moved, this can use resume() to
# continue from the same spot.
# Otherwise assumes that the QAudioOutput was stopped/reset,
# the updated position passed as start, and will
# start anew from there.
if self.state() == QAudio.SuspendedState:
print("Resuming the segment %d-%d ms" % (start,stop))
self.resume()
else:
if not self.keepSlider:
self.pressedStop()
sleep(0.1)
print("Playing segment: %d-%d ms" %(start, stop))
self.filterSeg(start, stop, audiodata)
def pressedPause(self):
self.keepSlider=True # a flag to avoid jumping the slider back to 0
self.suspend()
def pressedStop(self):
# stop and reset to window/segment start
self.keepSlider=False
self.stop()
if self.tempin.isOpen():
self.tempin.close()
def filterBand(self, start, stop, low, high, audiodata, sp):
# Selects the data between start-stop ms, relative to file start,
# bandpasses it and plays it.
self.timeoffset = max(0, start)
start = max(0, start * self.format().sampleRate() // 1000)
stop = min(stop * self.format().sampleRate() // 1000, len(audiodata))
segment = audiodata[int(start):int(stop)]
segment = sp.bandpassFilter(segment,sampleRate=None, start=low, end=high)
self.loadArray(segment)
def filterSeg(self, start, stop, audiodata):
# Selects the data between start-stop ms, relative to file start
# and plays it.
self.timeoffset = max(0, start)
start = max(0, int(start * self.format().sampleRate() // 1000))
stop = min(int(stop * self.format().sampleRate() // 1000), len(audiodata))
segment = audiodata[start:stop]
self.loadArray(segment)
def loadArray(self, audiodata):
# Plays the entire audiodata: puts it onto a buffer
# and then starts the QAudioOutput from that buffer
if self.format().sampleSize() == 16:
audiodata = audiodata.astype('int16') # 16 corresponds to sampwidth=2
elif self.format().sampleSize() == 32:
audiodata = audiodata.astype('int32')
elif self.format().sampleSize() == 24:
audiodata = audiodata.astype('int32')
print("Warning: 24-bit sample playback currently not supported")
elif self.format().sampleSize() == 8:
audiodata = audiodata.astype('uint8')
else:
print("ERROR: sampleSize %d not supported" % self.format().sampleSize())
return
# double mono sound to get two channels - simplifies reading
if self.format().channelCount()==2:
audiodata = np.column_stack((audiodata, audiodata))
# write filtered output to a BytesIO buffer
self.tempout = io.BytesIO()
# NOTE: scale=None rescales using data minimum/max. This can cause clipping. Use scale="none" if this causes weird playback sound issues.
# in particular for 8bit samples, we need more scaling:
if self.format().sampleSize() == 8:
scale = (audiodata.min()/2, audiodata.max()*2)
else:
scale = None
wavio.write(self.tempout, audiodata, self.format().sampleRate(), scale=scale, sampwidth=self.format().sampleSize() // 8)
# copy BytesIO@write to QBuffer@read for playing
self.temparr = QByteArray(self.tempout.getvalue()[44:])
# self.tempout.close()
if self.tempin.isOpen():
self.tempin.close()
self.tempin.setBuffer(self.temparr)
self.tempin.open(QIODevice.ReadOnly)
# actual timer is launched here, with time offset set asynchronously
sleep(0.2)
self.start(self.tempin)
def restart(self):
self.tempin.seek(0)
self.start(self.tempin)
def applyVolSlider(self, value):
# passes UI volume nonlinearly
# value = QAudio.convertVolume(value / 100, QAudio.LogarithmicVolumeScale, QAudio.LinearVolumeScale)
value = (math.exp(value/50)-1)/(math.exp(2)-1)
self.setVolume(value)
class FlowLayout(QtGui.QLayout):
# This is the flow layout which lays out a set of spectrogram pictures on buttons (for HumanClassify2) as
# nicely as possible
# From https://gist.github.com/Cysu/7461066
def __init__(self, parent=None, margin=0, spacing=-1):
super(FlowLayout, self).__init__(parent)
if parent is not None:
self.setMargin(margin)
self.setSpacing(spacing)
self.itemList = []
self.margin = margin
def __del__(self):
item = self.takeAt(0)
while item:
item = self.takeAt(0)
def addItem(self, item):
self.itemList.append(item)
def count(self):
return len(self.itemList)
def itemAt(self, index):
if index >= 0 and index < len(self.itemList):
return self.itemList[index]
return None
def takeAt(self, index):
if index >= 0 and index < len(self.itemList):
return self.itemList.pop(index)
return None
def expandingDirections(self):
return QtCore.Qt.Orientations(QtCore.Qt.Orientation(0))
def hasHeightForWidth(self):
return True
def heightForWidth(self, width):
height = self._doLayout(QtCore.QRect(0, 0, width, 0), True)
return height
def setGeometry(self, rect):
super(FlowLayout, self).setGeometry(rect)
self._doLayout(rect, False)
def sizeHint(self):
return self.minimumSize()
# def minimumSize(self):
# size = QtCore.QSize()
#
# for item in self.itemList:
# size = size.expandedTo(item.minimumSize())
#
# size += QtCore.QSize(2 * self.margin(), 2 * self.margin())
# return size
def _doLayout(self, rect, testOnly):
x = rect.x()
y = rect.y()
lineHeight = 0
for item in self.itemList:
wid = item.widget()
spaceX = self.spacing() + wid.style().layoutSpacing(
QtGui.QSizePolicy.PushButton,
QtGui.QSizePolicy.PushButton,
QtCore.Qt.Horizontal)
spaceY = self.spacing() + wid.style().layoutSpacing(
QtGui.QSizePolicy.PushButton,
QtGui.QSizePolicy.PushButton,
QtCore.Qt.Vertical)
nextX = x + item.sizeHint().width() + spaceX
if nextX - spaceX > rect.right() and lineHeight > 0:
x = rect.x()
y = y + lineHeight + spaceY
nextX = x + item.sizeHint().width() + spaceX
lineHeight = 0
if not testOnly:
item.setGeometry(
QtCore.QRect(QtCore.QPoint(x, y), item.sizeHint()))
x = nextX
lineHeight = max(lineHeight, item.sizeHint().height())
return y + lineHeight - rect.y()
class MessagePopup(QMessageBox):
""" Convenience wrapper around QMessageBox.
TYPES, based on main icon:
w - warning
d - done (successful completion)
t - thinking (questions)
o - other
a - about
"""
def __init__(self, type, title, text):
super(QMessageBox, self).__init__()
self.setText(text)
self.setWindowTitle(title)
self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)
if (type=="w"):
self.setIconPixmap(QPixmap("img/Owl_warning.png"))
elif (type=="d"):
self.setIcon(QMessageBox.Information)
self.setIconPixmap(QPixmap("img/Owl_done.png"))
elif (type=="t"):
self.setIcon(QMessageBox.Information)
self.setIconPixmap(QPixmap("img/Owl_thinking.png"))
elif (type=="a"):
# Easy way to set ABOUT text here:
self.setIconPixmap(QPixmap("img/AviaNZ.png"))
self.setText("The AviaNZ Program, v3.3-devel (May 2021)")
self.setInformativeText("By Stephen Marsland, Victoria University of Wellington. With code by Nirosha Priyadarshani, Julius Juodakis, and Virginia Listanti. Input from Isabel Castro, Moira Pryde, Stuart Cockburn, Rebecca Stirnemann, Sumudu Purage, and Rebecca Huistra. \n [email protected]")
elif (type=="o"):
self.setIconPixmap(QPixmap("img/AviaNZ.png"))
self.setWindowIcon(QIcon("img/Avianz.ico"))
# by default, adding OK button. Can easily be overwritten after creating
self.setStandardButtons(QMessageBox.Ok)
class PicButton(QAbstractButton):
# Class for HumanClassify dialogs to put spectrograms on buttons
# Also includes playback capability.
def __init__(self, index, spec, audiodata, format, duration, unbufStart, unbufStop, lut, guides=None, guidecol=None, loop=False, parent=None, cluster=False):
super(PicButton, self).__init__(parent)
self.index = index
self.mark = "green"
self.spec = spec
self.unbufStart = unbufStart
self.unbufStop = unbufStop
self.cluster = cluster
self.setMouseTracking(True)
self.playButton = QtGui.QToolButton(self)
self.playButton.setIcon(self.style().standardIcon(QtGui.QStyle.SP_MediaPlay))
self.playButton.hide()
# batmode frequency guides (in Y positions 0-1)
self.guides = guides
if guides is not None:
self.guidelines = [0]*len(self.guides)
self.guidecol = [QColor(*col) for col in guidecol]
# check if playback possible (e.g. batmode)
if len(audiodata)>0:
self.noaudio = False
self.playButton.clicked.connect(self.playImage)
else:
self.noaudio = True
# setImage reads some properties from self, to allow easy update
# when color map changes. Initialize with full colour scale,