How do I not get OSError: [Errno -9993] Illegal combination of I/O devices when using pyaudio - python-3.x

I believe it's this module that's crashing my program and throwing this error: OSError: [Errno -9993] Illegal combination of I/O devices. I wrapped the call to this module in a try except SystemExit block, and it still crashed. Any ideas how to fix this will be greatly appreciated.
I'm running on Ubuntu 18.04 in a Conda virtual environment using Python 3.6.10.
###############################################################################################
######## STT SPEECH TO TEXT FUNCTION THAT RETURNS THE VARIABLE: command
import pyaudio
from vosk import Model, KaldiRecognizer
def myCommand():
# "listens for commands"
# We imported vosk up above.
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True, frames_per_buffer=8000)
stream.start_stream()
model = Model("model-en")
rec = KaldiRecognizer(model, 16000)
while True:
data = stream.read(2000)
if len(data) == 0:
break
if rec.AcceptWaveform(data):
#print(rec.Result())
# I commented out this line and added the 3 lines below
myResult = rec.Result()
myList = myResult.split("text")
command = myList[1]
return command
######## END STT SPEECH TO TEXT FUNCTION THAT RETURNS THE VARIABLE: command
###############################################################################################
❯ pip list
Package Version
beautifulsoup4 4.9.0
certifi 2020.4.5.1
chardet 3.0.4
click 7.1.1
future 0.18.2
gTTS 2.1.1
gTTS-token 1.1.3
idna 2.9
isort 4.3.21
lazy-object-proxy 1.4.3
mccabe 0.6.1
mock 4.0.1
MouseInfo 0.1.3
mypy 0.770
mypy-extensions 0.4.3
numpy 1.18.1
Pillow 7.1.1
pip 20.0.2
psutil 5.7.0
PyAudio 0.2.11
PyAutoGUI 0.9.50
PyGetWindow 0.0.8
pylint 2.4.4
PyMsgBox 1.0.7
pyperclip 1.8.0
PyQt5 5.14.2
PyQt5-sip 12.7.2
PyRect 0.1.4
PyScreeze 0.1.26
python3-xlib 0.15
PyTweening 1.0.3
requests 2.23.0
setuptools 45.2.0
six 1.14.0
soupsieve 2.0
subprocess.run 0.0.8
typed-ast 1.4.1
typing-extensions 3.7.4.1
urllib3 1.25.9
vosk 0.3.3
wheel 0.34.2
wikipedia 1.4.0
wrapt 1.11.2
#
I'm also running this module, and I'm not 100% sure which is causing the problem, although I suspect the first:
###############################################################################################
######## TTS TEXT TO SPEECH FUNCTION
# This gets used all over to speak text aloud.
# It also prints to the console for people with bad memories.
from gtts import gTTS
import os
def talkToMe(mytext):
# "speaks audio passed as argument"
print(mytext)
# can handle multiline text.
#for line in mytext.splitlines():
# uses the google text to speech module to synthesize text
text_to_speech = gTTS(text=mytext, lang='en-uk')
# saves syntesized speech to audio.mp3
# this file gets written, played. and overwritten
# over and over again.
text_to_speech.save('audio.mp3')
# the sox modules wrapper is mpg123.
# This is called by the operating system imported os module.
os.system('mpg123 -q audio.mp3')
###############################################################################################
######## END TTS TEXT TO SPEECH FUNCTION
#
Here's what I'm seeing as error:
LOG (vosk[5.5.641~1-79319]:ComputeDerivedVars():ivector-extractor.cc:183) Computing derived variables for iVector extractor
LOG (vosk[5.5.641~1-79319]:ComputeDerivedVars():ivector-extractor.cc:204) Done.
LOG (vosk[5.5.641~1-79319]:RemoveOrphanNodes():nnet-nnet.cc:948) Removed 1 orphan nodes.
LOG (vosk[5.5.641~1-79319]:RemoveOrphanComponents():nnet-nnet.cc:847) Removing 2 orphan components.
LOG (vosk[5.5.641~1-79319]:Collapse():nnet-utils.cc:1472) Added 1 components, removed 2
LOG (vosk[5.5.641~1-79319]:CompileLooped():nnet-compile-looped.cc:345) Spent 0.028789 seconds in looped compilation.
ALSA lib pulse.c:243:(pulse_connect) PulseAudio: Unable to connect: Connection terminated
Expression 'ret' failed in 'src/hostapi/alsa/pa_linux_alsa.c', line: 1735
Expression 'AlsaOpen( &alsaApi->baseHostApiRep, params, streamDir, &self->pcm )' failed in 'src/hostapi/alsa/pa_linux_alsa.c', line: 1902
Expression 'PaAlsaStreamComponent_Initialize( &self->capture, alsaApi, inParams, StreamDirection_In, NULL != callback )' failed in 'src/hostapi/alsa/pa_linux_alsa.c', line: 2166
Expression 'PaAlsaStream_Initialize( stream, alsaHostApi, inputParameters, outputParameters, sampleRate, framesPerBuffer, callback, streamFlags, userData )' failed in 'src/hostapi/alsa/pa_linux_alsa.c', line: 2835
Traceback (most recent call last):
File "Juliet.py", line 376, in <module>
main()
File "Juliet.py", line 366, in main
output = mycommand.myCommand()[3:]
File "/home/bard/Code/Juliet/SpeakAndHear/mycommand.py", line 10, in myCommand
stream = p.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True, frames_per_buffer=8000)
File "/home/bard/miniconda3/envs/Juliet/lib/python3.6/site-packages/pyaudio.py", line 750, in open
stream = Stream(self, *args, **kwargs)
File "/home/bard/miniconda3/envs/Juliet/lib/python3.6/site-packages/pyaudio.py", line 441, in __init__
self._stream = pa.open(**arguments)
OSError: [Errno -9993] Illegal combination of I/O devices

