plyer stt encounter error on huawei device - python

I am trying to implement a kivy app which include the plyer.stt module, but it return error on stt.start() and return empty list
When I compile it, I made sure to give all all the permission needed (INTERNET,RECORD_AUDIO,FOREGROUND_SERVICE), I also made sure to allow microphone permission.
When I call stt.start(), I did not hear any 'beep' sound, I instead an error:
File "jnius/jnius_utils.pxi", line 91, in jnius.jnius.check_exception 10-31 22:13:49.969 28130 28130 I python : jnius.jnius.JavaException: JVM exception occurred: Not allowed to bind to service Intent { act=android.speech.RecognitionService cmp=com.huawei.vassistant/.voiceui.service.FakeRecognitionService } java.lang.SecurityException
and stt.result return me an empty list.
Can someone enlighten me on what is the reason that this happen and how can I bypass it?
Here are some snippets of my functions
Code:
def listen(self):
print(stt.exist())
if stt.listening:
self.stop_listening()
return
#Change button text
start_button = self.ids.start_button
start_button.text = 'Stop'
stt.start()
Clock.schedule_interval(self.check_state, 1 / 5)
def stop_listening(self):
start_button = self.ids.start_button
start_button.text = 'Start Listening'
stt.stop()
self.update()
Clock.unschedule(self.check_state)
def update(self):
#Display the result to a label on screen
app.root.append(str(stt.partial_results))
app.root.append(str(stt.results))
It seems that I get the error after executing stt.start()

Related

Calling a Ptoaster function within a Tkinter GUI class

