-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgui.ts
1459 lines (1368 loc) · 46.6 KB
/
gui.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// TODO End of movie
// TODO Will this work on my phone?
// TODO Previous page for annotating words
// TODO Metrics (cliks, locations, ?, words annotated)
// TODO submit should check for missing internal words
// TODO Unique ID generation
// TODO HIT Information in the submission, like ID number, etc
// TODO Maybe test for audio somehow before the person is qualified for the HIT
// TODO If we haven't loaded in 30 seconds, do something about it
function drawWaveformFromBuffer(width: number, height: number, shift: number, buffer: AudioBuffer) {
var data = buffer.getChannelData(0)
var step = Math.ceil(data.length / width)
var amp = height / 2
let normalize = Math.max(Math.abs(_.min(data)!), Math.abs(_.max(data)!))
let offset = _.mean(data)
waveformCtx.fillStyle = 'rgba(255, 255, 255, 0.9)'
for (var i = 0; i < width; i++) {
var min = 1.0
var max = -1.0
var datum
for (var j = 0; j < step; j++) {
datum = data[i * step + j]
if (datum < min) min = datum
if (datum > max) max = datum
}
min = (min - offset) / normalize
max = (max - offset) / normalize
if (!_.isUndefined(datum)) {
waveformCtx.fillRect(i, shift + min * amp, 1, (max - min) * amp)
}
}
}
function drawWaveform() {
waveformCtx.clearRect(0, 0, waveformCanvas.width, waveformCanvas.height)
if (buffers[BufferType.normal]) {
drawWaveformFromBuffer(
waveformCanvas.width,
waveformCanvas.height * 0.1,
waveformCanvas.height * 0.95,
buffers[BufferType.normal]!
)
}
}
function heightBottom(isReference: boolean) {
if (splitHeight) {
if (isReference) {
return '90%'
} else {
return '0%'
}
} else {
return '0%'
}
}
function heightTop(isReference: boolean) {
if (splitHeight) {
if (isReference) {
return '100%'
} else {
return '90%'
}
} else {
return '100%'
}
}
function heightText(isReference: boolean) {
if (splitHeight) {
if (isReference) {
return '99%'
} else {
return '47%'
}
} else {
if (isReference) {
return '55%'
} else {
return '47%'
}
}
}
function heightTopLine(isReference: boolean) {
if (splitHeight) {
if (isReference) {
return '93%'
} else {
return '50%'
}
} else {
return '50%'
}
}
function clickOnCanvas() {
clear()
stopPlaying()
setup(buffers[bufferKind]!)
lastClick = positionToAbsoluteTime(to<PositionInSpectrogram>(mousePosition().x))
// @ts-ignore
play(timeInMovieToTimeInBuffer(lastClick), d3.event.shiftKey ? endS - startS : defaultPlayLength())
}
function resizeCanvas() {
viewer_width = Math.min($('.panel').width()!, 3000) // 2240 // 1200
viewer_height = Math.min(window.innerHeight * 0.5, 800) // 830 // 565
viewer_border = 0
canvas.width = viewer_width
canvas.height = viewer_height
waveformCanvas.width = viewer_width
waveformCanvas.height = viewer_height
drawWaveform()
$('#d3')
.attr('width', viewer_width)
.attr('height', viewer_height + viewer_border)
$('#container')
.css('width', viewer_width)
.css('height', viewer_height + viewer_border)
}
resizeCanvas()
$(window).resize(() => {
stop()
resizeCanvas()
})
if (AudioContext) {
context = new AudioContext()
} else {
$('#loading').html(
'<h1><span class="label label-danger">Can\'t load audio context! Please use a recent free browser like the latest Chrome or Firefox.</span><h1>'
)
}
function setupAudioNodes() {
javascriptNode = context!.createScriptProcessor(256, 1, 1)
javascriptNode.connect(context!.destination)
}
setupAudioNodes()
function message(kind: string, msg: string) {
if (kind != 'success' && kind != 'warning')
recordMessage({
level: kind,
data: msg,
})
$('#loading')
.html('<h4><div class="alert alert-' + kind + '">' + msg + '</span></h4>')
.removeClass('invisible')
}
function setSegment(segmentName: string) {
const s = segmentName.split(':')
segment = segmentName
movieName = s[0]
startS = parseFloat(s[1])
endS = parseFloat(s[2])
}
// TODO Check all properties here
// TODO disable the default at some point
if ($.url().param().token) {
token = $.url().param().token
$.ajax({
type: 'POST',
data: JSON.stringify({ token: $.url().param().token }),
contentType: 'application/json',
async: false,
url: '/details',
success: function (data) {
if (data.response != 'ok') {
message('danger', 'Bad token!')
throw 'bad-token'
}
setSegment(data.segment)
},
})
} else {
if ($.url().param().segment) setSegment($.url().param().segment)
else setSegment('test:0:1')
}
if ($.url().param().nohelp) $('#help-panel').remove()
function tokenMode() {
stopPlaying()
mode = 'token'
bufferKind = BufferType.normal
$('.transcription-gui').addClass('display-none')
$('.annotation-gui').addClass('display-none')
// TOOD Maybe ressurect this one day?
// keyboardShortcutsOff()
}
function annotationMode() {
mode = 'annotation'
bufferKind = BufferType.normal
$('.transcription-gui').addClass('display-none')
$('.annotation-gui').removeClass('display-none')
keyboardShortcutsOn()
// TODO This is blocked by browsers anyway
// if(sourceNode) {
// stopPlaying()
// play(0)
// }
}
annotationMode()
// delay between hearing a word, figuring out that it's the one
// you want, pressing the button and the event firing
function defaultPlayLength(): TimeInBuffer {
switch (bufferKind) {
case BufferType.half:
return to(1.4)
case BufferType.normal:
return to(0.7)
}
}
function verifyStartBeforeEnd(index: number, startTime: TimeInMovie) {
if (annotations[index] && from(annotations[index].endTime!) - 0.01 <= from(startTime)) {
message('warning', 'The start of word would be after the end')
throw 'The start of word would be after the end'
}
return startTime
}
function verifyEndAfterStart(index: number, endTime: TimeInMovie) {
if (annotations[index] && from(annotations[index].startTime!) + 0.01 >= from(endTime)) {
message('warning', 'The end of word would be before the start')
throw 'The end of word would be before the start'
}
return endTime
}
function verifyTranscriptOrder(index: number, time: TimeInMovie) {
// Words that appear before this one the transcript should have earlier start times
if (
_.filter(
annotations,
a => isValidAnnotation(a) && from<TimeInMovie>(a.startTime!) > from<TimeInMovie>(time) && a.index < index
).length > 0
) {
message('warning', 'This word would start before a word that is earlier in the transcript')
throw 'This word would start before a word that is earlier in the transcript'
}
// Words that appear before this one the transcript should have earlier start times
else if (
_.filter(
annotations,
a => isValidAnnotation(a) && from<TimeInMovie>(a.startTime!) < from<TimeInMovie>(time) && a.index > index
).length > 0
) {
message('warning', 'This word would start after a word that is later in the transcript')
throw 'This word would start after a word that is later in the transcript'
} else {
return time
}
}
svgReferenceAnnotations.on('click', function (_d, _i) {
clickOnCanvas()
})
svgAnnotations.on('click', function (_d, _i) {
clickOnCanvas()
})
function drag(annotation: Annotation, position: DragPosition) {
return d3.behavior
.drag()
.on('dragstart', () => pushUndo(annotation))
.on('drag', function () {
// @ts-ignore
const dx = d3.event.dx
switch (position) {
case DragPosition.start:
annotation.startTime = verifyStartBeforeEnd(
annotation.index,
verifyTranscriptOrder(annotation.index, addConst(annotation.startTime!, from(positionToTime(to(dx)))))
)
break
case DragPosition.end:
annotation.endTime = verifyEndAfterStart(
annotation.index,
addConst(annotation.endTime!, from(positionToTime(to(dx))))
)
break
case DragPosition.both:
annotation.startTime = verifyTranscriptOrder(
annotation.index,
addConst(annotation.startTime!, from(positionToTime(to(dx))))
)
annotation.endTime = addConst(annotation.endTime!, from(positionToTime(to(dx))))
break
}
updateWord(annotation)
})
.on('dragend', function (_d, _i) {
selectWord(annotation)
$('#play-selection').click()
})
}
function loadSound(url: string, kind: BufferType, fn: any) {
var request = new XMLHttpRequest()
request.open('GET', url, true)
request.responseType = 'arraybuffer'
request.onload = () => {
context!.decodeAudioData(
request.response,
function (audioBuffer) {
buffers[kind] = audioBuffer
setup(buffers[kind]!)
if (fn) {
fn()
}
},
onError
)
}
request.send()
}
function clear() {
$('#loading').addClass('invisible')
}
function setup(buffer: AudioBuffer) {
sourceNode = context!.createBufferSource()
sourceNode.connect(javascriptNode)
sourceNode.buffer = buffer
startTime = to<TimeInBuffer>(context!.currentTime)
sourceNode.onended = () => {
audioIsPlaying -= 1
redraw()
}
if (!mute) sourceNode.connect(context!.destination)
// Maybe?
// sourceNode.playbackRate.value = 0.5
// sourceNode.loop = true
}
function play(offset_: TimeInBuffer, duration_?: TimeInBuffer) {
const offset = from(offset_)
startTime = to<TimeInBuffer>(context!.currentTime)
startOffset = offset_
if (duration_ != null) {
const duration = from(duration_)
endTime = offset + duration
audioIsPlaying += 1
// Math.max is required for .start() because we have sgments that start before our audio does
sourceNode.start(0, Math.max(0, offset), duration)
} else {
endTime = 1000000 // infinity seconds..
audioIsPlaying += 1
// Math.max is required for .start() because we have sgments that start before our audio does
sourceNode.start(0, Math.max(0, offset))
}
}
function stopPlaying() {
// Might need to do: player.sourceNode.noteOff(0) on some browsers?
try {
sourceNode.stop(0)
startOffset = to(context!.currentTime - from(add(startTime, startOffset)))
redraw()
} catch (err) {
// Calling stop more than once should be safe, although
// catching all errors is bad form
}
}
function onError(e: any) {
console.log(e)
}
function timeInMovieToPercent(time: TimeInMovie): string {
return 100 * ((from(time) - startS) / (endS - startS)) + '%'
}
function timeInMovieToTimeInBuffer(time: TimeInMovie): TimeInBuffer {
return positionToTimeInBuffer(absoluteTimeToPosition(time))
}
function absoluteTimeToPosition(time: TimeInMovie): PositionInSpectrogram {
return to(((from(time) - startS) / (endS - startS)) * canvas.width)
}
function timeToPosition(time: TimeInSegment): PositionInSpectrogram {
return to((from(time) / (endS - startS)) * canvas.width)
}
function timeInBufferToPosition(time: TimeInBuffer): PositionInSpectrogram {
return to((from(time) / sourceNode.buffer!.duration) * canvas.width)
}
function timeInMovieToPosition(time: TimeInMovie): PositionInSpectrogram {
return to(((from(time) - startS) / (endS - startS)) * canvas.width)
}
function positionToTime(position: PositionInSpectrogram): TimeInSegment {
return to((from(position) * (endS - startS)) / canvas.width)
}
function positionToTimeInBuffer(position: PositionInSpectrogram): TimeInBuffer {
return to((from(position) * sourceNode.buffer!.duration) / canvas.width)
}
function positionToAbsoluteTime(position: PositionInSpectrogram): TimeInMovie {
return to(startS + (from(position) * (endS - startS)) / canvas.width)
}
function redraw(timeOffset?: TimeInBuffer) {
ctx.clearRect(0, 0, canvas.width, canvas.height)
if (timeOffset != null && from<TimeInBuffer>(timeOffset) < endTime) {
var offset = timeInBufferToPosition(timeOffset)
ctx.fillStyle = 'rgba(255, 255, 255, 0.9)'
ctx.fillRect(from<PositionInSpectrogram>(offset), 1, 1, canvas.height)
}
if (lastClick != null) {
ctx.fillStyle = 'rgba(200, 0, 0, 0.9)'
ctx.fillRect(from<PositionInSpectrogram>(timeInMovieToPosition(lastClick)), 1, 2, canvas.height)
}
if (dragStart != null) {
ctx.fillStyle = 'rgba(200, 0, 0, 0.9)'
ctx.fillRect(from<PositionInSpectrogram>(timeInMovieToPosition(dragStart)), 1, 2, canvas.height)
}
}
function wordClickHandler(index: number) {
let annotation = annotations[index]
if (annotation.startTime != null) {
selectWord(annotation)
$('#play-selection').click()
} else {
if (lastClick != null) {
selectWord(startWord(index, lastClick))
$('#play-selection').click()
} else if (selected != null && annotations[selected].endTime != null) {
selectWord(startWord(index, addConst(annotations[selected].endTime!, Math.max(0, index - selected - 1) * 0.1)))
$('#play-selection').click()
} else message('warning', 'Place the marker first by clicking on the image')
}
}
function updateWords(words: string[]) {
$('#words').empty()
annotations = []
_.forEach(words, function (word, index) {
annotations[index] = { index: index, word: word }
$('#words')
.append($('<a href="#">').append($('<span class="word label label-danger">').text(word).data('index', index)))
.append(' ')
})
$('.word').click(function (e) {
clear()
e.preventDefault()
const index = $(this).data('index')
recordMouseClick(e, '.word', index + '')
wordClickHandler(index)
})
}
function updateWordsWithAnnotations(newWords: string[]) {
$('#words').empty()
const oldWords = words
const oldAnnotations = _.cloneDeep(annotations)
_.forEach(annotations, removeAnnotation)
const alignment = alignWords(newWords, oldWords)
words = newWords
annotations = []
_.forEach(words, function (word, index) {
annotations[index] = { word: word, index: index }
if (_.has(alignment, index)) {
const old = oldAnnotations[alignment[index]]
annotations[index].startTime = old.startTime
annotations[index].endTime = old.endTime
annotations[index].lastClickTimestamp = old.lastClickTimestamp
} else if (oldWords.length == newWords.length) {
// If there is no alignment but the number of words is unchanged, then
// we replaced one or more words. We preserve the annotations in that
// case.
const old = oldAnnotations[index]
annotations[index].startTime = old.startTime
annotations[index].endTime = old.endTime
annotations[index].lastClickTimestamp = old.lastClickTimestamp
}
})
_.forEach(words, function (word, index) {
$('#words')
.append($('<a href="#">').append($('<span class="word label label-danger">').text(word).data('index', index)))
.append(' ')
})
$('.word').click(function (e) {
clear()
e.preventDefault()
const index = $(this).data('index')
recordMouseClick(e, '.word', index + '')
wordClickHandler(index)
})
_.forEach(annotations, updateWord)
}
function startWord(index: number, time: TimeInMovie) {
if (
!_.find(annotations, function (key) {
return key.index != index && key.startTime == time
})
) {
verifyTranscriptOrder(index, time)
clear()
deleteWord(annotations[index])
selected = null
annotations[index] = {
index: index,
word: words[index],
startTime: time,
// TODO Constant
endTime: lift(time, p => Math.min(p + words[index].length * 0.05, endS)),
}
updateWord(annotations[index])
return annotations[index]
} else {
message('danger', "Words can't start at the same position")
throw "Words can't start at the same position"
}
}
function closestWord(time: TimeInMovie) {
return _.sortBy(
_.filter(annotations, function (annotation: Annotation) {
return annotation.startTime != null && annotation.startTime < time
}),
function (annotation: Annotation, _index: number) {
return sub(time, annotation.startTime!)
}
)[0]
}
function annotationColor(annotation: Annotation, isReference: boolean) {
if (isReference) return '#5bc0de'
if (annotation.endTime != null) {
if (annotation.index == selected) return 'orange'
else return '#6fe200'
} else {
return 'red'
}
}
function clearWordLabels(annotation: Annotation) {
$('.word')
.eq(annotation.index)
.removeClass('label-success')
.removeClass('label-warning')
.removeClass('label-info')
.removeClass('label-primary')
.removeClass('label-danger')
}
function handleClickOnAnnotatedWord(annotation: Annotation, isReference: boolean) {
return (e: any, j: any) => {
recordMouseClick(e, '#click-on-word', [cloneAnnotation(annotation), isReference])
// @ts-ignore
d3.event.stopPropagation()
if (!isReference) {
clear()
selectWord(annotation)
}
lastClick = positionToAbsoluteTime(to<PositionInSpectrogram>(mousePosition().x))
if (isReference) playAnnotation(annotation)
else $('#play-selection').click()
}
}
function handleDragOnAnnotatedWord(annotation: Annotation, isReference: boolean, position: DragPosition) {
if (!isReference) return drag(annotation, position)
else return () => null
}
function updateWordBySource(annotation: Annotation, isReference: boolean, worker: string) {
if (annotation.visuals == null)
// @ts-ignore
annotation.visuals = {}
// NB This check is redudant but it makes typescript understand that annotation.visuals != null
if (annotation.visuals != null) {
if (annotation.startTime != null) {
if (!isReference) {
clearWordLabels(annotation)
if (annotation.endTime == null) $('.word').eq(annotation.index).addClass('label-danger')
else if (annotation.index == selected) $('.word').eq(annotation.index).addClass('label-warning')
else $('.word').eq(annotation.index).addClass('label-success')
}
if (!annotation.visuals.group) {
annotation.visuals.group = (isReference ? svgReferenceAnnotations : svgAnnotations).append('g')
annotation.id = isReference ? worker + ':' + annotation.startTime : from<TimeInMovie>(annotation.startTime)
annotation.visuals.group.datum(isReference ? worker + ':' + annotation.startTime : annotation.index)
}
if (!annotation.visuals.startLine) {
annotation.visuals.startLine = annotation.visuals.group.append('line')
annotation.visuals.startLineHandle = annotation.visuals.group
.append('line')
.call(
// @ts-ignore
handleDragOnAnnotatedWord(annotation, isReference, DragPosition.start)
)
.on('click', handleClickOnAnnotatedWord(annotation, isReference))
}
annotation.visuals.startLine
.attr('x1', timeInMovieToPercent(annotation.startTime!))
.attr('x2', timeInMovieToPercent(annotation.startTime!))
.attr('y1', heightBottom(isReference))
.attr('y2', heightTop(isReference))
.attr('stroke', annotationColor(annotation, isReference))
.attr('opacity', 0.7)
.attr('stroke-width', '2')
annotation.visuals.startLineHandle
.attr('x1', timeInMovieToPercent(subConst(annotation.startTime!, handleOffset)))
.attr('x2', timeInMovieToPercent(subConst(annotation.startTime!, handleOffset)))
.attr('y1', heightBottom(isReference))
.attr('y2', heightTop(isReference))
.attr('stroke', annotationColor(annotation, isReference))
.attr('opacity', 0)
.attr('stroke-width', '12')
.attr('name', 'startLine')
if (!annotation.visuals.filler) {
annotation.visuals.filler = annotation.visuals.group
.insert('rect', ':first-child')
.call(
// @ts-ignore
handleDragOnAnnotatedWord(annotation, isReference, DragPosition.both)
)
.on('click', handleClickOnAnnotatedWord(annotation, isReference))
}
annotation.visuals.filler
.attr('x', timeInMovieToPercent(annotation.startTime!))
.attr('y', heightBottom(isReference))
.attr('width', timeInMovieToPercent(addConst(sub(annotation.endTime!, annotation.startTime!), startS)))
.attr('height', heightTop(isReference))
.attr('opacity', isReference ? 0 : 0.1)
.attr('stroke', annotationColor(annotation, isReference))
.attr('fill', annotationColor(annotation, isReference))
if (!annotation.visuals.endLine) {
annotation.visuals.endLine = annotation.visuals.group.append('line')
annotation.visuals.endLineHandle = annotation.visuals.group
.append('line')
.call(
// @ts-ignore
handleDragOnAnnotatedWord(annotation, isReference, DragPosition.end)
)
.on('click', handleClickOnAnnotatedWord(annotation, isReference))
}
annotation.visuals.endLine
.attr('x1', timeInMovieToPercent(annotation.endTime!))
.attr('x2', timeInMovieToPercent(annotation.endTime!))
.attr('y1', heightBottom(isReference))
.attr('y2', heightTop(isReference))
.attr('stroke', annotationColor(annotation, isReference))
.attr('opacity', 1)
.attr('stroke-width', '2')
annotation.visuals.endLineHandle
.attr('x1', timeInMovieToPercent(addConst(annotation.endTime!, handleOffset)))
.attr('x2', timeInMovieToPercent(addConst(annotation.endTime!, handleOffset)))
.attr('y1', heightBottom(isReference))
.attr('y2', heightTop(isReference))
.attr('stroke', annotationColor(annotation, isReference))
.attr('opacity', 0)
.attr('stroke-width', '12')
// .attr('name', 'endLine')
if (!annotation.visuals.topLine) annotation.visuals.topLine = annotation.visuals.group.append('line')
annotation.visuals.topLine
.attr('x1', timeInMovieToPercent(annotation.startTime!))
.attr('x2', timeInMovieToPercent(annotation.endTime!))
.attr('y1', heightTopLine(isReference))
.attr('y2', heightTopLine(isReference))
.attr('stroke', annotationColor(annotation, isReference))
.attr('opacity', 0.7)
.style('stroke-dasharray', '3, 3')
.attr('stroke-width', '2')
if (!annotation.visuals.text)
annotation.visuals.text = annotation.visuals.group.append('text').text(annotation.word)
annotation.visuals.text
.attr('filter', 'url(#blackOutlineEffect)')
.attr('font-family', 'sans-serif')
.attr('font-size', '15px')
.attr('class', 'unselectable')
.attr('fill', annotationColor(annotation, isReference))
.on('click', handleClickOnAnnotatedWord(annotation, isReference))
let textLocationTime = from(sub(annotation.endTime!, annotation.startTime!)) / 2 + from(annotation.startTime!)
if (from(annotation.startTime) < startS) {
textLocationTime = startS
annotation.visuals.text.attr('text-anchor', 'start')
} else if (from(annotation.endTime!) > endS) {
textLocationTime = endS
annotation.visuals.text.attr('text-anchor', 'end')
} else {
annotation.visuals.text.attr('text-anchor', 'middle')
}
annotation.visuals.text.attr('x', timeInMovieToPercent(to(textLocationTime))).attr('y', heightText(isReference))
} else {
$('.word').eq(annotation.index).addClass('label-danger')
}
}
}
function updateWord(annotation: Annotation) {
updateWordBySource(annotation, false, $.url().param().worker)
}
function removeAnnotation(annotation: Annotation) {
if (annotation.visuals) {
if (annotation.visuals.startLine) {
annotation.visuals.startLine.remove()
annotation.visuals.startLineHandle.remove()
}
if (annotation.visuals.endLine) {
annotation.visuals.endLine.remove()
annotation.visuals.endLineHandle.remove()
}
if (annotation.visuals.filler) {
annotation.visuals.filler.remove()
}
if (annotation.visuals.topLine) {
annotation.visuals.topLine.remove()
}
if (annotation.visuals.text) {
annotation.visuals.text.remove()
}
if (annotation.visuals.group) {
annotation.visuals.group.remove()
}
delete annotation.visuals
}
return annotation
}
function deleteWord(annotation: Annotation) {
if (selected != null) {
if (annotation.startTime != null) delete annotation.startTime
if (annotation.endTime != null) delete annotation.endTime
if (annotation.index != null) {
clearWordLabels(annotation)
updateWord(annotation)
}
removeAnnotation(annotation)
clearSelection()
} else message('warnig', 'Click a word to select it first')
}
function fillAnnotationPositions(annotation: Annotation) {
if (!annotation.lastClickTimestamp) annotation.lastClickTimestamp = -1
return annotation
}
function updateBackgroundWord(worker: string, annotation: Annotation) {
updateWordBySource(annotation, true, worker)
}
function clearSelection() {
selected = null
_.forEach(annotations, updateWord)
}
function find_annotation(id: string | number) {
if (typeof id === 'number') {
// return _.find(annotations, a => a.id == id); // TODO Switch to this
return annotations[id]
}
if (typeof id === 'string') {
return _.find(other_annotations_by_worker[id.split(':')[0]], a => a.id == id)
}
}
function shuffleSelection() {
// TODO This function is terrible
let workerAnnotations = svgAnnotations.selectAll('g').sort(function (a, b) {
// TODO Selection
return d3.ascending(
// @ts-ignore
find_annotation(a).lastClickTimestamp,
// @ts-ignore
find_annotation(b).lastClickTimestamp
)
})[0][0]
if (!_.isUndefined(workerAnnotations)) {
return workerAnnotations
}
return svgReferenceAnnotations.selectAll('g').sort(function (a, b) {
// TODO Selection
return d3.ascending(
// @ts-ignore
find_annotation(a).lastClickTimestamp,
// @ts-ignore
find_annotation(b).lastClickTimestamp
)
// @ts-ignore
})[0][0].__data__
}
function selectWord(annotation: Annotation) {
if (annotation != null) {
lastClick = null
selected = annotation.index
annotation.lastClickTimestamp = Date.now()
_.forEach(annotations, updateWord)
shuffleSelection()
}
}
function nextWord() {
var word = _.filter(annotations, function (annotation: Annotation) {
return annotation.startTime == null
})[0]
if (word) return word.index
else return null
}
function nextAnnotation(index: number) {
var word = _.filter(annotations, function (annotation: Annotation) {
return annotation.index > index && annotation.startTime != null
})[0]
if (word) return word.index
else return null
}
function previousAnnotation(index: number): number | null {
var word = _.last(
_.filter(annotations, function (annotation: Annotation) {
return annotation.index < index && annotation.startTime != null
})
)
if (word) return word.index
else return null
}
$('#play').click(function (e) {
recordMouseClick(e, '#play')
clear()
stopPlaying()
setup(buffers[bufferKind]!)
play(to(0))
})
$('#stop').click(function (e) {
recordMouseClick(e, '#stop')
clear()
stopPlaying()
redraw(startOffset)
})
$('#delete-selection').click(function (e) {
recordMouseClick(e, '#delete-selection', selected + '')
clear()
if (selected != null) {
var index = annotations[selected].index
deleteWord(annotations[selected])
const previous = previousAnnotation(index)
const next = nextAnnotation(index)
if (previous != null) selectWord(annotations[previous])
else if (next != null) selectWord(annotations[next])
else message('warning', 'Click a word to select it first')
} else message('warning', 'Click a word to select it first')
})
function playAnnotation(annotation: Annotation) {
stopPlaying()
setup(buffers[bufferKind]!)
if (annotation.endTime != null)
play(
timeInMovieToTimeInBuffer(annotation.startTime!),
sub(timeInMovieToTimeInBuffer(annotation.endTime), timeInMovieToTimeInBuffer(annotation.startTime!))
)
else play(timeInMovieToTimeInBuffer(annotation.startTime!), defaultPlayLength())
}
$('#play-selection').click(function (e) {
recordMouseClick(e, '#play-selection', selected + '')
clear()
if (selected != null) {
stopPlaying()
setup(buffers[bufferKind]!)
playAnnotation(annotations[selected])
} else message('warning', 'Click a word to select it first')
})
$('#start-next-word').click(function (e) {
clear()
if (lastClick != null) {
recordMouseClick(e, '#start-next-word', lastClick + '')
const firstMissingWord = _.head(_.filter(annotations, a => !isValidAnnotation(a)))
if (!firstMissingWord) {
message('warning', "All words are already annotated; can't start another one")
throw "All words are already annotated; can't start another one"
} else {
startWord(firstMissingWord.index, lastClick)
selectWord(firstMissingWord)
}
} else {
recordMouseClick(e, '#start-next-word', selected + '')
if (
selected != null &&
annotations[selected].endTime != null &&
(annotations[selected + 1] == null || annotations[selected + 1].endTime == null)
) {
if (selected + 1 >= words.length) {
message('warning', 'No next word to annotate')
return
}
selectWord(startWord(selected + 1, annotations[selected].endTime!))
$('#play-selection').click()
} else {
message('warning', 'Place the red marker or select a word to add another word after it')
throw 'Place the red marker or select a word to add another word after it'
}
}
})
$('#start-next-word-after-current-word').click(function (e) {
recordMouseClick(e, '#start-next-word-after-current-word', selected + '')
clear()
if (
selected != null &&
annotations[selected].endTime != null &&
(annotations[selected + 1] == null || annotations[selected + 1].endTime == null)
) {
if (selected + 1 >= words.length) {
message('warning', 'No next word to annotate')
return
}
selectWord(startWord(selected + 1, annotations[selected].endTime!))
$('#play-selection').click()
} else {
message('warning', 'Select a word to add another word after it')
throw 'Select a word to add another word after it'
}
})
$('#reset').click(function (e) {
recordMouseClick(e, '#reset')
clear()
location.reload()
})
// TODO Next must clear the loading flag whne it is done!
function submit(next: any) {
if (loading != LoadingState.ready) return
loading = LoadingState.submitting
clear()
message('warning', 'Submitting annotation')
sendTelemetry()
// TODO We should reenable this for mturk
// tokenMode()
const data = {
segment: segment,
token: token,
browser: browser,
width: canvas.width,
height: canvas.height,
words: words,
selected: selected,
start: startS,
end: endS,
startTime: startTime,
startOffset: startOffset,
lastClick: lastClick,
worker: $.url().param().worker,
annotations: _.map(
_.filter(annotations, a => !_.isUndefined(a.startTime)),
function (a) {
return {
startTime: a.startTime!,
endTime: a.endTime!,
index: a.index,
word: a.word,
}
}
),
}
recordSend({
data: data,
server: $.url().attr().host,
port: $.url().attr().port,
why: 'submit',
})
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
url: '/submission',
success: function (data) {
recordReceive({
response: data,
error: null,
status: '200',
server: $.url().attr().host,
port: $.url().attr().port,
why: 'submit',
})
if (data && data.response == 'ok') {
if (data.stoken != null && token != null) {
next()
message('success', 'Thanks!<br/>Enter the following two characters back into Amazon Turk: ' + data.stoken)
} else {