Update app.py
Browse files
app.py
CHANGED
@@ -3,144 +3,204 @@ import torch
|
|
3 |
import librosa
|
4 |
import numpy as np
|
5 |
import tempfile
|
6 |
-
from transformers import
|
7 |
-
from pyctcdecode import build_ctcdecoder
|
8 |
-
from huggingface_hub import hf_hub_download
|
9 |
from jiwer import wer
|
10 |
-
import json
|
11 |
-
import gzip
|
12 |
-
import shutil
|
13 |
import os
|
14 |
from pydub import AudioSegment
|
15 |
-
import torchaudio
|
16 |
-
import re
|
17 |
import time
|
|
|
18 |
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
model_choice = st.sidebar.selectbox("Choose Model", ["wav2vec2", "whisper"])
|
24 |
-
|
25 |
-
# Session State
|
26 |
-
for key in ["audio_bytes", "audio_path", "ground_truth", "wer_value", "predicted_text"]:
|
27 |
-
if key not in st.session_state:
|
28 |
-
st.session_state[key] = None if key in ["audio_bytes", "audio_path", "wer_value"] else ""
|
29 |
|
30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
tab1, tab2 = st.tabs(["๐ Upload Audio", "๐ค Record Audio"])
|
32 |
|
33 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
with tab1:
|
35 |
-
uploaded_file = st.file_uploader("Upload .wav or .mp3", type=["wav", "mp3"
|
36 |
if uploaded_file:
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
with tab2:
|
54 |
-
|
|
|
|
|
|
|
|
|
55 |
if audio_input:
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
st.
|
71 |
-
|
72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
|
74 |
@st.cache_resource
|
75 |
-
def
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
if not os.path.exists(arpa_path):
|
90 |
-
with gzip.open(arpa_gz_path, 'rb') as f_in, open(arpa_path, 'wb') as f_out:
|
91 |
-
shutil.copyfileobj(f_in, f_out)
|
92 |
-
return build_ctcdecoder(vocab_list, kenlm_model_path=arpa_path, alpha=0.2, beta=1.0)
|
93 |
|
94 |
@st.cache_resource
|
95 |
-
def
|
96 |
-
model = WhisperForConditionalGeneration.from_pretrained(
|
97 |
-
processor = WhisperProcessor.from_pretrained(
|
98 |
model.config.forced_decoder_ids = None
|
99 |
model.generation_config.forced_decoder_ids = None
|
|
|
100 |
model.config.suppress_tokens = []
|
101 |
return model, processor
|
102 |
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
if st.button("๐ Transcribe"
|
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 |
-
st.
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
|
|
|
|
|
|
|
|
|
|
|
3 |
import librosa
|
4 |
import numpy as np
|
5 |
import tempfile
|
6 |
+
from transformers import WhisperProcessor, WhisperForConditionalGeneration
|
|
|
|
|
7 |
from jiwer import wer
|
|
|
|
|
|
|
8 |
import os
|
9 |
from pydub import AudioSegment
|
|
|
|
|
10 |
import time
|
11 |
+
import re
|
12 |
|
13 |
+
# Constants
|
14 |
+
WHISPER_FINETUNED = "wy0909/whisper-medium_mixedLanguageModel"
|
15 |
+
WHISPER_PRETRAINED = "openai/whisper-medium"
|
16 |
+
MAX_RECORDING_SECONDS = 12
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
|
18 |
+
def capitalize_sentences(text):
|
19 |
+
sentences = re.split(r'(?<=[.!?]) +', text)
|
20 |
+
capitalized = [s.strip().capitalize() for s in sentences]
|
21 |
+
return ' '.join(capitalized)
|
22 |
+
|
23 |
+
# Main title
|
24 |
+
st.title("๐๏ธ Speech-to-Text with Whisper")
|
25 |
+
|
26 |
+
# Session state initialization
|
27 |
+
if "audio_bytes" not in st.session_state:
|
28 |
+
st.session_state.audio_bytes = None
|
29 |
+
if "audio_path" not in st.session_state:
|
30 |
+
st.session_state.audio_path = None
|
31 |
+
if "ground_truth" not in st.session_state:
|
32 |
+
st.session_state.ground_truth = ""
|
33 |
+
if "predicted_text" not in st.session_state:
|
34 |
+
st.session_state.predicted_text = ""
|
35 |
+
if "wer_value" not in st.session_state:
|
36 |
+
st.session_state.wer_value = None
|
37 |
+
if "selected_tab" not in st.session_state:
|
38 |
+
st.session_state.selected_tab = "๐ Upload Audio"
|
39 |
+
if "previous_tab" not in st.session_state:
|
40 |
+
st.session_state.previous_tab = "๐ Upload Audio"
|
41 |
+
|
42 |
+
# Tab Selection
|
43 |
tab1, tab2 = st.tabs(["๐ Upload Audio", "๐ค Record Audio"])
|
44 |
|
45 |
+
# Reset state if tab is changed
|
46 |
+
if st.session_state.selected_tab != st.session_state.previous_tab:
|
47 |
+
st.session_state.audio_bytes = None
|
48 |
+
st.session_state.audio_path = None
|
49 |
+
st.session_state.ground_truth = ""
|
50 |
+
st.session_state.predicted_text = ""
|
51 |
+
st.session_state.wer_value = None
|
52 |
+
st.session_state.previous_tab = st.session_state.selected_tab
|
53 |
+
|
54 |
+
# Tab 1: Upload Audio
|
55 |
with tab1:
|
56 |
+
uploaded_file = st.file_uploader("Upload a .wav or .mp3 file", type=["wav", "mp3"])
|
57 |
if uploaded_file:
|
58 |
+
try:
|
59 |
+
st.session_state.audio_bytes = uploaded_file.read()
|
60 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=f".{uploaded_file.name.split('.')[-1]}") as tmp:
|
61 |
+
tmp.write(st.session_state.audio_bytes)
|
62 |
+
st.session_state.audio_path = tmp.name
|
63 |
+
|
64 |
+
if uploaded_file.name.endswith(".mp3"):
|
65 |
+
audio = AudioSegment.from_mp3(st.session_state.audio_path)
|
66 |
+
wav_path = st.session_state.audio_path.replace(".mp3", ".wav")
|
67 |
+
audio.export(wav_path, format="wav")
|
68 |
+
os.unlink(st.session_state.audio_path)
|
69 |
+
st.session_state.audio_path = wav_path
|
70 |
+
|
71 |
+
librosa.load(st.session_state.audio_path, sr=16000)
|
72 |
+
st.audio(st.session_state.audio_bytes, format="audio/wav")
|
73 |
+
except Exception as e:
|
74 |
+
st.error(f"โ Failed to read audio file: {str(e)}")
|
75 |
+
if 'st.session_state.audio_path' in locals() and os.path.exists(st.session_state.audio_path):
|
76 |
+
os.unlink(st.session_state.audio_path)
|
77 |
+
st.session_state.audio_bytes = None
|
78 |
+
|
79 |
+
# Tab 2: Record Audio
|
80 |
with tab2:
|
81 |
+
st.session_state.selected_tab = "๐ค Record Audio"
|
82 |
+
st.caption(f"Click microphone below to start recording (max {MAX_RECORDING_SECONDS} seconds)")
|
83 |
+
|
84 |
+
audio_input = st.audio_input("๐๏ธ Record Audio")
|
85 |
+
|
86 |
if audio_input:
|
87 |
+
try:
|
88 |
+
# Get the audio bytes in the correct format
|
89 |
+
audio_bytes = audio_input.read() if hasattr(audio_input, 'read') else audio_input.getvalue()
|
90 |
+
|
91 |
+
# Save to temporary file
|
92 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
|
93 |
+
tmp.write(audio_bytes)
|
94 |
+
temp_path = tmp.name
|
95 |
+
|
96 |
+
# Check duration
|
97 |
+
audio_segment = AudioSegment.from_file(temp_path)
|
98 |
+
duration_seconds = len(audio_segment) / 1000
|
99 |
+
|
100 |
+
if duration_seconds > MAX_RECORDING_SECONDS:
|
101 |
+
st.error(f"โ Recording too long! Please keep it under {MAX_RECORDING_SECONDS} seconds.")
|
102 |
+
os.unlink(temp_path)
|
103 |
+
else:
|
104 |
+
# Store in session state
|
105 |
+
st.session_state.audio_bytes = audio_bytes
|
106 |
+
st.session_state.audio_path = temp_path
|
107 |
+
|
108 |
+
# Validate and display
|
109 |
+
librosa.load(st.session_state.audio_path, sr=16000)
|
110 |
+
|
111 |
+
except Exception as e:
|
112 |
+
st.error(f"โ Failed to process recorded audio: {str(e)}")
|
113 |
+
if 'temp_path' in locals() and os.path.exists(temp_path):
|
114 |
+
os.unlink(temp_path)
|
115 |
+
st.session_state.audio_bytes = None
|
116 |
+
st.session_state.audio_path = None
|
117 |
+
|
118 |
+
# Input ground truth for WER
|
119 |
+
st.session_state.ground_truth = st.text_input(
|
120 |
+
"Enter ground truth for WER calculation (Optional)",
|
121 |
+
value=st.session_state.ground_truth,
|
122 |
+
key="ground_truth_input"
|
123 |
+
)
|
124 |
+
|
125 |
+
# Whisper configuration
|
126 |
+
model_choice = st.selectbox(
|
127 |
+
"Select Whisper Model",
|
128 |
+
options=["Fine-tuned Model", "Pretrained Whisper-Medium Model"],
|
129 |
+
help="Choose the Whisper model to transcribe the audio"
|
130 |
+
)
|
131 |
|
132 |
@st.cache_resource
|
133 |
+
def load_finetuned_model_and_processor():
|
134 |
+
model = WhisperForConditionalGeneration.from_pretrained(
|
135 |
+
WHISPER_FINETUNED,
|
136 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
137 |
+
attn_implementation="flash_attention_2" if torch.cuda.is_available() else None
|
138 |
+
)
|
139 |
+
processor = WhisperProcessor.from_pretrained(WHISPER_FINETUNED)
|
140 |
+
model.config.forced_decoder_ids = None
|
141 |
+
model.generation_config.forced_decoder_ids = None
|
142 |
+
model.config.use_cache = None
|
143 |
+
model.config.suppress_tokens = []
|
144 |
+
if torch.cuda.is_available():
|
145 |
+
model = model.to("cuda")
|
146 |
+
return model, processor
|
|
|
|
|
|
|
|
|
147 |
|
148 |
@st.cache_resource
|
149 |
+
def load_pretrained_model_and_processor():
|
150 |
+
model = WhisperForConditionalGeneration.from_pretrained(WHISPER_PRETRAINED)
|
151 |
+
processor = WhisperProcessor.from_pretrained(WHISPER_PRETRAINED)
|
152 |
model.config.forced_decoder_ids = None
|
153 |
model.generation_config.forced_decoder_ids = None
|
154 |
+
model.config.use_cache = None
|
155 |
model.config.suppress_tokens = []
|
156 |
return model, processor
|
157 |
|
158 |
+
if model_choice == "Fine-tuned Model":
|
159 |
+
model, processor = load_finetuned_model_and_processor()
|
160 |
+
else:
|
161 |
+
model, processor = load_pretrained_model_and_processor()
|
162 |
+
|
163 |
+
# Transcription Button
|
164 |
+
if st.button("๐ Transcribe"):
|
165 |
+
if not st.session_state.audio_bytes:
|
166 |
+
st.error("โ Please upload or record an audio file first.")
|
167 |
+
else:
|
168 |
+
start_time = time.time()
|
169 |
+
try:
|
170 |
+
audio_input_data, _ = librosa.load(st.session_state.audio_path, sr=16000)
|
171 |
+
input_features = processor(
|
172 |
+
audio_input_data, sampling_rate=16000, return_tensors="pt"
|
173 |
+
).input_features
|
174 |
+
|
175 |
+
predicted_ids = model.generate(input_features)
|
176 |
+
transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)[0]
|
177 |
+
transcription = capitalize_sentences(transcription)
|
178 |
+
st.session_state.predicted_text = transcription
|
179 |
+
st.markdown("### ๐ Predicted Transcription")
|
180 |
+
st.success(st.session_state.predicted_text)
|
181 |
+
|
182 |
+
if st.session_state.ground_truth:
|
183 |
+
st.session_state.wer_value = wer(
|
184 |
+
st.session_state.ground_truth.lower(),
|
185 |
+
st.session_state.predicted_text.lower()
|
186 |
+
)
|
187 |
+
st.markdown("### ๐งฎ Word Error Rate (WER)")
|
188 |
+
st.write(f"WER: `{st.session_state.wer_value * 100:.2f}%`")
|
189 |
+
|
190 |
+
except Exception as e:
|
191 |
+
st.error(f"โ Transcription failed: {str(e)}")
|
192 |
+
|
193 |
+
finally:
|
194 |
+
# Clean up temporary files
|
195 |
+
if st.session_state.audio_path and os.path.exists(st.session_state.audio_path):
|
196 |
+
os.unlink(st.session_state.audio_path)
|
197 |
+
st.session_state.audio_bytes = None
|
198 |
+
st.session_state.audio_path = None
|
199 |
+
st.session_state.audio_path = None
|
200 |
+
st.session_state.predicted_text = ""
|
201 |
+
st.session_state.ground_truth = ""
|
202 |
+
st.session_state.wer_value = None
|
203 |
+
|
204 |
+
end_time = time.time()
|
205 |
+
duration = end_time - start_time
|
206 |
+
st.caption(f"๐ Time taken: {duration:.2f}s")
|