Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import speech_recognition as sr
|
| 3 |
+
from threading import Timer
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
def listen_for_speech():
|
| 7 |
+
# Initialize recognizer class
|
| 8 |
+
r = sr.Recognizer()
|
| 9 |
+
# Starts listening in the background (non-blocking)
|
| 10 |
+
with sr.Microphone() as source:
|
| 11 |
+
# Adjust for ambient noise for 1 second
|
| 12 |
+
r.adjust_for_ambient_noise(source, duration=1)
|
| 13 |
+
|
| 14 |
+
st.write("Listening...")
|
| 15 |
+
|
| 16 |
+
try:
|
| 17 |
+
# Listen for 5 seconds, then this turns into pumpkin (stops listening)
|
| 18 |
+
audio = r.listen(source, timeout=5, phrase_time_limit=5)
|
| 19 |
+
# Use Google Web Speech API to convert audio to text
|
| 20 |
+
text = r.recognize_google(audio)
|
| 21 |
+
st.write("You said: " + text)
|
| 22 |
+
except sr.WaitTimeoutError:
|
| 23 |
+
st.warning("Hmm... It seems the airwaves were silent. Please press the button and speak up!")
|
| 24 |
+
except Exception as e:
|
| 25 |
+
# Handle all possible exceptions from the recognizer
|
| 26 |
+
st.error(f"Oops! Something went wrong. Here's what: {e}")
|
| 27 |
+
|
| 28 |
+
def start_listening():
|
| 29 |
+
# This is where the magic happens... or starts happening
|
| 30 |
+
t = Timer(0, listen_for_speech)
|
| 31 |
+
t.start()
|
| 32 |
+
|
| 33 |
+
# We'll give it 10 seconds total before killing this quest for words
|
| 34 |
+
# Just enough to go "Anybody home?" or "Going once, going twice..."
|
| 35 |
+
time.sleep(10)
|
| 36 |
+
t.cancel()
|
| 37 |
+
|
| 38 |
+
# Streamlit app begins
|
| 39 |
+
st.title('The Blabber Be-Gone!')
|
| 40 |
+
|
| 41 |
+
if st.button('Press me and speak!'):
|
| 42 |
+
start_listening()
|