Error in google cloud speech API - python-3.x

I am trying to convert audio to text using Google Cloud Speech API, but I am getting the following error:
Traceback (most recent call last):
File "/home/prateek/Google Drive/projects/linuxAI/src/linuxAI.py", line 6, in <module>
client = speech.SpeechClient()
File "/usr/lib/python3.6/site-packages/google/cloud/gapic/speech/v1/speech_client.py", line 146, in __init__
ssl_credentials=ssl_credentials)
File "/usr/lib/python3.6/site-packages/google/gax/grpc.py", line 106, in create_stub
credentials = _grpc_google_auth.get_default_credentials(scopes)
File "/usr/lib/python3.6/site-packages/google/gax/_grpc_google_auth.py", line 62, in get_default_credentials
credentials, _ = google.auth.default(scopes=scopes)
File "/usr/lib/python3.6/site-packages/google/auth/_default.py", line 283, in default
raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)
google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or
explicitly create credential and re-run the application. For more
information, please see
https://developers.google.com/accounts/docs/application-default-credentials.
I am using this code:
"""Transcribe the given audio file."""
from google.cloud import speech
from google.cloud.speech import enums
from google.cloud.speech import types
client = speech.SpeechClient()
speech_file = "output.wav"
with open(speech_file, 'rb') as audio_file:
content = audio_file.read()
audio = types.RecognitionAudio(content=content)
config = types.RecognitionConfig(
encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=16000,
language_code='en-US')
response = client.recognize(config, audio)
# Each result is for a consecutive portion of the audio. Iterate through
# them to get the transcripts for the entire audio file.
for result in response.results:
# The first alternative is the most likely one for this portion.
print('Transcript: {}'.format(result.alternatives[0].transcript))
I found tutorial from here.

Did you authenticated using credentials?
First you need to create api keys.
https://support.google.com/cloud/answer/6158862?hl=en
Read this tutorial to authenticate.
https://cloud.google.com/speech/docs/auth
You can see some sample applications provided by Google.
https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/speech/cloud-client

Related

Bing Image Search SDK for Python: Getting 'Permission Denied'

I'm trying to use the example program provided by Microsoft here to test out the Bing Image Search Service associated with their Cognitive Service offering on Azure. I type the code in character by character (of course, using my own API key) and I get the below error message when I execute the program:
Traceback (most recent call last):
File "x.py", line 9, in <module>
image_results = client.images.search(query=search_term)
File "/home/rsbrownjr/anaconda3/envs/ibing/lib/python3.6/site-packages/azure/cognitiveservices/search/imagesearch/operations/images_operations.py", line 485, in search
raise models.ErrorResponseException(self._deserialize, response)
azure.cognitiveservices.search.imagesearch.models.error_response_py3.ErrorResponseException: Operation returned an invalid status code 'PermissionDenied'
I know without a doubt that I have the right API key put into the program. I'm on pricing tier S0 pay-as-you-go but I don't have any other options either. This has got to have a simple solution.
from azure.cognitiveservices.search.imagesearch import ImageSearchAPI
from msrest.authentication import CognitiveServicesCredentials
subscription_key = "MY API KEY HERE"
search_term = "canadian rockies"
client = ImageSearchAPI(CognitiveServicesCredentials(subscription_key))
image_results = client.images.search(query=search_term)
if image_results.value:
first_image_result = image_results.value[0]
print("Total number of images returned: {}".format(len(image_results.value)))
print("First image thumbnail url: {}".format(
first_image_result.thumbnail_url))
print("First image content url: {}".format(first_image_result.content_url))
else:
print("No image results returned!")
I just tested the code, the code is fine. So you must provided the wrong API key.
Here is my test key 52c32221ceaa4f388b26a2b85fb79bff. It is a 7 days free trial key. I got it here.

Python - LinkedIn API get profile error

