Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

online_feature_extractor.py 4.8 KB

You have to be logged in to leave a comment. Sign In
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
  1. # Copyright (c) Meta Platforms, Inc. and affiliates
  2. # All rights reserved.
  3. #
  4. # This source code is licensed under the license found in the
  5. # MIT_LICENSE file in the root directory of this source tree.
  6. from __future__ import annotations
  7. import math
  8. import torch
  9. from argparse import ArgumentParser, Namespace
  10. from typing import Any, List
  11. from fairseq2.data.audio import WaveformToFbankConverter, WaveformToFbankInput
  12. from simuleval.agents import SpeechToSpeechAgent
  13. from simuleval.agents.actions import Action, ReadAction, WriteAction
  14. from simuleval.data.segments import Segment, SpeechSegment
  15. from seamless_communication.streaming.agents.common import AgentStates
  16. SHIFT_SIZE = 10
  17. WINDOW_SIZE = 25
  18. SAMPLE_RATE = 16000
  19. FEATURE_DIM = 80
  20. class FeatureStates(AgentStates): # type: ignore
  21. def reset(self) -> None:
  22. super().reset()
  23. self.previous_residual_samples: List[float] = []
  24. self.tgt_lang = None
  25. def update_source(self, segment: Segment) -> None:
  26. """
  27. Update states from input segment
  28. Args:
  29. segment (~simuleval.agents.segments.Segment): input segment
  30. """
  31. self.source_finished = segment.finished
  32. if self.tgt_lang is None and segment.tgt_lang is not None:
  33. self.tgt_lang = segment.tgt_lang
  34. if not segment.is_empty:
  35. self.source.append(segment.content)
  36. class OnlineFeatureExtractorAgent(SpeechToSpeechAgent): # type: ignore
  37. """
  38. Extract speech features on the fly.
  39. """
  40. def __init__(self, args: Namespace):
  41. super().__init__(args)
  42. self.shift_size = args.shift_size
  43. self.window_size = args.window_size
  44. assert self.window_size >= self.shift_size
  45. self.sample_rate = args.sample_rate
  46. self.feature_dim = args.feature_dim
  47. self.num_samples_per_shift = int(self.shift_size * self.sample_rate / 1000)
  48. self.num_samples_per_window = int(self.window_size * self.sample_rate / 1000)
  49. self.len_ms_to_samples = lambda x: x * self.sample_rate / 1000
  50. self.convert_to_fbank = WaveformToFbankConverter(
  51. num_mel_bins=80,
  52. waveform_scale=2**15 if args.denormalize else 1.0,
  53. standardize=False,
  54. device=args.device,
  55. dtype=args.dtype,
  56. )
  57. def build_states(self) -> FeatureStates:
  58. return FeatureStates()
  59. @staticmethod
  60. def add_args(parser: ArgumentParser) -> None:
  61. parser.add_argument(
  62. "--shift-size",
  63. type=int,
  64. default=SHIFT_SIZE,
  65. help="Shift size of feature extraction window.",
  66. )
  67. parser.add_argument(
  68. "--window-size",
  69. type=int,
  70. default=WINDOW_SIZE,
  71. help="Window size of feature extraction window.",
  72. )
  73. parser.add_argument(
  74. "--feature-dim",
  75. type=int,
  76. default=FEATURE_DIM,
  77. help="Acoustic feature dimension.",
  78. )
  79. parser.add_argument(
  80. "--denormalize",
  81. action="store_true",
  82. help="denormalized to 16-bit signed integers",
  83. )
  84. def policy(self, states: FeatureStates) -> Action:
  85. if len(states.source) == 0:
  86. if states.source_finished:
  87. return WriteAction({}, finished=states.source_finished)
  88. else:
  89. return ReadAction()
  90. samples = states.source[-1]
  91. samples = states.previous_residual_samples + samples
  92. if len(samples) < self.num_samples_per_window:
  93. states.previous_residual_samples = samples
  94. return ReadAction()
  95. # num_frames is the number of frames from the new segment
  96. num_frames = math.floor(
  97. (len(samples) - self.len_ms_to_samples(self.window_size - self.shift_size))
  98. / self.num_samples_per_shift
  99. )
  100. # the number of frames used for feature extraction
  101. # including some part of the previous segment
  102. effective_num_samples = int(
  103. num_frames * self.len_ms_to_samples(self.shift_size)
  104. + self.len_ms_to_samples(self.window_size - self.shift_size)
  105. )
  106. input_samples = samples[:effective_num_samples]
  107. states.previous_residual_samples = samples[
  108. num_frames * self.num_samples_per_shift :
  109. ]
  110. data: WaveformToFbankInput = {
  111. "waveform": torch.tensor(input_samples).unsqueeze(0),
  112. "sample_rate": self.sample_rate,
  113. }
  114. output = self.convert_to_fbank(data)["fbank"]
  115. return WriteAction(
  116. SpeechSegment(
  117. content=output,
  118. tgt_lang=states.tgt_lang,
  119. finished=states.source_finished,
  120. ),
  121. finished=states.source_finished,
  122. )
  123. @classmethod
  124. def from_args(cls, args: Any, **kwargs: Any) -> OnlineFeatureExtractorAgent:
  125. return cls(args)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...