How to implement the Microsoft Speaker Recognition / Verification API in Python? - azure

I would like to implement the Speaker Recognition API from Microsoft's Cognitive Services for a Speaker Verification project. I already have a Speaker Recognition API key. I got the sample Python code directly from the documentation (on the bottom of the documentation):
https://westus.dev.cognitive.microsoft.com/docs/services/563309b6778daf02acc0a508/operations/563309b7778daf06340c9652
########### Python 3.2 #############
import http.client, urllib.request, urllib.parse, urllib.error, base64
headers = {
# Request headers
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': '{subscription key}',
}
params = urllib.parse.urlencode({
})
try:
conn = http.client.HTTPSConnection('westus.api.cognitive.microsoft.com')
conn.request("POST", "/spid/v1.0/verificationProfiles?%s" % params, "{body}", headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
####################################
This is the code sample for the first step, create and save a voice profile.
To conduct Speaker Verification, we need to do 3 steps:
1) Create Profile
2) Create Enrollment
3) Verification
I'm stuck already at the first step now. This is my first time working with APIs in general, so I'm not really sure what parts of the Python code I have to change. I know that I need do insert my API key in 'Ocp-Apim-Subscription-Key' but other than that, what else? For example, if I add my API key in that specific field and let the code run, I received this error message.
b'{"error":{"code":"BadRequest","message":"locale is not specified"}}'
Where do I need to insert the locale ("en-us") for example? It is not really clear to me from the documentation what I need to edit. If you can guide me what I need to insert/add in my API calls I would be very thankful.
Thanks so much in advance!

When you create a Speaker Recognition profile, it has to be linked with a locale, and you specify this locale in the request body. The body should be a JSON object like the following one:
{
"locale":"en-us",
}
For the sample to work, you need to replace "{body}" with the actual body value like this:
conn.request("POST", "/spid/v1.0/verificationProfiles?%s" % params, "{\"locale\":\"en-US\"}", headers)

Related

Looking for approach to post long text to slack through python script

