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

pretssel_vocoder.py 5.6 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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
  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 logging
  8. from argparse import ArgumentParser, Namespace
  9. from pathlib import Path
  10. from typing import Any, Dict, List
  11. import torch
  12. from fairseq2.assets import asset_store
  13. from fairseq2.data.audio import WaveformToFbankConverter, WaveformToFbankInput
  14. from seamless_communication.models.generator.loader import load_pretssel_vocoder_model
  15. from seamless_communication.models.unity import load_gcmvn_stats
  16. from seamless_communication.store import add_gated_assets
  17. from seamless_communication.streaming.agents.common import (
  18. AgentStates,
  19. NoUpdateTargetMixin,
  20. )
  21. from simuleval.agents import TextToSpeechAgent
  22. from simuleval.agents.actions import ReadAction, WriteAction
  23. from simuleval.data.segments import SpeechSegment
  24. logging.basicConfig(
  25. level=logging.INFO,
  26. format="%(asctime)s %(levelname)s -- %(name)s: %(message)s",
  27. )
  28. logger = logging.getLogger(__name__)
  29. class PretsselVocoderAgent(NoUpdateTargetMixin, TextToSpeechAgent): # type: ignore
  30. def __init__(self, args: Namespace) -> None:
  31. super().__init__(args)
  32. if args.gated_model_dir:
  33. add_gated_assets(args.gated_model_dir)
  34. logger.info(
  35. f"Loading the Vocoder model: {args.vocoder_name} on device={args.device}, dtype={args.dtype}"
  36. )
  37. assert "pretssel" in args.vocoder_name
  38. self.vocoder = load_pretssel_vocoder_model(
  39. args.vocoder_name, device=args.device, dtype=args.dtype
  40. )
  41. self.vocoder.eval()
  42. vocoder_model_card = asset_store.retrieve_card(args.vocoder_name)
  43. self.vocoder_sample_rate = vocoder_model_card.field("sample_rate").as_(int)
  44. self.vocoder_langs = vocoder_model_card.field("model_config").field("langs").as_list(str)
  45. self.upstream_idx = args.upstream_idx
  46. self.sample_rate = args.sample_rate # input sample rate
  47. self.tgt_lang = args.tgt_lang
  48. self.convert_to_fbank = WaveformToFbankConverter(
  49. num_mel_bins=80,
  50. waveform_scale=2**15,
  51. channel_last=True,
  52. standardize=False,
  53. device=args.device,
  54. dtype=args.dtype,
  55. )
  56. _gcmvn_mean, _gcmvn_std = load_gcmvn_stats(args.vocoder_name)
  57. self.gcmvn_mean = torch.tensor(
  58. _gcmvn_mean, device=args.device, dtype=args.dtype
  59. )
  60. self.gcmvn_std = torch.tensor(_gcmvn_std, device=args.device, dtype=args.dtype)
  61. def gcmvn_normalize(self, seqs: torch.Tensor) -> torch.Tensor:
  62. result: torch.Tensor = seqs.subtract(self.gcmvn_mean).divide(self.gcmvn_std)
  63. return result
  64. @torch.inference_mode()
  65. def policy(self, states: AgentStates) -> WriteAction:
  66. """
  67. The policy is always write if there is a waveform
  68. """
  69. units = states.source
  70. if len(units) == 0 or len(units[0]) == 0:
  71. if states.source_finished:
  72. return WriteAction(content=[], finished=True)
  73. else:
  74. return ReadAction()
  75. unit = units[0][0]
  76. # adjust the control symbols for the embedding
  77. unit += 4
  78. unit, duration = torch.unique_consecutive(unit, return_counts=True)
  79. duration *= 2
  80. if isinstance(states.upstream_states[self.upstream_idx].source, list):
  81. source: List[float] = sum(
  82. states.upstream_states[self.upstream_idx].source, []
  83. )
  84. else:
  85. source = states.upstream_states[self.upstream_idx].source
  86. audio_dict: WaveformToFbankInput = {
  87. "waveform": torch.tensor(
  88. source, dtype=torch.float32, device=self.device
  89. ).unsqueeze(1),
  90. "sample_rate": self.sample_rate,
  91. }
  92. feats = self.convert_to_fbank(audio_dict)["fbank"]
  93. feats = self.gcmvn_normalize(feats)
  94. tgt_lang = states.tgt_lang if states.tgt_lang else self.tgt_lang
  95. if tgt_lang not in self.vocoder_langs:
  96. logger.warning(f"{tgt_lang} not supported!")
  97. content = []
  98. else:
  99. wav = self.vocoder(
  100. unit,
  101. tgt_lang=tgt_lang,
  102. prosody_input_seqs=feats,
  103. durations=duration.unsqueeze(0),
  104. normalize_before=True,
  105. )
  106. content = wav[0][0][0].tolist()
  107. states.source = []
  108. return WriteAction(
  109. SpeechSegment(
  110. content=content,
  111. finished=states.source_finished,
  112. sample_rate=self.vocoder_sample_rate,
  113. tgt_lang=tgt_lang,
  114. ),
  115. finished=states.source_finished,
  116. )
  117. @classmethod
  118. def add_args(cls, parser: ArgumentParser) -> None:
  119. parser.add_argument(
  120. "--gated-model-dir",
  121. type=Path,
  122. required=False,
  123. help="SeamlessExpressive model directory.",
  124. )
  125. parser.add_argument(
  126. "--vocoder-name",
  127. type=str,
  128. help="Vocoder name - vocoder_pretssel or vocoder_pretssel_16khz",
  129. default="vocoder_pretssel",
  130. )
  131. parser.add_argument(
  132. "--upstream-idx",
  133. type=int,
  134. default=0,
  135. help="index of encoder states where states.source contains input audio",
  136. )
  137. @classmethod
  138. def from_args(
  139. cls, args: Namespace, **kwargs: Dict[str, Any]
  140. ) -> PretsselVocoderAgent:
  141. return cls(args)
Tip!

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

Comments

Loading...