Spaces:
Build error
Build error
Commit ·
436ea00
1
Parent(s): fae44b5
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import speech_recognition as sr
|
| 3 |
+
import pyaudio
|
| 4 |
+
import threading
|
| 5 |
+
import queue
|
| 6 |
+
|
| 7 |
+
FORMAT = pyaudio.paInt16
|
| 8 |
+
CHANNELS = 1
|
| 9 |
+
RATE = 44100
|
| 10 |
+
CHUNK = 1024
|
| 11 |
+
|
| 12 |
+
audio_queue = queue.Queue()
|
| 13 |
+
text_queue = queue.Queue()
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def recognize_worker():
|
| 17 |
+
recognizer = sr.Recognizer()
|
| 18 |
+
while True:
|
| 19 |
+
audio_data = audio_queue.get()
|
| 20 |
+
if audio_data is None:
|
| 21 |
+
break
|
| 22 |
+
try:
|
| 23 |
+
text = recognizer.recognize_google(audio_data)
|
| 24 |
+
text_queue.put(text)
|
| 25 |
+
except sr.UnknownValueError:
|
| 26 |
+
pass
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def audio_stream():
|
| 30 |
+
p = pyaudio.PyAudio()
|
| 31 |
+
stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK)
|
| 32 |
+
|
| 33 |
+
recognizer = sr.Recognizer()
|
| 34 |
+
while not stop_flag.is_set():
|
| 35 |
+
data = stream.read(CHUNK, exception_on_overflow=False)
|
| 36 |
+
if len(data) == 0:
|
| 37 |
+
break
|
| 38 |
+
audio_data = sr.AudioData(data, RATE, 2)
|
| 39 |
+
audio_queue.put(audio_data)
|
| 40 |
+
|
| 41 |
+
stream.stop_stream()
|
| 42 |
+
stream.close()
|
| 43 |
+
p.terminate()
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
st.title('Real-time Speech to Text')
|
| 47 |
+
|
| 48 |
+
stop_flag = threading.Event()
|
| 49 |
+
|
| 50 |
+
if st.button('Start Recording'):
|
| 51 |
+
stop_flag.clear()
|
| 52 |
+
threading.Thread(target=audio_stream, daemon=True).start()
|
| 53 |
+
threading.Thread(target=recognize_worker, daemon=True).start()
|
| 54 |
+
st.write('Recording started...')
|
| 55 |
+
|
| 56 |
+
if st.button('Stop Recording'):
|
| 57 |
+
stop_flag.set()
|
| 58 |
+
audio_queue.put(None)
|
| 59 |
+
st.write('Recording stopped.')
|
| 60 |
+
|
| 61 |
+
st.text_area('Text:', value='', key='text_area')
|
| 62 |
+
|
| 63 |
+
if not text_queue.empty():
|
| 64 |
+
st.session_state.text_area += text_queue.get() + '\n'
|