Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions python-speech-recognition/README.md
Original file line number Diff line number Diff line change
@@ -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).
54 changes: 54 additions & 0 deletions python-speech-recognition/audio_files.py
Original file line number Diff line number Diff line change
@@ -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))
Binary file not shown.
Binary file not shown.
119 changes: 119 additions & 0 deletions python-speech-recognition/guessing_game.py
Original file line number Diff line number Diff line change
@@ -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
21 changes: 21 additions & 0 deletions python-speech-recognition/microphone.py
Original file line number Diff line number Diff line change
@@ -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")
4 changes: 4 additions & 0 deletions python-speech-recognition/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
SpeechRecognition==3.18.0
PyAudio==0.2.14
faster-whisper==1.2.1
soundfile==0.14.0
24 changes: 24 additions & 0 deletions python-speech-recognition/whisper_offline.py
Original file line number Diff line number Diff line change
@@ -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)))
Loading