This is for an internal project. My end goal is to get details of my connections. who are in same city as I am.
I am new in using LinkedIn API . I have used code mentioned in answer here to generate the access token. Now I am using below line to get my LinkedIn profile.
application.get_profile(access_token['oauth_token'])
But I am getting below error.
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
application.get_profile(access_token['oauth_token'])
File "C:\Python34\lib\site-packages\python_linkedin-2.0-py3.4.egg\linkedin\linkedin.py", line 189, in get_profile
response = self.make_request('GET', url, params=params, headers=headers)
File "C:\Python34\lib\site-packages\python_linkedin-2.0-py3.4.egg\linkedin\linkedin.py", line 169, in make_request
params.update({'oauth2_access_token': self.authentication.token.access_token})
AttributeError: 'str' object has no attribute 'token'
Can someone please help me?
It is a bit late I guess. But for future reference, this error comes from the fact that you need to call explicitly the token element from the linkedin application.
For instance, to generate the application, you need to enter the following:
from linkedin_v2 import linkedin
application = linkedin.LinkedInApplication(token=access_token['oauth_token'])
From there, you can then call the different function from application (like "application.get_profile()").
BR
I don't think you need to pass the auth token again to get your profile. I am also using the python lib.
application.get_profile()
Should return the basic information for your profile. Then look into using selectors to specify what endpoints you want.

play mp3 without default player

I'm trying play mp3 without default player use, so I want try pyglet, but nothing works
import pyglet
music = pyglet.resource.media('D:/folder/folder/audio.mp3')
music.play()
pyglet.app.run()
I've tried it this way
music = pyglet.resource.media('D:\folder\folder\audio.mp3')
and like this:
music = pyglet.resource.media('D:\\folder\\folder\\audio.mp3')
but have this error
Traceback (most recent call last):
File "C:\Users\User\AppData\Roaming\Python\Python35\site-packages\pyglet\resource.py", line 624, in media
location = self._index[name]
KeyError: 'D:\folder\folder\audio.mp3'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:/PC/PyCharm_project/0_TEMP.py", line 3, in <module>
music = pyglet.resource.media('D:\folder\folder\audio.mp3')
File "C:\Users\User\AppData\Roaming\Python\Python35\site-packages\pyglet\resource.py", line 634, in media
raise ResourceNotFoundException(name)
pyglet.resource.ResourceNotFoundException: Resource "D:\folder\folder\audio.mp3" was not found on the path. Ensure that the filename has the correct captialisation.
It's because of the way you load the resource.
Try this code for instance:
import pyglet
music = pyglet.media.load(r'D:\folder\folder\audio.mp3')
music.play()
pyglet.app.run()
The way this works is that it loads a file and places it in a pyglet.resource.media container. Due to namespaces and other things, the code you wrote is only allowed to load resources from the working directory. So instead, you use pyglet.media.load which is able to load the resource you need into the current namespace (Note: I might be missusing the word "namespace" here, for lack of a better term without looking at the source code of pyglet, this is the best description I could come up with).
You could experiment by placing the .mp3 in the script folder and run your code again but with a relative path:
import pyglet
music = pyglet.resource.media('audio.mp3')
music.play()
pyglet.app.run()
But I'd strongly suggest you use pyglet.media.load() and have a look at the documentation

Pywinauto and Installshield

