viewer.py 11.4 KB
Newer Older
Anthony Larcher's avatar
Anthony Larcher committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# -*- coding: utf-8 -*-
#
# This file is part of s4d.
#
# s4d is a python package for speaker diarization.
# Home page: http://www-lium.univ-lemans.fr/s4d/
#
# s4d is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# s4d 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with s4d.  If not, see <http://www.gnu.org/licenses/>.


"""
Anthony Larcher's avatar
Anthony Larcher committed
23
Copyright 2014-2020 Sylvain Meignier
Anthony Larcher's avatar
Anthony Larcher committed
24
"""
Sylvain Meignier's avatar
Origin  
Sylvain Meignier committed
25
26

import matplotlib.pyplot as plot
Anthony Larcher's avatar
Anthony Larcher committed
27

Sylvain Meignier's avatar
Origin  
Sylvain Meignier committed
28
from matplotlib.patches import Rectangle
Anthony Larcher's avatar
Anthony Larcher committed
29
from .player import AudioPlayer
Sylvain Meignier's avatar
Origin  
Sylvain Meignier committed
30
31
32
33
34
35
36


class PlotDiar:
    """
    A viewer of segmentation
    """
    def __init__(self, seg, wav=None, title='', gui=False, pick=False, vgrid=False, size=(18, 9)):
Anthony Larcher's avatar
Anthony Larcher committed
37
38
39
40
41
42
43
44
45
46
        """

        :param seg:
        :param wav:
        :param title:
        :param gui:
        :param pick:
        :param vgrid:
        :param size:
        """
Sylvain Meignier's avatar
Origin  
Sylvain Meignier committed
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
        self.rect_picked = None
        self.rect_color = (0.0, 0.6, 1.0, 1.0)  # '#0099FF'
        self.rect_selected_color = (0.75, 0.75, 0, 1.0)  # 'y'

        plot.rcParams['keymap.fullscreen'] = 'ctrl+f'
        plot.rcParams['keymap.home'] = ''
        plot.rcParams['keymap.back'] = ''
        plot.rcParams['keymap.forward'] = ''
        plot.rcParams['keymap.pan'] = ''
        plot.rcParams['keymap.zoom'] = 'ctrl+z'
        plot.rcParams['keymap.quit'] = 'ctrl+q'
        plot.rcParams['keymap.grid'] = ''
        plot.rcParams['keymap.yscale'] = ''
        plot.rcParams['keymap.xscale'] = ''
        plot.rcParams['keymap.all_axes'] = ''
        plot.rcParams['toolbar'] = 'None'
        plot.rcParams['keymap.save'] = 'ctrl+s'
Sylvain Meignier's avatar
Sylvain Meignier committed
64
        # plot.rcParams.update({'font.family': 'courrier'})
Sylvain Meignier's avatar
Origin  
Sylvain Meignier committed
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

        self.pick = pick
        self.gui = gui
        self.vgrid = vgrid
        self.fig = plot.figure(figsize=size, facecolor='white', tight_layout=True)
        self.title = title

        self.ax = self.fig.add_subplot(1, 1, 1)
        cids = list()
        if self.gui:
            cids.append(
                self.fig.canvas.mpl_connect('key_press_event', self._on_keypress))
            cids.append(
                self.fig.canvas.mpl_connect('button_press_event', self._on_click))
            if pick:
                cids.append(self.fig.canvas.mpl_connect('pick_event', self._on_pick))
        self.height = 5
        self.maxx = 0
        self.maxy = 0
        self.end_play = 0
        self.seg = seg
        self.wav = wav
        self.audio = None
        if self.wav is not None and self.gui:
            self.audio = AudioPlayer(wav)
            self.timer = self.fig.canvas.new_timer(interval=10)
            self.timer.add_callback(self._update_timeline)
            self.timer.start()

        self.timeline = self.ax.plot([0, 0], [0, 0], color='r')[-1]
95
        self.map = self.seg.make_index(['show', 'cluster'])