The Problem
I'm working on a Python GUI, using Tkinter. I'm also trying to add "toaster" messages, using Ptoaster. Here's an example of what I'm trying to achieve:
from tkinter import *
import ptoaster
PADDING = 20
class MyInterface:
def __init__(self):
self.root = Tk()
self.label = self.make_label()
print_welcome()
def make_label(self):
result = Label(self.root, text="Hello, world!")
result.pack(padx=PADDING, pady=PADDING)
return result
def run_me(self):
self.root.mainloop()
def print_welcome():
message = "Hello again!"
ptoaster.notify("Hello!", message)
interface = MyInterface()
interface.run_me()
If I try to run the above code, one of two things will happen:
The command line will spit out the following error:
[xcb] Unknown sequence number while processing queue
[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
[xcb] Aborting, sorry about that.
python3: ../../src/xcb_io.c:260: poll_for_event: Assertion `!xcb_xlib_threads_sequence_lost' failed.
XIO: fatal IO error 25 (Inappropriate ioctl for device) on X server ":0"
after 207 requests (207 known processed) with 2 events remaining.
Aborted (core dumped)
My whole laptop will freeze, necessitating a hard reset.
However, if I move the call print_welcome() from outside of MyInterface, so that it's called before this class is initialised, then none of the above errors crop up.
What I'd Like to Know
How to call a function, from within a Tkinter GUI class, which causes a "toaster" message to be displayed, without causing the whole platform to crash.
Why the above errors are cropping up.
Documentation states it needs to be verified that the ptoaster.notify is called from the main program.
IMPORTANT - you need to make sure you call notify from the main program
Working code for me:
from tkinter import *
import ptoaster
PADDING = 20
class MyInterface:
def __init__(self):
self.root = Tk()
self.label = self.make_label()
print_welcome()
def make_label(self):
result = Label(self.root, text="Hello, world!")
result.pack(padx=PADDING, pady=PADDING)
return result
def run_me(self):
self.root.mainloop()
def print_welcome():
message = "Hello again!"
ptoaster.notify("Hello!", message)
if __name__ == '__main__':
interface = MyInterface()
interface.run_me()
Documentation (See: Sample Program)

Pywinauto unable to find/close pop-up window

Source code
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
if is_admin():
app = Application(backend='uia').start("C:\\Program Files (x86)\\Advantech\\AdamApax.NET Utility\\Program\\AdamNET.exe")
win = app['Advantech Adam/Apax .NET Utility (Win32) Version 2.05.11 (B19)']
win.wait('ready')
win.menu_select("Setup->Refresh Serial and Ethernet")
win.top_window().print_control_identifiers(filename="file.txt")
# win.top_window().OKButton.click_input() ---------This is what I hope to do
else
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
Problem Statement
I had to run this application with elevation rights. The above is my code. The problem is I can't identify the window (view in output image) that pops up after selection from menu. I need to close the window. Please excuse the line
win.top_window().print_control_identifiers(filename="file.txt")
It was meant write the identifiers into a text file because the structure of this code does not display the outputs for me to view. However, since nothing is appended, I guess pywinauto couldn't identify the dialog.
For a clearer understanding, please view the image (input) of when it selects the menu.
Input
Now, it pops up with this dialog (output)
Output
I've also used spy to identify the caption and it gives:
(Handle: 004E07D4,
Caption: Information,
Class: #32770(Dialog),
Style: 94C801C5)
Other things I've tried:
Besides using win.topwindow() to identify the dialog, I've used
win[Information].OKButton.click_input()
win[Information].OK.click_input()
win[Information].OK.close()
win[Information].OK.kill(soft=false)
win.Information.OKButton.click_input()
win.Information.OK.click_input()
win.Information.OK.close()
win.Information.OK.kill(soft=false)
app[Information] ...... curious if I could discover the new window from original application
I've also send keys like enter, space, esc & alt-f4 to close the dialog with libraries like keyboard, pynput & ctypes. It still doesn't work.
Link to download the same application: http://downloadt.advantech.com/download/downloadsr.aspx?File_Id=1-1NHAMZX
Any help would be greatly appreciated !
I finally found a thread that demonstrated the way multi thread works to solve this issue. I tried it myself and it works. It's a little different as a few parts of the code have depreciated. Here is the link to the solution:
How to stop a warning dialog from halting execution of a Python program that's controlling it?
Here are the edits I made to solve the problem:
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
if is_admin():
def __init__(self, window_name, quit_event):
threading.Thread.__init__(self)
self.quit_event = quit_event
self.window_name = window_name
def run(self):
while True:
try:
handles = windows.find_windows(title=self.window_name)
except windows.WindowNotFoundError:
pass
else:
for hwnd in handles:
app = Application()
app.connect(handle=hwnd)
popup = app[self.window_name]
popup.close()
if self.quit_event.is_set():
break
time.sleep(1)
quit_event = threading.Event()
mythread = ClearPopupThread('Information', quit_event)
mythread.start()
application = Application(backend="uia").start("C:\\Program Files (x86)\\Advantech\\AdamApax.NET Utility\\Program\\AdamNET.exe")
time.sleep(2)
win = application['Advantech Adam/Apax .NET Utility (Win32) Version 2.05.11 (B19)']
win.menu_select("Setup->Refresh Serial and Ethernet")
quit_event.set()
else:
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
The best thing is this solution works for every other dialog that halts the main script from working & I could use them to do different actions like clicking buttons, inserting values, by adding more multi threads.

How to call "process" function using ALAudioDevice "subscribe" method

I'm new at NAO programming and I'm having some trouble regarding the ALAudioDevice API.
My problem is the following one: I wrote a python module that should record raw data from the front microphone.
The documentation of the ALAudioDevice API says that the method "subscribe(...)" calls the function "process" automatically
and regularly with raw data from microphones as inputs. I wrote a code to execute this process (see bellow), and it runs without raising
the error flag. However, the subscribe is bypassing the function "process" and the module doesn't get any audio at all.
Has someone had the same problem?
import qi
class AudioModule(object):
def __init__(self):
super(AudioModule, self).__init__()
self.moduleName = "AudioModule"
try :
self.ALAudioDevice = ALProxy("ALAudioDevice")
except Exception, e:
self.logger.error("Error when creating proxy on ALAudioDevice:")
self.logger.error(e)
def begin_stream(self):
self.ALAudioDevice.setClientPreferences(self.moduleName, 16000, 3, 0)
self.ALAudioDevice.subscribe(self.moduleName)
def end_stream(self):
self.ALAudioDevice.unsubscribe(self.moduleName)
def processRemote( self, nbOfChannels, samplesByChannel, altimestamp, buffer ):
nbOfChannels = nbOfChannels
mylogger = qi.Logger("data")
mylogger.info("It works !" + str(nbOfChannels))
class MyClass(GeneratedClass):
def __init__(self):
GeneratedClass.__init__(self, False)
self.audio = AudioModule()
def onLoad(self):
self.serviceId = self.session().registerService("AudioModule", self.audio)
pass
def onUnload(self):
if self.serviceId != -1:
self.session().unregisterService(self.serviceId)
self.serviceId = -1
pass
def onInput_onStart(self):
self.audio.begin_stream()
self.onInput_onStop()
pass
def onInput_onStop(self):
self.audio.end_stream()
self.onUnload
self.onStopped()
pass
It appears you are subscribing to the audio from a Choregraphe box. I'm not sure it is supposed to work.
But in this configuration the Python code is executed from within the same process as the ALAudioDevice service. So probably you should name your callback "process" instead of "processRemote".
Otherwise, you can still do this from a separate Python script.

PyQt: mainWindow closed, but process still running

I'm writing a Python application with PyQt 5.10.It seems I have some sort of bug/memory leak, since when I call close() on my MainWindow the process keeps running. After a bit of research and debugging I was able to circumscribe the supposedly faulty code.This is my main:
if __name__ == '__main__':
app = QApplication(sys.argv)
matteo = God()
matteo.runApp()
sys.exit(app.exec())
Here you will find the runApp function from God class:
def runApp(self):
self.painter = Painter()
self.dbManager = DBManager()
self.userInput = UserInput()
self.excelFile = ExcelFile()
self.painter.connectToClasses(self, ["god","db","ui"])
self.excelFile.connectToClasses(self, ["god",])
self.painter.drawMainWindow()
self.loadConf()
self.openDB(True)
if self.dbManager.error==None:
self.painter.drawSearchWidget()
else:
print("Closed.")
The process keeps running when the app is not able to find the configuration file, and so it creates a new one from scratch and it asks the user to select the database which he wants to connect to. This prompts an error message - if the selected file is corrupted or it's not the right format - and I think there might lie my problem.That's the code:
def checkError(self, classType):
if classType=="db":
error = self.dbManager.error
elif classType=="excel":
error = self.excelFile.error
if error!=None:
self.painter.drawError(classType)
self.userInput.error = self.painter.error.clickedButton()
self.userInput.error = self.painter.error.buttonRole(self.userInput.error)
if (self.userInput.error==1):
self.painter.mainWindow.close()
return 0
return 1
def drawError(self, classType):
if (classType=="db"):
title = "Database"
error = self.dbManager.error
otherButton = "Browse"
elif (classType=="excel"):
title = "Excel file"
error = self.excelFile.error
try:
self.setErrorText(False, error)
if error[0]:
if self.error.icon()!=3:
self.error.setIcon(3)
buttons = self.error.buttons()
for button in buttons:
if button.text()!="Quit":
button.hide()
button.deleteLater()
except AttributeError:
self.error = QMessageBox()
self.setErrorText(True, error)
if (error[0]):
self.error.setIcon(3)
else:
self.error.setIcon(2)
self.error.addButton(otherButton, self.error.AcceptRole)
self.error.addButton("Quit", self.error.RejectRole)
self.error.setWindowTitle(title)
self.error.exec()
If the user clicks the quit button on the error window, the function closes main window and return 0. The other functions return and the application prints closed on the console. But the process keeps going.
I kind of resolved this issue calling sys.exit() instead of printing closed.
It's a brute force solution to say the least, but I needed to deliver the application fast and I had no time to debug it.I guess this sad story will end here.

error while binding functions to buttons in a loop

I am using kivy to make a small music player but i have some issues with it. I am using a screen manager which will direct the user to either his libraries, or the entire tracks list. When one of the two is selected i want to find and load all the titles as buttons, to be played when pressed. Here's the basic track class:
class Track(Button):
path = 'C:/Users/...../tracks/'
def __init__(self,title,**kwargs):
self.title = title
super(Track,self).__init__(text=self.title,**kwargs)
def playTrack(self):
self.sound = SoundLoader.load(self.path+self.title)
self.sound.play()
also here is a music class that finds all the tracks in the directory and adds them to a list:
class mymusic():
path = 'C:/Users/...../tracks'
def __init__(self,**kwargs):
self.tracks=os.listdir(self.path)
print self.tracks
def loadTracks(self):
trackslist = []
for i in self.tracks:
trackslist.append(Track(i))
return trackslist
Finally, here is the code i use, that is supposed to create the buttons (the sm below is the screen manager, and root,libraries and music are subclasses of screen):
f = lambda obj: obj.playTrack()
Music = music(name='Music')
layout = BoxLayout()
Music.add_widget(layout)
sm.add_widget(root(name='Root'))
sm.add_widget(libraries(name='My libaries'))
sm.add_widget(Music)
musicobj = mymusic()
tracklist = musicobj.loadTracks()
for i in tracklist:
print i
i.bind(on_press=f(i))
This does not work. By running it i get the following error:
Traceback (most recent call last):
File "C:\Users\Vlassis\Desktop\test.py", line 108, in <module>
i.bind(on_press=f(i))
File "kivy\_event.pyx", line 430, in kivy._event.EventDispatcher.bind (kivy\_event.c:5903)
AssertionError: None is not callable
also the last track in the directory plays in the background. I can't figure out why. Is the logic behind the code correct? How should i go about doing this? Thanks in advance.

Categories

Resources