pratikshahp commited on
Commit
7a07213
·
verified ·
1 Parent(s): 29015f5

Create app-speech-to-text.py

Browse files
Files changed (1) hide show
  1. app-speech-to-text.py +41 -0
app-speech-to-text.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import Speech2Text2Processor, SpeechEncoderDecoderModel
3
+ import streamlit as st
4
+ from audio_recorder_streamlit import audio_recorder
5
+ import numpy as np
6
+
7
+ # Function to transcribe audio to text
8
+ def transcribe_audio(audio_bytes):
9
+ processor = Speech2Text2Processor.from_pretrained("facebook/s2t-wav2vec2-large-en-de")
10
+ model = SpeechEncoderDecoderModel.from_pretrained("facebook/s2t-wav2vec2-large-en-de")
11
+
12
+ # Convert bytes to numpy array
13
+ audio_array = np.frombuffer(audio_bytes, dtype=np.int16)
14
+
15
+ # Cast audio array to double precision and normalize
16
+ audio_tensor = torch.tensor(audio_array, dtype=torch.float32) / 32768.0
17
+
18
+ input_values = processor(audio_tensor, return_tensors="pt", sampling_rate=16_000).input_values
19
+ logits = model(input_values).logits
20
+ predicted_ids = torch.argmax(logits, dim=-1)
21
+ transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)
22
+
23
+ return transcription[0]
24
+
25
+ # Streamlit app
26
+ st.title("Audio to Text Transcription")
27
+
28
+ audio_bytes = audio_recorder(pause_threshold=3.0, sample_rate=16_000)
29
+
30
+ if audio_bytes:
31
+ st.audio(audio_bytes, format="audio/wav")
32
+
33
+ transcription = transcribe_audio(audio_bytes)
34
+
35
+ if transcription:
36
+ st.write("Transcription:")
37
+ st.write(transcription)
38
+ else:
39
+ st.write("Error: Failed to transcribe audio.")
40
+ else:
41
+ st.write("No audio recorded.")