blisc commited on
Commit
474fe7b
·
1 Parent(s): 9e47e6c

Update to 2607 version

Browse files

Signed-off-by: Jason <jasoli@nvidia.com>

Files changed (3) hide show
  1. README.md +22 -3
  2. app.py +90 -69
  3. requirements.txt +2 -3
README.md CHANGED
@@ -4,11 +4,30 @@ emoji: 🐠
4
  colorFrom: green
5
  colorTo: green
6
  sdk: gradio
7
- sdk_version: 6.9.0
8
- python_version: 3.11
9
  app_file: app.py
10
  pinned: false
11
  license: other
 
 
 
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  colorFrom: green
5
  colorTo: green
6
  sdk: gradio
7
+ sdk_version: 6.19.0
 
8
  app_file: app.py
9
  pinned: false
10
  license: other
11
+ license_name: nvidia-open-model-license
12
+ license_link: https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-license
13
+ short_description: Nvidia Text-to-Speech with MagpieTTS.
14
  ---
15
 
16
+ # MagpieTTS Multilingual Demo
17
+
18
+ A live [Gradio](https://www.gradio.app/) demo for NVIDIA's **MagpieTTS Multilingual 357M** text-to-speech model. Type text, pick a language and speaker, and synthesize speech across 12 languages. The full model description and usage notes are shown inside the app.
19
+
20
+ - 🤗 **Model weights:** [nvidia/magpie_tts_multilingual_357m](https://huggingface.co/nvidia/magpie_tts_multilingual_357m)
21
+ - 🤗 **NanoCodec weights:** [nvidia/nemo-nano-codec-22khz-1.89kbps-21.5fps](https://huggingface.co/nvidia/nemo-nano-codec-22khz-1.89kbps-21.5fps)
22
+ - 💻 **NeMo Framework:** [github.com/NVIDIA-NeMo/NeMo](https://github.com/NVIDIA-NeMo/NeMo)
23
+
24
+ ## Run locally
25
+
26
+ ```bash
27
+ pip install -r requirements.txt
28
+ python app.py
29
+ ```
30
+
31
+ Requires an `HF_TOKEN` environment variable with access to [nvidia/magpie_tts_multilingual_357m](https://huggingface.co/nvidia/magpie_tts_multilingual_357m).
32
+
33
+ Use of this model is governed by the [NVIDIA Open Model License Agreement](https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-license).
app.py CHANGED
@@ -2,56 +2,79 @@
2
  To run locally, do python app.py
3
  """
4
  import os
 
5
  os.environ['OMP_NUM_THREADS'] = '2'
6
  import gradio as gr
7
- import numpy as np
8
  import spaces
9
- from huggingface_hub import hf_hub_download
10
- from huggingface_hub import login
11
  from nemo.collections.tts.modules.magpietts_inference.utils import ModelLoadConfig, load_magpie_model
12
 
13
  login(token=os.environ.get("HF_TOKEN"))
14
- print(f"login successful")
 
15
  server_port = os.getenv("SERVER_PORT")
16
- print(f"server_port {server_port}")
17
  if isinstance(server_port, str):
18
  server_port = int(server_port)
 
19
 
20
  CODEC_MODEL_PATH = "nvidia/nemo-nano-codec-22khz-1.89kbps-21.5fps"
21
 
22
- # Download a specific file
23
  CHECKPOINT_PATH = hf_hub_download(
24
  repo_id="nvidia/magpie_tts_multilingual_357m",
25
  filename="magpie_tts_multilingual_357m.nemo",
26
- token=os.environ.get("HF_TOKEN")
27
  )
28
-
29
- print(CHECKPOINT_PATH) # local path to the downloaded file
30
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
  BODY = """
33
- **MagpieTTS** is NVIDIA's state-of-the-art multilingual text-to-speech system built on the [NeMo](https://github.com/NVIDIA/NeMo) framework. \
34
  It employs a two-stage pipeline architecture: a language model generates discrete acoustic tokens from text, which are then decoded into \
35
  high-fidelity audio using a neural audio codec: [NanoCodec](https://huggingface.co/nvidia/nemo-nano-codec-22khz-1.89kbps-21.5fps). \
36
- The model is a text-to-speech model that generates speech in 5 different English speakers - Sofia, Aria, Jason, Leo, \
37
- [John Van Stan](https://librivox.org/reader/9017?primary_key=9017&search_category=reader&search_page=1&search_form=get_results&search_order=alpha). \
38
- Each speakers can speak nine different languages (En, Es, De, Fr, Vi, It, Zh, Hi, Ja). The model predicts discrete audio codec tokens autoregressively using \
39
- a transformer encoder-decoder architecture. It employs multi-codebook prediction (typically 8 codebooks) with optional local transformer refinement \
40
- for high-quality audio generation, and leverages techniques like attention priors, classifier-free guidance (CFG), and Group Relative Policy \
 
41
  Optimization (GRPO) for improved alignment.
42
 
43
  ### Key Features of the model
44
- - **Multilingual Support** — Synthesizes natural speech in English, Spanish, German, French, Vietnamese, Italian, Mandarin, Hindi and Japanese.
45
- - **Expressive Voices** — Multiple voice options with emotional tones and gender variations including 4 proprietary voices and 1 public voice
46
  - **Text Normalization** — Built-in text normalization for handling numbers, abbreviations, and special characters for all languages.
47
  ### Resources
48
  - 🤗 **MagpieTTS Weights**: [nvidia/magpie_tts_multilingual_357m](https://huggingface.co/nvidia/magpie_tts_multilingual_357m)
49
  - 🤗 **NanoCodec Weights**: [nvidia/nemo-nano-codec-22khz-1.89kbps-21.5fps](https://huggingface.co/nvidia/nemo-nano-codec-22khz-1.89kbps-21.5fps)
50
- - 💻 **NeMo Framework**: [github.com/NVIDIA/NeMo](https://github.com/NVIDIA/NeMo)
51
 
52
  Note about the demo:
53
  - Text normalization takes time to load, so if you want faster generation select "Do not apply TN."
54
- - Text normalization works for En, Es, De, Fr, It, Zh, Vi, Hi, Ja. Added support for Vi, Hi, Ja text normalization in V26.02 version of the checkpoint.
55
  - Text normalization is required for numbers to be processed and spoken.
56
  - When the model runs on ZeroGPU Hardware, expect slower generation because the model checkpoint is loaded everytime.
57
  - As the model's speakers are all native English speakers, expect accented speech in the other languages.
@@ -76,83 +99,81 @@ try:
76
  model.eval().cuda()
77
  print("Model loaded and ready for inference.")
78
  except Exception as e:
79
- print(f"exception in model loading is {e}")
80
- gr.Warning(f"exception in model loading is {e}")
81
 
82
  @spaces.GPU
83
  def demo_tts(input_text, language, speaker, apply_TN):
84
  global model
85
 
86
- speaker_map = {
87
- "John": 0,
88
- "Sofia": 1,
89
- "Aria": 2,
90
- "Jason": 3,
91
- "Leo": 4
92
- }
93
-
94
- # Validate input
95
  if not input_text or input_text.strip() == "":
96
- gr.Warning("Please enter some text to synthesize.")
97
  raise gr.Error("Please enter some text to synthesize.")
98
 
99
- # Load model on first call (inside GPU context)
100
  if model is None:
101
- # model = MagpieTTSModel.from_pretrained("nvidia/magpie_tts_multilingual_357m")
102
- model_config = ModelLoadConfig(
103
- nemo_file=CHECKPOINT_PATH,
104
- codecmodel_path=CODEC_MODEL_PATH,
105
- legacy_codebooks=False,
106
- legacy_text_conditioning=False,
107
- hparams_from_wandb=None,
108
- )
109
  try:
110
  model, _ = load_magpie_model(model_config)
 
 
111
  except Exception as e:
112
- gr.Warning(f"exception in model loading is {e}")
113
- model.eval().cuda()
114
- print("Model loaded and ready for inference.")
 
 
 
115
 
116
  apply_tn_flag = apply_TN == "Apply TN"
117
- speaker_idx = speaker_map[speaker]
 
118
  input_text = input_text.strip()
119
 
120
  if not (input_text.endswith(".") or input_text.endswith("?") or input_text.endswith("!")):
121
  input_text = f"{input_text}."
 
122
  try:
123
- audio, audio_len = model.do_tts(input_text, language=language, apply_TN=apply_tn_flag, speaker_index=speaker_idx)
 
 
 
124
  print(f"audio {audio.shape} audio_len {audio_len}")
125
  except Exception as e:
126
- import traceback
127
  traceback.print_exc()
128
- gr.Error(f"exception is {e}")
 
129
  audio_np = audio[0, :audio_len[0]].cpu().numpy()
130
 
131
  # Return only picklable objects (int and numpy array)
132
  return model.sample_rate, audio_np
133
 
134
- # def main():
135
  demo = gr.Interface(
136
  fn=demo_tts,
137
- inputs=[gr.Textbox(label="Text to synthesize"),
138
- gr.Dropdown(
139
- choices=["en", "de", "es", "fr", "it", "vi", "zh", "hi", "ja"],
140
- label="Target Language",
141
- info="Select the target language for the speech to be synthesized in",
142
- ),
143
- gr.Dropdown(
144
- choices=["Sofia", "Aria", "Jason", "Leo", "John"],
145
- label="Target Speaker",
146
- info="Select the target speaker whose voice you would like the the speech to be synthesized in",
147
- ),
148
- gr.Radio(
149
- ["Apply TN", "Do not apply TN"],
150
- value="Do not apply TN",
151
- label="Apply Text Normalization",
152
- info="Select if you want to apply text normalization to the input text"
153
- ),
154
- ],
 
 
 
155
  outputs="audio",
156
  description=BODY,
157
- title="Text to Speech MagpieTTS Multilingual Demo")
158
- demo.launch(server_port=server_port)
 
 
 
 
2
  To run locally, do python app.py
3
  """
4
  import os
5
+ os.environ["NUMBA_DISABLE_CUDA"] = "1"
6
  os.environ['OMP_NUM_THREADS'] = '2'
7
  import gradio as gr
 
8
  import spaces
9
+ from huggingface_hub import hf_hub_download, login
 
10
  from nemo.collections.tts.modules.magpietts_inference.utils import ModelLoadConfig, load_magpie_model
11
 
12
  login(token=os.environ.get("HF_TOKEN"))
13
+ print("login successful")
14
+
15
  server_port = os.getenv("SERVER_PORT")
 
16
  if isinstance(server_port, str):
17
  server_port = int(server_port)
18
+ print(f"server_port {server_port}")
19
 
20
  CODEC_MODEL_PATH = "nvidia/nemo-nano-codec-22khz-1.89kbps-21.5fps"
21
 
 
22
  CHECKPOINT_PATH = hf_hub_download(
23
  repo_id="nvidia/magpie_tts_multilingual_357m",
24
  filename="magpie_tts_multilingual_357m.nemo",
25
+ token=os.environ.get("HF_TOKEN"),
26
  )
27
+ print(f"checkpoint downloaded to {CHECKPOINT_PATH}")
28
+
29
+ SPEAKER_MAP = {
30
+ "Aria": 0,
31
+ "Jason": 1,
32
+ "John": 2,
33
+ "Leo": 3,
34
+ "Sofia": 4,
35
+ }
36
+
37
+ LANGUAGE_MAP = {
38
+ "Arabic-UAE": "ar-AE",
39
+ "Arabic-Saudi Arabia": "ar-SA",
40
+ "Arabic-MSA": "ar-MSA",
41
+ "Chinese": "zh",
42
+ "English": "en",
43
+ "French": "fr",
44
+ "German": "de",
45
+ "Hindi": "hi",
46
+ "Italian": "it",
47
+ "Japanese": "ja",
48
+ "Korean": "ko",
49
+ "Brazilian Portuguese": "pt-BR",
50
+ "Spanish": "es",
51
+ "Vietnamese": "vi",
52
+ }
53
 
54
  BODY = """
55
+ **MagpieTTS** is NVIDIA's state-of-the-art multilingual text-to-speech system built on the [NeMo Speech](https://github.com/NVIDIA-NeMo/Speech) framework. \
56
  It employs a two-stage pipeline architecture: a language model generates discrete acoustic tokens from text, which are then decoded into \
57
  high-fidelity audio using a neural audio codec: [NanoCodec](https://huggingface.co/nvidia/nemo-nano-codec-22khz-1.89kbps-21.5fps). \
58
+ The model synthesizes speech in 5 different English speakers - Sofia, Aria, Jason, Leo, \
59
+ [John Van Stan](https://librivox.org/reader/9017?primary_key=9017&search_category=reader&search_page=1&search_form=get_results&search_order=alpha) \
60
+ across 12 languages: Arabic, Chinese, English, French, German, Hindi, Italian, Japanese, Korean, Portuguese, Spanish, and Vietnamese. \
61
+ The model predicts discrete audio codec tokens autoregressively using a transformer encoder-decoder architecture. It employs multi-codebook \
62
+ prediction (typically 8 codebooks) with frame stacking (factor = 2) and a local transformer for fine-grained refinement of \
63
+ high-fidelity audio generation, and leverages techniques like attention priors, classifier-free guidance (CFG), and Group Relative Policy \
64
  Optimization (GRPO) for improved alignment.
65
 
66
  ### Key Features of the model
67
+ - **Multilingual Support** — Synthesizes natural speech in 12 languages: Arabic, Chinese, English, French, German, Hindi, Italian, Japanese, Korean, Portuguese, Spanish, and Vietnamese.
68
+ - **Expressive Voices** — Multiple voice options with emotional tones and gender variations including 4 proprietary voices and 1 public voice.
69
  - **Text Normalization** — Built-in text normalization for handling numbers, abbreviations, and special characters for all languages.
70
  ### Resources
71
  - 🤗 **MagpieTTS Weights**: [nvidia/magpie_tts_multilingual_357m](https://huggingface.co/nvidia/magpie_tts_multilingual_357m)
72
  - 🤗 **NanoCodec Weights**: [nvidia/nemo-nano-codec-22khz-1.89kbps-21.5fps](https://huggingface.co/nvidia/nemo-nano-codec-22khz-1.89kbps-21.5fps)
73
+ - 💻 **NeMo Framework**: [github.com/NVIDIA-NeMo/NeMo](https://github.com/NVIDIA-NeMo/NeMo)
74
 
75
  Note about the demo:
76
  - Text normalization takes time to load, so if you want faster generation select "Do not apply TN."
77
+ - Text normalization works for all supported languages.
78
  - Text normalization is required for numbers to be processed and spoken.
79
  - When the model runs on ZeroGPU Hardware, expect slower generation because the model checkpoint is loaded everytime.
80
  - As the model's speakers are all native English speakers, expect accented speech in the other languages.
 
99
  model.eval().cuda()
100
  print("Model loaded and ready for inference.")
101
  except Exception as e:
102
+ print(f"Exception in model loading: {e}")
103
+
104
 
105
  @spaces.GPU
106
  def demo_tts(input_text, language, speaker, apply_TN):
107
  global model
108
 
 
 
 
 
 
 
 
 
 
109
  if not input_text or input_text.strip() == "":
 
110
  raise gr.Error("Please enter some text to synthesize.")
111
 
112
+ # Reload model inside GPU context if it failed at startup (ZeroGPU fallback)
113
  if model is None:
 
 
 
 
 
 
 
 
114
  try:
115
  model, _ = load_magpie_model(model_config)
116
+ model.eval().cuda()
117
+ print("Model loaded and ready for inference.")
118
  except Exception as e:
119
+ raise gr.Error(f"Model failed to load: {e}")
120
+
121
+ if speaker not in SPEAKER_MAP:
122
+ raise gr.Error(f"Unknown speaker: {speaker!r}. Choose from {list(SPEAKER_MAP)}.")
123
+ if language not in LANGUAGE_MAP:
124
+ raise gr.Error(f"Unknown language: {language!r}. Choose from {list(LANGUAGE_MAP)}.")
125
 
126
  apply_tn_flag = apply_TN == "Apply TN"
127
+ speaker_idx = SPEAKER_MAP[speaker]
128
+ language_code = LANGUAGE_MAP[language]
129
  input_text = input_text.strip()
130
 
131
  if not (input_text.endswith(".") or input_text.endswith("?") or input_text.endswith("!")):
132
  input_text = f"{input_text}."
133
+
134
  try:
135
+ import traceback
136
+ audio, audio_len = model.do_tts(
137
+ input_text, language=language_code, apply_TN=apply_tn_flag, speaker_index=speaker_idx
138
+ )
139
  print(f"audio {audio.shape} audio_len {audio_len}")
140
  except Exception as e:
 
141
  traceback.print_exc()
142
+ raise gr.Error(f"Speech synthesis failed: {e}")
143
+
144
  audio_np = audio[0, :audio_len[0]].cpu().numpy()
145
 
146
  # Return only picklable objects (int and numpy array)
147
  return model.sample_rate, audio_np
148
 
149
+
150
  demo = gr.Interface(
151
  fn=demo_tts,
152
+ inputs=[
153
+ gr.Textbox(label="Text to synthesize"),
154
+ gr.Dropdown(
155
+ choices=LANGUAGE_MAP.keys(),
156
+ value="English",
157
+ label="Target Language",
158
+ info="Select the target language for the speech to be synthesized in",
159
+ ),
160
+ gr.Dropdown(
161
+ choices=["Aria", "Jason", "John", "Leo", "Sofia"],
162
+ value="Aria",
163
+ label="Target Speaker",
164
+ info="Select the target speaker whose voice you would like the the speech to be synthesized in",
165
+ ),
166
+ gr.Radio(
167
+ ["Apply TN", "Do not apply TN"],
168
+ value="Do not apply TN",
169
+ label="Apply Text Normalization",
170
+ info="Select if you want to apply text normalization to the input text",
171
+ ),
172
+ ],
173
  outputs="audio",
174
  description=BODY,
175
+ title="Text to Speech MagpieTTS Multilingual Demo",
176
+ )
177
+
178
+ if __name__ == "__main__":
179
+ demo.launch(server_port=server_port)
requirements.txt CHANGED
@@ -1,5 +1,4 @@
1
- nemo_toolkit[tts]@git+https://github.com/NVIDIA/NeMo.git@f767ae5ef6a12bd0ab9173e3e536a3c6f1e5c054
2
- git+https://github.com/NVIDIA/NeMo-text-processing.git@0153962265c77dbd43eab5584450954d9a4f8af0
3
  spaces
4
- gradio
5
  kaldialign
 
1
+ nemo_toolkit[tts] @ git+https://github.com/blisc/NeMo.git@3685fb15405304671ffa86d8d01d2b0c9ff09bda
2
+ git+https://github.com/NVIDIA/NeMo-text-processing.git@1f1263579fe57ba7ed783cad3dddee710fcc5064
3
  spaces
 
4
  kaldialign