Sylvain Meignier's avatar
Origin  
Sylvain Meignier committed
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
        self.time_stamp = list()
        self.time_stamp_idx = 0

    def _draw_timeline(self, t):
        """
        Draw the timeline a position t
        :param t: in second, a float

        """
        min, max = self.ax.get_ylim()
        self.timeline.set_data([t, t], [min, max])
        self._draw_info(t)

    def _update_timeline(self):
        """
        Update the timeline given the position in the audio player

        """
        if self.audio is not None and self.audio.playing():
            t = self.audio.time()
            min, max = self.ax.get_xlim()
            if t > self.end_play and self.rect_picked is not None:
                self.audio.pause()
                self.end_play = self.maxx
            self._draw_timeline(t)
            if t > max:
                self._dec_right(min, max)
            if t < min:
                self._dec_left(min, max)
            self.fig.canvas.draw()

    def _draw_info(self, t):
        """
        Draw information on segment and timestamp
        :param t: a float
        :return:
        """
        ch = 'time:{:s} ({:.3f} sec {:d} frame)'.format(self._hms(t), t,
                                                        int(t * 100))
        ch2 = '\n\n\n'
        if self.rect_picked is not None:
            s = self.rect_picked.get_x()
            w = self.rect_picked.get_width()
            e = s + w
            ch2 = 'segment  start: {:20s} ({:8.2f} sec {:8d} frame)\n'.format(
                self._hms(s), s, int(s * 100))
            ch2 += 'segment   stop: {:20s} ({:8.2f} sec {:8d} frame)\n'.format(
                self._hms(e), e, int(e * 100))
            ch2 += 'segment lenght: {:20s} ({:8.2f} sec {:8d} frame)\n'.format(
                self._hms(w), w, int(w * 100))

        plot.xlabel(ch + '\n' + ch2)

    def draw(self):
        """
        Draw the segmentation

        """
        y = 0
        labels_pos = []
        labels = []
        for show in self.map:
158
            for cluster in sorted(self.map[show].keys()):
159
                labels.append(cluster)