I've solved this. I needed to close my stream and terminate the process:
###############################################################################################
######## STT SPEECH TO TEXT FUNCTION THAT RETURNS THE VARIABLE: command
import pyaudio
from vosk import Model, KaldiRecognizer
def myCommand():
# "listens for commands"
# We imported vosk up above.
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True, frames_per_buffer=8000)
stream.start_stream()
model = Model("model-en")
rec = KaldiRecognizer(model, 16000)
while True:
data = stream.read(2000)
if len(data) == 0:
break
if rec.AcceptWaveform(data):
#print(rec.Result())
# I commented out this line and added the 3 lines below
myResult = rec.Result()
myList = myResult.split("text")
command = myList[1]
stream.stop_stream()
stream.close()
p.terminate()
return command
######## END STT SPEECH TO TEXT FUNCTION THAT RETURNS THE VARIABLE: command
###############################################################################################

Related

python pyttsx3 error -- _pickle.UnpicklingError: invalid load key, '\x00'

i am trying to convert text to speech using pyttsx3 in python. but iam getting the error -- _pickle.UnpicklingError: invalid load key, '\x00'.
it worked once. later it didn't
my code
import pyttsx3
engine = pyttsx3.init()
engine.say("I will speak this text")
engine.runAndWait()
error i am receiving is --
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\pyttsx3__init__.py",
line 20, in init
eng = _activeEngines[driverName]
File "C:\ProgramData\Anaconda3\lib\weakref.py", line 137, in
getitem
o = self.data[key]()
KeyError: None
During handling of the above exception, another exception occurred:
...
File "C:\ProgramData\Anaconda3\lib\site-packages\win32com\client\gencache.py", line 113, in _LoadDicts
version = p.load()
_pickle.UnpicklingError: invalid load key, '\x00'.
python version is 3.7.3 |
pyttsx3 version is 2.71|
pywin32 version is 224
please help
I had this problem as well and fixed it by deleting gen_py in my temp directory.
You can find this folder here:
C:\Users\USERNAME\AppData\Local\Temp\gen_py

AttributeError: module 'yaml' has no attribute 'warnings'

