I am trying to use IBM watson api for text to speech service. The service works if I use curl command but when I try to use the srrvice using Python SDK, It throws me below error.
Traceback (most recent call last):
File "/anaconda3/lib/python3.6/site-packages/ibm_cloud_sdk_core/base_service.py", line 234, in send
response.status_code, error_message, http_response=response)
ibm_cloud_sdk_core.api_exception.ApiException: Error: Forbidden, Code: 403
Method failed with status code 403: Forbidden
Below is the curl command
curl -X GET -u "apikey:myapiKey" --output hello_world.wav "https://api.eu-de.text-to-speech.watson.cloud.ibm.com/text-to-speech/api/v1/synthesize?accept=audio/wav&text=Hallo%20Welt&voice=de-DE_DieterVoice"
Below is the python code
from ibm_watson import TextToSpeechV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_watson import ApiException
import json
IBM_API_ENDPOINT = "https://api.eu-de.text-to-speech.watson.cloud.ibm.com/text-to-speech/api/v1/synthesize"
IBM_TTS_API_KEY = "myAPIKey"
authenticator = IAMAuthenticator(IBM_TTS_API_KEY)
text_to_speech = TextToSpeechV1(authenticator=authenticator)
text_to_speech.set_service_url(IBM_API_ENDPOINT)
try:
with open('IBM.wav', 'wb') as audio_file:
audio_file.write(text_to_speech.synthesize("Hallo world", voice='de-DE_DieterVoice', accept='audio/wav').get_result().content)
except ApiException as ex:
print("Method failed with status code " + str(ex.code) + ": " + ex.message)
Check the Current usage ( of 10000 Thousand char). I had the same issue when I reached the maximum limit of characters per month.
( Thousand char: Using 21091 of 10000)
This will because you are are tacking the method and the version at the end of the endpoint. As you are using the Python SDK for IBM-Watson the SDK take care of applying the method when you invoke synthesize. Consequently your endpoint should only be:
IBM_API_ENDPOINT = "https://api.eu-de.text-to-speech.watson.cloud.ibm.com"
Check the API documentation for further details - https://cloud.ibm.com/apidocs/text-to-speech/text-to-speech?code=python#service-endpoint
Related
I want to start a notebook server on my Jupyter Hub as described here and to get started, even the basic command that I am following is not working. I want to make a normal request using my token as mentioned here.
My code is:
import requests
token = "aa36d53a8cb5473a9e7ee07b1f3d8a49"
api_url = 'http://<some_no>.ap-south-1.elb.amazonaws.com/hub/api'
r = requests.get(api_url + '/users', headers={ 'Authorization': 'token %s' % token, } )
r.raise_for_status()
I, then, face an error, traceback of which is:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.7/site-packages/requests/models.py", line 940, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: http://<some_no>.ap-south-1.elb.amazonaws.com/hub/api/users
Note: I have generated the token as described in the official doc. I also added the same in my config.yaml file that Jupyter Hub states every now and then.
I am unable to figure out the correct way in such ill-mannered documentation.
Maybe there is a problem with your instance firewall configuration? Do you enable HTTP/HTTPS traffic?
To check if api is working, you can use endpoint which dont need authentication: http://<some-ip>/hup/api it should return the JupyterHub version.
I am a OpenStack noob here.
I try to use REST API to automate my openstack work. I can successfully authenticate my account and get token from curl with below command:
export AUTH_URL="https://my_url:5000/v2.0/tokens"
curl -v -X POST $AUTH_URL -d '{"auth":{"passwordCredentials":{"username": "myusername", "password":"myuser_password"}, "tenantId":"my_tenant_id"}}' -H 'Content-type: application/json' | python -m json.tool
But, when I try to use Pyton, with this code, it gave me this error:
Traceback (most recent call last):
File "./test.py", line 10, in <module>
keystone = ksclient.Client(auth_url=auth_url, username=user_name, password=user_pwd, tenant_name=tenant_name)
File "/usr/lib/python2.7/site-packages/keystoneclient/v2_0/client.py", line 176, in __init__
self.authenticate()
File "/usr/lib/python2.7/site-packages/positional/__init__.py", line 101, in inner
return wrapped(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/keystoneclient/httpclient.py", line 581, in authenticate
resp = self.get_raw_token_from_identity_service(**kwargs)
File "/usr/lib/python2.7/site-packages/keystoneclient/v2_0/client.py", line 220, in get_raw_token_from_identity_service
_("Authorization Failed: %s") % e)
keystoneauth1.exceptions.auth.AuthorizationFailure: Authorization Failed: The resource could not be found. (HTTP 404) (Request-ID:
My python code is below:
#!/usr/bin/env python
import keystoneclient.v2_0.client as ksclient
auth_url = "https://my_url:5000/v2.0/tokens"
user_name = "myusername"
user_pwd = "myuser_password"
tenant_name = "my_tenant_id"
keystone = ksclient.Client(auth_url=auth_url, username=user_name, password=user_pwd, tenant_name=tenant_name)
print keystone.auth_token
Can you please take a look at my code and see why the python code does not work?
Thanks!
You should only provide https://my_url:5000/v2.0 as the path when authenticating using the client.
See this documentation for more information.
You could also try something like this.
from keystoneauth1 import loading
from keystoneauth1 import session
from keystoneclient import client as keystoneclient
auth_url = 'https://my_url:5000'
user = '<user>'
password = '<password>'
tenant = '<tenant>'
loader = loading.get_plugin_loader('password')
keystone_auth = \
loader.load_from_options(
auth_url=auth_url,
username=user,
password=password,
user_domain_name=tenant
)
keystone_session = session.Session(
auth=keystone_auth,
verify=False
)
print(keystone_session.get_token())
Keep in mind that the Keystone V2 API has been deprecated, and removed in the latest versions of Openstack. If possible I would recommend moving over to the V3 API as soon as possible.
I am trying to get the exception code from Twitter API (using twython), but it returns an HTTP error code instead.
Here you can see the codes from twitter API.
For example:
try:
twitter.retweet(id=tweet["id"])
except TwythonError as e:
print("FAILED to retweet: [tweet_id:" + str(tweet["id"]) + "]")
print(e.error_code)
The following prints HTTP error code instead of twitter API code
print(e.error_code)
For example instead of API error code 261 or 271, 272,... it prints HTTP error 403 (Forbidden).
This is a problem because I cannot distinguish between codes that share the same HTTP error code.
If you print out all of e with print(e), you will get additional information.
I'm having a problem getting a picture in facebook.
I'm using python plus facebook graph api. I research getting or how to download a picture in facebook so here's what i got.
import os
import json
import urllib
import pprint
ACCESS_TOKEN = 'ACCESS_TOKEN_SAMPLE'
host = "https://graph.facebook.com/v2.8"
path = "/me?fields=id,name,picture"
params = urllib.urlencode({"access_token": ACCESS_TOKEN})
url = "{host}{path}?{params}".format(host=host, path=path, params=params)
resp = urllib.urlopen(url).read()
getDATA = json.loads(resp)
os.system("echo " + str(getDATA) | tee >log.txt)
I tried to understand it but I'm having an error running this. Here's the error i got:
{uerror: {umessage: uAn active access token must be used to query information about the current user., ucode: 2500, utype: uOAuthException, ufbtrace_id: uGLoKMknFrR1}}
Also I'm trying to put the downloaded data to a log file. I need an output which has like a downloading progress or bar? Like when you run a speedtest in a terminal it shows the size of the data that it downloads.
This code now works.
I'm having an issue inserting a new blog post on to google's Blogger site via python2.7 calling an API.
I have all the oauth2client modules from google to handle the authentication.
I have permission to use the Blogger V3 api - this is activated on the google developer console.
I have run simple api requests with the same credentials.dat that have worked:
this worked (full code not included)
service = build('blogger','v3', http=http)
try:
request = service.blogs().get(blogId="6814573853229626501")
response = request.execute()
print response
The google api discovery service leads me to believe this is what the code should look like to insert a post
https://developers.google.com/apis-explorer/#p/blogger/v3/blogger.posts.insert
service = build('blogger','v3', http=http)
try:
body = {
"kind": "blogger#post",
"id": "6814573853229626501",
"title": "posted via python",
"content":"<div>hello world test</div>"
}
request = service.posts().insert(blogId="6814573853229626501",body=body)
response = request.execute()
print response
I'm sure it's the body=body part that I'm messing up? Any clues?
here is the error that I get:
Traceback (most recent call last):
File "blogger.py", line 104, in <module>
main()
File "blogger.py", line 93, in main
response = request.execute()
File "/usr/local/lib/python2.7/dist-packages/google_api_python_client-1.0c2-py2.7.egg/apiclient/http.py", line 654, in execute
raise HttpError(resp, content, self.uri)
apiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/blogger/v3/blogs/6814573853229626501/posts?alt=json returned "Invalid Value">
If you're interested I'm experimenting with posting charts from my google fusion tables generated by eBay data that i'm interested in at the time.
You can post on any blogger somehow
__author__ = 'spandey2405#gmail.com (Saurabh Pandey)'
import sys
from oauth2client import client
from googleapiclient import sample_tools
# Authenticate and construct service.
service, flags = sample_tools.init(
argv, 'blogger', 'v3', __doc__, __file__,
scope='https://www.googleapis.com/auth/blogger')
try:
users = service.users()
# Retrieve this user's profile information
thisuser = users.get(userId='self').execute()
print('This user\'s display name is: %s' % thisuser['displayName'])
blogs = service.blogs()
# Retrieve the list of Blogs this user has write privileges on
thisusersblogs = blogs.listByUser(userId='self').execute()
for blog in thisusersblogs['items']:
print('The blog named \'%s\' is at: %s' % (blog['name'], blog['url']))
posts = service.posts()
body = {
"kind": "blogger#post",
"id": "6701167141462934671",
"title": "posted via python",
"content":"<div>hello world test</div>"
}
insert = posts.insert(blogId='6701167141462934671', body=body)
posts_doc = insert.execute()
print posts_doc
except client.AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run'
'the application to re-authorize')
You do not need the "data": object wrapper around your data, the client library will add that if the server needs it. This documentation shows the form of the object to use in the insert call:
https://google-api-client-libraries.appspot.com/documentation/blogger/v3/python/latest/blogger_v3.posts.html#insert