Spaces:
Sleeping
Sleeping
Modified app.py, added streamlit session state persistence
Browse files
app.py
CHANGED
@@ -5,21 +5,15 @@ import streamlit as st
|
|
5 |
import torchaudio as ta
|
6 |
|
7 |
from io import BytesIO
|
8 |
-
from transformers import
|
9 |
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
else:
|
14 |
-
device = "cpu"
|
15 |
-
torch_dtype = torch.float32
|
16 |
|
17 |
-
SAMPLING_RATE=16000
|
18 |
-
task = "transcribe"
|
19 |
|
20 |
-
|
21 |
-
|
22 |
-
# load Whisper model and processor
|
23 |
processor = WhisperProcessor.from_pretrained("openai/whisper-small")
|
24 |
model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-small")
|
25 |
|
@@ -31,113 +25,74 @@ st.sidebar.header("Upload Audio Files")
|
|
31 |
uploaded_files = st.sidebar.file_uploader("Choose audio files", type=["mp3", "wav"], accept_multiple_files=True)
|
32 |
submit_button = st.sidebar.button("Submit")
|
33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
|
35 |
-
# def transcribe_audio(audio_data):
|
36 |
-
# recognizer = sr.Recognizer()
|
37 |
-
# with sr.AudioFile(audio_data) as source:
|
38 |
-
# audio = recognizer.record(source)
|
39 |
-
# try:
|
40 |
-
# # Transcribe the audio using Google Web Speech API
|
41 |
-
# transcription = recognizer.recognize_google(audio)
|
42 |
-
# return transcription
|
43 |
-
# except sr.UnknownValueError:
|
44 |
-
# return "Unable to transcribe the audio."
|
45 |
-
# except sr.RequestError as e:
|
46 |
-
# return f"Could not request results; {e}"
|
47 |
|
48 |
def detect_language(audio_file):
|
49 |
-
whisper_model = whisper.load_model("
|
|
|
50 |
mel = whisper.log_mel_spectrogram(trimmed_audio).to(whisper_model.device)
|
51 |
-
|
52 |
-
|
53 |
-
print(f"Detected language: {
|
54 |
-
return
|
55 |
-
|
56 |
-
# if submit_button and uploaded_files is not None:
|
57 |
-
# st.write("Files uploaded successfully!")
|
58 |
-
|
59 |
-
# for uploaded_file in uploaded_files:
|
60 |
-
# # Display file name and audio player
|
61 |
-
|
62 |
-
# st.write(f"**File name**: {uploaded_file.name}")
|
63 |
-
# st.audio(uploaded_file, format=uploaded_file.type)
|
64 |
-
|
65 |
-
# # Transcription section
|
66 |
-
# st.write("**Transcription**:")
|
67 |
-
|
68 |
-
# # Read the uploaded file data
|
69 |
-
# waveform, sampling_rate = ta.load(uploaded_file.getvalue())
|
70 |
-
# resampled_inp = ta.functional.resample(waveform, orig_freq=sampling_rate, new_freq=SAMPLING_RATE)
|
71 |
-
|
72 |
-
# input_features = processor(resampled_inp[0], sampling_rate=16000, return_tensors='pt').input_features
|
73 |
-
|
74 |
-
# if task == "translate":
|
75 |
-
|
76 |
-
# # Detect Language
|
77 |
-
# lang = detect_language(input_features)
|
78 |
-
# with open('languages.pkl', 'rb') as f:
|
79 |
-
# lang_dict = pickle.load(f)
|
80 |
-
# detected_language = lang_dict[lang]
|
81 |
-
|
82 |
-
# # Set decoder & Predict translation
|
83 |
-
# forced_decoder_ids = processor.get_decoder_prompt_ids(language=detected_language, task="translate")
|
84 |
-
# predicted_ids = model.generate(input_features, forced_decoder_ids=forced_decoder_ids)
|
85 |
-
# else:
|
86 |
-
# predicted_ids = model.generate(input_features)
|
87 |
-
# # decode token ids to text
|
88 |
-
# transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)
|
89 |
-
# for i in range(len(transcription)):
|
90 |
-
# st.write(transcription[i])
|
91 |
-
# # print(waveform, sampling_rate)
|
92 |
-
# # Run transcription function and display
|
93 |
-
# # import pdb;pdb.set_trace()
|
94 |
-
# # st.write(audio_data.getvalue())
|
95 |
-
|
96 |
|
97 |
|
|
|
98 |
if submit_button and uploaded_files is not None:
|
99 |
-
|
100 |
-
detected_languages = []
|
101 |
|
102 |
for uploaded_file in uploaded_files:
|
103 |
-
# Read the uploaded file data
|
104 |
waveform, sampling_rate = ta.load(BytesIO(uploaded_file.read()))
|
105 |
-
|
106 |
-
# Resample if necessary
|
107 |
if sampling_rate != SAMPLING_RATE:
|
108 |
waveform = ta.functional.resample(waveform, orig_freq=sampling_rate, new_freq=SAMPLING_RATE)
|
109 |
|
110 |
-
|
111 |
-
detected_language = detect_language(waveform
|
112 |
-
detected_languages.append(detected_language)
|
113 |
|
114 |
-
|
115 |
-
|
116 |
-
|
|
|
117 |
|
118 |
with col1:
|
119 |
st.write(f"**File name**: {uploaded_file.name}")
|
120 |
-
st.audio(BytesIO(uploaded_file.
|
121 |
-
st.write(f"**Detected Language**: {detected_languages[i]}")
|
122 |
|
123 |
with col2:
|
124 |
-
#
|
|
|
|
|
125 |
if st.button(f"Transcribe {uploaded_file.name}"):
|
126 |
-
# Transcription process
|
127 |
-
input_features = processor(waveform[0], sampling_rate=SAMPLING_RATE, return_tensors='pt').input_features
|
128 |
predicted_ids = model.generate(input_features)
|
129 |
transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)
|
130 |
-
|
|
|
|
|
|
|
|
|
131 |
st.write(line)
|
132 |
|
133 |
if st.button(f"Translate {uploaded_file.name}"):
|
134 |
-
# Translation process
|
135 |
with open('languages.pkl', 'rb') as f:
|
136 |
lang_dict = pickle.load(f)
|
137 |
-
detected_language_name = lang_dict[detected_languages[i]]
|
138 |
|
139 |
forced_decoder_ids = processor.get_decoder_prompt_ids(language=detected_language_name, task="translate")
|
140 |
predicted_ids = model.generate(input_features, forced_decoder_ids=forced_decoder_ids)
|
141 |
translation = processor.batch_decode(predicted_ids, skip_special_tokens=True)
|
142 |
-
|
|
|
|
|
|
|
|
|
143 |
st.write(line)
|
|
|
5 |
import torchaudio as ta
|
6 |
|
7 |
from io import BytesIO
|
8 |
+
from transformers import WhisperProcessor, WhisperForConditionalGeneration
|
9 |
|
10 |
+
# Set up device and dtype
|
11 |
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
12 |
+
torch_dtype = torch.float16 if device == "cuda:0" else torch.float32
|
|
|
|
|
|
|
13 |
|
14 |
+
SAMPLING_RATE = 16000
|
|
|
15 |
|
16 |
+
# Load Whisper model and processor
|
|
|
|
|
17 |
processor = WhisperProcessor.from_pretrained("openai/whisper-small")
|
18 |
model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-small")
|
19 |
|
|
|
25 |
uploaded_files = st.sidebar.file_uploader("Choose audio files", type=["mp3", "wav"], accept_multiple_files=True)
|
26 |
submit_button = st.sidebar.button("Submit")
|
27 |
|
28 |
+
# Session state to hold data
|
29 |
+
if 'audio_files' not in st.session_state:
|
30 |
+
st.session_state.audio_files = []
|
31 |
+
st.session_state.transcriptions = {}
|
32 |
+
st.session_state.translations = {}
|
33 |
+
st.session_state.detected_languages = []
|
34 |
+
st.session_state.waveforms = []
|
35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
|
37 |
def detect_language(audio_file):
|
38 |
+
whisper_model = whisper.load_model("small")
|
39 |
+
trimmed_audio = whisper.pad_or_trim(audio_file)
|
40 |
mel = whisper.log_mel_spectrogram(trimmed_audio).to(whisper_model.device)
|
41 |
+
_, probs = whisper_model.detect_language(mel[0])
|
42 |
+
detected_lang = max(probs, key=probs.get)
|
43 |
+
print(f"Detected language: {detected_lang}")
|
44 |
+
return detected_lang
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
|
46 |
|
47 |
+
# Process uploaded files
|
48 |
if submit_button and uploaded_files is not None:
|
49 |
+
st.session_state.audio_files = uploaded_files
|
50 |
+
st.session_state.detected_languages = []
|
51 |
|
52 |
for uploaded_file in uploaded_files:
|
|
|
53 |
waveform, sampling_rate = ta.load(BytesIO(uploaded_file.read()))
|
|
|
|
|
54 |
if sampling_rate != SAMPLING_RATE:
|
55 |
waveform = ta.functional.resample(waveform, orig_freq=sampling_rate, new_freq=SAMPLING_RATE)
|
56 |
|
57 |
+
st.session_state.waveforms.append(waveform)
|
58 |
+
detected_language = detect_language(waveform)
|
59 |
+
st.session_state.detected_languages.append(detected_language)
|
60 |
|
61 |
+
# Display uploaded files and options
|
62 |
+
if 'audio_files' in st.session_state and st.session_state.audio_files:
|
63 |
+
for i, uploaded_file in enumerate(st.session_state.audio_files):
|
64 |
+
col1, col2 = st.columns([1, 3])
|
65 |
|
66 |
with col1:
|
67 |
st.write(f"**File name**: {uploaded_file.name}")
|
68 |
+
st.audio(BytesIO(uploaded_file.read()), format=uploaded_file.type)
|
69 |
+
st.write(f"**Detected Language**: {st.session_state.detected_languages[i]}")
|
70 |
|
71 |
with col2:
|
72 |
+
# import pdb;pdb.set_trace()
|
73 |
+
input_features = processor(st.session_state.waveforms[i][0], sampling_rate=SAMPLING_RATE, return_tensors='pt').input_features
|
74 |
+
|
75 |
if st.button(f"Transcribe {uploaded_file.name}"):
|
|
|
|
|
76 |
predicted_ids = model.generate(input_features)
|
77 |
transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)
|
78 |
+
st.session_state.transcriptions[i] = transcription
|
79 |
+
|
80 |
+
if st.session_state.transcriptions.get(i):
|
81 |
+
st.write("**Transcription**:")
|
82 |
+
for line in st.session_state.transcriptions[i]:
|
83 |
st.write(line)
|
84 |
|
85 |
if st.button(f"Translate {uploaded_file.name}"):
|
|
|
86 |
with open('languages.pkl', 'rb') as f:
|
87 |
lang_dict = pickle.load(f)
|
88 |
+
detected_language_name = lang_dict[st.session_state.detected_languages[i]]
|
89 |
|
90 |
forced_decoder_ids = processor.get_decoder_prompt_ids(language=detected_language_name, task="translate")
|
91 |
predicted_ids = model.generate(input_features, forced_decoder_ids=forced_decoder_ids)
|
92 |
translation = processor.batch_decode(predicted_ids, skip_special_tokens=True)
|
93 |
+
st.session_state.translations[i] = translation
|
94 |
+
|
95 |
+
if st.session_state.translations.get(i):
|
96 |
+
st.write("**Translation**:")
|
97 |
+
for line in st.session_state.translations[i]:
|
98 |
st.write(line)
|