I had written a code in python to fetch the huge set (80 lines) of data from DB, now I would like to post that data in slack through webhook. I tried posting the data directly,but its not working for me, so I decided to save the data in txt/.png file and post it in slack
I tried below code in python after saving my data in report.txt file, but its not helping me
headers = {
'Content-type': 'application/json',
}
data = open('\\results\report.txt')
response = requests.post('https://jjjjjjj.slack.com/services/mywebhook', headers=headers, data=data)
Please share me the Curl command which will fit in python script to post the attachment in slack or please suggest me any better approach to post more than 50 lines for data to slack
I would suggest to upload long text as text file. That way Slack will automatically format it with a preview and users can click on it to see the whole content.
To upload a file you need to use files_upload API method. With it you can also include an initial message with your upload.
Here is an example using the standard Slack library. Here I am reading the data from a file, but you would of course use your data instead:
import slack
import os
# init slack client with access token
slack_token = os.environ['SLACK_TOKEN']
client = slack.WebClient(token=slack_token)
# fetch demo text from file
with open('long.txt', 'r', encoding='utf-8') as f:
text = f.read()
# upload data as file
response = client.files_upload(
content=text,
channels='general',
filename='long.txt',
title='Very long text',
initial_comment='Here is the very long text as requested:'
)
assert response['ok']
The trick is to use content not file to pass the data. If you use file the API will try to load a file from your filesystem.
The below code works fine for me..... :)
headers = { 'Authorization': 'Bearer xxxx-XXXXX-XXXXX', #Bot Token }
files = {
'file': ('LocationOfthefile\report.txt', open('LocationOfthefile\report.txt', 'rb')),
'initial_comment': (None, 'Some Text For Header'),
'channels': (None, 'Channel_Names'),
}
response = requests.post('slack.com/api/files.upload', headers=headers, files=files)

Posting data on Airtable API does not work

I am trying to create a new table on Airtable with the aid of the post method. I have the following code :
# importing the requests library
import requests
# defining the api-endpoint
API_ENDPOINT = "https://api.airtable.com/v0/appa3r2UUo4JxpjSv/Table%201?api_key=MYKEY"
# data to be sent to api
data = {
'fields': {
'Name': 'Andromachis Row'
}
}
# sending post request and saving response as response object
r = requests.post(url = API_ENDPOINT, data = data)
# extracting response text
print(r.text)
Despite that when I run the script I get an error saying:
(mypyth) PS C:\Users\andri\PythonProjects\mypyth> py post_API.py
{"error":{"type":"INVALID_REQUEST_UNKNOWN","message":"Invalid request: parameter validation failed. Check your request data."}}
Does anyone understand why this happens? I am really desperate! Thanks in advance

Return csv data as a result for IBM Cloud Function

I have a function written in Python for IBM cloud. Which return results as json, for the following python dictionaries:
return {"billing_for_org": output1, "billing_for_org2:": output2}
Is there a way to return this data as a CSV file? So when I invoke the api I am able to download the data as CSV file?
Here is some sample I tested. Let me know if its what you are looking for.
import sys
import csv
import io
def main(dict):
output = io.StringIO()
my_dict = {"billing_for_org": "$100", "billing_for_org2": "$200"}
w = csv.DictWriter(output, my_dict.keys())
w.writeheader()
w.writerow(my_dict)
return {"body": output.getvalue(),
"headers": {'Content-Type': 'text/csv','Content-Disposition':'attachment;filename=myfilename.csv'}}
I am not sure how you are invoking the function as Rest API or Web Action.
I tested above code as web action function and got the result. Please note that extension says http at the end of Url which makes the function to return Non-Default(Json) payloads.
Example Url - https://openwhisk.ng.bluemix.net/api/v1/web/demo_dev/hello-world/helloworld.http
Response Received -
Body:
billing_for_org,billing_for_org2
$100,$200
Headers:
Content-Type →text/csv; charset=UTF-8 Content-Length →45 Connection
→keep-alive Content-Disposition →attachment;filename=myfilename.csv
Reference -
https://console.bluemix.net/docs/openwhisk/openwhisk_webactions.html#openwhisk_webactions.
https://developer.ibm.com/answers/answers/406943/view.html

Trying to use Yelp API for something other than business_id

I'm a student and only a few weeks into Python, so bear with me. I found a good answer in this link for initially working with Yelp's v3 API to at least get it to successfully make a request by business_id: How to use Yelp's new API
However, I can't seem to figure out how to search by anything other than reviews using the code that someone provided above (copy-pasted here as the below does work, just not what I need it for:
import requests
import yelp
from config import api_key
API_KEY = api_key
API_HOST = 'https://api.yelp.com'
BUSINESS_PATH = '/v3/businesses/'
def get_business(business_id):
business_path = BUSINESS_PATH + business_id
url = API_HOST + business_path + '/reviews'
headers = {'Authorization': f"Bearer {API_KEY}"}
response = requests.get(url, headers=headers)
return response.json()
results = get_business('the-white-horse-pub-kansas-city')
pprint(results)
Again, the code does work if you're only looking up one place by name. But when I try something other than "/reviews" in the url function, such as "search" or "term" or something else going off of the Yelp Fusion API documentation (https://yelp.com/developers/documentation/v3/business_search), I can't get anything to pull. My intent is to pull a bunch of breweries in the local area and then eventually put them in a dataframe, but I can't figure out what parameters or code to use, other than 'review'.
I believe I found an answer where you can at least look for type if you add the first item to the dependencies and the lower items as a separate function:
BUSINESS_PATH_CAT = '/v3/categories/'
def get_all_categories(alias):
url = API_HOST + BUSINESS_PATH_CAT + alias
headers = {'Authorization': f"Bearer {API_KEY}"}
response = requests.get(url, headers=headers)
return response.json()
results = get_all_categories('brewpubs')
pprint(results)
Aside from this though, on the authentication guide for Yelp Fusion, it discusses using Postman. If you're a fellow noob, setting this up can be a lifesaver as this allowed me to actually see the HTTP wording and how it's split up for search terms and how to add them compared to the API documentation.

Microsoft Emotion Video API Python 3.2

I am trying to analyze a video via Emotion API by Microsoft using Python 3.2
I am encountering the following error:
b'{ "error": { "code": "Unauthorized", "message": "Access denied due to invalid subscription key. Make sure you are subscribed to an API you are trying to call and provide the right key." } }'
I am using Emotion API subscription key (i have also used the Face API key, and computer vision key just in case).
Code:
import http.client, urllib.request, urllib.parse, urllib.error, base64
headers = {
# Request headers
'Ocp-Apim-Subscription-Key': '{subscription key}',
}
params = urllib.parse.urlencode({
})
try:
conn = http.client.HTTPSConnection('westus.api.cognitive.microsoft.com')
conn.request("GET", "/emotion/v1.0/operations/{oid}?%s" % params, "{body}", headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
Your code works. Just make sure you wait 10 minutes after generating the API key so that it starts working (it says so in the Azure Portal).
Also, in general for Cognitive Services, make sure that the API key you have corresponds to the region you're trying to hit (West US, etc.)

Resources