diff --git a/python-speech-recognition/README.md b/python-speech-recognition/README.md new file mode 100644 index 0000000000..6c726fe600 --- /dev/null +++ b/python-speech-recognition/README.md @@ -0,0 +1,28 @@ +# The Ultimate Guide to Speech Recognition With Python + +This folder contains the sample code for the Real Python tutorial [The Ultimate Guide to Speech Recognition With Python](https://realpython.com/python-speech-recognition/). + +## Setup + +Create and activate a virtual environment, then install the pinned dependencies. You need Python 3.10 or later. The code was tested on Python 3.14. At the time of writing, faster-whisper doesn't install on Python 3.15: + +```console +$ python -m pip install -r requirements.txt +``` + +PyAudio needs the PortAudio library. On Ubuntu or Debian, run `sudo apt-get install build-essential python3-dev portaudio19-dev` first. On macOS, run `brew install portaudio` first. See the tutorial for details. + +## Usage + +Run the scripts from this folder, so that they can find the files in `audio_files/`: + +- `audio_files.py` transcribes `harvard.wav` and `jackhammer.wav` with the Google Web Speech API, including the `offset`, `duration`, and noise examples. +- `whisper_offline.py` transcribes the same files offline with Whisper through faster-whisper. +- `microphone.py` transcribes a phrase from your default microphone. +- `guessing_game.py` is the "Guess the Word" game: + +```console +$ python guessing_game.py +``` + +The audio files are Harvard Sentences from the [Open Speech Repository](http://www.voiptroubleshooter.com/open_speech/index.html). diff --git a/python-speech-recognition/audio_files.py b/python-speech-recognition/audio_files.py new file mode 100644 index 0000000000..b972926520 --- /dev/null +++ b/python-speech-recognition/audio_files.py @@ -0,0 +1,54 @@ +"""Transcribe the sample audio files with the Google Web Speech API. + +Run this script from the folder that contains `audio_files/`. +""" + +import speech_recognition as sr + +r = sr.Recognizer() +harvard = sr.AudioFile("audio_files/harvard.wav") +jackhammer = sr.AudioFile("audio_files/jackhammer.wav") + +# Using record() to capture data from a file +with harvard as source: + audio = r.record(source) +print(type(audio)) +print(repr(r.recognize_google(audio))) + +# Capturing segments with offset and duration +with harvard as source: + audio = r.record(source, duration=4) +print(repr(r.recognize_google(audio))) + +with harvard as source: + audio1 = r.record(source, duration=4) + audio2 = r.record(source, duration=4) +print(repr(r.recognize_google(audio1))) +print(repr(r.recognize_google(audio2))) + +with harvard as source: + audio = r.record(source, offset=4, duration=3) +print(repr(r.recognize_google(audio))) + +with harvard as source: + audio = r.record(source, offset=4.7, duration=2.8) +print(repr(r.recognize_google(audio))) + +# The effect of noise on speech recognition +with jackhammer as source: + audio = r.record(source) +print(repr(r.recognize_google(audio))) + +with jackhammer as source: + r.adjust_for_ambient_noise(source) + audio = r.record(source) +try: + print(repr(r.recognize_google(audio))) +except sr.UnknownValueError: + print("UnknownValueError: the API couldn't recognize any words") + +with jackhammer as source: + r.adjust_for_ambient_noise(source, duration=0.5) + audio = r.record(source) +print(repr(r.recognize_google(audio))) +print(r.recognize_google(audio, show_all=True)) diff --git a/python-speech-recognition/audio_files/harvard.wav b/python-speech-recognition/audio_files/harvard.wav new file mode 100644 index 0000000000..b05ec794dc Binary files /dev/null and b/python-speech-recognition/audio_files/harvard.wav differ diff --git a/python-speech-recognition/audio_files/jackhammer.wav b/python-speech-recognition/audio_files/jackhammer.wav new file mode 100644 index 0000000000..87622f56e9 Binary files /dev/null and b/python-speech-recognition/audio_files/jackhammer.wav differ diff --git a/python-speech-recognition/guessing_game.py b/python-speech-recognition/guessing_game.py new file mode 100644 index 0000000000..4c71f9c479 --- /dev/null +++ b/python-speech-recognition/guessing_game.py @@ -0,0 +1,119 @@ +import random +import time + +import speech_recognition as sr + + +def recognize_speech_from_mic(recognizer, microphone): + """Transcribe speech recorded from `microphone`. + + Returns a dictionary with three keys: + "success": a boolean indicating whether or not the API request was + successful + "error": `None` if no error occurred, otherwise a string containing + an error message if the API could not be reached or + speech was unrecognizable + "transcription": `None` if speech could not be transcribed, + otherwise a string containing the transcribed text + """ + # Check that recognizer and microphone arguments are appropriate type + if not isinstance(recognizer, sr.Recognizer): + raise TypeError("`recognizer` must be `Recognizer` instance") + + if not isinstance(microphone, sr.Microphone): + raise TypeError("`microphone` must be `Microphone` instance") + + # Adjust the recognizer sensitivity to ambient noise and record audio + # from the microphone + with microphone as source: + recognizer.adjust_for_ambient_noise(source) + audio = recognizer.listen(source) + + # Set up the response object + response = { + "success": True, + "error": None, + "transcription": None, + } + + # Try recognizing the speech in the recording + # If a RequestError or UnknownValueError exception is caught, + # update the response object accordingly + try: + response["transcription"] = recognizer.recognize_google(audio) + except sr.RequestError: + # API was unreachable or unresponsive + response["success"] = False + response["error"] = "API unavailable" + except sr.UnknownValueError: + # Speech was unintelligible + response["error"] = "Unable to recognize speech" + + return response + + +if __name__ == "__main__": + # Set the list of words, maximum number of guesses, and prompt limit + WORDS = ["apple", "banana", "grape", "orange", "mango", "lemon"] + NUM_GUESSES = 3 + PROMPT_LIMIT = 5 + + # Create recognizer and mic instances + recognizer = sr.Recognizer() + microphone = sr.Microphone() + + # Get a random word from the list + word = random.choice(WORDS) + + # Format the instructions string + instructions = ( + "I'm thinking of one of these words:\n" + f"{', '.join(WORDS)}\n" + f"You have {NUM_GUESSES} tries to guess which one.\n" + ) + + # Show instructions and wait 3 seconds before starting the game + print(instructions) + time.sleep(3) + + for i in range(NUM_GUESSES): + # Get the guess from the user + # If a transcription is returned, break out of the loop and + # continue + # If no transcription returned and API request failed, break + # loop and continue + # If API request succeeded but no transcription was returned, + # re-prompt the user to say their guess again. Do this up + # to PROMPT_LIMIT times + for j in range(PROMPT_LIMIT): + print(f"Guess {i + 1}. Speak!") + guess = recognize_speech_from_mic(recognizer, microphone) + if guess["transcription"]: + break + if not guess["success"]: + break + print("I didn't catch that. What did you say?\n") + + # If there was an error, stop the game + if guess["error"]: + print(f"ERROR: {guess['error']}") + break + + # Show the user the transcription + print(f"You said: {guess['transcription']}") + + # Determine if guess is correct and if any attempts remain + guess_is_correct = guess["transcription"].lower() == word.lower() + user_has_more_attempts = i < NUM_GUESSES - 1 + + # Determine if the user has won the game + # If not, repeat the loop if user has more attempts + # If no attempts left, the user loses the game + if guess_is_correct: + print("Correct! You win!") + break + elif user_has_more_attempts: + print("Incorrect. Try again.\n") + else: + print(f"Sorry, you lose!\nI was thinking of '{word}'.") + break diff --git a/python-speech-recognition/microphone.py b/python-speech-recognition/microphone.py new file mode 100644 index 0000000000..b216a42709 --- /dev/null +++ b/python-speech-recognition/microphone.py @@ -0,0 +1,21 @@ +"""Transcribe speech from your default microphone. + +Requires PyAudio and a working microphone. +""" + +import speech_recognition as sr + +r = sr.Recognizer() +mic = sr.Microphone() + +print(sr.Microphone.list_microphone_names()) + +print("Say something!") +with mic as source: + r.adjust_for_ambient_noise(source) + audio = r.listen(source, timeout=5, phrase_time_limit=10) + +try: + print(repr(r.recognize_google(audio))) +except sr.UnknownValueError: + print("Unable to recognize speech") diff --git a/python-speech-recognition/requirements.txt b/python-speech-recognition/requirements.txt new file mode 100644 index 0000000000..a9b43b1ee4 --- /dev/null +++ b/python-speech-recognition/requirements.txt @@ -0,0 +1,4 @@ +SpeechRecognition==3.18.0 +PyAudio==0.2.14 +faster-whisper==1.2.1 +soundfile==0.14.0 diff --git a/python-speech-recognition/whisper_offline.py b/python-speech-recognition/whisper_offline.py new file mode 100644 index 0000000000..e396d364b5 --- /dev/null +++ b/python-speech-recognition/whisper_offline.py @@ -0,0 +1,24 @@ +"""Transcribe the sample audio files offline with faster-whisper. + +The first run downloads the Whisper models from the Hugging Face Hub. +""" + +import speech_recognition as sr + +r = sr.Recognizer() +harvard = sr.AudioFile("audio_files/harvard.wav") +jackhammer = sr.AudioFile("audio_files/jackhammer.wav") + +with harvard as source: + audio = r.record(source) +print(repr(r.recognize_faster_whisper(audio))) + +with jackhammer as source: + audio = r.record(source) +print(repr(r.recognize_faster_whisper(audio))) +print(r.recognize_faster_whisper(audio, show_dict=True)) +print(repr(r.recognize_faster_whisper(audio, language="en"))) + +# Choosing a model size +for model in ["tiny", "base", "small"]: + print(model, repr(r.recognize_faster_whisper(audio, model=model)))