My application is packaged using InstallShield. The first thing that happens when you execute the exe is that IS extracts the msi file; this takes about 10 seconds.
I can't look for my main window until the msi extraction is done, so I use time.sleep. Then I look for and find the handle of my window. But the call to app.window_(handle=1234).Wait("enabled", timeout=25, retry_interval=0.5) blows up with these error messages.
*C:\python32>python test.py
| [2558122] |
Traceback (most recent call last):
File "test.py", line 16, in <module>
dlg = app.Window_(handle=hwnd).Wait("enabled", timeout=25, retry_interval=0.
5)
File "C:\python32\lib\site-packages\pywinauto\application.py", line 380, in Wa
it
WaitUntil(timeout, retry_interval, lambda: self.__check_all_conditions(check
_method_names))
File "C:\python32\lib\site-packages\pywinauto\timings.py", line 292, in WaitUn
til
func_val = func(*args)
File "C:\python32\lib\site-packages\pywinauto\application.py", line 380, in <l
ambda>
WaitUntil(timeout, retry_interval, lambda: self.__check_all_conditions(check
_method_names))
File "C:\python32\lib\site-packages\pywinauto\application.py", line 337, in __
check_all_conditions
check = getattr(self, check_name)
File "C:\python32\lib\site-packages\pywinauto\application.py", line 252, in __
getattr__
ctrls = _resolve_control(self.criteria)
File "C:\python32\lib\site-packages\pywinauto\application.py", line 755, in _r
esolve_control
criteria)
File "C:\python32\lib\site-packages\pywinauto\timings.py", line 356, in WaitUn
tilPasses
func_val = func(*args)
File "C:\python32\lib\site-packages\pywinauto\application.py", line 522, in _g
et_ctrl
findwindows.find_window(**criteria[0]))
File "C:\python32\lib\site-packages\pywinauto\controls\HwndWrapper.py", line 1
80, in __new__
new_class = cls.FindWrapper(handle)
File "C:\python32\lib\site-packages\pywinauto\controls\HwndWrapper.py", line 1
12, in FindWrapper
class_name = handleprops.classname(handle)
File "C:\python32\lib\site-packages\pywinauto\handleprops.py", line 94, in cla
ssname
win32functions.GetClassName (handle, ctypes.byref(class_name), 256)
ctypes.ArgumentError: argument 1: <class 'TypeError'>: Don't know how to convert
parameter 1*
This is the code. I am an experienced programmer but a Python newbie. I have worked on this all day, googled my brains out, and have tried everything I can think of. Thanks in advance.
from pywinauto import application
from pywinauto import findwindows
app = application.Application()
app.start("MyInstallShieldApp.exe")
time.sleep(15)
hwnd=findwindows.find_windows(title=u"InstallShield Wizard", class_name="MsiDialogCloseClass")
print ("|", str(hwnd), "|")
dlg = app.Window_(handle=hwnd).Wait("enabled", timeout=25, retry_interval=0.5)
The problem in hwnd, it is a list, but handle=hwnd requires an int.
You should use find_window instead of find_windows or use only the first handle from hwnd, e.g.
hwnd = findwindows.find_windows(...
dlg = app.Window_(handle=hwnd[0])...
Also it may be useful for you to use SWAPY - UI inspector & code generator for pywinauto.
This question is a year old, but hopefully this will help anyone else in the same position. I initially had something similar to OP and was completely lost because I figured it would be as simple as the 7zip installation example provided in the pywinauto github repo. What I found, however, is that the actual installation opens up in a second process, defeating the point of opening the application with Application().start() to launch and hook onto the program simultaneously.
What I did was I used the Inspect program from the Windows SDK to locate the names of the elements and the window that held them once InstallShield was done extracting the .msi file. Instead of opening the InstallShield executable with start(), I used the subprocess module's popen() function to open the installer and then used Application().connect() to hook into the installer once it was extracted via InstallShield. Below is a rough version of what I did to get this functional, mixing my findings with the examples, documentation, and the OP:
import time
import subprocess
from pywinauto import application
# Open the module via Popen
# I tried using run() first but that prevented the click for reasons unknown
subprocess.Popen(r"C:\Users\fixer446\My Documents\InstallationFiles\Setup.exe")
# Let InstallShield extract the files and the installer load completely
time.sleep(15)
# Hook onto the newly opened setup window
app = application.Application().connect(title="Setup.WindowName", class_name="MsiDialogCloseClass")
# Work with the window and the controls within as advertised in pywinauto
# You may have to play around with this a little
installer = app["Setup.WindowName"]
installer["Next >"].Wait("enabled")
installer["Next >"].Click()
Hope this helps.
app.Window_(...) can take the same arguments as find_windows(...). Yeah, it's not highlighted in the docs now. But the code might be shorter:
from pywinauto import application
from pywinauto import findwindows
app = application.Application()
app.start("MyInstallShieldApp.exe")
# the dialog may not exist yet here
dlg_spec = app.Window_(title=u"InstallShield Wizard", class_name="MsiDialogCloseClass")
# after this line the dialog exists or exception is raised
dlg = dlg_spec.Wait("enabled", timeout=25, retry_interval=0.5)
# dlg is a DialogWrapper object (for really existing dialog)
You may read more detailed description of 2-level WindowSpecification concept in this answer.
I will move it into the docs with coming pywinauto 0.6.0 (a bit later).

Pyro4, receiving: not enough data

I'm trying to run a function on the server with Pyro4.
Have a look at the code:
==========================Client======================
import Pyro4
def square(x):
return x**2
remoteServer = Pyro4.Proxy('PYRONAME:server')
print(remoteServer.evaluate(square, 4))
===========================Server==========================
import Pyro4
class Server(object):
def evaluate(self, func, args):
return func(*args)
def main():
server = Server()
Pyro4.Daemon.serveSimple({server: "server"},ns=True)
if __name__ == '__main__':
main()
========================Naming Server========================
import Pyro4
Pyro4.naming.startNSloop()
===========================================================
And got an error: "Pyro4.errors.ConnectionClosedError: receiving: not enough data". Look at the full stack trace below:
Traceback (most recent call last):
File "C:\Users\Alex\Desktop\2.py", line 9, in <module>
print(remoteServer.evaluate(square, 4))
File "C:\Users\Alex\AppData\Roaming\Python\Python34\site-packages\Pyro4\core.py", line 169, in __call__
return self.__send(self.__name, args, kwargs)
File "C:\Users\Alex\AppData\Roaming\Python\Python34\site-packages\Pyro4\core.py", line 380, in _pyroInvoke
msg = message.Message.recv(self._pyroConnection, [message.MSG_RESULT], hmac_key=self._pyroHmacKey)
File "C:\Users\Alex\AppData\Roaming\Python\Python34\site-packages\Pyro4\message.py", line 161, in recv
msg = cls.from_header(connection.recv(cls.header_size))
File "C:\Users\Alex\AppData\Roaming\Python\Python34\site-packages\Pyro4\socketutil.py", line 460, in recv
return receiveData(self.sock, size)
File "C:\Users\Alex\AppData\Roaming\Python\Python34\site-packages\Pyro4\socketutil.py", line 195, in receiveData
raise err
Pyro4.errors.ConnectionClosedError: receiving: not enough data
I want the server executes the function that is passed to a method (function).
PS: Windows7, Python 3.4.1
I've found similar question (How to send a function to a remote Pyro object), but didn't work for me.
Tried to use callback decorator #pyro4.callback, but even official example (https://github.com/delmic/Pyro4/tree/master/examples/callback : server2.py, client2.py) didn't work (with python 3.4 and python 2.7) => only message: "server: doing callback 1 to client" is showed and nothing happens.
Thanks
The github repo you're linking to is not the official one. It's a clone (from quite an old version). This is the official repo: https://github.com/irmen/Pyro4
As to your problem: it is not possible to serialize functions and send them over the wire. If you tell Pyro to use pickle as a serialization protocol, you can do more tricks, but pickle still needs to have the module source or bytecodes available on both sides of the connetion.
The reason your client crashes is because the server aborts the connection due to a Pyro protocol error. If you enable the logging it will show up in the server's logfile, something like: "Pyro4.errors.ProtocolError: unsupported serialized class: builtins.function".
Also a tip: you don't have to start the name server using a separate source code file. You can start it directly from the command line.
Lastly, the #pyro4.callback decorator is unrelated, please read http://pythonhosted.org/Pyro4/clientcode.html?highlight=callback#pyro-callbacks for what it is intended for. It influences the way Pyro handles exceptions, nothing more.
edit: note that since Pyro 4.35 this error will be correctly reported back to the client and it will no longer get an aborted connection.

Resources