I want to try an example of LSTM online, but I meet some problems. This is my first time to use YAML.
I run the code including the parts below and these errors occur:
Traceback (most recent call last):
File "lstm_test.py", line 112, in <module>
lstm_predict(strings)
File "lstm_test.py", line 74, in lstm_predict
yaml.warnings({'YAMLLoadWarning': False})
AttributeError: module 'yaml' has no attribute 'warnings'
I run the code on Windows 10, and I use Python 3.7.
def lstm_predict(strings):
print('loading model......')
with open('../model/lstm.yml', 'r') as f:
yaml_string = yaml.load(f)
model = model_from_yaml(yaml_string)
print('loading weights......')
model.load_weights('../model/lstm.h5')
model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy'])
for string in strings:
line = Converter('zh-hant').convert(string.encode().decode('utf-8'))
string0 = line.encode('utf-8')
print("="*20)
data=input_transform(string0)
data.reshape(1,-1)
#print data
result=model.predict_classes(data)
print(result) # [[1]]
if result[0]==1:
print(string,' positive')
elif result[0]==0:
print(string,' neural')
else:
print(string,' negative')
Actually, I get the error:
AttributeError: module 'yaml' has no attribute 'warnings'.
But, theoretically I think it should not raise any errors. What do I possibly miss?
I have a similar problem as following picture
It is okay now when I install PyYAML package like below command
pipenv run pip install PyYAML --upgrade --force-reinstall
by the way, it is a different package between pyyaml and PyYAML

Deprecation error when using imageio.ffmpeg.download()

I'm trying to merge the prerecorded videos using python Opencv.
But i'm getting the error while importing.
"Traceback (most recent call last):
File "video.py", line 4, in <module>
from moviepy. editor import VideoFileClip,concatenate_videoclips
File "/home/pi/.virtualenvs/cv/lib/python3.5/site-packages/moviepy/editor.py", line 26, in <module>
imageio.plugins.ffmpeg.download()
File "/home/pi/.virtualenvs/cv/lib/python3.5/site-packages/imageio/plugins/ffmpeg.py", line 40, in download
"imageio.ffmpeg.download() has been deprecated. "
RuntimeError: imageio.ffmpeg.download() has been deprecated. Use 'pip install imageio-ffmpeg' instead.'"
would anyone please help to get out of this problem
Here is the code:
import cv2
import os
import time
from moviepy.editor import VideoFileClip,concatenate_videoclips
def vidcapt():
a = time.strftime("%H,%M,%S")
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(a+'.avi', fourcc, 24.0, (640,480))
t1 = time.time()
while(cap.isOpened()):
ret, frame = cap.read()
if ret == True:
out.write(frame)
cv2.imshow('frame',frame)
t2 = time.time()
time_diff = t2-t1
if time_diff >= 5:
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()
while True:
vidcapt()
clip1 = VideoFileClip("11,05,42.avi")
clip2 = VideoFileClip("11,05,47.avi").subclip(50,60)
final_clip = concatenate_videoclips([clip1,clip2])
final_clip.write_videofile("merged.avi")
try this instead:
sudo pip3 install imageio==2.4.1
hope to solve your issue.
you need to install imageio-ffmpeg along with imageio.
So install both of these packages with specified versions
pip3 install imageio==2.4.1
pip install imageio-ffmpeg
Cheers
Or, simply comment those two lines in editor.py, that refer to an already deprecated function
#if os.getenv('FFMPEG_BINARY', 'ffmpeg-imageio') == 'ffmpeg-imageio':
# imageio.plugins.ffmpeg.download()
It's:
imageio_download_bin ffmpeg
Or:
conda install ffmpeg -c conda-forge
Or:
imageio.plugins.ffmpeg.download()

Error when loading audio file from zip in python

