Speech Recognition: AttributeError: module 'speech_recognition' has no attribute 'Recognizer' - python

I'm trying to run a speech recognition using the Speech Recognition Project
I installed SpeechRecognition as illustrated. My code ran correctly for a few times.
I was trying to input different files. Now I started getting the following error:
import speech_recognition as sr
Traceback (most recent call last):
File "<ipython-input-1-a4d5c9aae5d0>", line 1, in <module>
import speech_recognition as sr
File "/Users/Sashank/Documents/Deep_Learning_A_Z/Personal Projects/Speech recognition/speech_recognition.py", line 7, in <module>
r = sr.Recognizer()
AttributeError: module 'speech_recognition' has no attribute 'Recognizer'
The confusing thing is that I'm only executing the first line of the code, which is to import the library. And it returns the error.
import speech_recognition as sr
And the error seems to be corresponding to the next line of code, which I've not yet executed:
r = sr.Recognizer()
I'm new to both programming as well as to python. I'm using spyder3. I've restarted the kernel a few times. I tried to install SpeechRecognition again on terminal. I closed and opened spyder also a few times, but now facing the same error again and again.
Please help.
Full Code:
# Speech Recognition
# Importing Library
import speech_recognition as sr
# Creating a recognition object
r = sr.Recognizer()
# Extracting the audio & removing ambient noice
audio_file = sr.AudioFile('ambient_noise_recording.wav')
with audio_file as source:
r.adjust_for_ambient_noise(source)
audio = r.record(source)
# Recognize the audio
r.recognize_google(audio)

File "/Users/Sashank/Documents/Deep_Learning_A_Z/Personal Projects/Speech recognition/speech_recognition.py", line 7, in
Your name of the file is speech_recognition.py and python is looking not to the speech_recognition module but search the Recognizer in your module (file).
You need simple to rename your module (file).
For example from speech_recognition.py to sp_recog.py

Related

Speech Recognition module in python throwing OSError

I am trying to transcribe text from an audio file with the speech recognition module in python. However, whenever I try to run the code, the module throws an OSError. I have disabled the lines of code that say “try” and “except”, since the code returns “Sorry... run again...” if I don’t. I have made sure that the audio sample is 16 bit, but even then I can’t get it to work. I am running Pythonista on an iPad Air, but I get the same results when using a MacBook Air. Is there a problem with software compatibility? I am also new to python, so can anybody help me with this issue?
The code:
#import library
import os
import speech_recognition as sr
import wave
# Initialize recognizer class (for recognizing the speech)
r = sr.Recognizer()
# Reading Audio file as source
# listening the audio file and store in audio_text variable
with sr.AudioFile('audio1.wav') as source:
audio_text = r.listen(source)
# recoginize_() method will throw a request error if the API is unreachable, hence using exception handling
#try:
# using google speech recognition
text = r.recognize_google(audio_text)
print('Converting audio transcripts into text ...')
print(text)
#except:
#print('Sorry.. run again...')
The Traceback:
Traceback (most recent call last):
File "/private/var/mobile/Containers/Shared/AppGroup/34AFF89C-1113-4021-BF04-27338D54F87B/Pythonista3/Documents/program/program.py", line 21, in <module>
text = r.recognize_google(audio_text)
File "/private/var/mobile/Containers/Shared/AppGroup/34AFF89C-1113-4021-BF04-27338D54F87B/Pythonista3/Documents/site-packages-3/speech_recognition/__init__.py", line 828, in recognize_google
convert_width=2 # audio samples must be 16-bit
File "/private/var/mobile/Containers/Shared/AppGroup/34AFF89C-1113-4021-BF04-27338D54F87B/Pythonista3/Documents/site-packages-3/speech_recognition/__init__.py", line 445, in get_flac_data
flac_converter = get_flac_converter()
File "/private/var/mobile/Containers/Shared/AppGroup/34AFF89C-1113-4021-BF04-27338D54F87B/Pythonista3/Documents/site-packages-3/speech_recognition/__init__.py", line 1196, in get_flac_converter
raise OSError("FLAC conversion utility not available - consider installing the FLAC command line application by running `apt-get install flac` or your operating system's equivalent")
OSError: FLAC conversion utility not available - consider installing the FLAC command line application by running `apt-get install flac` or your operating system's equivalent

