Michael Hu commited on
Commit
0ee4f42
·
1 Parent(s): e68cae8

support nvdia Parakeet TDT ASR

Browse files
Files changed (3) hide show
  1. app.py +17 -5
  2. requirements.txt +3 -1
  3. utils/stt.py +129 -30
app.py CHANGED
@@ -44,14 +44,18 @@ def configure_page():
44
  </style>
45
  """, unsafe_allow_html=True)
46
 
47
- def handle_file_processing(upload_path):
48
  """
49
  Execute the complete processing pipeline:
50
  1. Speech-to-Text (STT)
51
  2. Machine Translation
52
  3. Text-to-Speech (TTS)
 
 
 
 
53
  """
54
- logger.info(f"Starting processing for: {upload_path}")
55
  progress_bar = st.progress(0)
56
  status_text = st.empty()
57
 
@@ -59,8 +63,8 @@ def handle_file_processing(upload_path):
59
  # STT Phase
60
  logger.info("Beginning STT processing")
61
  status_text.markdown("🔍 **Performing Speech Recognition...**")
62
- with st.spinner("Initializing Whisper model..."):
63
- english_text = transcribe_audio(upload_path)
64
  progress_bar.progress(30)
65
  logger.info(f"STT completed. Text length: {len(english_text)} characters")
66
 
@@ -172,6 +176,14 @@ def main():
172
  format_func=lambda x: x
173
  )
174
  speed = st.sidebar.slider("Speech Speed", 0.5, 2.0, 1.0, 0.1)
 
 
 
 
 
 
 
 
175
 
176
  uploaded_file = st.file_uploader(
177
  "Select Audio File (MP3/WAV)",
@@ -185,7 +197,7 @@ def main():
185
  with open(upload_path, "wb") as f:
186
  f.write(uploaded_file.getbuffer())
187
 
188
- results = handle_file_processing(upload_path)
189
  if results:
190
  render_results(*results)
191
 
 
44
  </style>
45
  """, unsafe_allow_html=True)
46
 
47
+ def handle_file_processing(upload_path, asr_model="whisper"):
48
  """
49
  Execute the complete processing pipeline:
50
  1. Speech-to-Text (STT)
51
  2. Machine Translation
52
  3. Text-to-Speech (TTS)
53
+
54
+ Args:
55
+ upload_path: Path to the uploaded audio file
56
+ asr_model: ASR model to use (whisper or parakeet)
57
  """
58
+ logger.info(f"Starting processing for: {upload_path} using {asr_model} model")
59
  progress_bar = st.progress(0)
60
  status_text = st.empty()
61
 
 
63
  # STT Phase
64
  logger.info("Beginning STT processing")
65
  status_text.markdown("🔍 **Performing Speech Recognition...**")
66
+ with st.spinner(f"Initializing {asr_model.capitalize()} model..."):
67
+ english_text = transcribe_audio(upload_path, model_name=asr_model)
68
  progress_bar.progress(30)
69
  logger.info(f"STT completed. Text length: {len(english_text)} characters")
70
 
 
176
  format_func=lambda x: x
177
  )
178
  speed = st.sidebar.slider("Speech Speed", 0.5, 2.0, 1.0, 0.1)
179
+
180
+ # Model selection
181
+ asr_model = st.selectbox(
182
+ "Select Speech Recognition Model",
183
+ options=["whisper", "parakeet"],
184
+ index=0,
185
+ help="Choose the ASR model for speech recognition"
186
+ )
187
 