I am making a game, and I need to load some password protected audio files from a .zip file, but I get this error:
io.UnsupportedOperation: seek
io.UnsupportedOperation: seek
io.UnsupportedOperation: seek
b'hey you did it!' #THIS IS FROM THE PROGRAM
Traceback (most recent call last):
File "C:\Python36\lib\zipfile.py", line 849, in read
data = self._read1(n)
File "C:\Python36\lib\zipfile.py", line 917, in _read1
data += self._read2(n - len(data))
File "C:\Python36\lib\zipfile.py", line 949, in _read2
data = self._fileobj.read(n)
File "C:\Python36\lib\zipfile.py", line 705, in read
self._file.seek(self._pos)
AttributeError: 'NoneType' object has no attribute 'seek'
And this is my code below:
from zipfile import ZipFile
from PIL import Image
from io import BytesIO
import pygame
from pygame.locals import *
import pyganim
import sys
pygame.init()
root = pygame.display.set_mode((320, 240), 0, 32)
pygame.display.set_caption('image load test')
#THIS IS HOW TO LOAD IMAGES (WORKS)
with ZipFile("spam.zip", 'r') as archive:
mcimg = archive.read('a.png', pwd=b'onlyforthedev')
mc = pygame.image.load(BytesIO(mcimg))
anime = pyganim.PygAnimation([(mc, 100),
(mc, 100)])
anime.play()
#THIS IS HOW TO LOAD MUSIC (DOES NOT WORK)
with ZipFile('spam.zip') as zippie:
with zippie.open('zora.mp3', pwd=b'onlyforthedev') as zora:
pygame.mixer.music.load(zora)
pygame.mixer.music.play(-1)
#THIS IS HOW TO LOAD TEXT (WORKS)
with ZipFile('spam.zip') as myzip:
with myzip.open('eggs.txt', pwd=b'onlyforthedev') as myfile:
print(myfile.read())
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
root.fill((100, 50, 50))
anime.blit(root, (100, 50))
pygame.display.update()
What can I do to load sound files without raising such an error? And what is 'seek'?
I also get this error on python 3.6.
I am going to guess that pygame.mixer.music.load calls the seek method on zippie, which is a ZipExtFile.
From python 3.7 ZipExtFile objects now have a seek method. I think that if you upgrade to python 3.7.2 or newer, then your error should go away.
Try to replace
pygame.mixer.music.load(zora)
with
with BytesIO(zora.read()) as zora_bio:
pygame.mixer.music.load(zora_bio)
This worked for me on python 3.6 with h5py.File().
I'm guessing it's the same problem as with pygame..load().
EDIT:
I now realize the above solution already exists in your code when you LOAD IMAGES:
with ZipFile("spam.zip", 'r') as archive:
mcimg = archive.read('a.png', pwd=b'onlyforthedev')
mc = pygame.image.load(BytesIO(mcimg))
So for uniformity, you could LOAD MUSIC in a similar way:
with ZipFile('spam.zip') as zippie:
zora = zippie.read('zora.mp3', pwd=b'onlyforthedev')
pygame.mixer.music.load(BytesIO(zora))

Last unbuffered line can't be read

I'm trying to read the last line from a command like 'apt-get download firefox'. Normally the output will be like
Get:1 http://archive.ubuntu.com/ubuntu/ utopic/main firefox amd64 32.0+build1-0ubuntu2 [34.9 MB]
2% [1 firefox 646 kB/34.9 MB 2%]
with the last line continuously updating (it is not writing a newline until it reaches 100%). My goal is now to read the progress in realtime. Here is my current example code:
#!/usr/bin/python3 -u
# coding=utf-8
import subprocess, sys
pipe = subprocess.Popen(['apt-get', 'download', 'firefox'], 0, stderr = subprocess.PIPE, stdout = subprocess.PIPE)
while True:
content = pipe.stdout.read(1).decode()
if content == '':
break
sys.stdout.write(content)
sys.stdout.flush()
pipe.wait()
I have disabled the output buffering for the subprocess call and also for binary output for the Python process (with the -u argument). But I'm only getting the first line but not the progress of the second line. Does somebody know how I can achieve this?
If stdout of apt-get is redirected to a pipe e.g.,
$ apt-get download firefox | cat
then it doesn't report progress (the last line e.g., 2% [1 firefox 646 kB/34.9 MB 2%] will not be in the output). stdout=subprocess.PIPE naturally creates a pipe; therefore apt-get doesn't print the download progress in your case.
If you want both to capture apt-get output and to see it on the screen in real-time with the last line (progress report) present then you could use pexpect module to trick the child process into thinking that it runs in a terminal:
import sys
import pexpect # $ pip install pexpect
output, exitstatus = pexpect.runu('apt-get download firefox',
logfile=sys.stdout,
withexitstatus=1)
You could do the same using only stdlib pty module:
#!/usr/bin/env python3
import os
import pty
output = []
def read(fd):
data = os.read(fd, 1024)
output.append(data)
return data
status = pty.spawn(['apt-get', 'download', 'firefox'], read)
#eryksun on Python Issue tracker suggested apt-get's --quiet option:
#!/usr/bin/env python3
import shlex
from io import TextIOWrapper
from subprocess import Popen, PIPE
output = []
with Popen(shlex.split("apt-get --quiet=0 download firefox"),
stdout=PIPE, bufsize=1) as p:
# recognize '\r' as newline but don't convert it to '\n'
for line in TextIOWrapper(p.stdout, newline=''):
print(line, end='', flush=True) # print to terminal
output.append(line) # save for later
print(p.returncode)

Resources