Download code/voice.py from kartik20032003/sunai: direct link, hf CLI and curl.
- Browser
- Download file 1.27 kB
-
https://huggingface.co/kartik20032003/sunai/resolve/main/code/voice.py
- Command line
-
hf download hf://kartik20032003/sunai/code/voice.py
-
curl -L -o voice.py https://huggingface.co/kartik20032003/sunai/resolve/main/code/voice.py
1.27 kB
| import speech_recognition as sr | |
| import pyttsx3 | |
| _engine = None | |
| def _get_engine(): | |
| global _engine | |
| if _engine is None: | |
| _engine = pyttsx3.init() | |
| _engine.setProperty("rate", 175) # slightly faster speech | |
| return _engine | |
| def speak(text): | |
| print(f"Sunday: {text}") | |
| try: | |
| eng = _get_engine() | |
| eng.say(text) | |
| eng.runAndWait() | |
| except Exception: | |
| pass | |
| def listen(): | |
| r = sr.Recognizer() | |
| r.pause_threshold = 0.8 # stop listening after 0.8s of silence | |
| try: | |
| with sr.Microphone() as source: | |
| print("Listening...") | |
| r.adjust_for_ambient_noise(source, duration=0.5) | |
| audio = r.listen(source, timeout=5, phrase_time_limit=10) | |
| text = r.recognize_google(audio) | |
| print(f"You: {text}") | |
| return text | |
| except sr.WaitTimeoutError: | |
| print("[No speech detected]") | |
| return "" | |
| except sr.UnknownValueError: | |
| print("[Couldn't understand, try again]") | |
| return "" | |
| except sr.RequestError: | |
| print("[Mic/network error — switching to text input]") | |
| return None # None signals caller to fall back to keyboard | |
| except Exception: | |
| return "" |