diar_tools.py 129 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
25
26
"""


27
28
from __future__ import unicode_literals

Anthony Larcher's avatar
Anthony Larcher committed
29
30
import collections
import copy
31
32
33
34
35
import logging
import numbers
import numpy as np
import pandas as pd
import pyannote.metrics.segmentation as pyaseg
36
import pyannote.metrics.diarization as pyadiar
37
import pyannote.core as pyacore
Anthony Larcher's avatar
Anthony Larcher committed
38
39
40

from .scoring import DER
from .diar import Diar, Segment
41
42
43
44
45

# Returns a diar object by adjusting the boundaries according both a diar and a tolerance
## WARNING: The boundary matching rests on the nearest distance. In any case, it doesn't take into consideration the labels
## tolerance: In centiseconds
def adjustBoundAccordingToDiarAndTolerance(diar,diarBasis,diarUem=None,tolerance=25):
Anthony Larcher's avatar
Anthony Larcher committed
46
47
48
49
50
51
52
53
    """

    :param diar:
    :param diarBasis:
    :param diarUem:
    :param tolerance:
    :return:
    """
54
55
    assert isinstance(diar,Diar) and isinstance(diarBasis,Diar) and ((isinstance(diarUem,Diar) and len(diarOverlapArea(diarUem))==0) or diarUem is None) and isinstance(tolerance,numbers.Number)
    basis=boundHypToChange(diar,diarBasis,diarUem,False,tolerance)
56
57
58
59
60
61
62
63
64
    basisI={v: k for k, v in basis.items()}
    dOut=copy.deepcopy(diar)
    for i in dOut:
        if i['start'] in basisI:
            i['start']=basisI[i['start']]
        if i['stop'] in basisI:
            i['stop']=basisI[i['stop']]
    return dOut

65
66
# Returns a diar object with a new column detailing the overlapped segments
def advancedOverlapDiar(diar):
Anthony Larcher's avatar
Anthony Larcher committed
67
68
69
70
71
    """

    :param diar:
    :return:
    """
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
    assert isinstance(diar,Diar)
    out_diar=diarOverlapArea(diar)
    out_diar.add_attribut("OverlappedSegments",None)
    for i in out_diar:
        listTmp=list()
        for j in diar:
            if Segment.intersection(i,j) is not None:
                listTmp.append(copy.deepcopy(j))
        i["OverlappedSegments"]=listTmp

    out_diar_tmp=copy.deepcopy(diar)
    out_diar_tmp.add_attribut("OverlappedSegments",None)
    for i in out_diar:
        out_diar_tmp=releaseFramesFromSegment(i,out_diar_tmp)
    out_diar.append_diar(out_diar_tmp)
    out_diar.sort()
    return out_diar

90
91
92
93
94
95
# Returns a dict object with an automaton which only corrects the assignment errors
## WARNING: The diarizations in parameter have to be with no overlapped segment. Put them apart
## WARNING: The automaton follows the temporal order
## tolerance: In centiseconds
## diarFinal__clusterToDeleteAccordingToDiarRef: List of clusters to delete in the diarFinal only
def automatonAssignment(diarHyp,diarRef,diarUem=None,tolerance=0,diarFinal__clusterToDeleteAccordingToDiarRef=list()):
Anthony Larcher's avatar
Anthony Larcher committed
96
97
98
99
100
101
102
103
104
    """

    :param diarHyp:
    :param diarRef:
    :param diarUem:
    :param tolerance:
    :param diarFinal__clusterToDeleteAccordingToDiarRef:
    :return:
    """
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
    assert isinstance(diarHyp,Diar) and (diarUem is None or isinstance(diarUem,Diar)) and isinstance(diarRef,Diar) and isinstance(tolerance,numbers.Number) and isinstance(diarFinal__clusterToDeleteAccordingToDiarRef,list)
    for u in diarFinal__clusterToDeleteAccordingToDiarRef:
        assert isinstance(u,str)

    actionsAssignmentHumanCorrection=collections.OrderedDict()
    actionsAssignmentCreate=list()
    actionsAssignmentChange=list()
    actionsAssignmentNothing=list()
    actionsAssignmentCreateBis=list()
    actionsAssignmentHumanCorrection["Create"]=actionsAssignmentCreate
    actionsAssignmentHumanCorrection["Change"]=actionsAssignmentChange
    actionsAssignmentHumanCorrection["Nothing"]=actionsAssignmentNothing
    dictionary=dict()

    actionsIncrementalAssignmentHumanCorrection=collections.OrderedDict()
    actionsIncrementalAssignmentCreate=list()
    actionsIncrementalAssignmentChange=list()
    actionsIncrementalAssignmentNothing=list()
    actionsIncrementalAssignmentHumanCorrection["Create"]=actionsIncrementalAssignmentCreate
    actionsIncrementalAssignmentHumanCorrection["Change"]=actionsIncrementalAssignmentChange
    actionsIncrementalAssignmentHumanCorrection["Nothing"]=actionsIncrementalAssignmentNothing

    diarIncremental=dict()

    idxIncremental=dict()

    if diarUem is not None:
        diarRef=releaseFramesAccordingToDiar(diarRef,diarUem)
        diarHyp=releaseFramesAccordingToDiar(diarHyp,diarUem)

    diarRaw=Diar()
    diarRaw.append(start=min(diarRef.unique('start')+diarHyp.unique('start')),stop=max(diarRef.unique('stop')+diarHyp.unique('stop')))
    diarRef=copy.deepcopy(diarRef)
    diarHyp=copy.deepcopy(diarHyp)
    diarRef.sort()
    diarHyp.sort()
    tolerance=abs(tolerance)     

    assert len(diarOverlapArea(diarRef))==0, "Error: diarRef parameter have some overlapped segments.\nReason: No overlap segment allowed.\nSolution: Please put them apart.\n"
    assert len(diarOverlapArea(diarHyp))==0, "Error: diarHyp parameter have some overlapped segments.\nReason: No overlap segment allowed.\nSolution: Please put them apart.\n"

    actionsIncrementalAssignmentCreateTurn=list()
    actionsIncrementalAssignmentChangeTurn=list()
    actionsIncrementalAssignmentNothingTurn=list()

    # To avoid to create clusters with the same id
    cpt=0

    for j in diarHyp:

        idxIncremental[len(idxIncremental)]=(j['start'],j['stop'])
        valueRefTmp=None
        diarTmp=Diar()
        diarTmp.append_seg(j)
        match=matchingSegmentsFromSegment(j,diarRef)

        bestMatchValue=None
        bestMatch=None
        if len(match)!=0:
            for x in match:
                if bestMatchValue is None:
                    bestMatchValue=match[x]
                    bestMatch=x
                elif bestMatchValue.duration()<match[x].duration():
                    bestMatchValue=match[x]
                    bestMatch=x
        fakeTmp=Diar.intersection(diarTmp,diarRef)
        if fakeTmp is not None:
            fakeDuration=j.duration()-fakeTmp.duration()
        else:
            fakeDuration=0

        if len(match)!=0:
            if bestMatchValue.duration() < fakeDuration:
                valueRefTmp='speakerManualFake'
            else:
                valueRefTmp=bestMatch
        else:
            valueRefTmp='speakerManualFake'

        keep=False
        if valueRefTmp!='speakerManualFake':
            for y in diarRef:
                if Segment.intersection(y,j) is not None and segmentExistAccordingToTolerance(y,tolerance):
                    keep=True
                    break
        else:
            diarRefFake=copy.deepcopy(diarRaw)
            if diarUem is not None:
                diarRefFake=releaseFramesAccordingToDiar(diar=diarRefFake,basisDiar=diarUem)
            diarRefFake=releaseFramesAccordingToDiar(diar=diarRefFake,basisDiar=diarRef)
            
            for y in diarRefFake:
                y['show']==j['show']
                if Segment.intersection(y,j) is not None and segmentExistAccordingToTolerance(y,tolerance):
                    keep=True
                    break

        if not keep:
            diarHyp=dropSegment(j,diarHyp)
        else:
            applyChange=False
            if valueRefTmp == "speakerManualFake":
                speakerName="speakerManualFake"
            else:
                speakerName="speakerManual"
            if valueRefTmp not in dictionary:
                if j['cluster'] in actionsAssignmentCreateBis:
                    dictionary[valueRefTmp]=speakerName+str(cpt+1)
                    actionsAssignmentCreateBis.append(speakerName+str(cpt+1))
                    actionsAssignmentCreate.append([copy.deepcopy(valueRefTmp),speakerName+str(cpt+1),copy.deepcopy(j)])
                    actionsIncrementalAssignmentCreateTurn.append([copy.deepcopy(valueRefTmp),speakerName+str(cpt+1),copy.deepcopy(j)])
                    applyChange=True
                    cpt+=1
                else:
                    dictionary[valueRefTmp]=copy.deepcopy(j['cluster'])
                    actionsAssignmentCreateBis.append(copy.deepcopy(j['cluster']))
                    actionsAssignmentCreate.append(copy.deepcopy([valueRefTmp,j['cluster'],copy.deepcopy(j)]))
                    actionsIncrementalAssignmentCreateTurn.append(copy.deepcopy([valueRefTmp,j['cluster'],copy.deepcopy(j)]))
            else:
                if j['cluster'] == dictionary[valueRefTmp]:
                    actionsAssignmentNothing.append(copy.deepcopy(j))
                    actionsIncrementalAssignmentNothingTurn.append(copy.deepcopy(j))
                else:
                    actionsAssignmentChange.append(copy.deepcopy([dictionary[valueRefTmp],j]))
                    actionsIncrementalAssignmentChangeTurn.append(copy.deepcopy([dictionary[valueRefTmp],j]))
                    applyChange=True
            if applyChange:
                # Updates the diar object for the merges afterward
                segmentTmp=copy.deepcopy(j)
                segmentTmp['cluster']=dictionary[valueRefTmp]
                diarHyp=dropSegment(j,diarHyp)
                diarHyp.append_seg(segmentTmp)
                diarHyp.sort()

        actionsIncrementalAssignmentCreate.append(actionsIncrementalAssignmentCreateTurn)
        actionsIncrementalAssignmentChange.append(actionsIncrementalAssignmentChangeTurn)
        actionsIncrementalAssignmentNothing.append(actionsIncrementalAssignmentNothingTurn)
        actionsIncrementalAssignmentCreateTurn=list()
        actionsIncrementalAssignmentChangeTurn=list()
        actionsIncrementalAssignmentNothingTurn=list()

        # Stores each diar after each human interaction
        diarIncremental[len(diarIncremental)]=(copy.deepcopy(diarHyp))

    # Deletes segments whose the cluster mainly matches with those present in diarFinal__clusterToDeleteAccordingToDiarRef
    for u in diarFinal__clusterToDeleteAccordingToDiarRef:
        if u in dictionary:
            diarHyp=dropCluster(dictionary[u],diarHyp)
    
    rtn=dict()
    rtn['idxIncremental']=idxIncremental
    rtn['diar']=dict()
    rtn['diar']['final']=diarHyp
    rtn['diar']['incremental']=diarIncremental
    rtn['action']=dict()
    rtn['action']['incremental']=actionsIncrementalAssignmentHumanCorrection
    rtn['action']['sum']=actionsAssignmentHumanCorrection

    return rtn

# Returns a dict object with an automaton which only corrects the segmentation errors 
## WARNING: The diarizations in parameter have to be with no overlapped segment. Put them apart
## WARNING: The automaton follows the temporal order
## tolerance: In centiseconds
## diarFinal__clusterToDeleteAccordingToDiarRef: List of clusters to delete in the diarFinal only
271
## modeNoGap: Drops or not the segment actions (i.e. createSegment & deleteSegment)
272
273
274
## modeNoGap__mergeStrat_BiggestCluster: Whether we merge in the temporal order or first the biggest cluster for a given reference segment (only useful when the modeNoGap is False)
## deleteBoundarySameConsecutiveSpk: Whether we delete a boundary for two consecutive segments with the same speaker
def automatonSegmentation(diarHyp,diarRef,diarUem=None,tolerance=0,modeNoGap=False,modeNoGap__mergeStrat_BiggestCluster=False,diarFinal__clusterToDeleteAccordingToDiarRef=list(),deleteBoundarySameConsecutiveSpk=False):
Anthony Larcher's avatar
Anthony Larcher committed
275
276
277
278
279
280
281
282
283
284
285
286
    """

    :param diarHyp:
    :param diarRef:
    :param diarUem:
    :param tolerance:
    :param modeNoGap:
    :param modeNoGap__mergeStrat_BiggestCluster:
    :param diarFinal__clusterToDeleteAccordingToDiarRef:
    :param deleteBoundarySameConsecutiveSpk:
    :return:
    """
287
    assert isinstance(diarHyp,Diar) and isinstance(diarRef,Diar) and isinstance(modeNoGap__mergeStrat_BiggestCluster,bool) and isinstance(modeNoGap,bool) and (diarUem is None or isinstance(diarUem,Diar)) and isinstance(tolerance,numbers.Number) and isinstance(diarFinal__clusterToDeleteAccordingToDiarRef,list) and isinstance(deleteBoundarySameConsecutiveSpk,bool)
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
    for u in diarFinal__clusterToDeleteAccordingToDiarRef:
        assert isinstance(u,str)

    actionsSegmentationHumanCorrection=collections.OrderedDict()
    actionsSegmentationBoundary=collections.OrderedDict()
    actionsSegmentationBoundaryCreate=list()
    actionsSegmentationBoundaryMerge=list()
    # Create Format: [segment, position of the new boundary] -> We have to cut the segment into two parts
    actionsSegmentationBoundary["Create"]=actionsSegmentationBoundaryCreate
    # Merge Format: [segment1, segment2] -> We have to move the segment (the two segments have to have the same attributes)
    actionsSegmentationBoundary["Merge"]=actionsSegmentationBoundaryMerge
    if modeNoGap == False:
        actionsSegmentationSegment=collections.OrderedDict()        
        actionsSegmentationSegmentCreate=list()
        actionsSegmentationSegmentDelete=list()
        # Create Format: [show,cluster,cluster_type, start, end] -> We have to create a new segment
        actionsSegmentationSegment["Create"]=actionsSegmentationSegmentCreate
        # Delete Format: [segment] -> We have to delete a segment
        actionsSegmentationSegment["Delete"]=actionsSegmentationSegmentDelete
    # Nothing Format: [segment] -> Nothing to do, correct segmentation
    actionsSegmentationNothing=list()
    actionsSegmentationHumanCorrection["Boundary"]=actionsSegmentationBoundary
    if modeNoGap == False:
        actionsSegmentationHumanCorrection["Segment"]=actionsSegmentationSegment
    actionsSegmentationHumanCorrection["Nothing"]=actionsSegmentationNothing

    actionsIncrementalSegmentationHumanCorrection=collections.OrderedDict()
    actionsIncrementalSegmentationBoundary=collections.OrderedDict()
    actionsIncrementalSegmentationBoundaryCreate=list()
    actionsIncrementalSegmentationBoundaryMerge=list()
    # Create Format: [segment, position of the new boundary] -> We have to cut the segment into two parts
    actionsIncrementalSegmentationBoundary["Create"]=actionsIncrementalSegmentationBoundaryCreate
    # Merge Format: [segment1, segment2] -> We have to move the segment (the two segments have to have the same attributes)
    actionsIncrementalSegmentationBoundary["Merge"]=actionsIncrementalSegmentationBoundaryMerge
    if modeNoGap == False:
        actionsIncrementalSegmentationSegment=collections.OrderedDict()        
        actionsIncrementalSegmentationSegmentCreate=list()
        actionsIncrementalSegmentationSegmentDelete=list()
        # Create Format: [show,cluster,cluster_type, start, end] -> We have to create a new segment
        actionsIncrementalSegmentationSegment["Create"]=actionsIncrementalSegmentationSegmentCreate
        # Delete Format: [segment] -> We have to delete a segment
        actionsIncrementalSegmentationSegment["Delete"]=actionsIncrementalSegmentationSegmentDelete
    # Nothing Format: [segment] -> Nothing to do. Correct segmentation
    actionsIncrementalSegmentationNothing=list()
    actionsIncrementalSegmentationHumanCorrection["Boundary"]=actionsIncrementalSegmentationBoundary
    if modeNoGap == False:
        actionsIncrementalSegmentationHumanCorrection["Segment"]=actionsIncrementalSegmentationSegment
    actionsIncrementalSegmentationHumanCorrection["Nothing"]=actionsIncrementalSegmentationNothing

    diarIncremental=dict()

    idxIncremental=dict()

    if diarUem is not None:
        diarRef=releaseFramesAccordingToDiar(diarRef,diarUem)
        diarHyp=releaseFramesAccordingToDiar(diarHyp,diarUem)

    diarRaw=Diar()
    diarRaw.append(start=min(diarRef.unique('start')+diarHyp.unique('start')),stop=max(diarRef.unique('stop')+diarHyp.unique('stop')))
    diarRef=copy.deepcopy(diarRef)
    diarHyp=copy.deepcopy(diarHyp)
    showname=diarRef.unique('show')[0]
    diarRef.sort()
    diarHyp.sort()
352
353
354
355
    tolerance=abs(tolerance)
    if not strictBoundary:
        diarRef.pack()
        diarHyp.pack()     
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

    assert len(diarOverlapArea(diarRef))==0, "Error: diarRef parameter have some overlapped segments.\nReason: No overlap segment allowed.\nSolution: Please put them apart.\n"
    assert len(diarOverlapArea(diarHyp))==0, "Error: diarHyp parameter have some overlapped segments.\nReason: No overlap segment allowed.\nSolution: Please put them apart.\n"

    actionsIncrementalSegmentationBoundaryCreateTurn=list()
    actionsIncrementalSegmentationBoundaryMergeTurn=list()
    if modeNoGap == False:
        actionsIncrementalSegmentationSegmentCreateTurn=list()
        actionsIncrementalSegmentationSegmentDeleteTurn=list()
    actionsIncrementalSegmentationNothingTurn=list()

    # To avoid to create clusters with the same id
    cpt=0

    for i,valueRef in enumerate(diarRef):
    # WARNING: Each string supposes the start boundary is validate/correct (modified in the previous iteration if need be), that it doesn't overtake the reference segment (works with the tolerance as well)

    # SELECTS ALL THE HYPOTHESIS SEGMENTS BEFORE THE FIRST REFERENCE SEGMENT (means wrong clustered since silence in the reference)
        if i==0:
            valueTmp=copy.deepcopy(diarHyp)
            for y in diarHyp:
                if y['start']<(valueRef['start']-tolerance) and y['stop']<=(valueRef['start']+tolerance):
                    if modeNoGap==False:
                        actionsSegmentationSegmentDelete.append(copy.deepcopy(y))
                        actionsIncrementalSegmentationSegmentDeleteTurn.append(copy.deepcopy(y))
                    valueTmp=dropSegment(y,valueTmp)
                elif y['start']<(valueRef['start']-tolerance) and y['stop']>(valueRef['start']+tolerance):
                    actionsSegmentationBoundaryCreate.append(copy.deepcopy([y,valueRef['start']]))
                    actionsIncrementalSegmentationBoundaryCreateTurn.append(copy.deepcopy([y,valueRef['start']]))
                    valueTmp=splitSegment(y,valueTmp,valueRef['start'])
                    yTmp=copy.deepcopy(y)
                    yTmp['stop']=valueRef['start']
                    if modeNoGap==False:
                        actionsSegmentationSegmentDelete.append(copy.deepcopy(yTmp))
                        actionsIncrementalSegmentationSegmentDeleteTurn.append(copy.deepcopy(yTmp))
                    valueTmp=dropSegment(yTmp,valueTmp)
                elif tolerance!=0 and y['start']>=(valueRef['start']-tolerance) and y['stop']<=(valueRef['start']+tolerance):
                    # No action, all the segments in this tous les segments are dropped
                    valueTmp=dropSegment(y,valueTmp)
                else:
                    break
            # Updates diarHyp
            diarHyp=valueTmp

    # SELECTS ALL THE HYPOTHESIS SEGMENTS BETWEEN TWO REFERENCE SEGMENTS AND MAKES THEM SILENCE
        if i!=0 and diarRef[i-1]['stop']!=valueRef['start']:
            valueRefPrev=diarRef[i-1]
            valueTmp=copy.deepcopy(diarHyp)
            for y in diarHyp:
                if valueRef['start']-diarRef[i-1]['stop']<=tolerance*2:
                    # Directly deletes if the interval is smaller than tolerance*2
                    if y['start']>=(valueRefPrev['stop']-tolerance) and y['stop']<=(valueRef['start']+tolerance):
                        # No action, all the segments in this interval are dropped
                        valueTmp=dropSegment(y,valueTmp)
                    elif y['start']>=(valueRefPrev['stop']-tolerance) and y['stop']>(valueRef['start']+tolerance):
                        # Part allowing to know if we cut the segment or directly drop it
                        stopTmp=None
                        for u in range(i,len(diarRef)):
                            if y['stop']<=diarRef[u]['start']+tolerance:
                                break
                            elif y['stop']>diarRef[u]['start']+tolerance and y['stop']<=diarRef[u]['stop']+tolerance:
                                if segmentExistAccordingToTolerance(diarRef[u],tolerance):
                                    stopTmp=diarRef[u]['start']
                                break
                            elif not segmentExistAccordingToTolerance(diarRef[u],tolerance):
                                pass
                            else:
                                stopTmp=diarRef[u]['start']
                                break
                        if stopTmp is not None:
                            # Action here since tolerance of the valueRef segment and following ones don't crush it
                            if y['start']<(valueRef['start']-tolerance):
                                actionsSegmentationBoundaryCreate.append(copy.deepcopy([y,stopTmp]))
                                actionsIncrementalSegmentationBoundaryCreateTurn.append(copy.deepcopy([y,stopTmp]))
                                valueTmp=splitSegment(y,valueTmp,stopTmp)
                                yTmp=copy.deepcopy(y)
                                yTmp['stop']=stopTmp
                                if modeNoGap==False:
                                    actionsSegmentationSegmentDelete.append(copy.deepcopy(yTmp))
                                    actionsIncrementalSegmentationSegmentDeleteTurn.append(copy.deepcopy(yTmp))
                                valueTmp=dropSegment(yTmp,valueTmp)
                            break
                        else:
                            # No action since tolerance of the valueRef segment and following ones crush it
                            if modeNoGap==False:
                                actionsSegmentationSegmentDelete.append(copy.deepcopy(y))
                                actionsIncrementalSegmentationSegmentDeleteTurn.append(copy.deepcopy(y))
                            valueTmp=dropSegment(y,valueTmp)               
                else:
                    if y['start']>=(valueRefPrev['stop']-tolerance) and y['start']<(valueRef['start']-tolerance) and y['stop']<=(valueRef['start']+tolerance) and y['stop']>(valueRefPrev['stop']+tolerance):
                        if modeNoGap==False:
                            actionsSegmentationSegmentDelete.append(copy.deepcopy(y))
                            actionsIncrementalSegmentationSegmentDeleteTurn.append(copy.deepcopy(y))
                        valueTmp=dropSegment(y,valueTmp)
                    elif y['start']>=(valueRefPrev['stop']-tolerance) and y['start']<(valueRef['start']-tolerance) and y['stop']>(valueRef['start']+tolerance):
                        actionsSegmentationBoundaryCreate.append(copy.deepcopy([y,valueRef['start']]))
                        actionsIncrementalSegmentationBoundaryCreateTurn.append(copy.deepcopy([y,valueRef['start']]))
                        valueTmp=splitSegment(y,valueTmp,valueRef['start'])
                        yTmp=copy.deepcopy(y)
                        yTmp['stop']=valueRef['start']
                        if modeNoGap==False:
                            actionsSegmentationSegmentDelete.append(copy.deepcopy(yTmp))
                            actionsIncrementalSegmentationSegmentDeleteTurn.append(copy.deepcopy(yTmp))
                        valueTmp=dropSegment(yTmp,valueTmp)
                    elif tolerance!=0 and y['start']>=(valueRef['start']-tolerance) and y['stop']<=(valueRef['start']+tolerance):
                        # No action, all the segments in this interval are dropped
                        valueTmp=dropSegment(y,valueTmp)
                    elif y['start']>=(valueRef['start']-tolerance):
                        break
            # Updates diarHyp
            diarHyp=valueTmp

    # BEHAVIOR FOR A GIVEN REFERENCE SEGMENT
        # Counts the number of segment matching
        listHypRefSegment=list()
        # Whose the number in tolerance on the stop boundary
        listHypRefSegmentWithinTolerance=list()
        valueTmp=copy.deepcopy(diarHyp)
        for y in diarHyp:
            if Segment.intersection(y,valueRef) is not None:
                if tolerance==0: 
                    listHypRefSegment.append(y)
                elif tolerance!=0 and y['start']>=(valueRef['start']-tolerance):
                    listHypRefSegment.append(y)
                    if y['start']>=(valueRef['stop']-tolerance) and y['stop']<=(valueRef['stop']+tolerance):
                        listHypRefSegmentWithinTolerance.append(y)
        # If 0 creating
        if len(listHypRefSegment)==0 or (len(listHypRefSegment)==len(listHypRefSegmentWithinTolerance)):
            if modeNoGap == True:
                if segmentExistAccordingToTolerance(valueRef,tolerance):
                    logging.error("Cannot have absence of a segment in Transcriber mode.")
                    raise Exception("Absence of a segment.")
            if tolerance!=0:
                valueTmp2=copy.deepcopy(valueTmp)
                for u in valueTmp2:
                    if u['start']>=(valueRef['stop']-tolerance) and u['stop']<=(valueRef['stop']+tolerance):
                        # No action, all the segments in this interval are dropped
                        valueTmp=dropSegment(u,valueTmp)
                    elif u['start']>=(valueRef['stop']+tolerance):
                        break
            if modeNoGap == False:
                # Checks valueRef is not overtaken by tolerance
                if segmentExistAccordingToTolerance(valueRef,tolerance):
                    # Absence of the segment, so we create it
                    actionsSegmentationSegmentCreate.append(copy.deepcopy(Segment([valueRef['show'],valueRef['cluster'],'speakerManualNotDetected'+str(cpt+1),valueRef['start'],valueRef['stop']],['show','cluster','cluster_type','start','stop'])))                    
                    actionsIncrementalSegmentationSegmentCreateTurn.append(copy.deepcopy(Segment([valueRef['show'],valueRef['cluster'],'speakerManualNotDetected'+str(cpt+1),valueRef['start'],valueRef['stop']],['show','cluster','cluster_type','start','stop'])))  
                    valueTmp.append(show=showname, cluster='speakerManualNotDetected'+str(cpt+1), start=valueRef['start'], stop=valueRef['stop'])
                    cpt+=1
        # If 1 then affectation + moving boundary if need be and/or creating boundary on stop
        # If > 1 then affectation + moving boundary if need be and/or creating boundary on stop + merge
        else:
            # Checks valueRef is not overtaken by tolerance
            if not segmentExistAccordingToTolerance(valueRef,tolerance):
                for z in listHypRefSegment:
                    # Directly deletes if the interval is smaller than tolerance*2
                    if z['start']>=(valueRef['start']-tolerance) and z['stop']<=(valueRef['stop']+tolerance):
                        # No action, all the segments in this interval are dropped
                        valueTmp=dropSegment(z,valueTmp)
                    elif z['start']>=(valueRef['start']-tolerance) and z['stop']>(valueRef['stop']+tolerance):
                        # Part allowing to know if we cut the segment or directly drop it
                        stopTmp=None
                        for u in range(i+1,len(diarRef)):
                            if z['stop']<=diarRef[u]['start']+tolerance:
                                break
                            elif z['stop']>diarRef[u]['start']+tolerance and z['stop']<=diarRef[u]['stop']+tolerance:
                                if segmentExistAccordingToTolerance(diarRef[u],tolerance):
                                    stopTmp=diarRef[u]['start']
                                break
                            elif not segmentExistAccordingToTolerance(diarRef[u],tolerance):
                                pass
                            else:
                                stopTmp=diarRef[u]['start']
                                break
                        if stopTmp is not None:
                            # Action here since tolerance of the valueRef segment and following ones don't crush it
                            if z['start']<(valueRef['stop']-tolerance):
                                actionsSegmentationBoundaryCreate.append(copy.deepcopy([z,stopTmp]))
                                actionsIncrementalSegmentationBoundaryCreateTurn.append(copy.deepcopy([z,stopTmp]))
                                valueTmp=splitSegment(z,valueTmp,stopTmp)
                                zTmp=copy.deepcopy(z)
                                zTmp['stop']=stopTmp
                                if modeNoGap == False:
                                    actionsSegmentationSegmentDelete.append(copy.deepcopy(zTmp))
                                    actionsIncrementalSegmentationSegmentDeleteTurn.append(copy.deepcopy(zTmp))
                                valueTmp=dropSegment(zTmp,valueTmp)
                            break
                        else:
                            # No action since tolerance of the valueRef segment and following ones crush it
                            if modeNoGap == False:
                                actionsSegmentationSegmentDelete.append(copy.deepcopy(z))
                                actionsIncrementalSegmentationSegmentDeleteTurn.append(copy.deepcopy(z))
                            valueTmp=dropSegment(z,valueTmp)
                # Drops the segments (left which are not in listHypRefSegment) in the tolerance margin (+ or - tolerance)
                valueTmp2=copy.deepcopy(valueTmp)
                for u in valueTmp2:
                    if u['start']>=(valueRef['stop']-tolerance) and u['stop']<=(valueRef['stop']+tolerance):
                        # No action, all the segments in this interval are dropped
                        valueTmp=dropSegment(u,valueTmp)
                    elif u['start']>=(valueRef['stop']+tolerance):
                        break
            else:
                # Allows to know whether we do treatments for segments with wrong boundaries
                perfectBoundary=False
                # Checks perfect boundary
                if len(listHypRefSegment)==1 and boundariesInTolerance(boundarySegment=listHypRefSegment[0],segment=valueRef,tolerance=tolerance):
                    actionsSegmentationNothing.append(copy.deepcopy(listHypRefSegment[0]))
                    actionsIncrementalSegmentationNothingTurn.append(copy.deepcopy(listHypRefSegment[0]))
                    perfectBoundary=True
                if not perfectBoundary:
                    for z in listHypRefSegment:
                        # We cut if boundary not ok to stay in the reference segment
Anthony Larcher's avatar
Anthony Larcher committed
567
                        if z['stop']>(valueRef['stop']+tolerance):
568
569
570
                            actionsSegmentationBoundaryCreate.append(copy.deepcopy([z,valueRef['stop']]))
                            actionsIncrementalSegmentationBoundaryCreateTurn.append(copy.deepcopy([z,valueRef['stop']]))
                            valueTmp=splitSegment(z,valueTmp,valueRef['stop'])
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
                if tolerance!=0:
                    valueTmp2=copy.deepcopy(valueTmp)
                    for u in valueTmp2:
                        if u['start']>=(valueRef['stop']-tolerance) and u['stop']<=(valueRef['stop']+tolerance):
                            # No action, all the segments in this interval are dropped
                            valueTmp=dropSegment(u,valueTmp)
                        elif u['start']>=(valueRef['stop']+tolerance):
                            break
                if not perfectBoundary:
                    # Gets the new segments, modified by previous steps
                    listHypRefSegment=list()
                    # The value from where starts the segments to avoir an overlap with a previous segment which overtakes valueRef['start']
                    valueBoundaryStart=None
                    for y in valueTmp:
                        if Segment.intersection(y,valueRef) is not None:
                            if tolerance==0: 
                                listHypRefSegment.append(y)
                            elif tolerance!=0 and y['start']>=(valueRef['start']-tolerance):
                                listHypRefSegment.append(y)
                            elif tolerance!=0:
                                valueBoundaryStart=copy.deepcopy(y['stop'])
                    if valueBoundaryStart is None:
                        valueBoundaryStart=valueRef['start']                    
594
                    if modeNoGap__mergeStrat_BiggestCluster == True:
595
596
597
598
599
600
601
602
603
604
605
606
607
608
                        # Gets the cluster (it which has the most present frames)
                        dictHypRefSegmentDuration=dict()
                        for y in listHypRefSegment:
                            if y['cluster'] in dictHypRefSegmentDuration:
                                dictHypRefSegmentDuration[y['cluster']]+=y.duration()
                            else:
                                dictHypRefSegmentDuration[y['cluster']]=y.duration()
                        clusterName=max(dictHypRefSegmentDuration.keys(),key=(lambda keys: dictHypRefSegmentDuration[keys]))
                    else:
                        cls=listHypRefSegment[0]
                        for y in listHypRefSegment:
                            if cls['start']>y['start']:
                                cls=y
                        clusterName=cls['cluster']
609
610
                    # Moves the boundaries
                    # Pre-string for a good running: listHypRefSegment sorted in ascending order on start, don't overtake the value valueRef['stop'] and valueRef['start']
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
                    if modeNoGap == False:            
                        for idx,z in enumerate(listHypRefSegment): 
                            nearStop=valueRef['stop']
                            if idx==0:
                                boundStop=z['stop']
                            if z['stop']>=valueRef['stop']:
                                # If we reach the value of ref stop with an overlap segment
                                boundStop=valueRef['stop']
                            if boundStop!=valueRef['stop']:    
                                for r in range(idx+1,len(listHypRefSegment)):
                                    if (idx!=0 and z['stop']<=boundStop) or (z['stop']>=listHypRefSegment[r]['start'] and z['stop']<=listHypRefSegment[r]['stop']):
                                        nearStop=None
                                        break
                                    elif listHypRefSegment[r]['start']>z['stop'] and nearStop>listHypRefSegment[r]['start']:
                                        nearStop=listHypRefSegment[r]['start']
                            if nearStop is not None and boundStop!=valueRef['stop']:
                                if idx==0 and z['start']>valueRef['start'] and valueBoundaryStart!=z['start']:
                                    actionsSegmentationSegmentCreate.append(copy.deepcopy(Segment([valueRef['show'],clusterName,z['cluster_type'],valueBoundaryStart,z['start']],['show','cluster','cluster_type','start','stop']))) 
                                    actionsSegmentationSegmentCreate.append(copy.deepcopy(Segment([valueRef['show'],clusterName,z['cluster_type'],z['stop'],nearStop],['show','cluster','cluster_type','start','stop'])))
                                    actionsIncrementalSegmentationSegmentCreateTurn.append(copy.deepcopy(Segment([valueRef['show'],clusterName,z['cluster_type'],valueBoundaryStart,z['start']],['show','cluster','cluster_type','start','stop']))) 
                                    actionsIncrementalSegmentationSegmentCreateTurn.append(copy.deepcopy(Segment([valueRef['show'],clusterName,z['cluster_type'],z['stop'],nearStop],['show','cluster','cluster_type','start','stop'])))
                                    valueTmp.append(show=showname,cluster=clusterName,cluster_type=z['cluster_type'],start=valueBoundaryStart,stop=z['start'])
                                    valueTmp.append(show=showname,cluster=clusterName,cluster_type=z['cluster_type'],start=z["stop"],stop=nearStop)
                                    boundStop=nearStop
                                else:
                                    actionsSegmentationSegmentCreate.append(copy.deepcopy(Segment([valueRef['show'],clusterName,z['cluster_type'],z['stop'],nearStop],['show','cluster','cluster_type','start','stop'])))
                                    actionsIncrementalSegmentationSegmentCreateTurn.append(copy.deepcopy(Segment([valueRef['show'],clusterName,z['cluster_type'],z['stop'],nearStop],['show','cluster','cluster_type','start','stop'])))
                                    valueTmp.append(show=showname,cluster=clusterName,cluster_type=z['cluster_type'],start=z['stop'],stop=nearStop)
                                    boundStop=nearStop
                            else:
                                if idx==0 and z['start']>valueRef['start'] and valueBoundaryStart!=z['start']:
                                    actionsSegmentationSegmentCreate.append(copy.deepcopy(Segment([valueRef['show'],clusterName,z['cluster_type'],valueBoundaryStart,z['start']],['show','cluster','cluster_type','start','stop'])))                    
                                    actionsIncrementalSegmentationSegmentCreateTurn.append(copy.deepcopy(Segment([valueRef['show'],clusterName,z['cluster_type'],valueBoundaryStart,z['start']],['show','cluster','cluster_type','start','stop']))) 
                                    valueTmp.append(show=showname,cluster=clusterName,cluster_type=z['cluster_type'],start=valueBoundaryStart,stop=z['start'])
                                if boundStop<z['stop']:
                                    if z['stop']>=valueRef['stop']:
                                        boundStop=valueRef['stop']
                                    else:
                                        boundStop=z['stop']
                    # Gets the new segments, modified by the previous steps
                    listHypRefSegment=list()
                    for y in valueTmp:
                        if Segment.intersection(y,valueRef) is not None:
                            if tolerance==0: 
                                listHypRefSegment.append(y)
                            elif tolerance!=0 and y['start']>=(valueRef['start']-tolerance):
Anthony Larcher's avatar
Anthony Larcher committed
657
                                listHypRefSegment.append(y)
658
                    # Replaces the segments which are not in the correct cluster
659
660
661
662
663
664
665
                    if modeNoGap == False:
                        replaced=False
                        for y in listHypRefSegment:
                            if y['cluster']!=clusterName:
                                replaced=True
                                yTmp=copy.deepcopy(y)
                                yTmp['cluster']=clusterName
666
667
                                actionsSegmentationSegmentDelete.append(copy.deepcopy(y)) 
                                actionsIncrementalSegmentationSegmentDeleteTurn.append(copy.deepcopy(y))
668
                                valueTmp=dropSegment(y,valueTmp)
669
670
                                actionsSegmentationSegmentCreate.append(copy.deepcopy(Segment([valueRef['show'],yTmp['cluster'],yTmp['cluster_type'],yTmp['start'],yTmp['stop']],['show','cluster','cluster_type','start','stop']))) 
                                actionsIncrementalSegmentationSegmentCreateTurn.append(copy.deepcopy(Segment([valueRef['show'],yTmp['cluster'],yTmp['cluster_type'],yTmp['start'],yTmp['stop']],['show','cluster','cluster_type','start','stop']))) 
671
672
673
                                valueTmp.append_seg(yTmp)  
                        if replaced:
                            valueTmp.sort()
674
675
676
677
678
679
680
681
682
                    # Merges among them if > 1
                    if len(listHypRefSegment)>1:
                        # Gets the new segments, modified by the previous steps
                        listTmp=list()
                        for y in valueTmp:
                            if Segment.intersection(y,valueRef) is not None:
                                if tolerance==0: 
                                    listTmp.append(y)
                                elif tolerance!=0 and y['start']>=(valueRef['start']-tolerance):
Anthony Larcher's avatar
Anthony Larcher committed
683
                                    listTmp.append(y)
684
                        if not (not deleteBoundarySameConsecutiveSpk and listTmp[0]['cluster']==listTmp[1]['cluster']):
685
686
687
688
689
690
691
                            actionsSegmentationBoundaryMerge.append(copy.deepcopy([listTmp[0],listTmp[1]]))
                            actionsIncrementalSegmentationBoundaryMergeTurn.append(copy.deepcopy([listTmp[0],listTmp[1]]))
                            if modeNoGap == True and listTmp[0]['cluster']!=listTmp[1]['cluster']:
                                listTmp[1]['cluster']=listTmp[0]['cluster']
                            newSegment,valueTmp=mergeSegment(listTmp[0],listTmp[1],valueTmp)
                        else:
                            newSegment=listTmp[1]
692
693
694
695
696
                        for y in range(2,len(listTmp)):
                            if modeNoGap == True:
                                if not (Segment.intersection(newSegment,listTmp[y]) is not None or newSegment["stop"]==listTmp[y]["start"] or newSegment["start"]==listTmp[y]["stop"]):
                                    logging.error("Cannot have absence of a segment in Transcriber mode.")
                                    raise Exception("Absence of a segment.")
697
                            if not (not deleteBoundarySameConsecutiveSpk and newSegment['cluster']==listTmp[y]['cluster']):
698
699
700
701
702
703
704
                                actionsSegmentationBoundaryMerge.append(copy.deepcopy([newSegment,listTmp[y]]))
                                actionsIncrementalSegmentationBoundaryMergeTurn.append(copy.deepcopy([newSegment,listTmp[y]]))
                                if modeNoGap == True and newSegment['cluster']!=listTmp[y]['cluster']:
                                    listTmp[y]['cluster']=newSegment['cluster']
                                newSegment,valueTmp=mergeSegment(newSegment,listTmp[y],valueTmp)
                            else:
                                newSegment=listTmp[y]
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
        # Updates diarHyp
        diarHyp=valueTmp

    # SELECTS ALL THE HYPOTHESIS SEGMENTS AFTER THE LAST REFERENCE SEGMENT (means wrong clustered since silence in the reference)
        if i==len(diarRef)-1:
            valueTmp=copy.deepcopy(diarHyp)
            for y in diarHyp:     
                if y['start']>=valueRef['stop']:
                    if modeNoGap == False:
                        actionsSegmentationSegmentDelete.append(copy.deepcopy(y))
                        actionsIncrementalSegmentationSegmentDeleteTurn.append(copy.deepcopy(y))
                    valueTmp=dropSegment(y,valueTmp)
            # Updates diarHyp
            diarHyp=valueTmp
        actionsIncrementalSegmentationBoundaryCreate.append(actionsIncrementalSegmentationBoundaryCreateTurn)
        actionsIncrementalSegmentationBoundaryMerge.append(actionsIncrementalSegmentationBoundaryMergeTurn)
        if modeNoGap == False:
            actionsIncrementalSegmentationSegmentCreate.append(actionsIncrementalSegmentationSegmentCreateTurn)
            actionsIncrementalSegmentationSegmentDelete.append(actionsIncrementalSegmentationSegmentDeleteTurn)
        actionsIncrementalSegmentationNothing.append(actionsIncrementalSegmentationNothingTurn)
        actionsIncrementalSegmentationBoundaryCreateTurn=list()
        actionsIncrementalSegmentationBoundaryMergeTurn=list()
        if modeNoGap == False:
            actionsIncrementalSegmentationSegmentCreateTurn=list()
            actionsIncrementalSegmentationSegmentDeleteTurn=list()
        actionsIncrementalSegmentationNothingTurn=list()
        # Stores each diar after each human interaction
        diarIncremental[len(diarIncremental)]=(copy.deepcopy(diarHyp))
        idxIncremental[len(idxIncremental)]=(valueRef['start'],valueRef['stop'])

    # Deletes segments whose the cluster mainly matches with those present in diarFinal__clusterToDeleteAccordingToDiarRef
    for u in diarFinal__clusterToDeleteAccordingToDiarRef:
        if u in diarRef.unique("cluster"):
            diarRefTmp=diarRef.filter("cluster",'==',u)
            for t in diarHyp:
                for o in diarRefTmp:
                    if Segment.intersection(t,o) is not None:
                        match=matchingSegmentsFromSegment(t,diarRef)
                        bestMatchValue=None
                        bestMatch=None
                        if len(match)!=0:
                            for x in match:
                                if bestMatchValue is None:
                                    bestMatchValue=match[x]
                                    bestMatch=x
                                elif bestMatchValue.duration()<match[x].duration():
                                    bestMatchValue=match[x]
                                    bestMatch=x
                        diarTmp=Diar()
                        diarTmp.append_seg(t)
                        fakeTmp=Diar.intersection(diarTmp,diarRef)
                        if fakeTmp is not None:
                            fakeDuration=t.duration()-fakeTmp.duration()
                        else:
                            fakeDuration=0

                        if len(match)!=0:
                            if bestMatchValue.duration() < fakeDuration:
                                pass
                            else:
                                if bestMatch==u:
                                    diarHyp=dropSegment(t,diarHyp)                                            
     
    rtn=dict()
    rtn['idxIncremental']=idxIncremental
    rtn['diar']=dict()
    rtn['diar']['final']=diarHyp
    rtn['diar']['incremental']=diarIncremental
    rtn['action']=dict()
    rtn['action']['incremental']=actionsIncrementalSegmentationHumanCorrection
    rtn['action']['sum']=actionsSegmentationHumanCorrection

    return rtn

# Returns a dict object with an automaton which only corrects the segmentation and assignment errors
## WARNING: The diarizations in parameter have to be with no overlapped segment. Put them apart
## WARNING: The automaton follows the temporal order
## tolerance: In centiseconds
## diarFinal__clusterToDeleteAccordingToDiarRef: List of clusters to delete in the diarFinal only
784
## modeNoGap: Drops or not the segment actions (i.e. createSegment & deleteSegment)
785
## deleteBoundarySameConsecutiveSpk: Whether we delete a boundary for two consecutive segments with the same speaker
Anthony Larcher's avatar
Anthony Larcher committed
786
787
788
## deleteBoundaryMergeCluster: The action "delete a boundary" can merge two consecutive segments with different cluster names (it takes the name of the left/first segment)
def automatonSegmentationAssignment(diarHyp,diarRef,diarUem=None,tolerance=0,modeNoGap=False,diarFinal__clusterToDeleteAccordingToDiarRef=list(),deleteBoundarySameConsecutiveSpk=False,deleteBoundaryMergeCluster=False):
    assert isinstance(diarHyp,Diar) and isinstance(diarRef,Diar) and isinstance(modeNoGap,bool) and (diarUem is None or isinstance(diarUem,Diar)) and isinstance(tolerance,numbers.Number) and isinstance(diarFinal__clusterToDeleteAccordingToDiarRef,list) and isinstance(deleteBoundarySameConsecutiveSpk,bool) and isinstance(deleteBoundaryMergeCluster,bool)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
    for u in diarFinal__clusterToDeleteAccordingToDiarRef:
        assert isinstance(u,str)

    actionsAssignmentHumanCorrection=collections.OrderedDict()
    actionsAssignmentCreate=list()
    actionsAssignmentChange=list()
    actionsAssignmentNothing=list()
    actionsAssignmentCreateBis=list()
    actionsAssignmentHumanCorrection["Create"]=actionsAssignmentCreate
    actionsAssignmentHumanCorrection["Change"]=actionsAssignmentChange
    actionsAssignmentHumanCorrection["Nothing"]=actionsAssignmentNothing
    dictionary=dict()

    actionsSegmentationHumanCorrection=collections.OrderedDict()
    actionsSegmentationBoundary=collections.OrderedDict()
    actionsSegmentationBoundaryCreate=list()
    actionsSegmentationBoundaryMerge=list()
    # Create Format: [segment, position of the new boundary] -> We have to cut the segment into two parts
    actionsSegmentationBoundary["Create"]=actionsSegmentationBoundaryCreate
    # Merge Format: [segment1, segment2] -> We have to move the segment (the two segments have to have the same attributes)
    actionsSegmentationBoundary["Merge"]=actionsSegmentationBoundaryMerge
    if modeNoGap==False:
        actionsSegmentationSegment=collections.OrderedDict()        
        actionsSegmentationSegmentCreate=list()
        actionsSegmentationSegmentDelete=list()
        # Create Format: [show,cluster,cluster_type, start, end] -> We have to create a new segment
        actionsSegmentationSegment["Create"]=actionsSegmentationSegmentCreate
        # Delete Format: [segment] -> We have to delete a segment
        actionsSegmentationSegment["Delete"]=actionsSegmentationSegmentDelete
    # Nothing Format: [segment] -> Nothing to do, correct segmentation
    actionsSegmentationNothing=list()
    actionsSegmentationHumanCorrection["Boundary"]=actionsSegmentationBoundary
    if modeNoGap==False:
        actionsSegmentationHumanCorrection["Segment"]=actionsSegmentationSegment
    actionsSegmentationHumanCorrection["Nothing"]=actionsSegmentationNothing

    actionsIncrementalAssignmentHumanCorrection=collections.OrderedDict()
    actionsIncrementalAssignmentCreate=list()
    actionsIncrementalAssignmentChange=list()
    actionsIncrementalAssignmentNothing=list()
    actionsIncrementalAssignmentHumanCorrection["Create"]=actionsIncrementalAssignmentCreate
    actionsIncrementalAssignmentHumanCorrection["Change"]=actionsIncrementalAssignmentChange
    actionsIncrementalAssignmentHumanCorrection["Nothing"]=actionsIncrementalAssignmentNothing

    actionsIncrementalSegmentationHumanCorrection=collections.OrderedDict()
    actionsIncrementalSegmentationBoundary=collections.OrderedDict()
    actionsIncrementalSegmentationBoundaryCreate=list()
    actionsIncrementalSegmentationBoundaryMerge=list()
    # Create Format: [segment, position of the new boundary] -> We have to cut the segment into two parts
    actionsIncrementalSegmentationBoundary["Create"]=actionsIncrementalSegmentationBoundaryCreate
    # Merge Format: [segment1, segment2] -> We have to move the segment (the two segments have to have the same attributes)
    actionsIncrementalSegmentationBoundary["Merge"]=actionsIncrementalSegmentationBoundaryMerge
    if modeNoGap==False:
        actionsIncrementalSegmentationSegment=collections.OrderedDict()        
        actionsIncrementalSegmentationSegmentCreate=list()
        actionsIncrementalSegmentationSegmentDelete=list()
        # Create Format: [show,cluster,cluster_type, start, end] -> We have to create a new segment
        actionsIncrementalSegmentationSegment["Create"]=actionsIncrementalSegmentationSegmentCreate
        # Delete Format: [segment] -> We have to delete a segment
        actionsIncrementalSegmentationSegment["Delete"]=actionsIncrementalSegmentationSegmentDelete
    # Nothing Format: [segment] -> Nothing to do, correct segmentation
    actionsIncrementalSegmentationNothing=list()
    actionsIncrementalSegmentationHumanCorrection["Boundary"]=actionsIncrementalSegmentationBoundary
    if modeNoGap==False:
        actionsIncrementalSegmentationHumanCorrection["Segment"]=actionsIncrementalSegmentationSegment
    actionsIncrementalSegmentationHumanCorrection["Nothing"]=actionsIncrementalSegmentationNothing

    diarIncremental=dict()

    idxIncremental=dict()

    if diarUem is not None:
        diarRef=releaseFramesAccordingToDiar(diarRef,diarUem)
        diarHyp=releaseFramesAccordingToDiar(diarHyp,diarUem)

    diarRaw=Diar()
    diarRaw.append(start=min(diarRef.unique('start')+diarHyp.unique('start')),stop=max(diarRef.unique('stop')+diarHyp.unique('stop')))
    diarRef=copy.deepcopy(diarRef)
    diarHyp=copy.deepcopy(diarHyp)
    showname=diarRef.unique('show')[0]
    diarRef.sort()
    diarHyp.sort()
    tolerance=abs(tolerance)     

    assert len(diarOverlapArea(diarRef))==0, "Error: diarRef parameter have some overlapped segments.\nReason: No overlap segment allowed.\nSolution: Please put them apart.\n"
    assert len(diarOverlapArea(diarHyp))==0, "Error: diarHyp parameter have some overlapped segments.\nReason: No overlap segment allowed.\nSolution: Please put them apart.\n"


    actionsIncrementalAssignmentCreateTurn=list()
    actionsIncrementalAssignmentChangeTurn=list()
    actionsIncrementalAssignmentNothingTurn=list()
    actionsIncrementalSegmentationBoundaryCreateTurn=list()
    actionsIncrementalSegmentationBoundaryMergeTurn=list()
    if modeNoGap==False:
        actionsIncrementalSegmentationSegmentCreateTurn=list()
        actionsIncrementalSegmentationSegmentDeleteTurn=list()
    actionsIncrementalSegmentationNothingTurn=list()

    # To avoid to create clusters with the same id
    cpt=0

    for i,valueRef in enumerate(diarRef):
    # WARNING: Each string supposes the start boundary is validate/correct (modified in the previous iteration if need be), that it doesn't overtake the reference segment (works with the tolerance as well)

    # SELECTS ALL THE HYPOTHESIS SEGMENTS BEFORE THE FIRST REFERENCE SEGMENT (means wrong clustered since silence in the reference)
        if i==0:
            valueTmp=copy.deepcopy(diarHyp)
            for y in diarHyp:
                if y['start']<(valueRef['start']-tolerance) and y['stop']<=(valueRef['start']+tolerance):
                    if modeNoGap==False:
                        actionsSegmentationSegmentDelete.append(copy.deepcopy(y))
                        actionsIncrementalSegmentationSegmentDeleteTurn.append(copy.deepcopy(y))
                    valueTmp=dropSegment(y,valueTmp)
                elif y['start']<(valueRef['start']-tolerance) and y['stop']>(valueRef['start']+tolerance):
                    actionsSegmentationBoundaryCreate.append(copy.deepcopy([y,valueRef['start']]))
                    actionsIncrementalSegmentationBoundaryCreateTurn.append(copy.deepcopy([y,valueRef['start']]))
                    valueTmp=splitSegment(y,valueTmp,valueRef['start'])
                    yTmp=copy.deepcopy(y)
                    yTmp['stop']=valueRef['start']
                    if modeNoGap==False:
                        actionsSegmentationSegmentDelete.append(copy.deepcopy(yTmp))
                        actionsIncrementalSegmentationSegmentDeleteTurn.append(copy.deepcopy(yTmp))
                    valueTmp=dropSegment(yTmp,valueTmp)
                elif tolerance!=0 and y['start']>=(valueRef['start']-tolerance) and y['stop']<=(valueRef['start']+tolerance):
                    # No action, all the segments in this tous les segments are dropped
                    valueTmp=dropSegment(y,valueTmp)
                else:
                    break
            # Updates diarHyp
            diarHyp=valueTmp

    # SELECTS ALL THE HYPOTHESIS SEGMENTS BETWEEN TWO REFERENCE SEGMENTS AND MAKES THEM SILENCE
        if i!=0 and diarRef[i-1]['stop']!=valueRef['start']:
            valueRefPrev=diarRef[i-1]
            valueTmp=copy.deepcopy(diarHyp)
            for y in diarHyp:
                if valueRef['start']-diarRef[i-1]['stop']<=tolerance*2:
                    # Directly deletes if the interval is smaller than tolerance*2
                    if y['start']>=(valueRefPrev['stop']-tolerance) and y['stop']<=(valueRef['start']+tolerance):
                        # No action, all the segments in this interval are dropped
                        valueTmp=dropSegment(y,valueTmp)
                    elif y['start']>=(valueRefPrev['stop']-tolerance) and y['stop']>(valueRef['start']+tolerance): 
                        # Part allowing to know if we cut the segment or directly drop it
                        stopTmp=None
                        for u in range(i,len(diarRef)):
                            if y['stop']<=diarRef[u]['start']+tolerance:
                                break
                            elif y['stop']>diarRef[u]['start']+tolerance and y['stop']<=diarRef[u]['stop']+tolerance:
                                if segmentExistAccordingToTolerance(diarRef[u],tolerance):
                                    stopTmp=diarRef[u]['start']
                                break
                            elif not segmentExistAccordingToTolerance(diarRef[u],tolerance):
                                pass
                            else:
                                stopTmp=diarRef[u]['start']
                                break
                        if stopTmp is not None:
                            # Action here since tolerance of the valueRef segment and following ones don't crush it
                            if y['start']<(valueRef['start']-tolerance):
                                actionsSegmentationBoundaryCreate.append(copy.deepcopy([y,stopTmp]))
                                actionsIncrementalSegmentationBoundaryCreateTurn.append(copy.deepcopy([y,stopTmp]))
                                valueTmp=splitSegment(y,valueTmp,stopTmp)
                                yTmp=copy.deepcopy(y)
                                yTmp['stop']=stopTmp
                                if modeNoGap==False:
                                    actionsSegmentationSegmentDelete.append(copy.deepcopy(yTmp))
                                    actionsIncrementalSegmentationSegmentDeleteTurn.append(copy.deepcopy(yTmp))
                                valueTmp=dropSegment(yTmp,valueTmp)
                            break
                        else:
                            # No action since tolerance of the valueRef segment and following ones crush it
                            if modeNoGap==False:
                                actionsSegmentationSegmentDelete.append(copy.deepcopy(y))
                                actionsIncrementalSegmentationSegmentDeleteTurn.append(copy.deepcopy(y))
                            valueTmp=dropSegment(y,valueTmp)
                else:
                    if y['start']>=(valueRefPrev['stop']-tolerance) and y['start']<(valueRef['start']-tolerance) and y['stop']<=(valueRef['start']+tolerance) and y['stop']>(valueRefPrev['stop']+tolerance):
                        if modeNoGap==False:
                            actionsSegmentationSegmentDelete.append(copy.deepcopy(y))
                            actionsIncrementalSegmentationSegmentDeleteTurn.append(copy.deepcopy(y))
                        valueTmp=dropSegment(y,valueTmp)
                    elif y['start']>=(valueRefPrev['stop']-tolerance) and y['start']<(valueRef['start']-tolerance) and y['stop']>(valueRef['start']+tolerance):
                        actionsSegmentationBoundaryCreate.append(copy.deepcopy([y,valueRef['start']]))
                        actionsIncrementalSegmentationBoundaryCreateTurn.append(copy.deepcopy([y,valueRef['start']]))
                        valueTmp=splitSegment(y,valueTmp,valueRef['start'])
                        yTmp=copy.deepcopy(y)
                        yTmp['stop']=valueRef['start']
                        if modeNoGap==False:
                            actionsSegmentationSegmentDelete.append(copy.deepcopy(yTmp))
                            actionsIncrementalSegmentationSegmentDeleteTurn.append(copy.deepcopy(yTmp))
                        valueTmp=dropSegment(yTmp,valueTmp)
                    elif tolerance!=0 and y['start']>=(valueRef['start']-tolerance) and y['stop']<=(valueRef['start']+tolerance):
                        # No action, all the segments in this interval are dropped
                        valueTmp=dropSegment(y,valueTmp)
                    elif y['start']>=(valueRef['start']-tolerance):
                        break
            # Updates diarHyp
            diarHyp=valueTmp

    # BEHAVIOR FOR A GIVEN REFERENCE SEGMENT
        # Counts the number of segment matching
        listHypRefSegment=list()
        # Whose the number in tolerance on the stop boundary
        listHypRefSegmentWithinTolerance=list()
        valueTmp=copy.deepcopy(diarHyp)
        for y in diarHyp:
            if Segment.intersection(y,valueRef) is not None:
                if tolerance==0: 
                    listHypRefSegment.append(y)
                elif tolerance!=0 and y['start']>=(valueRef['start']-tolerance):
                    listHypRefSegment.append(y)
                    if y['start']>=(valueRef['stop']-tolerance) and y['stop']<=(valueRef['stop']+tolerance):
                        listHypRefSegmentWithinTolerance.append(y)
        # If 0 creating
        if len(listHypRefSegment)==0 or (len(listHypRefSegment)==len(listHypRefSegmentWithinTolerance)):
            if modeNoGap == True:
                if segmentExistAccordingToTolerance(valueRef,tolerance):
                    logging.error("Cannot have absence of a segment in Transcriber mode.")
                    raise Exception("Absence of a segment.")
            if tolerance!=0:
                valueTmp2=copy.deepcopy(valueTmp)
                for u in valueTmp2:
                    if u['start']>=(valueRef['stop']-tolerance) and u['stop']<=(valueRef['stop']+tolerance):
                        # No action, all the segments in this interval are dropped
                        valueTmp=dropSegment(u,valueTmp)
                    elif u['start']>=(valueRef['stop']+tolerance):
                        break
            if modeNoGap == False:
                # Checks valueRef is not overtaken by tolerance
                if segmentExistAccordingToTolerance(valueRef,tolerance):
                    # Absence of the segment, so we create it
                    actionsSegmentationSegmentCreate.append(copy.deepcopy(Segment([valueRef['show'],valueRef['cluster'],valueRef['cluster_type'],valueRef['start'],valueRef['stop']],['show','cluster','cluster_type','start','stop'])))                    
                    actionsIncrementalSegmentationSegmentCreateTurn.append(copy.deepcopy(Segment([valueRef['show'],valueRef['cluster'],valueRef['cluster_type'],valueRef['start'],valueRef['stop']],['show','cluster','cluster_type','start','stop'])))    
                    # Affectation part
                    if valueRef['cluster'] not in dictionary:
                        dictionary[copy.deepcopy(valueRef['cluster'])]='speakerManualNotDetected'+str(cpt+1)
                        actionsAssignmentCreateBis.append('speakerManualNotDetected'+str(cpt+1))
                        actionsAssignmentCreate.append([copy.deepcopy(valueRef['cluster']),'speakerManualNotDetected'+str(cpt+1),Segment([valueRef['show'],valueRef['cluster'],valueRef['cluster_type'],valueRef['start'],valueRef['stop']],['show','cluster','cluster_type','start','stop'])])
                        actionsIncrementalAssignmentCreateTurn.append([copy.deepcopy(valueRef['cluster']),'speakerManualNotDetected'+str(cpt+1),Segment([valueRef['show'],valueRef['cluster'],valueRef['cluster_type'],valueRef['start'],valueRef['stop']],['show','cluster','cluster_type','start','stop'])])
                        valueTmp.append(show=showname, cluster='speakerManualNotDetected'+str(cpt+1), start=valueRef['start'], stop=valueRef['stop'])
                        cpt+=1
                    else:
                        # Create with the already associated cluster
                        valueTmp.append(show=showname, cluster=dictionary[valueRef['cluster']], start=valueRef['start'], stop=valueRef['stop'])   
        # If 1 then affectation + moving boundary if need be and/or creating boundary on stop
        # If > 1 then affectation + moving boundary if need be and/or creating boundary on stop + merge
        else:
            # Checks valueRef is not overtaken by tolerance
            if not segmentExistAccordingToTolerance(valueRef,tolerance):
                for z in listHypRefSegment:
                    # Directly deletes if the interval is smaller than tolerance*2
                    if z['start']>=(valueRef['start']-tolerance) and z['stop']<=(valueRef['stop']+tolerance):
                        # No action, all the segments in this interval are dropped
                        valueTmp=dropSegment(z,valueTmp)
                    elif z['start']>=(valueRef['start']-tolerance) and z['stop']>(valueRef['stop']+tolerance):
                        # Part allowing to know if we cut the segment or directly drop it
                        stopTmp=None
                        for u in range(i+1,len(diarRef)):
                            if z['stop']<=diarRef[u]['start']+tolerance:
                                break
                            elif z['stop']>diarRef[u]['start']+tolerance and z['stop']<=diarRef[u]['stop']+tolerance:
                                if segmentExistAccordingToTolerance(diarRef[u],tolerance):
                                    stopTmp=diarRef[u]['start']
                                break
                            elif not segmentExistAccordingToTolerance(diarRef[u],tolerance):
                                pass
                            else:
                                stopTmp=diarRef[u]['start']
                                break
                        if stopTmp is not None:
                            # Action here since tolerance of the valueRef segment and following ones don't crush it
                            if z['start']<(valueRef['stop']-tolerance):
                                actionsSegmentationBoundaryCreate.append(copy.deepcopy([z,stopTmp]))
                                actionsIncrementalSegmentationBoundaryCreateTurn.append(copy.deepcopy([z,stopTmp]))
                                valueTmp=splitSegment(z,valueTmp,stopTmp)
                                zTmp=copy.deepcopy(z)
                                zTmp['stop']=stopTmp
                                if modeNoGap == False:
                                    actionsSegmentationSegmentDelete.append(copy.deepcopy(zTmp))
                                    actionsIncrementalSegmentationSegmentDeleteTurn.append(copy.deepcopy(zTmp))
                                valueTmp=dropSegment(zTmp,valueTmp)
                            break
                        else:
                            # No action since tolerance of the valueRef segment and following ones crush it
                            if modeNoGap == False:
                                actionsSegmentationSegmentDelete.append(copy.deepcopy(z))
                                actionsIncrementalSegmentationSegmentDeleteTurn.append(copy.deepcopy(z))
                            valueTmp=dropSegment(z,valueTmp)
                # Drops the segments (left which are not in listHypRefSegment) in the tolerance margin (+ or - tolerance)
                valueTmp2=copy.deepcopy(valueTmp)
                for u in valueTmp2:
                    if u['start']>=(valueRef['stop']-tolerance) and u['stop']<=(valueRef['stop']+tolerance):
                        # No action, all the segments in this interval are dropped
                        valueTmp=dropSegment(u,valueTmp)
                    elif u['start']>=(valueRef['stop']+tolerance):
                        break
            else:
                # Allows to know whether we do treatments for segments with wrong boundaries
                perfectBoundary=False
                # Checks perfect boundary
                if len(listHypRefSegment)==1 and boundariesInTolerance(boundarySegment=listHypRefSegment[0],segment=valueRef,tolerance=tolerance):
                    actionsSegmentationNothing.append(copy.deepcopy(listHypRefSegment[0]))
                    actionsIncrementalSegmentationNothingTurn.append(copy.deepcopy(listHypRefSegment[0]))
                    perfectBoundary=True
                if not perfectBoundary:
                    for z in listHypRefSegment:
                        # We cut if boundary not ok to stay in the reference segment
                        if z['stop']>(valueRef['stop']+tolerance):
1097
1098
1099
                            actionsSegmentationBoundaryCreate.append(copy.deepcopy([z,valueRef['stop']]))
                            actionsIncrementalSegmentationBoundaryCreateTurn.append(copy.deepcopy([z,valueRef['stop']]))
                            valueTmp=splitSegment(z,valueTmp,valueRef['stop'])
1100
1101
1102
1103
1104
1105
1106
1107
                if tolerance!=0:
                    valueTmp2=copy.deepcopy(valueTmp)
                    for u in valueTmp2:
                        if u['start']>=(valueRef['stop']-tolerance) and u['stop']<=(valueRef['stop']+tolerance):
                            # No action, all the segments in this interval are dropped
                            valueTmp=dropSegment(u,valueTmp)
                        elif u['start']>=(valueRef['stop']+tolerance):
                            break
Anthony Larcher's avatar
Anthony Larcher committed
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
                # Gets the new segments, modified by previous steps
                listHypRefSegment=list()
                for y in valueTmp:
                    if Segment.intersection(y,valueRef) is not None:
                        if tolerance==0: 
                            listHypRefSegment.append(y)
                        elif tolerance!=0 and y['start']>=(valueRef['start']-tolerance):
                            listHypRefSegment.append(y)
                for idx,z in enumerate(listHypRefSegment):
                    # Affectation part
                    applyChange=False
                    if valueRef['cluster'] not in dictionary:
                        if z['cluster'] in actionsAssignmentCreateBis:
                            dictionary[copy.deepcopy(valueRef['cluster'])]='speakerManual'+str(cpt+1)
                            actionsAssignmentCreateBis.append('speakerManual'+str(cpt+1))
                            actionsAssignmentCreate.append([copy.deepcopy(valueRef['cluster']),'speakerManual'+str(cpt+1),copy.deepcopy(z)])
                            actionsIncrementalAssignmentCreateTurn.append([copy.deepcopy(valueRef['cluster']),'speakerManual'+str(cpt+1),copy.deepcopy(z)])
                            applyChange=True
                            cpt+=1
                        else:
                            dictionary[copy.deepcopy(valueRef['cluster'])]=copy.deepcopy(z['cluster'])
                            actionsAssignmentCreateBis.append(copy.deepcopy(z['cluster']))
                            actionsAssignmentCreate.append(copy.deepcopy([valueRef['cluster'],z['cluster'],copy.deepcopy(z)]))
                            actionsIncrementalAssignmentCreateTurn.append(copy.deepcopy([valueRef['cluster'],z['cluster'],copy.deepcopy(z)]))
                    else:
                        if z['cluster'] == dictionary[valueRef['cluster']]:
                            actionsAssignmentNothing.append(copy.deepcopy(z))
                            actionsIncrementalAssignmentNothingTurn.append(copy.deepcopy(z))
                        else:
                            actionsAssignmentChange.append(copy.deepcopy([dictionary[valueRef['cluster']],z]))
                            actionsIncrementalAssignmentChangeTurn.append(copy.deepcopy([dictionary[valueRef['cluster']],z]))
                            applyChange=True
                    if applyChange:
                        # Updates the diar for the merges afterward
                        segmentTmp=copy.deepcopy(z)
                        segmentTmp['cluster']=dictionary[valueRef['cluster']]
                        valueTmp=dropSegment(z,valueTmp)
                        valueTmp.append_seg(segmentTmp)
                        valueTmp.sort()
                    if deleteBoundaryMergeCluster:
                        break
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
                if not perfectBoundary:
                    # Gets the new segments, modified by the previous steps
                    listHypRefSegment=list()
                    # The value from where starts the segments to avoir an overlap with a previous segment which overtakes valueRef['start']
                    valueBoundaryStart=None
                    for y in valueTmp:
                        if Segment.intersection(y,valueRef) is not None:
                            if tolerance==0: 
                                listHypRefSegment.append(y)
                            elif tolerance!=0 and y['start']>=(valueRef['start']-tolerance):
                                listHypRefSegment.append(y)
                            elif tolerance!=0:
                                valueBoundaryStart=copy.deepcopy(y['stop'])
                    if valueBoundaryStart is None:
                        valueBoundaryStart=valueRef['start']
                    if modeNoGap == False:        
                        for idx,z in enumerate(listHypRefSegment): 
                            # Moves the boundaries
                            # Pre-string for a good running: listHypRefSegment sorted in ascending order on start, don't overtake the value valueRef['stop'] and valueRef['start']
                            nearStop=valueRef['stop']
                            if idx==0:
                                boundStop=z['stop']
                            if z['stop']>=valueRef['stop']:
                                # If we reach the value of ref stop with an overlap segment
                                boundStop=valueRef['stop']                                
                            if boundStop!=valueRef['stop']:    
                                for r in range(idx+1,len(listHypRefSegment)):
                                    if (idx!=0 and z['stop']<=boundStop) or (z['stop']>=listHypRefSegment[r]['start'] and z['stop']<=listHypRefSegment[r]['stop']):
                                        nearStop=None
                                        break
                                    elif listHypRefSegment[r]['start']>z['stop'] and nearStop>listHypRefSegment[r]['start']:
                                        nearStop=listHypRefSegment[r]['start']
                            if nearStop is not None and boundStop!=valueRef['stop']:
                                if idx==0 and z['start']>valueRef['start'] and valueBoundaryStart!=z['start']:
                                    actionsSegmentationSegmentCreate.append(copy.deepcopy(Segment([valueRef['show'],z['cluster'],z['cluster_type'],valueBoundaryStart,z['start']],['show','cluster','cluster_type','start','stop']))) 
                                    actionsSegmentationSegmentCreate.append(copy.deepcopy(Segment([valueRef['show'],z['cluster'],z['cluster_type'],z['stop'],nearStop],['show','cluster','cluster_type','start','stop']))) 
                                    actionsIncrementalSegmentationSegmentCreateTurn.append(copy.deepcopy(Segment([valueRef['show'],z['cluster'],z['cluster_type'],valueBoundaryStart,z['start']],['show','cluster','cluster_type','start','stop']))) 
                                    actionsIncrementalSegmentationSegmentCreateTurn.append(copy.deepcopy(Segment([valueRef['show'],z['cluster'],z['cluster_type'],z['stop'],nearStop],['show','cluster','cluster_type','start','stop']))) 
                                    valueTmp.append(show=showname,cluster=z['cluster'],cluster_type=z['cluster_type'],start=valueBoundaryStart,stop=z['start'])
                                    valueTmp.append(show=showname,cluster=z['cluster'],cluster_type=z['cluster_type'],start=z["stop"],stop=nearStop)
                                    boundStop=nearStop
                                else:
                                    actionsSegmentationSegmentCreate.append(copy.deepcopy(Segment([valueRef['show'],z['cluster'],z['cluster_type'],z['stop'],nearStop],['show','cluster','cluster_type','start','stop']))) 
                                    actionsIncrementalSegmentationSegmentCreateTurn.append(copy.deepcopy(Segment([valueRef['show'],z['cluster'],z['cluster_type'],z['stop'],nearStop],['show','cluster','cluster_type','start','stop']))) 
                                    valueTmp.append(show=showname,cluster=z['cluster'],cluster_type=z['cluster_type'],start=z['stop'],stop=nearStop)
                                    boundStop=nearStop
                            else:
                                if idx==0 and z['start']>valueRef['start'] and valueBoundaryStart!=z['start']:
                                    actionsSegmentationSegmentCreate.append(copy.deepcopy(Segment([valueRef['show'],z['cluster'],z['cluster_type'],valueBoundaryStart,z['start']],['show','cluster','cluster_type','start','stop'])))                    
                                    actionsIncrementalSegmentationSegmentCreateTurn.append(copy.deepcopy(Segment([valueRef['show'],z['cluster'],z['cluster_type'],valueBoundaryStart,z['start']],['show','cluster','cluster_type','start','stop'])))  
                                    valueTmp.append(show=showname,cluster=z['cluster'],cluster_type=z['cluster_type'],start=valueBoundaryStart,stop=z['start'])
                                if boundStop<z['stop']:
                                    if z['stop']>=valueRef['stop']:
                                        boundStop=valueRef['stop']
                                    else:
                                        boundStop=z['stop']
                    # Gets the new segments, modified by the previous steps
                    listHypRefSegment=list()
                    for y in valueTmp:
                        if Segment.intersection(y,valueRef) is not None:
                            if tolerance==0: 
                                listHypRefSegment.append(y)
                            elif tolerance!=0 and y['start']>=(valueRef['start']-tolerance):
Anthony Larcher's avatar
Anthony Larcher committed
1212
                                listHypRefSegment.append(y)
1213
1214
1215
1216
1217
1218
1219
1220
1221
                    # Merges among them if > 1
                    if len(listHypRefSegment)>1:
                        # Gets the new segments, modified by the previous steps
                        listTmp=list()
                        for y in valueTmp:
                            if Segment.intersection(y,valueRef) is not None:
                                if tolerance==0: 
                                    listTmp.append(y)
                                elif tolerance!=0 and y['start']>=(valueRef['start']-tolerance):
Anthony Larcher's avatar
Anthony Larcher committed
1222
1223
                                    listTmp.append(y)
                        if not (not deleteBoundarySameConsecutiveSpk and listTmp[0]['cluster']==listTmp[1]['cluster']):
1224
1225
1226
1227
1228
1229
                            actionsSegmentationBoundaryMerge.append(copy.deepcopy([listTmp[0],listTmp[1]]))
                            actionsIncrementalSegmentationBoundaryMergeTurn.append(copy.deepcopy([listTmp[0],listTmp[1]]))
                            if modeNoGap == True and listTmp[0]['cluster']!=listTmp[1]['cluster']:
                                listTmp[1]['cluster']=listTmp[0]['cluster']
                            newSegment,valueTmp=mergeSegment(listTmp[0],listTmp[1],valueTmp)
                        else:
1230
                            newSegment=listTmp[1]
1231
1232
1233
1234
1235
                        for y in range(2,len(listTmp)):
                            if modeNoGap == True:
                                if not (Segment.intersection(newSegment,listTmp[y]) is not None or newSegment["stop"]==listTmp[y]["start"] or newSegment["start"]==listTmp[y]["stop"]):
                                    logging.error("Cannot have absence of a segment in Transcriber mode.")
                                    raise Exception("Absence of a segment.")
Anthony Larcher's avatar
Anthony Larcher committed
1236
                            if not (not deleteBoundarySameConsecutiveSpk and newSegment['cluster']==listTmp[y]['cluster']):
1237
1238
1239
                                actionsSegmentationBoundaryMerge.append(copy.deepcopy([newSegment,listTmp[y]]))
                                actionsIncrementalSegmentationBoundaryMergeTurn.append(copy.deepcopy([newSegment,listTmp[y]]))
                                if modeNoGap == True and newSegment['cluster']!=listTmp[y]['cluster']:
1240
                                    valueTmp=dropSegment(listTmp[y],valueTmp)
1241
                                    listTmp[y]['cluster']=newSegment['cluster']
1242
1243
                                    valueTmp.append_seg(listTmp[y])
                                    valueTmp.sort()
1244
1245
                                newSegment,valueTmp=mergeSegment(newSegment,listTmp[y],valueTmp)
                            else:
Anthony Larcher's avatar
Anthony Larcher committed
1246
                                newSegment=listTmp[y]                    
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
        # Updates diarHyp
        diarHyp=valueTmp

    # SELECTS ALL THE HYPOTHESIS SEGMENTS AFTER THE LAST REFERENCE SEGMENT (means wrong clustered since silence in the reference)
        if i==len(diarRef)-1:
            valueTmp=copy.deepcopy(diarHyp)
            for y in diarHyp:     
                if y['start']>=valueRef['stop']:
                    if modeNoGap == False:
                        actionsSegmentationSegmentDelete.append(copy.deepcopy(y))
                        actionsIncrementalSegmentationSegmentDeleteTurn.append(copy.deepcopy(y))
                    valueTmp=dropSegment(y,valueTmp)
            # Updates diarHyp
            diarHyp=valueTmp
        actionsIncrementalAssignmentCreate.append(actionsIncrementalAssignmentCreateTurn)
        actionsIncrementalAssignmentChange.append(actionsIncrementalAssignmentChangeTurn)
        actionsIncrementalAssignmentNothing.append(actionsIncrementalAssignmentNothingTurn)
        actionsIncrementalSegmentationBoundaryCreate.append(actionsIncrementalSegmentationBoundaryCreateTurn)
        actionsIncrementalSegmentationBoundaryMerge.append(actionsIncrementalSegmentationBoundaryMergeTurn)
        if modeNoGap == False:
            actionsIncrementalSegmentationSegmentCreate.append(actionsIncrementalSegmentationSegmentCreateTurn)
            actionsIncrementalSegmentationSegmentDelete.append(actionsIncrementalSegmentationSegmentDeleteTurn)
        actionsIncrementalSegmentationNothing.append(actionsIncrementalSegmentationNothingTurn)
        actionsIncrementalAssignmentCreateTurn=list()
        actionsIncrementalAssignmentChangeTurn=list()
        actionsIncrementalAssignmentNothingTurn=list()
        actionsIncrementalSegmentationBoundaryCreateTurn=list()
        actionsIncrementalSegmentationBoundaryMergeTurn=list()
        if modeNoGap == False:
            actionsIncrementalSegmentationSegmentCreateTurn=list()
            actionsIncrementalSegmentationSegmentDeleteTurn=list()
        actionsIncrementalSegmentationNothingTurn=list()
        # Stores each diar after each human interaction
        diarIncremental[len(diarIncremental)]=(copy.deepcopy(diarHyp))
        idxIncremental[len(idxIncremental)]=(valueRef['start'],valueRef['stop'])

    # Deletes segments whose the cluster mainly matches with those present in diarFinal__clusterToDeleteAccordingToDiarRef
    for u in diarFinal__clusterToDeleteAccordingToDiarRef:
        if u in dictionary:
            diarHyp=dropCluster(dictionary[u],diarHyp)
    
    rtn=dict()
    rtn['idxIncremental']=idxIncremental
    rtn['diar']=dict()
    rtn['diar']['final']=diarHyp
    rtn['diar']['incremental']=diarIncremental
    rtn['action']=dict()
    rtn['action']['incremental']=dict()
    rtn['action']['incremental']['assignment']=actionsIncrementalSegmentationHumanCorrection
    rtn['action']['incremental']['segmentation']=actionsIncrementalAssignmentHumanCorrection
    rtn['action']['sum']=dict()
    rtn['action']['sum']['assignment']=actionsAssignmentHumanCorrection
    rtn['action']['sum']['segmentation']=actionsSegmentationHumanCorrection

    return rtn

1303
1304
1305
# Returns a border structure from an hypothesis diar object and a reference diar object according to the uem diar object
## A border is a list which matches the labels from the hypothesis and the reference
## tolerance: In centiseconds
1306
def border(diarHyp,diarRef,diarUem=None,tolerance=0,nonSpeechNameRef="NONSPEECHREF",nonSpeechNameHyp="NONSPEECHHYP",toleranceNameRef="TOLERANCE",toleranceNameHyp="TOLERANCE"):
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
    assert isinstance(diarHyp,Diar) and isinstance(diarRef,Diar) and (diarUem is None or isinstance(diarUem,Diar)) and isinstance(nonSpeechNameRef,str) and isinstance(nonSpeechNameHyp,str) and isinstance(tolerance,numbers.Number) and tolerance>=0
    if diarUem is not None:
        diarUem=compressDiar(diarUem)
        uem_start= min(diarUem.unique('start'))
        uem_stop = max(diarUem.unique('stop'))
        diarRef=releaseFramesAccordingToDiar(diarRef,diarUem)
        diarHyp=releaseFramesAccordingToDiar(diarHyp,diarUem)
    else:
        uem_start= min(diarRef.unique('start')+diarHyp.unique('start'))
        uem_stop = max(diarRef.unique('stop')+diarHyp.unique('stop'))
        diarUem=Diar()
        diarUem.append(start=uem_start,stop=uem_stop)

1320
    # Overtakes the clusters for the tolerance if need be
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
    if tolerance >0:
        oldDiarRef=copy.deepcopy(diarRef)
        diarHyp=releaseFramesAccordingToDiarWithToleranceBoundaries(diarHyp,oldDiarRef,tolerance)
        diarRef=releaseFramesAccordingToDiarWithToleranceBoundaries(diarRef,oldDiarRef,tolerance)
        for idx,i in enumerate(oldDiarRef):
            if idx==0:
                diarHyp.append(start=i['start'],stop=i['stop']+tolerance,cluster=toleranceNameHyp)
                diarRef.append(start=i['start'],stop=i['stop']+tolerance,cluster=toleranceNameRef)
            elif idx==len(oldDiarRef-1):
                diarHyp.append(start=i['start']-tolerance,stop=i['stop'],cluster=toleranceNameHyp)
                diarRef.append(start=i['start']-tolerance,stop=i['stop'],cluster=toleranceNameRef)
            else:
                diarHyp.append(start=i['start']-tolerance,stop=i['stop']+tolerance,cluster=toleranceNameHyp)
                diarRef.append(start=i['start']-tolerance,stop=i['stop']+tolerance,cluster=toleranceNameRef)

1336
    # Fills the wholes to be comparable
1337
1338
1339
    ref_diar=fillDiar(nonSpeechNameRef,diarUem,diarRef)
    hyp_diar=fillDiar(nonSpeechNameHyp,diarUem,diarHyp)
    
1340
    # Creates vectors
1341
1342
    ref_vect = vector(ref_diar,start=uem_start,stop=uem_stop)
    hyp_vect = vector(hyp_diar,start=uem_start,stop=uem_stop)
1343

1344
    # Creates the Border
1345
1346
    border = collections.OrderedDict()

1347
    # Selects the components of the Border by avoiding repetitions
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
    for j in diarUem:
        border[j['start']] = [j['start'], ref_vect[j['start']], hyp_vect[j['start']], 'start', -1]
        for i in sorted(range(j['start']+1,j['stop'])):
            if ref_vect[i-1] != ref_vect[i]:
                k = 'ref'
                if hyp_vect[i-1] != hyp_vect[i]:
                    k = 'refhyp'
                border[i] = [i, ref_vect[i], hyp_vect[i], k , -1]
            elif hyp_vect[i-1] != hyp_vect[i]:
                border[i] = [i, ref_vect[i], hyp_vect[i], 'hyp', -1]

1359
    # Converts the Border into list
1360
1361
1362
1363
    border_list = list()
    for idx in border:
        border_list.append(border[idx])

1364
    # Updates the "stop" of each Border component
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
    for j in diarUem:
        listTmp=list()
        for i in range(0, len(border_list)):
            if border_list[i][0]>=j['start'] and border_list[i][0]<=j['stop']:
                listTmp.append(i)
            elif border_list[i][0]>j['stop']:
                break
        for idx,i in enumerate(listTmp):
            if idx!=0:
                l = border_list[i][0] - border_list[i-1][0]
                border_list[i-1][4] = l
            if idx==len(listTmp)-1:
                border_list[i][4] = j['stop'] - border_list[i][0]

    return border_list

# Returns the HCIQ measure for a border structure
## tolerance: In centiseconds
## cb (createBoundary), db (deleteBoundary), cn (createName), sn (selectName), v (validate) are weights
1384
def borderHCIQ(diarHyp,diarRef,diarUem=None,cb=1,db=1,cn=1,sn=1,v=0,tolerance=0,nameAlreadySet=set(),nonSpeechNameRef="NONSPEECHREF",nonSpeechNameHyp="NONSPEECHHYP",toleranceNameRef="TOLERANCE",toleranceNameHyp="TOLERANCE"):
1385
1386
    assert isinstance(cb,numbers.Number) and isinstance(db,numbers.Number) and isinstance(cb,numbers.Number) and isinstance(cn,numbers.Number) and isinstance(v,numbers.Number) and isinstance(sn,numbers.Number)
    assert cb>=0 and db>=0 and cn>=0 and sn>=0 and v>=0
1387
    get=borderHumanCorrectionsToDo(diarHyp,diarRef,diarUem,False,nameAlreadySet,tolerance,nonSpeechNameRef,nonSpeechNameHyp,toleranceNameRef,toleranceNameHyp)
1388
1389
1390
1391
    HCIQ=(get["create_boundary"]*cb)+(get["delete_boundary"]*db)+(get["create_name"]*cn)+(get["select_name"]*sn)+(get["validate"]*v)
    return HCIQ

# Returns a dict object with the human corrections to do on the diarHyp parameter according to the diarRef and diarUem parameters for a border structure
1392
def borderHumanCorrectionsToDo(diarHyp,diarRef,diarUem=None,verbose=False,nameAlreadySet=set(),tolerance=0,nonSpeechNameRef="NONSPEECHREF",nonSpeechNameHyp="NONSPEECHHYP",toleranceNameRef="TOLERANCE",toleranceNameHyp="TOLERANCE"):
1393
1394
1395
1396
1397
1398
1399
1400
1401
    assert isinstance(verbose,bool) and isinstance(diarHyp,Diar) and isinstance(diarRef,Diar) and (diarUem is None or isinstance(diarUem,Diar)) and isinstance(nameAlreadySet,set)
    if diarUem is not None:
        diarUem=compressDiar(diarUem)
    else:
        uem_start= min(diarRef.unique('start')+diarHyp.unique('start'))
        uem_stop = max(diarRef.unique('stop')+diarHyp.unique('stop'))
        diarUem=Diar()
        diarUem.append(start=uem_start,stop=uem_stop)

1402
    # Creates the Border
1403
    border_list=border(diarHyp,diarRef,diarUem,tolerance,nonSpeechNameRef,nonSpeechNameHyp,toleranceNameRef,toleranceNameHyp)
1404

1405
    # Initializes action counters
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
    output=dict()
    output["validate"]=0
    output["create_boundary"]=0
    output["delete_boundary"]=0
    output["create_name"]=0
    output["select_name"]=0
    output["name_set"]=copy.deepcopy(nameAlreadySet)

    for z in diarUem:
        listTmp=list()
        for i in range(0, len(border_list)):
            if border_list[i][0]>=z['start'] and border_list[i][0]<=z['stop']:
                listTmp.append(i)
            elif border_list[i][0]>z['stop']:
                break
        if verbose:
            logging.info('='*10)
        for idx,i in enumerate(listTmp):
            if idx==0:
                prev_idx, prev_ref, prev_hyp, prev_border, prev_l = border_list[i]

1427
                # Checks the first identical ref and hyp 
1428
1429
                if prev_hyp != prev_ref:
                    if prev_ref in output["name_set"]:
1430
                        # Selects name if existing
1431
1432
1433
                        output["select_name"] += 1
                        border_list[i][2] = prev_ref
                    else:
1434
                        # Creates name if existing
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
                        output["create_name"] += 1
                        if prev_hyp not in output["name_set"]:
                            borderRenameAll(border_list, i, prev_ref)
                        else:
                            border_list[i][2] = prev_ref
                        output["name_set"].add(prev_ref)
                    
                    prev_idx, prev_ref, prev_hyp, prev_border, prev_l = border_list[i]
                    if verbose: 
                        logging.info(prev_border, prev_idx, prev_l, 'ref=', prev_ref, 'hyp=', hyp, 'new hyp=', prev_hyp, 'cmp=', hyp == prev_ref , 'v=', output["validate"], 'cb=', output["create_boundary"], 'db=', output["delete_boundary"], 'cn=', output["create_name"], 'sn=', output["select_name"])
                else:
1446
                    # Validates if existing
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
                    output["validate"] += 1
                    
                    if verbose:   
                        logging.info(prev_idx, ' ref=', prev_ref, ' hyp=', prev_hyp, ' cmp=', prev_ref==prev_hyp , 'v=', output["validate"], 'cb=', output["create_boundary"], 'db=', output["delete_boundary"], 'cn=', output["create_name"], 'sn=', output["select_name"])
                if verbose:
                    logging.info('-'*10)
            else:
                idx, ref, hyp, border, l = border_list[i]
                if verbose:   
                    logging.info(prev_idx, 'vs', idx,';', prev_ref, 'vs', ref, ';', prev_hyp,'vs', hyp)
                if hyp == ref:
                    # ref A A
                    # hyp A A
                    output["validate"] += 1
                    if verbose: 
                        logging.info('validate ref : A A / hyp A A')
                else :
                    if prev_ref == ref:
                        # ref : A A
                        # hyp : A B
                        # B to A
                        borderRenameFollowing(border_list,i,ref)
                        output["delete_boundary"] += 1
                        output["name_set"].add(ref)
                        if verbose:   
                            logging.info('delete ref : A A / hyp A B')
                    else:
                        if prev_hyp == hyp:
                            # ref : A B
                            # hyp : A A
                            # create boundary and create/select name
                            output["create_boundary"] += 1
                            if verbose:   
                                logging.info('create_boundary ref : A B / hyp A A')

                        # ref : A B
                        # hyp : A C/A
                        # create/select name
                        if ref in output["name_set"]:
                            output["select_name"] += 1
                            border_list[i][2] = ref
                            if verbose:   
                                logging.info('select_name ref : A B / hyp A A/C')
                        else:
                            output["create_name"] += 1
                            if hyp not in output["name_set"]:
                                borderRenameAll(border_list, i, ref)
                            else:
                                border_list[i][2]=ref
                            output["name_set"].add(ref)
                            if verbose:   
                                logging.info('create_name ref : A B / hyp A A/C', output["name_set"])

                prev_idx, prev_ref, prev_hyp, prev_border, prev_l = border_list[i]
                if verbose: 
                    logging.info(prev_border, prev_idx, prev_l, 'ref=', prev_ref, 'hyp=', hyp, 'new hyp=', prev_hyp, 'cmp=', hyp == prev_ref , 'v=', output["validate"], 'cb=', output["create_boundary"], 'db=', output["delete_boundary"], 'cn=', output["create_name"], 'sn=', output["select_name"], '\n')
    return output

# Renames all the names identical to the one at the "idx" position by "name" for a border structure
def borderRenameAll(border, idx, name):
    assert isinstance(border,list) and isinstance(idx,numbers.Number) and isinstance(name,str)
    old = border[idx][2]
    for j in range(idx, len(border)):
        if border[j][2] == old:
            border[j][2] = name

# Renames only if the following borders at the "idx" position have the same name as the previous one for a border structure
def borderRenameFollowing(border,idx,name):
    assert isinstance(border,list) and isinstance(idx,numbers.Number) and isinstance(name,str)
    oldN=border[idx][2]
    oldV=border[idx][0]+border[idx][4]
    border[idx][2]=name
    for j in range(idx+1, len(border)):
        if border[j][0]==oldV and border[j][2] == oldN:
            border[j][2] = name
            oldV=border[j][0]+border[j][4]
        else:
            break

# Checks if the boundarySegment parameter is in the tolerance of the segment parameter
## tolerance: In centiseconds
def boundariesInTolerance(boundarySegment,segment,tolerance):
    assert isinstance(segment,Segment) and isinstance(tolerance,numbers.Number) and isinstance(boundarySegment,Segment)
    if (boundarySegment['start']<=segment['start']+tolerance and boundarySegment['start']>=segment['start']-tolerance) and (boundarySegment['stop']<=segment['stop']+tolerance and boundarySegment['stop']>=segment['stop']-tolerance):
        return True
    return False

1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
# Returns a dictionary object which represents the reference boundaries linked to the hypothesis boundaries
## WARNING: The boundary matching rests on the nearest distance. In any case, it doesn't take into consideration the labels
## tolerance: In centiseconds
def boundHypToChange(diarHyp,diarRef,diarUem=None,verbose=False,tolerance=25):
    assert isinstance(verbose,bool) and isinstance(diarHyp,Diar) and isinstance(diarRef,Diar) and ((isinstance(diarUem,Diar) and len(diarOverlapArea(diarUem))==0) or diarUem is None) and len(diarOverlapArea(diarRef))==0 and len(diarOverlapArea(diarHyp))==0  
    diarHyp=copy.deepcopy(diarHyp)
    diarRef=copy.deepcopy(diarRef)
    if diarUem is not None:
        diarUem=compressDiar(diarUem)
        diarRef=releaseFramesAccordingToDiar(diarRef,diarUem)
        diarHyp=releaseFramesAccordingToDiar(diarHyp,diarUem)
    boundHyp=set(diarHyp.unique("stop")).union(set(diarHyp.unique("start")))
    boundRef=set(diarRef.unique("stop")).union(set(diarRef.unique("start")))
    boundHyp=list(boundHyp)
    boundRef=list(boundRef)
    boundHyp.sort()
    boundRef.sort()

    affected=dict()
    for i in boundRef:
        affected[i]=None

    matrix=np.full((len(boundRef), len(boundHyp)), tolerance+1000)
    for idxI,i in enumerate(sorted(boundRef)):
        for idxJ,j in enumerate(sorted(boundHyp)):
            val=abs(i-j)
            if abs(val)<=tolerance:
                matrix[idxI,idxJ]=val
            else:
                matrix[idxI,idxJ]=tolerance+1000
    if diarUem is not None:
        matrixTmp=np.full((len(boundRef), len(boundHyp)), tolerance+1000)
        for y in diarUem:
            for idxI,i in enumerate(sorted(boundRef)):
                for idxJ,j in enumerate(sorted(boundHyp)):
                    if i>=y['start'] and i<=y['stop'] and j>=y['start'] and j<=y['stop']:
                        matrixTmp[idxI,idxJ]=matrix[idxI,idxJ]
        matrix=matrixTmp
           
    if verbose:
        print(boundHyp)
        print(boundRef)

    while matrix.min() <= tolerance:
        jPos=None
        iPos=None
        if verbose:
            print("---")
            print(affected)
            print(matrix)
            print(matrix.min())
        for i in range(0,len(matrix)):
            for j in range(0,len(matrix[i])):
                if matrix[i,j]==matrix.min():
                    jPos=j
                    iPos=i
                    break
            if jPos is not None:
                break
        if verbose:
            print("LIGNE:",iPos)
            print("COLONNE:",jPos)
        boundHypPosVal=boundHyp[jPos]
        boundRefPosVal=boundRef[iPos]
        if verbose:
            print("HYP",boundHypPosVal)
            print("REF",boundRefPosVal)
        cross=False
        for y in affected:
            if affected[y] is not None and y!=boundRefPosVal:
                if not ((y<boundRefPosVal and affected[y]<boundHypPosVal) or (y>boundRefPosVal and affected[y]>boundHypPosVal)):
                    cross=True
        if not cross:
            affected[boundRefPosVal]=boundHypPosVal
            for y in range(0,len(boundHyp)):
                matrix[iPos,y]=1000+tolerance
        matrix[iPos,jPos]=1000+tolerance
    return affected

1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
# Checks the structure of a diar object
def certifyDiar(diar):
    if not isinstance(diar,Diar):
        return False
    for i in diar:
        if not isinstance(i,Segment):
            print(i.__class__)
            return False
    return True

# Checks if two diar objects are identical
def compareDiar(diar1,diar2):
    assert isinstance(diar1,Diar) and isinstance(diar2,Diar)
    diar1=copy.deepcopy(diar1)
    diar2=copy.deepcopy(diar2)
    diar1.sort()
    diar2.sort()
    if len(diar1)!=len(diar2):
        return False
    for j,val in enumerate(diar1):
        if not (diar1[j]['show']==diar2[j]['show'] and diar1[j]['cluster']==diar2[j]['cluster'] and diar1[j]['cluster_type']==diar2[j]['cluster_type'] and diar1[j]['start']==diar2[j]['start'] and diar1[j]['stop']==diar2[j]['stop']):
            return False
    return True

# Returns a compressed diar object
def compressDiar(diar):
1639
    assert isinstance(diar,Diar)
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
    diarOut=copy.deepcopy(diar)
    for i in diarOut:
        i["show"]="show"
        i["cluster"]="cluster"
    diarOut.pack()
    return diarOut

# Returns the occurence of a given segment
def countOccurenceSegment(segment,diar):
    assert isinstance(segment,Segment) and isinstance(diar,Diar)
    cpt=0
    for i in diar:
        if i['show']==segment['show'] and i['cluster']==segment['cluster'] and i['cluster_type']==segment['cluster_type'] and i['start']==segment['start'] and i['stop']==segment['stop']:
            cpt+=1
    return cpt

# Returns a diar object by cutting with a rolling mean in low energy area in order to only have segments with a given max size 
## winSize, maxSegSize, securityMarginSize: In centiseconds
## c0 of cepstrum have to be the energy
def cutBigSegmentLowEnergy(diar,cepstrum,maxSegSize,securityMarginSize,winSize=100):
    assert isinstance(diar,Diar) and isinstance(maxSegSize,numbers.Number) and isinstance(securityMarginSize,numbers.Number) and isinstance(winSize,numbers.Number)
    assert (securityMarginSize*2)<maxSegSize and (winSize/2)<=securityMarginSize
    flag=False
    diar=copy.deepcopy(diar)
    outputDiar=copy.deepcopy(diar)
1665
1666
    # Computes rolling mean and std in the window of size win, gets numpy array
    # Mean and std have NAN at the beginning and the end of the output array
1667
    df = pd.DataFrame(cepstrum)
1668
    r = df.rolling(window=int(winSize/2), center=False)
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
    mean = r.mean().values
    for i in diar:
        if i.duration()>maxSegSize:
            value=i['start']+securityMarginSize
            for y in range(i['start']+securityMarginSize,i['stop']-securityMarginSize,1):
                if mean[y][0]<mean[value][0]:
                    value=y
            outputDiar=splitSegment(i,outputDiar,value)
            if (value-i['start'])>maxSegSize or (i['stop']-value)>maxSegSize:
                flag=True
    if flag:
        return cutBigSegmentLowEnergy(outputDiar,cepstrum,maxSegSize,securityMarginSize,winSize)
    else:
        return outputDiar

1684
1685
1686
1687
1688
1689
1690
1691
# Returns a diar object with the overlap areas
def diarOverlapArea(diar):
    assert isinstance(diar,Diar)
    out_diar_tmp=copy.deepcopy(diar)
    idx = out_diar_tmp.features_by_cluster()
    clusters = out_diar_tmp.unique('cluster')
    show = out_diar_tmp.unique('show')

1692
    # Last frame
1693
1694
    l = max(out_diar_tmp.unique('stop'))

1695
    # Counts the speaker number by frame
1696
1697
1698
1699
    s = np.zeros(l)
    for cluster in clusters:
        s[idx[cluster]] += 1

1700
    # Vector of indexes counting more than one speaker
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
    npTmp=np.squeeze(np.asarray(np.argwhere(s > 1)))
    if npTmp.size<=1:
        notUnique=set()
        if npTmp.size==1:
            notUnique.add(int(npTmp))
    else:
        notUnique = set(npTmp)

    out_diar = Diar()
    for cluster in clusters:
        for i in list(set(idx[cluster]) & notUnique):
            out_diar.append(show=show[0], cluster="OVERLAP", start=i, stop=i+1)
    out_diar.pack()
    for i in out_diar:
        listTmp=set()
        for j in out_diar_tmp:
            if Segment.intersection(i,j) is not None:
                listTmp.add(j["cluster"])
        listTmp=list(listTmp)
        listTmp.sort()
        cluster=listTmp[0]
        for j in range(1,len(listTmp)):
            cluster+=(" / "+listTmp[j])
        i["cluster"]=cluster
    return out_diar

1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
# Returns a diar object without the segments having the cluster name put in parameter
def dropCluster(cluster,diar):
    assert isinstance(cluster,str) and isinstance(diar,Diar)
    out_diar=Diar()
    for i in diar:
        if i['cluster']==cluster:
            pass
        else:
            out_diar.append_seg(i)
    return copy.deepcopy(out_diar)

# Returns a diar object without the segment put in parameter
def dropSegment(segment,diar):
    assert isinstance(segment,Segment) and isinstance(diar,Diar) and countOccurenceSegment(segment,diar)==1
    out_diar=Diar()
    for i in diar:
        if i['show']==segment['show'] and i['cluster']==segment['cluster'] and i['cluster_type']==segment['cluster_type'] and i['start']==segment['start'] and i['stop']==segment['stop']:
            pass
        else:
            out_diar.append_seg(i)
    return copy.deepcopy(out_diar)

# Checks if the segment is available in the diar object
def existSegment(segment,diar):
    assert isinstance(segment,Segment) and isinstance(diar,Diar)
    return (0!=len(diar.filter("show",'==',segment['show']).filter("cluster","==",segment['cluster']).filter('cluster_type',"==",segment['cluster_type']).filter('start',"==",segment['start']).filter('stop',"==",segment['stop'])))

# Checks if only the segment boundaries are available in the diar object
## WARNING: Don't care of the other information
def existSegmentBoundary(segment,diar):
    assert isinstance(segment,Segment