diar_tools.py 128 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
# coding: utf8
from __future__ import unicode_literals

import logging
import numbers
import copy
import collections
import numpy as np
import pandas as pd
import pyannote.metrics.segmentation as pyaseg
11
import pyannote.metrics.diarization as pyadiar
12
13
14
15
16
17
18
19
import pyannote.core as pyacore
from s4d.scoring import DER
from s4d.diar import Diar, Segment

# 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):
20
21
    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)
22
23
24
25
26
27
28
29
30
    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

31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# Returns a diar object with a new column detailing the overlapped segments
def advancedOverlapDiar(diar):
    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

51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# 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()):
    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
223
## modeNoGap: Drops or not the segment actions (i.e. createSegment & deleteSegment)
224
225
226
227
## 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):
    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)
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
    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()
292
293
294
295
    tolerance=abs(tolerance)
    if not strictBoundary:
        diarRef.pack()
        diarHyp.pack()     
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533

    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
                        if z['stop']>(valueRef['stop']+tolerance):
                            actionsSegmentationBoundaryCreate.append(copy.deepcopy([z,valueRef['stop']]))
                            actionsIncrementalSegmentationBoundaryCreateTurn.append(copy.deepcopy([z,valueRef['stop']]))
                            valueTmp=splitSegment(z,valueTmp,valueRef['stop'])
                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']                    
534
                    if modeNoGap__mergeStrat_BiggestCluster == True:
535
536
537
538
539
540
541
542
543
544
545
546
547
548
                        # 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']
549
550
                    # 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']
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
                    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):
                                listHypRefSegment.append(y)
                    # Replaces the segments which are not in the correct cluster
599
600
601
602
603
604
605
                    if modeNoGap == False:
                        replaced=False
                        for y in listHypRefSegment:
                            if y['cluster']!=clusterName:
                                replaced=True
                                yTmp=copy.deepcopy(y)
                                yTmp['cluster']=clusterName
606
607
                                actionsSegmentationSegmentDelete.append(copy.deepcopy(y)) 
                                actionsIncrementalSegmentationSegmentDeleteTurn.append(copy.deepcopy(y))
608
                                valueTmp=dropSegment(y,valueTmp)
609
610
                                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']))) 
611
612
613
                                valueTmp.append_seg(yTmp)  
                        if replaced:
                            valueTmp.sort()
614
615
616
617
618
619
620
621
622
623
                    # 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):
                                    listTmp.append(y)
624
625
626
627
628
629
630
631
                        if not (not deleteBoundarySameConsecutiveSpk and listTmp[0]['cluster']==listTmp[1]['cluster']):
                            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]
632
633
634
635
636
                        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.")
637
638
639
640
641
642
643
644
                            if not (not deleteBoundarySameConsecutiveSpk and newSegment['cluster']==listTmp[y]['cluster']):
                                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]
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
        # 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
724
## modeNoGap: Drops or not the segment actions (i.e. createSegment & deleteSegment)
725
## deleteBoundarySameConsecutiveSpk: Whether we delete a boundary for two consecutive segments with the same speaker
726
727
728
## 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)
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
    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):