I'm trying to use the watson developer cloud python library to interface with the IBM Speech to Text API in an effort to detect which phonemes or syllables exist in some text. But I'm running into some issues relating to a required parameter called customization_id, and I'm hoping someone might be able to provide more context on what value to pass in. I wasn't able to understand after reading the docs. Here is a code snippet:
from watson_developer_cloud import TextToSpeechV1, WatsonApiException
API_KEY = "<redacted>"
URL = "https://gateway-wdc.watsonplatform.net/text-to-speech/api"
client = TextToSpeechV1(iam_apikey=API_KEY, url=URL)
try:
#response = client.get_word(customization_id="1", word="HELLO WORLD")
#> Malformed GUID: '1'
#response = client.get_word(word="HELLO WORLD")
#> get_word() missing 1 required positional argument: 'customization_id'
#response = client.get_word(customization_id=None, word="HELLO WORLD")
#> ValueError: customization_id must be provided
#response = client.get_word(customization_id="GA", word="HELLO WORLD")
#> ERROR 400: Malformed GUID: 'GA'
# WHAT VALUE TO USE FOR CUSTOMIZATION_ID ??? ...
response = client.get_word(customization_id="_______", word="HELLO WORLD") #>
print("RESPONSE")
print(type(response))
except WatsonApiException as ex:
print(f"ERROR {str(ex.code)}: {ex.message}")
EDIT: It is possible the expected value is the identifier of a new custom voice model. I've started investigating that strategy here, but unfortunately I'm also running into issues on that one as well. The approach might be something like:
# ...
voice_model_response = client.create_voice_model(
name="My Custom Model",
language=LANG,
description="to get a valid 'customization_id' value..."
).get_result()
customization_id = voice_model_response["customization_id"]
response = client.get_word(customization_id=customization_id, word="HELLO WORLD")
# ...
I think you have misread the documentation for the Speech to Text service.
You can create a customisation to modify how a corpus uses pronunciation to detect words
https://cloud.ibm.com/apidocs/speech-to-text?code=python#add-custom-words
But to do that you need to create a customisation, which you can’t do with a lite account.
https://cloud.ibm.com/apidocs/speech-to-text?code=python#create-a-custom-language-model
You can use the API to list which customisations you have already created.
https://cloud.ibm.com/apidocs/speech-to-text?code=python#list-custom-language-models
It turns out I was using the wrong URL and wrong API Key. After fixing the URL to really be "https://gateway-wdc.watsonplatform.net/text-to-speech/api" and creating and upgrading a new standard-level text to speech service and using that service's API Key, I was able to implement the two-step process I mentioned in the updated part of my question.
Related
I'm a code newbie so please be kind :) I've got my google credentials set and I've checked the documentation for the python library for artifact registry (v1), but clearly doing something daft, as I'm receiving this response back - google.api_core.exceptions.InvalidArgument: 400 Request contains an invalid argument.
Here's my code:
from google.cloud import artifactregistry_v1
# Using Application Default Credentails is easiest
# export GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json
client = artifactregistry_v1.ArtifactRegistryClient()
# Best obtained from the environment
project = "**REDACTED**"
location = "europe-west2"
repository = "test"
parent = f"projects/{project}/locations/{location}/repositories/{repository}"
request = artifactregistry_v1.ListTagsRequest(parent=parent)
page_result = client.list_tags(request=request)
for response in page_result:
print(response)
Here's the official docs, I can't work out what I've done wrong: https://cloud.google.com/python/docs/reference/artifactregistry/latest/google.cloud.artifactregistry_v1.services.artifact_registry.ArtifactRegistryClient#google_cloud_artifactregistry_v1_services_artifact_registry_ArtifactRegistryClient_list_tags
EDIT
Just seen on the Google docs for the Class ListTagsRequest (here) it says parent expects a string (which is what i've done), but noticed in PyCharm it's highlighted and telling me expected type 'Dict', and got 'str' instead....
I was finally able to find the correct code :
from google.cloud import artifactregistry_v1
def get_package_tags_from_artifact_registry():
# Using Application Default Credentails is easiest
# export GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json
client = artifactregistry_v1.ArtifactRegistryClient()
# Best obtained from the environment
project = "{project_id}"
location = "{location}"
repository = "{repository}"
package_name = "{package_name}"
parent = f"projects/{project}/locations/{location}/repositories/{repository}/packages/{package_name}"
request = artifactregistry_v1.ListTagsRequest(
parent=parent
)
page_result = client.list_tags(
request=request
)
for response in page_result:
print(response)
return page_result
if __name__ == '__main__':
result = get_package_tags_from_artifact_registry()
I checked from this doc and tested with a parent path including the package name.
I'm trying to utilize pygci to pull voting district data for a particular address. I've enabled the Google Civic Information API for the listed key, but all I'm getting is
"Response was not valid Json"
when I try to run this code:
*from pygci import GCivicInfo, GCivicInfoError
API_KEY = 'AIzaSyA1EBhUzaHBaaFB8H7LiWfVQsf0KnuwRSs'
address = "4935 Spruce St. Philadelphia, PA 19139"
CivicInfo = GCivicInfo(api_key=API_KEY)
try:
CivicInfo.get_representative_by_address(params=address)
except GCivicInfoError as e:
print(e)*
Looking at the docs for the underlying API, it ultimately needs the address to have the keyword "address" encoded as a URL parameter:
GET https://civicinfo.googleapis.com/civicinfo/v2/representatives?address=4935%20Spruce%20St.%20Philadelphia%2C%20PA%2019139&key=your_api_key
With the requests library, you encode parameters into the URL this way by passing it a dict. So I was going to suggest you try:
CivicInfo.get_representative_by_address(params={"address": address})
But looking at pygci, it appears get_representative_by_address overwrites params with ''. If you still get an error, there's may be a bug in the library, or I've misunderstood its code.
https://github.com/moosh3/pygci/blob/f80c336a4417f57ce80495e02f0a4a45eb0f4ce1/pygci/endpoints.py#L33
def get_representative_by_address(self, params):
"""Looks up political geography and representative
information for a single address
:param address: (optional) type=string
:param includeOffices: (optional) type=boolean, default=True
"""
address = ''
return self.get('/representatives?', params=address)
I am trying to learn Requests and practicing by connecting to the weather API. But for some reason I can't get it to work? It is clear the weather API is wanting the param in a certain way that I cannot seem to figure out how it translates to Requests.
Here is my code:
r = requests.get('http://api.openweathermap.org/data/2.5/weather', q={'Anderson'})
Here is the link to the API page:
https://openweathermap.org/current
I see the weather pages wants the param in terms of q = city, but the error I get is:
TypeError: request() got an unexpected keyword argument 'q'
Also here the the Requests page that I am referring to: http://docs.python-requests.org/en/master/
Thanks for the help!
Please review the requests user manual, at least the quickstart guide.
The RESTful API you are about to use expects GET request with q="City Name" parameter. Moreover you must have the appid and add it for every request.
Register you application and choose a pricing plan https://openweathermap.org/price
Pass both q="City Name" and APPID=xxx parameters
Here is corresponding request:
api_url = 'http://api.openweathermap.org/data/2.5/weather'
appid = ...
r = requests.get(url=api_url, params=dict(q='Anderson', APPID=appid))
You need an appid for openweather, which for individual use is free (https://openweathermap.org/appid#get)
>>> import requests
>>> r = requests.get('http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1')
>>> loc_weather = r.content.strip()
>>> loc_weather
'{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09d"}],"base":"stations","main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15},"visibility":10000,"wind":{"speed":4.1,"deg":80},"clouds":{"all":90},"dt":1485789600,"sys":{"type":1,"id":5091,"message":0.0103,"country":"GB","sunrise":1485762037,"sunset":1485794875},"id":2643743,"name":"London","cod":200}'
Try changing your call to the one that follows (by adding the api key to the params):
r = requests.get('http://api.openweathermap.org/data/2.5/weather', params={'q': 'Anderson', 'APPID': YOUR_API_KEY})
This worked for weatherbit.
The url:
url = "https://api.weatherbit.io/v2.0/history/daily"
Create a payload:
payload = {'key':'12345fcfa0hjde13a7896fbdae1ghjkjh',
'city_id': '1261481', # This is New Delhi
'start_date': '2021-03-13',
'end_date': '2021-03-14'}
Call it using GET (the website specifies that GET call is supported):
data = requests.get(url, params=payload)
assert data.status_code == 200
assert 'error' not in data.json().keys()
Your data:
data.json() # Or text or content
My sys specs: Python 3.8, Request 2.25.1
I'm using foursquare API python client from mLewisLogic code from Github.
Honestly i don't understand about access token in foursquare API. It's only valid for 1 request?
Here's my code
import json
def setup():
client = foursquare.Foursquare(client_id='CLIENT_ID', client_secret='CLIENT_SECRET', redirect_uri='http://localhost')
auth_uri = client.oauth.auth_url()
code = "CODE"
user_access_token = client.oauth.get_token(code)
client.set_access_token(user_access_token)
return client
if __name__ == '__main__':
client = setup()
file = open('dataHasil.json', 'wb')
abc = json.dumps(client.users.search(params={'twitter': 'dindaasusanti'}))
file.write(abc.encode())
Code above works, but if i add 2 more lines.
abcd = json.dumps(client.users.search(params={'twitter': 'path'}))
file.write(abcd.encode())
It produce error
Response format invalid , missing meta property. data: {'error':'invalid_grant'}
please help me, i want to search many user account's information
note : i paste the CODE manually following instruction from https://developer.foursquare.com/overview/auth#access
I am trying to use templates which I have created on Sendgrid. What I want to do is, use the template that I have created on Sendgrid to send an email (with substituting the substitution tags).
Here is what I tried -
import sendgrid
sg = sendgrid.SendGridClient('<username>', '<password>')
message = sendgrid.Mail()
message.add_to('<to-email-address>')
message.set_subject('My Test Email')
message.add_substitution('customer_link', 'http://my-domain.com/customer-id')
message.add_filter('templates', 'enable', '1')
message.add_filter('templates', 'template_id', '<alphanumeric-template-id>')
message.add_from('<from-email-address>')
status, msg = sg.send(message)
However, this gives me an error that '{"errors":["Missing email body"],"message":"error"}'. I tried adding the following lines but still the same error -
message.set_html('')
message.set_text('')
So, the exact code I am using after using set_html is -
import sendgrid
sg = sendgrid.SendGridClient('<username>', '<password>')
message = sendgrid.Mail()
message.add_to('<to-email-address>')
message.set_subject('My Test Email')
message.add_substitution('customer_link', 'http://my-domain.com/customer-id')
message.add_filter('templates', 'enable', '1')
message.add_filter('templates', 'template_id', '<alphanumeric-template-id>')
message.add_from('<from-email-address>')
message.set_html('')
message.set_text('')
status, msg = sg.send(message)
What am I missing here? The python documentation for the library doesn't seem to contain anything.
Edit - One of the workaround that I found is derived from the answer below. I do set message.set_html(' ') and message.set_text(' '), that is basically, give a whitespace string. This is weird, though, but works for this case.
The official documentation it is indeed poor, since it just mentions an example. However, it provides you a link to its Github sendgrid-python repository in which you can find broader examples and the code itself (sometimes it is faster to look at this!).
Find here a full example listed in the Github page:
import sendgrid
sg = sendgrid.SendGridClient('YOUR_SENDGRID_USERNAME', 'YOUR_SENDGRID_PASSWORD')
message = sendgrid.Mail()
message.add_to('John Doe <john#email.com>')
message.set_subject('Example')
message.set_html('Body')
message.set_text('Body')
message.set_from('Doe John <doe#email.com>')
status, msg = sg.send(message)
#or
message = sendgrid.Mail(to='john#email.com', subject='Example', html='Body', text='Body', from_email='doe#email.com')
status, msg = sg.send(message)
However, in this case you are using a template and in Sendgrid's blog they mention:
Template Engine Demo – Q&A
Do I have to use the body and subject substitution tags in my
template? What If I don’t want to pass any substitution variables in
my email?
No. You can pass a blank value through with your API call and not
specify any variables.
although apparently it is not like this and you need to append some kind of html and text in your message instance.
So the workaround here is what you discovered: to set the html and text to a non-empty string:
message.set_html(' ')
message.set_text(' ')