Sylvain Meignier's avatar
Origin  
Sylvain Meignier committed
160
                labels_pos.append(y + self.height // 2)
161
                for row in self.map[show][cluster]:
Sylvain Meignier's avatar
Origin  
Sylvain Meignier committed
162
163
164
                    x = row['start'] / 100
                    self.time_stamp.append(x)
                    self.time_stamp.append(row['stop'] / 100)
165
                    w = row.duration() / 100
Sylvain Meignier's avatar
Origin  
Sylvain Meignier committed
166
167
                    self.maxx = max(self.maxx, row['stop'] / 100)
                    c = self.rect_color
168
                    if row._attributes.exist('color'):
Sylvain Meignier's avatar
Origin  
Sylvain Meignier committed
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
                        c = row['color']
                    rect = plot.Rectangle((x, y), w, self.height,
                                          color=c, picker=self.pick)
                    self.ax.add_patch(rect)
                y += self.height
        if self.gui:
            plot.xlim([0, min(600, self.maxx)])
        else:
            plot.xlim([0, self.maxx])

        plot.ylim([0, y])
        plot.yticks(labels_pos, labels)
        self.maxy = y
        self.end_play = self.maxx
        for show in self.map:
184
            for cluster in self.map[show]:
Sylvain Meignier's avatar
Origin  
Sylvain Meignier committed
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
                self.ax.plot([0, self.maxx], [y, y], linestyle=':',
                             color='#AAAAAA')
                y -= self.height

        plot.title(self.title + ' (last frame: ' + str(self.maxx) + ')')
        if self.gui:
            self._draw_info(0)
        plot.tight_layout()
        self.time_stamp = list(set(self.time_stamp))
        self.time_stamp.sort()

        if self.vgrid:
            for x in  self.time_stamp:
                self.ax.plot([x, x], [0, self.maxy], linestyle=':',
                             color='#AAAAAA')

    def _dec_right(self, min, max):
        """
        Move right
        :param min: a float
        :param max: a float

        """
        dec = (max - min) // 10
        diff = max - min
        if max + dec <= self.maxx:
Sylvain Meignier's avatar
Sylvain Meignier committed
211
            print('** 1 ', min, max, dec)
Sylvain Meignier's avatar
Origin  
Sylvain Meignier committed
212
213
            plot.xlim(min + dec, max + dec)
        else:
Sylvain Meignier's avatar
Sylvain Meignier committed
214
            print('** 2 ', min, max, dec, diff)
Sylvain Meignier's avatar
Origin  
Sylvain Meignier committed
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
            plot.xlim(self.maxx - diff, self.maxx)

    def _dec_left(self, min, max):
        """
        Move left
        :param min: a float
        :param max: a float

        """
        dec = (max - min) // 10
        diff = max - min
        if min - dec >= 0:
            plot.xlim(min - dec, max - dec)
        else:
            plot.xlim(0, diff)

    def _on_keypress(self, event):
        """
        manage the keypress event
        :param event: a key event

        """
Sylvain Meignier's avatar
Sylvain Meignier committed
237
238
        hmin, hmax = self.ax.get_xlim()
        diff = hmax - hmin
Sylvain Meignier's avatar
Origin  
Sylvain Meignier committed
239
        if event.key == 'ctrl++' or event.key == 'ctrl+=':
Sylvain Meignier's avatar
Sylvain Meignier committed
240
            plot.xlim(hmin * 1.5, hmax * 1.5)
Sylvain Meignier's avatar
Origin  
Sylvain Meignier committed
241
        elif event.key == 'ctrl+-':
Sylvain Meignier's avatar
Sylvain Meignier committed
242
            plot.xlim(hmin / 1.5, hmax / 1.5)
Sylvain Meignier's avatar
Origin  
Sylvain Meignier committed
243
244
245
246
        elif event.key == 'escape':
            plot.xlim(0, self.maxx)
            plot.ylim(0, self.maxy)
        elif event.key == 'right':
Sylvain Meignier's avatar
Sylvain Meignier committed
247
            self._dec_right(hmin, hmax)
Sylvain Meignier's avatar
Origin  
Sylvain Meignier committed
248
        elif event.key == 'left':
Sylvain Meignier's avatar
Sylvain Meignier committed
249
            self._dec_left(hmin, hmax)
Sylvain Meignier's avatar
Origin  
Sylvain Meignier committed
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
        elif event.key == 'ctrl+right':
            plot.xlim(self.maxx - diff, self.maxx)
        elif event.key == 'ctrl+left':
            plot.xlim(0, diff)
        elif event.key == 'alt+right':
            self.time_stamp_idx = min(len(self.time_stamp)-1, self.time_stamp_idx + 1)
            if self.audio is not None:
                self.audio.pause()
                self.audio.seek(self.time_stamp[self.time_stamp_idx])
            self._draw_timeline(self.time_stamp[self.time_stamp_idx])
        elif event.key == 'alt+left':
            self.time_stamp_idx = max(0, self.time_stamp_idx - 1)
            if self.audio is not None:
                self.audio.pause()
                self.audio.seek(self.time_stamp[self.time_stamp_idx])
            self._draw_timeline(self.time_stamp[self.time_stamp_idx])
        elif event.key is None and self.audio is not None:
            self.audio.play()
        elif event.key == ' ' and self.audio is not None:
            self.audio.pause()

        self.fig.canvas.draw()

    def _on_click(self, event):
        """
        manage the mouse event
        :param event: a mouse event

        """
        if event.xdata is not None and self.rect_picked is None:
            if self.audio is not None:
                self.audio.pause()
                self.audio.seek(event.xdata)
            self._draw_timeline(event.xdata)
            self.fig.canvas.draw()

    def _on_pick(self, event):
        """
        manage the selection of a segment
        :param event: a picked event

        """
        if isinstance(event.artist, Rectangle) and event.mouseevent.dblclick:
            print('on pick dbclick')
            rect = event.artist
            x, y = rect.get_xy()
            w = rect.get_width()
            c = rect.get_fc()
            if self.rect_picked is not None:
                if self._colors_are_equal(c, self.rect_selected_color):
                    rect.set_color(self.rect_color)
                    self.rect_picked = None
                    self.end_play = self.maxx
                else:
                    self.rect_picked.set_color(self.rect_color)
                    rect.set_color(self.rect_selected_color)
                    self.rect_picked = rect
                    if self.audio is not None:
                        self.audio.pause()
                        self.audio.seek(x)
Sylvain Meignier's avatar
Sylvain Meignier committed
310
                    self.time_stamp_idx = self.time_stamp.index(x)
Sylvain Meignier's avatar
Origin  
Sylvain Meignier committed
311
312
313
314
315
316
317
318
319
                    self.end_play = x + w
                    self._draw_timeline(x)
            else:
                rect.set_color(self.rect_selected_color)
                self.rect_picked = rect

                if self.audio is not None:
                    self.audio.pause()
                    self.audio.seek(x)
Sylvain Meignier's avatar
Sylvain Meignier committed
320
                self.time_stamp_idx = self.time_stamp.index(x)
Sylvain Meignier's avatar
Origin  
Sylvain Meignier committed
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
                self.end_play = x + w
                self._draw_timeline(x)

            self.fig.canvas.draw()

    @classmethod
    def _colors_are_equal(cls, c1, c2):
        """
        Compare two colors
        """
        for i in range(4):
            if c1[i] != c2[i]:
                return False
        return True

    @classmethod
    def _hms(cls, s):
        """
        conversion of seconds into hours, minutes and secondes
        :param s:
        :return: int, int, float
        """
        h = int(s) // 3600
        s %= 3600
        m = int(s) // 60
        s %= 60
        return '{:d}:{:d}:{:.2f}'.format(h, m, s)