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.)
Related
My problem is that i can't get image on google drive when using 'https://www.googleapis.com/drive/v3/files/<file_id>/export?mimeType=image%2Fjpeg'
Here, my code:
from pydrive import auth, drive
import requests
gauth = auth.GoogleAuth()
scope = ["https://www.googleapis.com/auth/drive"]
gauth.credentials = auth.ServiceAccountCredentials.from_json_keyfile_name('my_json.json', scope)
drv = drive.GoogleDrive(gauth)
access_token = drv.auth.credentials.get_access_token().access_token
url = 'https://www.googleapis.com/drive/v3/files/' + file_id + '/export?mimeType=image%2Fjpeg'
res = requests.get(url, headers={'Authorization': 'Bearer ' + access_token})
Respone error (403):
{
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "dailyLimitExceededUnreg",
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
"extendedHelp": "https://code.google.com/apis/console"
}
],
"code": 403,
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
}
}
I just reuqest 10-20 times. This error response seem wrong.
How i can fix above code to get response ?
Thanks in advance for help!
I believe your goal is as follows.
From My original file is *.jpg. I used mimeType=image/jpeg and your script, you want to download a JPEG file from Google Drive using the service account.
Modification points:
When you want to download a JPEG file, I think that your endpoint is required to be modified.
I think that when the access token is not used for the endpoint, the error of Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup. occurs. But, when the invalid access token is used, an error of Invalid Credentials occurs. In your script, even when the access token is invalid, I think that an error of Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup. doesn't occur. So I'm worried that your showing script might be different from your tested script. Please confirm this again.
If a JPEG file is downloaded from Google Drive using the service account, how about the following modification?
Modified script:
from pydrive import auth, drive
import requests
file_id = "###" # Please set the file ID of the JPEG file.
gauth = auth.GoogleAuth()
scope = ["https://www.googleapis.com/auth/drive"]
gauth.credentials = auth.ServiceAccountCredentials.from_json_keyfile_name('my_json.json', scope)
drv = drive.GoogleDrive(gauth)
access_token = drv.auth.credentials.get_access_token().access_token
url = "https://www.googleapis.com/drive/v3/files/" + file_id + "?alt=media"
res = requests.get(url, headers={"Authorization": "Bearer " + access_token})
Note:
In this case, it supposes that your service account can access the JPEG file on Google Drive. Please be careful about this. If an error like File not found occurs, please check about this, again.
For example, when you want to download a JPEG file using pydrive, you can also the following script.
from pydrive import auth, drive
import requests
file_id = "###" # Please set the file ID of the JPEG file.
gauth = auth.GoogleAuth()
scope = ["https://www.googleapis.com/auth/drive"]
gauth.credentials = auth.ServiceAccountCredentials.from_json_keyfile_name('my_json.json', scope)
drv = drive.GoogleDrive(gauth)
drv.CreateFile({"id": file_id}).GetContentFile("sample.jpg")
References:
Download files
PyDrive
I am trying to get the tweets in a 10 miles radius around Twitter's headquarters in San Francisco location using Tweepy API. I have authenitication information (api key, etc.) in an external .json file.
Below is my code:
import tweepy as tw
import json
import pandas as pd
import datetime
secrets = json.loads(open('secrets.json').read())
api_key = secrets['api_key']
api_secret_key = secrets['api_secret_key']
access_token = secrets['access_token']
access_token_secret = secrets['access_token_secret']
auth = tw.OAuthHandler(api_key, api_secret_key)
auth.set_access_token(access_token, access_token_secret)
api = tw.API(auth)
try:
api.verify_credentials()
print('Authenticated')
except:
print("Error authenticating")
# After running the above, I get status 'Authenitcated'
start = '2020-09-01'
end = '2020-09-26'
location = '37.7749, 122.4149, 10miles'
query = "*"
max_tweets = 1000
tweet_search_results = [status for status in tw.Cursor(api.search, query=query, geocode=location, since=start, until=end).items(max_tweets)]
After running the above, I get this error:
TweepError: Twitter error response: status code = 403
This status code means access to the requested resource is forbidden for some reason. The server understood the request, but will not fulfill due to the client-related issues.
Within the same code I am able to get the list of tweets for a specific user name, but without geolocation data.
Why am I getting 403 when trying to get geolocation tweets?
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)
I'm trying to retrieve data from the google business api, I've set up a service account and written code that successfully generates a bearer authorization token.
I've then passed this as a header through a get request but I receive this response:
{'error': {'code': 404, 'message': 'Requested entity was not found.', 'status': 'NOT_FOUND'}}
Using postman and sending an oauth request returns the desired information, but as this is meant to be set for automated unattended running, I wanted to explore the service account approach. Myscript is here:
'''
import jwt
import requests
import time
import json
iat = time.time()
exp = iat + 3600
payload = {'iss': 'xxxxx.iam.gserviceaccount.com',
'sub': 'xxxxx.iam.gserviceaccount.com',
'aud': 'https://mybusiness.googleapis.com/',
'iat': iat,
'exp': exp}
additional_headers = {'kid': 'xxxxxx'}
signed_jwt = jwt.encode(payload, "-----BEGIN PRIVATE KEY-----xxxxxxx-----END PRIVATE KEY-----\n", headers=additional_headers,
algorithm='RS256')
print(signed_jwt.decode())
response = requests.get('https://mybusiness.googleapis.com/v4/accounts/xxxxxx/locations', headers = {'Authorization':'Bearer '+signed_jwt.decode()})
response = response.json()
print(response)
'''
any help would be greatly appreciated
In 2020, retrieving data from GMB API using Service Accounts is still not possible (It s*cks!).
Here is the reason: https://support.google.com/business/thread/1856166?msgid=1856214
So I'm trying to follow The microsoft face api documentation here for the "FindSimilar" feature. There is an example at the bottom of the page where I use this code:
########### Python 3.2 #############
import http.client, urllib.request, urllib.parse, urllib.error, base64
headers = {
# Request headers
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': '{api key}',
}
params = urllib.parse.urlencode({
})
try:
conn = http.client.HTTPSConnection('westus.api.cognitive.microsoft.com')
conn.request("POST", "/face/v1.0/findsimilars?%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))
I'm getting an error where it tells me my subscription key is invalid, but I checked my azure account status and I see no issues:
b'\n\t\t\t\t\t{"error":{"code":"Unspecified","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."}}\n \t\t'
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.
It indicates that Invalid subscription Key or user/plan is blocked. I recommand that you could check the APi Key.
headers = {
# Request headers
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': '3c658abc64b348c1a5...',
}