Impossible to use pyttsx3: No module named 'pywintypes', but pywin32 is installed

I try to use speech synthesis in Python 3.9.13 [MSC v.1929 64 bit (AMD64)].
If I understand well, pyttxs3 is the dedicated module (thank you in advance for any possible alternative!), which I installed successfully:
c:\>pip install -U pyttsx3
Requirement already satisfied: pyttsx3 in c:\users\...\python39\site-packages (2.90)
Requirement already satisfied: comtypes in c:\users\...\python39\site-packages (from pyttsx3) (1.1.11)
Requirement already satisfied: pywin32 in c:\users\...\python39\site-packages (from pyttsx3) (304)
Requirement already satisfied: pypiwin32 in c:\users\...\python39\site-packages (from pyttsx3) (223)
but I cannot initialize the engine: when I do
>>> e = pyttsx3.init()
Traceback (most recent call last):
File "C:\Users\...\Python39\site-packages\pyttsx3\__init__.py", line 20, in init
eng = _activeEngines[driverName]
File "C:\Program Files\...\lib\weakref.py", line 137, in __getitem__
o = self.data[key]()
KeyError: None
During handling of the above exception, another exception occurred:
...
File "C:\Users\...\Python39\site-packages\pyttsx3\drivers\sapi5.py", line 10, in <module>
import pythoncom
File "C:\Users\...\Python39\site-packages\pythoncom.py", line 2, in <module>
import pywintypes
ModuleNotFoundError: No module named 'pywintypes'
I noticed that part of the scripts are in my Users\...\AppData\Local\Packages\PythonSoftwareFoundation... and some are in "C:\Program Files\WindowsApps\PythonSoftwareFoundation.... I wonder whether that might be the reason for the errors.
How could I fix this? (I also found that there are other modules, speech and pyttsx, which however appear to be for Python 2.7: they produce Syntax error: print "..." - did you mean print("...")? Is there a Python 3 version of speech or any other alternative?)
pyttxs3 is a little (actually very) glitched for example after i removed a part of my code which involved speaking something it still spoke my old code i removed the whole pyttxs3 from my code it still didn't work at last i had to uninstall the package. I used this function. You need to install pygame (it is a game making package but we will use it) and gtts i.e google text to speech
import os
from pygame import *
from gtts import *
def speak(text: str):
try:
tts_ = gTTS(text=text, lang='en')
ran = random.randint(0, 1000000)
audio_file = 'audio-' + str(ran) + '.mp3'
tts_.save(audio_file)
# Starting the mixer
mixer.init()
# Loading the song
mixer.music.load("C:///Users/roopa/PycharmProjects/pokemon game/" + audio_file)
# Start playing the song
mixer.music.play()
clock = time.Clock()
# infinite loop
while mixer.music.get_busy():
clock.tick(60)
mixer.music.unload()
os.remove(audio_file)
except gTTSError:
print('unknown error')
Roop's answer didn't work out completely for me due to an error "Failed loading libmpg123-0.dll", but it enabled me to find the following working solution:
import gtts # text to mp3 file
import random # for random file name generation
import playsound # to play mp3 file
import os # to remove audio file
def say(text: str, block = True, lang = 'en'):
"""Text-to-speech synthesis using google TTS. If block=True,
waits until the text is spoken. If False, return a cleanup
function to delete the temporary audio file."""
audio_file = f'audio-{random.randint(0, 1000000)}.mp3'
gtts.gTTS(text, lang = lang).save(audio_file)
playsound.playsound(audio_file, block = block)
if block:
os.remove(audio_file)
else:
print(f"Playing sound, don't forget to do: os.remove('{audio_file}')"
"\n(You can do so by calling the returned function.)")
return(lambda: os.remove(audio_file))
if __name__=='__main__':
cleanup = say("Good morning, Max!")
if cleanup: # if block = True, function returns None
import time
time.sleep(10)
cleanup()
(It appears to be a known bug of playsound that the sound isn't played to the end if the script ends too early, therefore I added the sleep(10), but obviously you can do other stuff instead.)
That said, the question regarding pyttsx3 and pywin32 remains open.

unable to use speech recognition in python

I am trying to make a virtual assistant for which I need the speech recognition module but it's showing a timeout error I tried to increase the timeout manually to 5 seconds yet the issue prevails.
import speech_recognition as sr
import pyaudio
import sounddevice as sd
a = sd.query_devices()
print (a)
r = sr.Recognizer()
with sr.Microphone(device_index=2) as source:
print('say....')
audio = r.listen(source)
voice_data = r.recognize_google(audio)
print(voice_data)
The error shown is as follows
Traceback (most recent call last):
File "/Users/vipulvasant/Desktop/my codes/ABP/main.py", line 10, in <module>
audio = r.listen(source)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/speech_recognition/_init_.py", line 618, in listen
raise WaitTimeoutError("listening timed out while waiting for phrase to start")
speech_recognition.WaitTimeoutError: listening timed out while waiting for phrase to start
this is the first step towards my dream of making my own virtual assistant
Adding a simple a while True: statement should fix the issue.
As i ran into the same issue and this was my solution.
import speech_recognition as sr
import pyaudio
import sounddevice as sd
a = sd.query_devices()
print (a)
r = sr.Recognizer()
while True:
with sr.Microphone(device_index=2) as source:
print('say....')
audio = r.listen(source)
voice_data = r.recognize_google(audio)
print(voice_data)
Here try this. I don't know if this is what you are asking for but I hope it helps:
import speech_recognition
r = sr.Recognizer()
with sr.Microphone() as source:
print("Speak:")
audio = r.listen(source)
voice_data = r.recognize_google(audio)
print(voice_data)

I was trying to convert speech to text and having bad error and don't know why,

My Code is having Bad error :
Code:
!pip install pipwin
!pipwin install pyaudio
# Audio to Text
!pip install pyttsx3
!pip install SpeechRecognition
import pyttsx3
import speech_recognition as sr
r = sr.Recognizer()
with sr.AudioFile('20211102_114210.wav') as source:
audio = r.record(source)
output = r.recognize(audio)
print('OUTPUT: ' + output)
Error Statement :
ttributeError
Traceback (most recent call last)
<ipython-input-24-3e877ae72a16> in <module>
10 with sr.AudioFile('20211102_114210.wav') as source:
11 audio = r.record(source)
---> 12 output = r.recognize(audio)
13 print('OUTPUT: ' + output)
14
AttributeError: 'Recognizer' object has no attribute 'recognize'
I don't understand the error
Perhaps [this link] (AttributeError: 'Recognizer' object has no attribute 'recognize') will work for you. You can try
output = r.recognize_google(audio)
When using speech recognition, I guess you need listen -
import pyttsx3
import speech_recognition as sr
r = sr.Recognizer()
with sr.AudioFile('20211102_114210.wav') as source:
audio = r.record(source)
output = r.listen(audio)
print('OUTPUT: ' + output)
recognize is not a part of Speech Recognition Module. You need listenfunction

How to fix the error 'AttributeError: module 'board' has no attribute 'SCK'' I am using raspberry pi

I am using a modul max31865 and a pt100 sensor to measure the temperature but, I have a problem when i run the program,because appears this error
Traceback (most recent call last):
File "/home/pi/eduardo/videos/temperature.py", line 5, in <module>
spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
AttributeError: module 'board' has no attribute 'SCLK'
I don't know what the problem is.
import board
import busio
import digitalio
import adafruit_max31865
spi = busio.SPI(board.SCLK, MOSI=board.MOSI, MISO=board.MISO)
cs = digitalio.DigitalInOut(board.D5) # Chip select of the MAX31865 board.
sensor = adafruit_max31865.MAX31865(spi, cs, wires=3)
print('Temperature: {0:0.3f}C'.format(sensor.temperature))
print('Resistance: {0:0.3f} Ohms'.format(sensor.resistance))`enter code here`
I expect to read the temperature
Kind regards.
Are you very sure that should not be board.SCLK? Your code seems to be quite close to this example and that is how the constant is spelled there.
Have you enabled I2C interface in raspi-config?
This did it for me
sudo pip3 install --force-reinstall adafruit-blinka

Categories