188
  uploaded_file = st.file_uploader(
189
  "Select Audio File (MP3/WAV)",
 
197
  with open(upload_path, "wb") as f:
198
  f.write(uploaded_file.getbuffer())
199
 
200
+ results = handle_file_processing(upload_path, asr_model=asr_model)
201
  if results:
202
  render_results(*results)
203
 
requirements.txt CHANGED
@@ -12,4 +12,6 @@ accelerate>=1.2.0
12
  soundfile>=0.13.0
13
  kokoro>=0.7.9
14
  ordered-set>=4.1.0
15
- phonemizer-fork>=3.3.2
 
 
 
12
  soundfile>=0.13.0
13
  kokoro>=0.7.9
14
  ordered-set>=4.1.0
15
+ phonemizer-fork>=3.3.2
16
+ # NeMo Toolkit with ASR support
17
+ nemo_toolkit[asr]
utils/stt.py CHANGED
@@ -1,51 +1,77 @@
1
  """
2
- Speech Recognition Module using Whisper Large-v3
 
3
  Handles audio preprocessing and transcription
4
  """
5
 
6
  import logging
7
  import numpy as np
 
 
 
8
  logger = logging.getLogger(__name__)
9
 
10
  import torch
11
  from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor
12
  from pydub import AudioSegment
13
- import soundfile as sf # Add this import
14
 
15
- def transcribe_audio(audio_path):
16
- """
17
- Convert audio file to text using Whisper ASR model
18
- Args:
19
- audio_path: Path to input audio file
20
- Returns:
21
- Transcribed English text
22
- """
23
- logger.info(f"Starting transcription for: {audio_path}")
24
 
25
- try:
26
- # Audio conversion
 
 
 
 
 
 
 
 
 
 
27
  logger.info("Converting audio format")
28
  audio = AudioSegment.from_file(audio_path)
29
  processed_audio = audio.set_frame_rate(16000).set_channels(1)
30
- wav_path = audio_path.replace(".mp3", ".wav")
 
 
31
  processed_audio.export(wav_path, format="wav")
32
  logger.info(f"Audio converted to: {wav_path}")
 
33
 
34
- # Model initialization
35
- logger.info("Loading Whisper model")
36
- device = "cuda" if torch.cuda.is_available() else "cpu"
37
- logger.info(f"Using device: {device}")
38
 
39
- model = AutoModelForSpeechSeq2Seq.from_pretrained(
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  "openai/whisper-large-v3",
41
  torch_dtype=torch.float32,
42
  low_cpu_mem_usage=True,
43
  use_safetensors=True
44
- ).to(device)
 
 
 
 
 
 
 
 
 
 
45
 
46
- processor = AutoProcessor.from_pretrained("openai/whisper-large-v3")
47
- logger.info("Model loaded successfully")
48
-
49
  # Processing
50
  logger.info("Processing audio input")
51
  logger.debug("Loading audio data")
@@ -53,20 +79,20 @@ def transcribe_audio(audio_path):
53
  audio_data = audio_data.astype(np.float32)
54
 
55
  # Increase chunk length and stride for longer transcriptions
56
- inputs = processor(
57
  audio_data,
58
  sampling_rate=16000,
59
  return_tensors="pt",
60
  # Increase chunk length to handle longer segments
61
- chunk_length_s=60, # Increased from 30
62
- stride_length_s=10 # Increased from 5
63
- ).to(device)
64
 
65
  # Transcription
66
  logger.info("Generating transcription")
67
  with torch.no_grad():
68
  # Add max_length parameter to allow for longer outputs
69
- outputs = model.generate(
70
  **inputs,
71
  language="en",
72
  task="transcribe",
@@ -74,11 +100,84 @@ def transcribe_audio(audio_path):
74
  no_repeat_ngram_size=3 # Prevent repetition in output
75
  )
76
 
77
- result = processor.batch_decode(outputs, skip_special_tokens=True)[0]
78
- logger.info(f"transcription: %s" % result)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  logger.info(f"Transcription completed successfully")
80
  return result
81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  except Exception as e:
83
  logger.error(f"Transcription failed: {str(e)}", exc_info=True)
84
  raise
 
1
  """
2
+ Speech Recognition Module
3
+ Supports multiple ASR models including Whisper and Parakeet
4
  Handles audio preprocessing and transcription
5
  """
6
 
7
  import logging
8
  import numpy as np
9
+ import os
10
+ from abc import ABC, abstractmethod
11
+
12
  logger = logging.getLogger(__name__)
13
 
14
  import torch
15
  from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor
16
  from pydub import AudioSegment
17
+ import soundfile as sf
18
 
19
+ class ASRModel(ABC):
20
+ """Base class for ASR models"""
 
 
 
 
 
 
 
21
 
22
+ @abstractmethod
23
+ def load_model(self):
24
+ """Load the ASR model"""
25
+ pass
26
+
27
+ @abstractmethod
28
+ def transcribe(self, audio_path):
29
+ """Transcribe audio to text"""
30
+ pass
31
+
32
+ def preprocess_audio(self, audio_path):
33
+ """Convert audio to required format"""
34
  logger.info("Converting audio format")
35
  audio = AudioSegment.from_file(audio_path)
36
  processed_audio = audio.set_frame_rate(16000).set_channels(1)
37
+ wav_path = audio_path.replace(".mp3", ".wav") if audio_path.endswith(".mp3") else audio_path
38
+ if not wav_path.endswith(".wav"):
39
+ wav_path = f"{os.path.splitext(wav_path)[0]}.wav"
40
  processed_audio.export(wav_path, format="wav")
41
  logger.info(f"Audio converted to: {wav_path}")
42
+ return wav_path
43
 
 
 
 
 
44
 
45
+ class WhisperModel(ASRModel):
46
+ """Whisper ASR model implementation"""
47
+
48
+ def __init__(self):
49
+ self.model = None
50
+ self.processor = None
51
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
52
+
53
+ def load_model(self):
54
+ """Load Whisper model"""
55
+ logger.info("Loading Whisper model")
56
+ logger.info(f"Using device: {self.device}")
57
+
58
+ self.model = AutoModelForSpeechSeq2Seq.from_pretrained(
59
  "openai/whisper-large-v3",
60
  torch_dtype=torch.float32,
61
  low_cpu_mem_usage=True,
62
  use_safetensors=True
63
+ ).to(self.device)
64
+
65
+ self.processor = AutoProcessor.from_pretrained("openai/whisper-large-v3")
66
+ logger.info("Whisper model loaded successfully")
67
+
68
+ def transcribe(self, audio_path):
69
+ """Transcribe audio using Whisper"""
70
+ if self.model is None or self.processor is None:
71
+ self.load_model()
72
+
73
+ wav_path = self.preprocess_audio(audio_path)
74
 
 
 
 
75
  # Processing
76
  logger.info("Processing audio input")
77
  logger.debug("Loading audio data")
 
79
  audio_data = audio_data.astype(np.float32)
80
 
81
  # Increase chunk length and stride for longer transcriptions
82
+ inputs = self.processor(
83
  audio_data,
84
  sampling_rate=16000,
85
  return_tensors="pt",
86
  # Increase chunk length to handle longer segments
87
+ chunk_length_s=60,
88
+ stride_length_s=10
89
+ ).to(self.device)
90
 
91
  # Transcription
92
  logger.info("Generating transcription")
93
  with torch.no_grad():
94
  # Add max_length parameter to allow for longer outputs
95
+ outputs = self.model.generate(
96
  **inputs,
97
  language="en",
98
  task="transcribe",
 
100
  no_repeat_ngram_size=3 # Prevent repetition in output
101
  )
102
 
103
+ result = self.processor.batch_decode(outputs, skip_special_tokens=True)[0]
104
+ logger.info(f"Transcription completed successfully")
105
+ return result
106
+
107
+
108
+ class ParakeetModel(ASRModel):
109
+ """Parakeet ASR model implementation"""
110
+
111
+ def __init__(self):
112
+ self.model = None
113
+
114
+ def load_model(self):
115
+ """Load Parakeet model"""
116
+ try:
117
+ import nemo.collections.asr as nemo_asr
118
+ logger.info("Loading Parakeet model")
119
+ self.model = nemo_asr.models.ASRModel.from_pretrained(model_name="nvidia/parakeet-tdt-0.6b-v2")
120
+ logger.info("Parakeet model loaded successfully")
121
+ except ImportError:
122
+ logger.error("Failed to import nemo_toolkit. Please install with: pip install -U 'nemo_toolkit[asr]'")
123
+ raise
124
+
125
+ def transcribe(self, audio_path):
126
+ """Transcribe audio using Parakeet"""
127
+ if self.model is None:
128
+ self.load_model()
129
+
130
+ wav_path = self.preprocess_audio(audio_path)
131
+
132
+ # Transcription
133
+ logger.info("Generating transcription with Parakeet")
134
+ output = self.model.transcribe([wav_path])
135
+ result = output[0].text
136
  logger.info(f"Transcription completed successfully")
137
  return result
138
 
139
+
140
+ class ASRFactory:
141
+ """Factory for creating ASR model instances"""
142
+
143
+ @staticmethod
144
+ def get_model(model_name="whisper"):
145
+ """
146
+ Get ASR model by name
147
+ Args:
148
+ model_name: Name of the model to use (whisper or parakeet)
149
+ Returns:
150
+ ASR model instance
151
+ """
152
+ if model_name.lower() == "whisper":
153
+ return WhisperModel()
154
+ elif model_name.lower() == "parakeet":
155
+ return ParakeetModel()
156
+ else:
157
+ logger.warning(f"Unknown model: {model_name}, falling back to Whisper")
158
+ return WhisperModel()
159
+
160
+
161
+ def transcribe_audio(audio_path, model_name="whisper"):
162
+ """
163
+ Convert audio file to text using specified ASR model
164
+ Args:
165
+ audio_path: Path to input audio file
166
+ model_name: Name of the ASR model to use (whisper or parakeet)
167
+ Returns:
168
+ Transcribed English text
169
+ """
170
+ logger.info(f"Starting transcription for: {audio_path} using {model_name} model")
171
+
172
+ try:
173
+ # Get the appropriate model
174
+ asr_model = ASRFactory.get_model(model_name)
175
+
176
+ # Transcribe audio
177
+ result = asr_model.transcribe(audio_path)
178
+ logger.info(f"transcription: %s" % result)
179
+ return result
180
+
181
  except Exception as e:
182
  logger.error(f"Transcription failed: {str(e)}", exc_info=True)
183
  raise