I am trying to use Python speech_recognition to get an input from the system audio and then to print it as output. Unfortunately, I'm having some problems with the devices list. In fact, it seems that speech_recognition only recognizes microphones as devices of input.
My idea is the following: I am very slow at writing down notes of important videocalls, so I would like to have Python speech_recognition write them down for me so I can catch up with missing pieces. Do you think it is possible? How?
This is my code until now:
import pyaudio
import speech_recognition as sr
r=sr.Recognizer()
r.energy_threshold=4000
for index, name in enumerate(sr.Microphone.list_microphone_names()):
print("Microphone with name \"{1}\" found for `Microphone(device_index={0})`".format(index, name))
# returns a list of 15 devices (microphone, system speakers, headphones...)
with sr.Microphone(device_index=4) as source:
audio = r.listen(source)
# index = 4 is my headphones
try:
print("Speech was:" + r.recognize_google(audio))
except LookupError:
print('Speech not understood')
When just looking at it, it seems good. But when running it, it cannot recognize my headphones (system audio) as devices and returns the following errors:
Traceback (most recent call last):
File "...", line 10, in <module>
with sr.Microphone(device_index=4) as source:
File "...\speech_recognition\__init__.py", line 141, in __enter__
input=True, # stream is an input stream
File "...pyaudio.py", line 750, in open
stream = Stream(self, *args, **kwargs)
File "...pyaudio.py", line 441, in __init__
self._stream = pa.open(**arguments)
OSError: [Errno -9998] Invalid number of channels
and when putting "normal microphone" as input:
line 858, in recognize_google
if not isinstance(actual_result, dict) or len(actual_result.get("alternative", [])) == 0: raise UnknownValueError()
speech_recognition.UnknownValueError
Can you help me figure this out please?
The microphone error is given when the result of the audio wasn't understood as words. You can fix that by adding a try/except around the statement with "except [the name of the import].UnknownValueError. This will result in whatever is put under except to be run if the "UnknownValueError" error is encountered. As for the headphones, I believe the issue is that you are using an output device for an input function.
Related
I am trying to implement a background listing using speech_recognition python library. Following code use for that. When I run this code I got the following error message. How can I solve this issue?
Error MSG:
RuntimeError: Decoder_set_kws returned -1
Python library - https://github.com/Uberi/speech_recognition#readme
Code:
import speech_recognition as sr
import time
r = sr.Recognizer()
# Words that sphinx should listen closely for. 0-1 is the sensitivity
# of the wake word.
keywords = [("google", 1), ("hey google", 1), ]
source = sr.Microphone(device_index = device_id, sample_rate = sample_rate, chunk_size = chunk_size)
def callback(recognizer, audio): # this is called from the background thread
try:
speech_as_text = recognizer.recognize_sphinx(audio, keyword_entries=keywords)
print(speech_as_text)
# Look for your "Ok Google" keyword in speech_as_text
if "google" in speech_as_text or "hey google":
recognize_main()
except sr.UnknownValueError:
print("Oops! Didn't catch that")
def recognize_main():
print("Recognizing Main...")
audio_data = r.listen(source)
# interpret the user's words however you normally interpret them
def start_recognizer():
print("Main...")
r.listen_in_background(source, callback)
time.sleep(1000000)
start_recognizer()
Full Error MSG:
Exception in thread Thread-6: Traceback (most recent call last):
File "C:\Users\aa\anaconda3\envs\env1\lib\threading.py", line 926, in
_bootstrap_inner
self.run() File "C:\Users\aa\anaconda3\envs\env1\lib\threading.py", line 870, in run
self._target(*self.args, **self.kwargs) File "C:\Users\aa\anaconda3\envs\env1\lib\site-packages\speech_recognition_init.py",
line 616, in threaded_listen
if running[0]: callback(self, audio) File "", line 16, in callback
speech_as_text = recognizer.recognize_sphinx(audio, keyword_entries=keywords) File
"C:\Users\aa\anaconda3\envs\env1\lib\site-packages\speech_recognition_init.py",
line 683, in recognize_sphinx
decoder.set_kws("keywords", f.name) File "C:\Users\aa\anaconda3\envs\env1\lib\site-packages\pocketsphinx\pocketsphinx.py",
line 309, in set_kws
return _pocketsphinx.Decoder_set_kws(self, name, keyfile) RuntimeError: Decoder_set_kws returned -1
I am using PyUSB library to read data from my USB mouse in windows. I was able to run the code in a UBUNTU virtual machine, but I can't replicate the same in windows. Can someone tell me what am I doing wrong? Following is the code and the error it throws :
import usb.core
import usb.util
# decimal vendor and product values
dev = usb.core.find(idVendor=1133, idProduct=49278)
if dev is None :
raise ValueError('Device is not found')
print(dev)
# first endpoint
interface = 0
endpoint = dev[0][(0,0)][0]
# if the OS kernel already claimed the device, which is most likely true
if dev.is_kernel_driver_active(interface) is True:
# tell the kernel to detach
dev.detach_kernel_driver(interface)
# claim the device
usb.util.claim_interface(dev, interface)
collected = 0
attempts = 50
while collected < attempts :
try:
data = dev.read(endpoint.bEndpointAddress,endpoint.wMaxPacketSize)
collected += 1
print(data)
except usb.core.USBError as e:
data = None
if e.args == ('Operation timed out',):
continue
# release the device
usb.util.release_interface(dev, interface)
# reattach the device to the OS kernel
dev.attach_kernel_driver(interface)
Traceback (most recent call last):
File "c:\BCD\i360\python\usb_reader.py", line 27, in <module>
if dev.is_kernel_driver_active(interface) is True:
File "C:\Python\Python38\lib\site-packages\usb\core.py", line 1107, in is_kernel_driver_active
self._ctx.managed_open()
File "C:\Python\Python38\lib\site-packages\usb\core.py", line 113, in wrapper
return f(self, *args, **kwargs)
File "C:\Python\Python38\lib\site-packages\usb\core.py", line 131, in managed_open
self.handle = self.backend.open_device(self.dev)
File "C:\Python\Python38\lib\site-packages\usb\backend\libusb1.py", line 804, in open_device
return _DeviceHandle(dev)
File "C:\Python\Python38\lib\site-packages\usb\backend\libusb1.py", line 652, in __init__
_check(_lib.libusb_open(self.devid, byref(self.handle)))
File "C:\Python\Python38\lib\site-packages\usb\backend\libusb1.py", line 600, in _check
raise NotImplementedError(_strerror(ret))
NotImplementedError: Operation not supported or unimplemented on this platform
The error says exactly what's wrong: You're using a function that makes no sense on your operating system (Windows).
So, don't do that? Either, if you know this is something only running on Windows, remove the check, or better, try:-handle the exception.
dev.is_kernel_driver_active(interface) is not supported in Windows
I am trying to do speech recognition using python and the library SpeechRecognition. When I run the basic code from the docs I get the error message shown below.
Traceback (most recent call last):
File "C:\Python37\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "C:\Python37\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Python37\lib\site-packages\speech_recognition\__main__.py", line 8, in <module>
with m as source: r.adjust_for_ambient_noise(source)
File "C:\Python37\lib\site-packages\speech_recognition\__init__.py", line 141, in __enter__
input=True, # stream is an input stream
File "C:\Python37\lib\site-packages\pyaudio.py", line 750, in open
stream = Stream(self, *args, **kwargs)
File "C:\Python37\lib\site-packages\pyaudio.py", line 441, in __init__
self._stream = pa.open(**arguments)
OSError: [Errno -9985] Device unavailable
I have tried using multiple microphone indexes but none of them pick anything up (program runs forever until I quit it), but when I try it with my default actual microphone it gives me the error.
When running python -m speech_recognition to test if it was installed in command prompt I got the same error message as shown above so the code is not an issue. I have also tried running the program as an admin and made sure my microphone was set as default. I also only have python 3 installed so it is not an issue with multiple versions.
import speech_recognition as sr
r = sr.Recognizer()
with sr.Microphone() as source:
print("Boss.. plz say some")
audio = r.listen(source)
print("143 Boss")
try:
text = r.recognize_google(audio)
except Exception as e:
print (e)
Use this code, if you still face problem comment else accept the answer.
import speech_recognition as sr
import pyaudio
r=sr.Recognizer()
with sr.Microphone()as source:
print(" speak :")
audio=r.listen(source)
try:
output=r.recognize_google(audio)
print(" you said :".format(output))
except:
print(" i cont recognize what u said place spaek clear")
ERRORS:
Traceback (most recent call last):
File "d:/codes/speechreg.py", line 5, in <module>
with sr.Microphone()as source:
File "C:\Users\bjman\AppData\Local\Programs\Python\Python37\lib\site-packages\speech_recognition\__init__.py", line 141, in __enter__
input=True, # stream is an input stream
File "C:\Users\bjman\AppData\Local\Programs\Python\Python37\lib\site-packages\pyaudio.py", line 750, in open
stream = Stream(self, *args, **kwargs)
File "C:\Users\bjman\AppData\Local\Programs\Python\Python37\lib\site-packages\pyaudio.py", line 441, in __init__
self._stream = pa.open(**arguments)
OSError: [Errno -9999] Unanticipated host error
Have you tried to enable access to your microphone? Try enabling microphone using this guid.
I think your code didn't print the output. try to change the following line,
print(" you said :{}".format(output))
And this code will perform as your desire.You can try it as well!
import speech_recognition as sr
import pyaudio
r=sr.Recognizer()
with sr.Microphone()as source:
print(" speak :")
audio=r.listen(source)
try:
value = r.recognize_google(audio)
if str is bytes:
result = u"{}".format(value).encode("utf-8")
else:
result = "{}".format(value)
with open("outputs.txt","a") as f:
f.write(result)
print(result)
except:
print(" i cont recognize what u said place spaek clear")
I'm trying to connect a POS receipt printer to python and have been using python-escpos to do so. I'm running windows 10.
My code in my file 'print.py' is:
from escpos.printer import Usb
p = Usb(0x0456,0x0808)
p.text('Hello World\n')
but when i run it i get the following error log:
Traceback (most recent call last):
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 223, in get_interface_and_endpoint
return self._ep_info[endpoint_address]
KeyError: 1
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "print.py", line 5, in <module>
p.text('Hello World\n')
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\escpos\escpos.py", line 437, in text
self._raw(txt.encode())
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\escpos\printer.py", line 73, in _raw
self.device.write(self.out_ep, msg, self.timeout)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 940, in write
intf, ep = self._ctx.setup_request(self, endpoint)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 102, in wrapper
return f(self, *args, **kwargs)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 215, in setup_request
intf, ep = self.get_interface_and_endpoint(device, endpoint_address)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 102, in wrapper
return f(self, *args, **kwargs)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 225, in get_interface_and_endpoint
for intf in self.get_active_configuration(device):
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 102, in wrapper
return f(self, *args, **kwargs)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 239, in get_active_configuration
bConfigurationValue=self.backend.get_configuration(self.handle)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\backend\libusb0.py", line 510, in get_configuration
100)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\backend\libusb0.py", line 593, in ctrl_transfer
timeout
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\backend\libusb0.py", line 431, in _check
raise USBError(errmsg, ret)
usb.core.USBError: [Errno None] b'libusb0-dll:err [control_msg] sending control message failed, win error: A device which does not exist was specified.\r\n\n'
Does anyone know what i need to do to make this work.
I have installed libusb into my System32 and SysWOW64 folders, aswell as installing a libusb-32 driver for my printer with zadig.
The printer i'm using is a 'Hoin 58mm POS Printer'.
I would be grateful if someone could explain to me why i'm having this error and how to solve it!
Firstly, you can check this link for the complete thread.
As suggested by KM4YRI,
I ran into the same No backend available exception when trying to follow the tutorial on a Windows 7 machine. The following worked for me, per one of the StackOverflow replies:
1. Download the latest Windows binary: https://sourceforge.net/projects/libusb/files/libusb-1.0/libusb-1.0.21/libusb-1.0.21.7z/download
2. Unzip using 7zip into a temp dir
3. If on 64-bit Windows, copy `MS64\dll\libusb-1.0.dll` into `C:\windows\system32`. If on 32-bit windows, copy `MS32\dll\libusb-1.0.dll` into `C:\windows\SysWOW64`.
I've verified the above answer on Windows-10 64-bit version.
I had a tight experience with that error using at least 3 different USB Storage Devices. After hours of trials I ended up to a feeling that USB transmission errors are the cause of this error.
The USB bus will return it in a random pattern for a low quality connection as if a device remove has presumably happened.
In my scenario I was bulk writing sectors to a \\.\PhysicalDriveN device and I noticed that after a short period the connection reestablished and the file handle was still valid and going.
To overcome the error I've ended up with the following steps:
Seek To File Position;
Write Sector;
For any 433 error:
250 ms delay;
Seek To file Position, ignoring ERROR_NO_SUCH_DEVICE and ERROR_NOT_READY errors and trying for at least 1000 ms before giving up;
Read Sector, ignoring ERROR_NO_SUCH_DEVICE and ERROR_NOT_READY errors and retrying for up to 1000 ms before giving up;
Specially for my scenario: I've compared input buffer and read buffer and stop if matching;
Repeat the whole procedure up to 5 times.
So the idea here is the following: The device driver returns ERROR_NO_SUCH_DEVICE assuming a device remove scenario, but still in a pending state. As the problem is simply quality of physical connection, the link continues and the bus driver starts a renegotiation, in which case a ERROR_NOT_READY is temporarily returned. When the link is stable and negotiated, communication continues without the need to reopen the device handle.
I would recommend adding a sleep statement of a second or two in between the instantiation of the USB printer, and the attempt to print to it. e.g:
from escpos.printer import Usb
from time import sleep
p = Usb(0x0456,0x0808)
sleep(1)
p.text('Hello World\n')