-
Notifications
You must be signed in to change notification settings - Fork 160
/
result.py
2619 lines (2350 loc) · 103 KB
/
result.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import warnings
import re
import torch
import numpy as np
from typing import Union, List, Tuple, Optional, Callable
from copy import deepcopy
from itertools import chain
from tqdm import tqdm
from .stabilization import suppress_silence, get_vad_silence_func, VAD_SAMPLE_RATES
from .stabilization.nonvad import audio2timings
from .stabilization.utils import filter_timings
from .text_output import *
from .utils import str_to_valid_type, format_timestamp, UnsortedException
from .audio.utils import audio_to_tensor_resample
from .default import get_min_word_dur, get_append_punctuations, get_prepend_punctuations
__all__ = ['WhisperResult', 'Segment']
def _combine_attr(obj: object, other_obj: object, attr: str):
if (val := getattr(obj, attr)) is not None:
other_val = getattr(other_obj, attr)
if isinstance(val, list):
if other_val is None:
setattr(obj, attr, None)
else:
val.extend(other_val)
else:
new_val = None if other_val is None else ((val + other_val) / 2)
setattr(obj, attr, new_val)
def _increment_attr(obj: object, attr: str, val: Union[int, float]):
if (curr_val := getattr(obj, attr, None)) is not None:
setattr(obj, attr, curr_val + val)
def _round_timestamp(ts: Union[float, None]):
if not ts:
return ts
return round(ts, 3)
class WordTiming:
def __init__(
self,
word: str,
start: float,
end: float,
probability: Optional[float] = None,
tokens: Optional[List[int]] = None,
left_locked: bool = False,
right_locked: bool = False,
segment_id: Optional[int] = None,
id: Optional[int] = None,
segment: Optional['Segment'] = None,
round_ts: bool = True,
ignore_unused_args: bool = False
):
if not ignore_unused_args and segment_id is not None:
warnings.warn('The parameter ``segment_id`` is ignored. '
'Specify the current segment instance with ``segment``.',
stacklevel=2)
self.round_ts = round_ts
self.word = word
self._start = self.round(start)
self._end = self.round(end)
self.probability = probability
self.tokens = tokens
self.left_locked = left_locked
self.right_locked = right_locked
self.segment = segment
self.id = id
def __repr__(self):
return f'WordTiming(start={self.start}, end={self.end}, word="{self.word}")'
def __len__(self):
return len(self.word)
def __add__(self, other: 'WordTiming'):
self_copy = WordTiming(
word=self.word + other.word,
start=min(self.start, other.start),
end=max(self.end, other.end),
probability=self.probability,
tokens=None if self.tokens is None else self.tokens.copy(),
left_locked=self.left_locked or other.left_locked,
right_locked=self.right_locked or other.right_locked,
id=self.id,
segment=self.segment
)
_combine_attr(self_copy, other, 'probability')
_combine_attr(self_copy, other, 'tokens')
return self_copy
def __deepcopy__(self, memo=None):
return self.copy(copy_tokens=True)
def __copy__(self):
return self.copy()
def copy(
self,
keep_segment: bool = False,
copy_tokens: bool = False
):
return WordTiming(
word=self.word,
start=self.start,
end=self.end,
probability=self.probability,
tokens=None if (self.tokens is None) else (self.tokens.copy() if copy_tokens else self.tokens),
left_locked=self.left_locked,
right_locked=self.right_locked,
id=self.id,
segment=self.segment if keep_segment else None,
round_ts=self.round_ts
)
def round(self, timestamp: float) -> float:
if not self.round_ts:
return timestamp
return _round_timestamp(timestamp)
def to_display_str(self):
return f"[{format_timestamp(self.start)}] -> [{format_timestamp(self.end)}] \"{self.word}\""
@property
def start(self):
return self._start
@property
def end(self):
return self._end
@start.setter
def start(self, val):
self._start = self.round(val)
@end.setter
def end(self, val):
self._end = self.round(val)
@property
def segment_id(self):
return None if self.segment is None else self.segment.id
@property
def duration(self):
return self.round(self.end - self.start)
def round_all_timestamps(self):
warnings.warn('``.round_all_timestamps()`` is deprecated and will be removed in future versions. '
'Use ``.round_ts=True`` to round timestamps by default instead.',
stacklevel=2)
self.round_ts = True
def offset_time(self, offset_seconds: float):
self.start = self.start + offset_seconds
self.end = self.end + offset_seconds
def to_dict(self):
return dict(
word=self.word,
start=self.start,
end=self.end,
probability=self.probability,
tokens=None if self.tokens is None else self.tokens.copy()
)
def lock_left(self):
self.left_locked = True
def lock_right(self):
self.right_locked = True
def lock_both(self):
self.lock_left()
self.lock_right()
def unlock_both(self):
self.left_locked = False
self.right_locked = False
def suppress_silence(self,
silent_starts: np.ndarray,
silent_ends: np.ndarray,
min_word_dur: Optional[float] = None,
nonspeech_error: float = 0.3,
keep_end: Optional[bool] = True):
suppress_silence(self, silent_starts, silent_ends, min_word_dur, nonspeech_error, keep_end)
return self
def rescale_time(self, scale_factor: float):
self.start = self.start * scale_factor
self.end = self.end * scale_factor
def clamp_max(self, max_dur: float, clip_start: bool = False, verbose: bool = False):
if self.duration > max_dur:
if clip_start:
new_start = round(self.end - max_dur, 3)
if verbose:
print(f'Start: {self.start} -> {new_start}\nEnd: {self.end}\nText:"{self.word}"\n')
self.start = new_start
else:
new_end = round(self.start + max_dur, 3)
if verbose:
print(f'Start: {self.start}\nEnd: {self.end} -> {new_end}\nText:"{self.word}"\n')
self.end = new_end
def set_segment(self, segment: 'Segment'):
warnings.warn('``.set_segment(current_segment_instance)`` is deprecated and will be removed in future versions.'
' Use ``.segment = current_segment`` instead.',
stacklevel=2)
self.segment = segment
def get_segment(self) -> Union['Segment', None]:
"""
Return instance of :class:`stable_whisper.result.Segment` that this instance is a part of.
"""
warnings.warn('``.get_segment()`` will be removed in future versions. Use ``.segment`` instead.',
stacklevel=2)
return self.segment
def _words_by_lock(words: List[WordTiming], only_text: bool = False, include_single: bool = False):
"""
Return a nested list of words such that each sublist contains words that are locked together.
"""
all_words = []
for word in words:
if len(all_words) == 0 or not (all_words[-1][-1].right_locked or word.left_locked):
all_words.append([word])
else:
all_words[-1].append(word)
if only_text:
all_words = list(map(lambda ws: list(map(lambda w: w.word, ws)), all_words))
if not include_single:
all_words = [ws for ws in all_words if len(ws) > 1]
return all_words
class Segment:
def __init__(
self,
start: Optional[float] = None,
end: Optional[float] = None,
text: Optional[str] = None,
seek: Optional[float] = None,
tokens: List[int] = None,
temperature: Optional[float] = None,
avg_logprob: Optional[float] = None,
compression_ratio: Optional[float] = None,
no_speech_prob: Optional[float] = None,
words: Optional[Union[List[WordTiming], List[dict]]] = None,
id: Optional[int] = None,
result: Optional["WhisperResult"] = None,
round_ts: bool = True,
ignore_unused_args: bool = False
):
if words:
if ignore_unused_args:
start = end = text = tokens = None
else:
if (start or end) is not None:
warnings.warn('Arguments for ``start`` and ``end`` will be ignored '
'and the ``start`` and ``end`` will taken from the first and last ``words``.',
stacklevel=2)
if text is not None:
warnings.warn('The argument for ``text`` will be ignored '
'and it will always be the concatenation of text in ``words``',
stacklevel=2)
if tokens is not None:
warnings.warn('The argument for ``tokens`` will be ignored '
'and it will always be the concatenation of tokens in ``words``',
stacklevel=2)
self.round_ts = round_ts
self._default_start = self.round(start) if start else 0.0
self._default_end = self.round(end) if end else 0.0
self._default_text = text or ''
self._default_tokens = tokens or []
self.seek = seek
self.temperature = temperature
self.avg_logprob = avg_logprob
self.compression_ratio = compression_ratio
self.no_speech_prob = no_speech_prob
self.words = words
if self.words and isinstance(words[0], dict):
self.words = [
WordTiming(
**word,
segment=self,
round_ts=self.round_ts,
ignore_unused_args=True
) for word in self.words
]
self.id = id
self._reversed_text = False
self.result = result
def __repr__(self):
return f'Segment(start={self.start}, end={self.end}, text="{self.text}")'
def __getitem__(self, index: int) -> WordTiming:
if self.words is None:
raise ValueError('segment contains no words')
return self.words[index]
def __delitem__(self, index: int):
if self.words is None:
raise ValueError('segment contains no words')
del self.words[index]
self.reassign_ids(index)
def __deepcopy__(self, memo=None):
return self.copy(copy_words=True, copy_tokens=True)
def __copy__(self):
return self.copy()
def copy(
self,
new_words: Optional[List[WordTiming]] = None,
keep_result: bool = False,
copy_words: bool = False,
copy_tokens: bool = False
):
if new_words is None:
if self.has_words:
words = [w.copy(copy_tokens=copy_tokens) for w in self.words] if copy_words else self.words
else:
words = None
def_start = self._default_start
def_end = self._default_end
def_text = self._default_text
def_tokens = self._default_tokens
else:
words = [w.copy(copy_tokens=copy_tokens) for w in new_words] if copy_words else new_words
def_start = def_end = def_text = def_tokens = None
new_seg = Segment(
start=def_start,
end=def_end,
text=def_text,
seek=self.seek,
tokens=def_tokens,
temperature=self.temperature,
avg_logprob=self.avg_logprob,
compression_ratio=self.compression_ratio,
no_speech_prob=self.no_speech_prob,
words=words,
id=self.id,
result=self.result if keep_result else None,
round_ts=self.round_ts,
ignore_unused_args=True
)
return new_seg
def round(self, timestamp: float) -> float:
if not self.round_ts:
return timestamp
return _round_timestamp(timestamp)
def to_display_str(self, only_segment: bool = False):
line = f'[{format_timestamp(self.start)} --> {format_timestamp(self.end)}] "{self.text}"'
if self.has_words and not only_segment:
line += '\n' + '\n'.join(
f"-{w.to_display_str()}" for w in self.words
) + '\n'
return line
@property
def has_words(self):
return bool(self.words)
@property
def ori_has_words(self):
return self.words is not None
@property
def start(self):
if self.has_words:
return self.words[0].start
return self._default_start
@property
def end(self):
if self.has_words:
return self.words[-1].end
return self._default_end
@start.setter
def start(self, val):
if self.has_words:
self.words[0].start = val
return
self._default_start = self.round(val)
@end.setter
def end(self, val):
if self.has_words:
self.words[-1].end = val
return
self._default_end = self.round(val)
@property
def text(self) -> str:
if self.has_words:
return ''.join(word.word for word in self.words)
return self._default_text
@property
def tokens(self) -> List[int]:
if self.has_words and self.words[0].tokens:
return list(chain.from_iterable(word.tokens for word in self.words))
return self._default_tokens
@property
def duration(self):
return self.end - self.start
def word_count(self):
if self.has_words:
return len(self.words)
return -1
def char_count(self):
if self.has_words:
return sum(len(w) for w in self.words)
return len(self.text)
def add(self, other: 'Segment', copy_words: bool = False, newline: bool = False):
if self.ori_has_words == other.ori_has_words:
words = (self.words + other.words) if self.ori_has_words else None
else:
self_state = 'with' if self.ori_has_words else 'without'
other_state = 'with' if other.ori_has_words else 'without'
raise ValueError(f"Can't merge segment {self_state} words and a segment {other_state} words.")
self_copy = self.copy(words, copy_words=copy_words)
_combine_attr(self_copy, other, 'temperature')
_combine_attr(self_copy, other, 'avg_logprob')
_combine_attr(self_copy, other, 'compression_ratio')
_combine_attr(self_copy, other, 'no_speech_prob')
self_copy._default_end = other._default_end
self_copy._default_text += other._default_text
self_copy._default_tokens += other._default_tokens
if newline:
if self_copy.has_words:
if not self_copy.words[len(self.words)-1].word.endswith('\n'):
self_copy.words[len(self.words)-1].word += '\n'
else:
if self_copy.text[len(self.text)-1] != '\n':
self_copy._default_text = self_copy.text[:len(self.text)] + '\n' + self_copy.text[len(self.text):]
return self_copy
def __add__(self, other: 'Segment'):
return self.add(other, copy_words=True)
def _word_operations(self, operation: str, *args, **kwargs):
if self.has_words:
for w in self.words:
getattr(w, operation)(*args, **kwargs)
def round_all_timestamps(self):
warnings.warn('``.round_all_timestamps()`` is deprecated and will be removed in future versions. '
'Use ``.round_ts=True`` to round timestamps by default instead.',
stacklevel=2)
self.round_ts = True
def offset_time(self, offset_seconds: float):
if self.seek is not None:
self.seek += offset_seconds
if self.has_words:
self._word_operations('offset_time', offset_seconds)
else:
self.start = self.start + offset_seconds
self.end = self.end + offset_seconds
def add_words(self, index0: int, index1: int, inplace: bool = False):
if self.has_words:
new_word = self.words[index0] + self.words[index1]
if inplace:
i0, i1 = sorted([index0, index1])
self.words[i0] = new_word
del self.words[i1]
return new_word
def rescale_time(self, scale_factor: float):
if self.seek is not None:
self.seek *= scale_factor
if self.has_words:
self._word_operations('rescale_time', scale_factor)
else:
self.start = self.start * scale_factor
self.end = self.end * scale_factor
def apply_min_dur(self, min_dur: float, inplace: bool = False):
"""
Merge any word with adjacent word if its duration is less than ``min_dur``.
"""
segment = self if inplace else deepcopy(self)
if not self.has_words:
return segment
max_i = len(segment.words) - 1
if max_i == 0:
return segment
for i in reversed(range(len(segment.words))):
if max_i == 0:
break
if segment.words[i].duration < min_dur:
if i == max_i:
segment.add_words(i-1, i, inplace=True)
elif i == 0:
segment.add_words(i, i+1, inplace=True)
else:
if segment.words[i+1].duration < segment.words[i-1].duration:
segment.add_words(i-1, i, inplace=True)
else:
segment.add_words(i, i+1, inplace=True)
max_i -= 1
return segment
def _to_reverse_text(
self,
prepend_punctuations: Optional[str] = None,
append_punctuations: Optional[str] = None,
):
"""
Return a copy with words reversed order per segment.
"""
warnings.warn('``_to_reverse_text()`` is deprecated and will be removed in future versions.',
category=DeprecationWarning, stacklevel=2)
prepend_punctuations = get_prepend_punctuations(prepend_punctuations)
if prepend_punctuations and ' ' not in prepend_punctuations:
prepend_punctuations += ' '
append_punctuations = get_append_punctuations(append_punctuations)
self_copy = self.copy(copy_words=True)
has_prepend = bool(prepend_punctuations)
has_append = bool(append_punctuations)
if has_prepend or has_append:
word_objs = (
self_copy.words
if self_copy.has_words else
[WordTiming(w, 0, 1, 0) for w in self_copy.text.split(' ')]
)
for word in word_objs:
new_append = ''
if has_prepend:
for _ in range(len(word)):
char = word.word[0]
if char in prepend_punctuations:
new_append += char
word.word = word.word[1:]
else:
break
new_prepend = ''
if has_append:
for _ in range(len(word)):
char = word.word[-1]
if char in append_punctuations:
new_prepend += char
word.word = word.word[:-1]
else:
break
word.word = f'{new_prepend}{word.word}{new_append[::-1]}'
self_copy._default_text = ''.join(w.word for w in reversed(word_objs))
return self_copy
def to_dict(self, reverse_text: Union[bool, tuple] = False):
if reverse_text:
warnings.warn('``reverse_text=True`` is deprecated and will be removed in future versions. '
'RTL text playback issues are caused by the video player incorrectly parsing tags '
'(note: tags come from ``segment_level=True + word_level=True``).')
segment = self._to_reverse_text(*(reverse_text if reverse_text else []))
else:
segment = self
seg_dict = dict(
start=segment.start,
end=segment.end,
text=segment.text,
seek=segment.seek,
tokens=None if segment.tokens is None else segment.tokens.copy(),
temperature=segment.temperature,
avg_logprob=segment.avg_logprob,
compression_ratio=segment.compression_ratio,
no_speech_prob=segment.no_speech_prob,
)
if segment.has_words:
seg_dict['words'] = [w.to_dict() for w in segment.words]
elif segment.ori_has_words:
seg_dict['words'] = []
if reverse_text:
seg_dict['reversed_text'] = True
return seg_dict
def words_by_lock(self, only_text: bool = True, include_single: bool = False):
return _words_by_lock(self.words, only_text=only_text, include_single=include_single)
@property
def left_locked(self):
if self.has_words:
return self.words[0].left_locked
return False
@property
def right_locked(self):
if self.has_words:
return self.words[-1].right_locked
return False
def lock_left(self):
if self.has_words:
self.words[0].lock_left()
def lock_right(self):
if self.has_words:
self.words[-1].lock_right()
def lock_both(self):
self.lock_left()
self.lock_right()
def unlock_all_words(self):
self._word_operations('unlock_both')
def reassign_ids(self, start: Optional[int] = None):
if self.has_words:
for i, word in enumerate(self.words[start:], start or 0):
word.segment = self
word.id = i
def update_seg_with_words(self):
warnings.warn('Attributes that required updating are now properties based on the ``words`` except for ``id``. '
'``update_seg_with_words()`` is deprecated and will be removed in future versions. '
'Use ``.reassign_ids()`` to manually update ids',
stacklevel=2)
self.reassign_ids()
def suppress_silence(self,
silent_starts: np.ndarray,
silent_ends: np.ndarray,
min_word_dur: Optional[float] = None,
word_level: bool = True,
nonspeech_error: float = 0.3,
use_word_position: bool = True):
min_word_dur = get_min_word_dur(min_word_dur)
if self.has_words:
ending_punctuations = get_append_punctuations()
words = self.words if word_level or len(self.words) == 1 else [self.words[0], self.words[-1]]
for i, w in enumerate(words, 1):
if use_word_position:
keep_end = not (w.word[-1] in ending_punctuations or i == len(words))
else:
keep_end = None
w.suppress_silence(silent_starts, silent_ends, min_word_dur, nonspeech_error, keep_end)
else:
suppress_silence(self,
silent_starts,
silent_ends,
min_word_dur,
nonspeech_error)
return self
def get_locked_indices(self):
locked_indices = [i
for i, (left, right) in enumerate(zip(self.words[1:], self.words[:-1]))
if left.left_locked or right.right_locked]
return locked_indices
def get_gaps(self, as_ndarray=False):
if self.has_words:
s_ts = np.array([w.start for w in self.words])
e_ts = np.array([w.end for w in self.words])
gap = s_ts[1:] - e_ts[:-1]
return gap if as_ndarray else gap.tolist()
return []
def get_gap_indices(self, max_gap: float = 0.1): # for splitting
if not self.has_words or len(self.words) < 2:
return []
if max_gap is None:
max_gap = 0
indices = (self.get_gaps(True) > max_gap).nonzero()[0].tolist()
return sorted(set(indices) - set(self.get_locked_indices()))
def get_punctuation_indices(self, punctuation: Union[List[str], List[Tuple[str, str]], str]): # for splitting
if not self.has_words or len(self.words) < 2:
return []
if isinstance(punctuation, str):
punctuation = [punctuation]
indices = []
for p in punctuation:
if isinstance(p, str):
for i, s in enumerate(self.words[:-1]):
if s.word.endswith(p):
indices.append(i)
elif i != 0 and s.word.startswith(p):
indices.append(i-1)
else:
ending, beginning = p
indices.extend([i for i, (w0, w1) in enumerate(zip(self.words[:-1], self.words[1:]))
if w0.word.endswith(ending) and w1.word.startswith(beginning)])
return sorted(set(indices) - set(self.get_locked_indices()))
def get_length_indices(self, max_chars: int = None, max_words: int = None, even_split: bool = True,
include_lock: bool = False):
# for splitting
if not self.has_words or (max_chars is None and max_words is None):
return []
assert max_chars != 0 and max_words != 0, \
f'max_chars and max_words must be greater 0, but got {max_chars} and {max_words}'
if len(self.words) < 2:
return []
indices = []
if even_split:
char_count = -1 if max_chars is None else sum(map(len, self.words))
word_count = -1 if max_words is None else len(self.words)
exceed_chars = max_chars is not None and char_count > max_chars
exceed_words = max_words is not None and word_count > max_words
if exceed_chars:
splits = np.ceil(char_count / max_chars)
chars_per_split = char_count / splits
cum_char_count = np.cumsum([len(w.word) for w in self.words[:-1]])
indices = [
(np.abs(cum_char_count-(i*chars_per_split))).argmin()
for i in range(1, int(splits))
]
if max_words is not None:
exceed_words = any(j-i+1 > max_words for i, j in zip([0]+indices, indices+[len(self.words)]))
if exceed_words:
splits = np.ceil(word_count / max_words)
words_per_split = word_count / splits
cum_word_count = np.array(range(1, len(self.words)+1))
indices = [
np.abs(cum_word_count-(i*words_per_split)).argmin()
for i in range(1, int(splits))
]
else:
curr_words = 0
curr_chars = 0
locked_indices = []
if include_lock:
locked_indices = self.get_locked_indices()
for i, word in enumerate(self.words):
curr_words += 1
curr_chars += len(word)
if i != 0:
if (
max_chars is not None and curr_chars > max_chars
or
max_words is not None and curr_words > max_words
) and i-1 not in locked_indices:
indices.append(i-1)
curr_words = 1
curr_chars = len(word)
return indices
def get_duration_indices(self, max_dur: float, even_split: bool = True, include_lock: bool = False):
if not self.has_words or (total_duration := np.sum([w.duration for w in self.words])) <= max_dur:
return []
if even_split:
splits = np.ceil(total_duration / max_dur)
dur_per_split = total_duration / splits
cum_dur = np.cumsum([w.duration for w in self.words[:-1]])
indices = [
(np.abs(cum_dur - (i * dur_per_split))).argmin()
for i in range(1, int(splits))
]
else:
indices = []
curr_total_dur = 0.0
locked_indices = self.get_locked_indices() if include_lock else []
for i, word in enumerate(self.words):
curr_total_dur += word.duration
if i != 0:
if curr_total_dur > max_dur and i - 1 not in locked_indices:
indices.append(i - 1)
curr_total_dur = word.duration
return indices
def split(self, indices: List[int]):
if len(indices) == 0:
return []
if indices[-1] != len(self.words) - 1:
indices.append(len(self.words) - 1)
seg_copies = []
prev_i = 0
for i in indices:
i += 1
new_words = self.words[prev_i:i]
new_seg = self.copy(new_words, copy_words=False)
seg_copies.append(new_seg)
prev_i = i
return seg_copies
def set_result(self, result: 'WhisperResult'):
warnings.warn('``.set_result(current_result_instance)`` is deprecated and will be removed in future versions. '
'Use ``.result = current_result_instance`` instead.',
stacklevel=2)
self.result = result
def get_result(self) -> Union['WhisperResult', None]:
"""
Return outer instance of :class:`stable_whisper.result.WhisperResult` that ``self`` is a part of.
"""
warnings.warn('``.get_result()`` will be removed in future versions. Use ``.result`` instead.',
stacklevel=2)
return self.result
class WhisperResult:
def __init__(
self,
result: Union[str, dict, list],
force_order: bool = False,
check_sorted: Union[bool, str] = True,
show_unsorted: bool = True
):
result, self.path = self._standardize_result(result)
self.ori_dict = result.get('ori_dict') or result
self.language = self.ori_dict.get('language')
self._regroup_history = result.get('regroup_history', '')
self._nonspeech_sections = result.get('nonspeech_sections', [])
segments = (result.get('segments', self.ori_dict.get('segments')) or {}).copy()
self.segments = [Segment(**s, ignore_unused_args=True) for s in segments] if segments else []
self._forced_order = force_order
if self._forced_order:
self.force_order()
self.raise_for_unsorted(check_sorted, show_unsorted)
self.remove_no_word_segments(any(seg.has_words for seg in self.segments))
def __getitem__(self, index: int) -> Segment:
return self.segments[index]
def __delitem__(self, index: int):
del self.segments[index]
self.reassign_ids(True, start=index)
@property
def duration(self):
if not self.segments:
return 0.0
return _round_timestamp(self.segments[-1].end - self.segments[0].start)
@staticmethod
def _standardize_result(result: Union[str, dict, List[dict], List[List[dict]]]) -> Tuple[dict, Union[str, None]]:
path = None
if isinstance(result, str):
path = result
result = load_result(path)
if isinstance(result, dict):
return result, path
if not isinstance(result, list):
raise TypeError(f'Expect result to be list but got {type(result)}')
if not result or not result[0]:
return {}, path
if isinstance(result[0], list):
if not isinstance(result[0][0], dict):
raise NotImplementedError(f'Got list of list of {type(result[0])} but expects list of list of dict')
result = dict(
segments=[
dict(
start=words[0]['start'],
end=words[-1]['end'],
text=''.join(w['word'] for w in words),
words=words
)
for words in result if words
]
)
elif isinstance(result[0], dict):
result = dict(segments=result)
else:
raise NotImplementedError(f'Got list of {type(result[0])} but expects list of list/dict')
return result, path
def force_order(self):
prev_ts_end = 0
timestamps = self.all_words_or_segments()
for i, ts in enumerate(timestamps, 1):
if ts.start < prev_ts_end:
ts.start = prev_ts_end
if ts.start > ts.end:
if prev_ts_end > ts.end:
warnings.warn('Multiple consecutive timestamps are out of order. Some parts will have no duration.')
ts.start = ts.end
for j in range(i-2, -1, -1):
if timestamps[j].end > ts.end:
timestamps[j].end = ts.end
if timestamps[j].start > ts.end:
timestamps[j].start = ts.end
else:
if ts.start != prev_ts_end:
ts.start = prev_ts_end
else:
ts.end = ts.start if i == len(timestamps) else timestamps[i].start
prev_ts_end = ts.end
def raise_for_unsorted(self, check_sorted: Union[bool, str] = True, show_unsorted: bool = True):
if check_sorted is False:
return
all_parts = self.all_words_or_segments()
if not all_parts:
return
is_word = isinstance(all_parts[0], WordTiming)
timestamps = np.array(list(chain.from_iterable((p.start, p.end) for p in all_parts)))
if len(timestamps) > 1 and (unsorted_mask := timestamps[:-1] > timestamps[1:]).any():
if show_unsorted:
def get_part_info(idx):
curr_part = all_parts[idx]
seg_id = curr_part.segment_id if is_word else curr_part.id
word_id_str = f'Word ID: {curr_part.id}\n' if is_word else ''
return (
f'Segment ID: {seg_id}\n{word_id_str}'
f'Start: {curr_part.start}\nEnd: {curr_part.end}\n'
f'Text: "{curr_part.word if is_word else curr_part.text}"'
), curr_part.start, curr_part.end
for i, unsorted in enumerate(unsorted_mask, 2):
if unsorted:
word_id = i//2-1
part_info, start, end = get_part_info(word_id)
if i % 2 == 1:
next_info, next_start, _ = get_part_info(word_id+1)
part_info += f'\nConflict: end ({end}) > next start ({next_start})\n{next_info}'
else:
part_info += f'\nConflict: start ({start}) > end ({end})'
print(part_info, end='\n\n')
data = self.to_dict()
if check_sorted is True:
raise UnsortedException(data=data)
warnings.warn('Timestamps are not in ascending order. '
'If data is produced by Stable-ts, please submit an issue with the saved data.')
save_as_json(data, check_sorted)
def update_all_segs_with_words(self):
warnings.warn('Attributes that required updating are now properties based on the ``words`` except for ``id``. '
'``update_all_segs_with_words()`` is deprecated and will be removed in future versions. '
'Use ``.reassign_ids()`` to manually update ids',
stacklevel=2)
self.reassign_ids()
def update_nonspeech_sections(self, silent_starts, silent_ends):
self._nonspeech_sections = [
dict(start=round(s, 3), end=round(e, 3)) for s, e in zip(silent_starts, silent_ends)
]
def add_segments(self, index0: int, index1: int, inplace: bool = False, lock: bool = False, newline: bool = False):
new_seg = self.segments[index0].add(self.segments[index1], copy_words=False, newline=newline)
if lock and self.segments[index0].has_words:
lock_idx = len(self.segments[index0].words)
new_seg.words[lock_idx - 1].lock_right()
if lock_idx < len(new_seg.words):
new_seg.words[lock_idx].lock_left()
if inplace:
i0, i1 = sorted([index0, index1])
self.segments[i0] = new_seg
del self.segments[i1]
return new_seg
def rescale_time(self, scale_factor: float):
for s in self.segments:
s.rescale_time(scale_factor)
def apply_min_dur(self, min_dur: float, inplace: bool = False):
"""
Merge any word/segment with adjacent word/segment if its duration is less than ``min_dur``.
"""
result = self if inplace else deepcopy(self)
max_i = len(result.segments) - 1
if max_i == 0:
return result
for i in reversed(range(len(result.segments))):
if max_i == 0:
break
if result.segments[i].duration < min_dur:
if i == max_i:
result.add_segments(i-1, i, inplace=True)
elif i == 0: