Microsoft Bing Speech API using Python: No JSON Object - python

I'm trying to implement the Microsoft Bing Speech REST API with Python and I've found some code online.
https://www.taygan.co/blog/2018/02/09/getting-started-with-speech-to-text
import json
import requests
YOUR_API_KEY = 'ENTER_YOUR_KEY_HERE'
YOUR_AUDIO_FILE = 'ENTER_PATH_TO_YOUR_AUDIO_FILE_HERE'
MODE = 'interactive'
LANG = 'en-US'
FORMAT = 'simple'
def handler():
# 1. Get an Authorization Token
token = get_token()
# 2. Perform Speech Recognition
results = get_text(token, YOUR_AUDIO_FILE)
# 3. Print Results
print(results)
def get_token():
# Return an Authorization Token by making a HTTP POST request to Cognitive Services with a valid API key.
url = 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken'
headers = {
'Ocp-Apim-Subscription-Key': YOUR_API_KEY
}
r = requests.post(url, headers=headers)
token = r.content
return(token)
def get_text(token, audio):
# Request that the Bing Speech API convert the audio to text
url = 'https://speech.platform.bing.com/speech/recognition/{0}/cognitiveservices/v1?language={1}&format={2}'.format(MODE, LANG, FORMAT)
headers = {
'Accept': 'application/json',
'Ocp-Apim-Subscription-Key': YOUR_API_KEY,
'Transfer-Encoding': 'chunked',
'Content-type': 'audio/wav; codec=audio/pcm; samplerate=16000',
'Authorization': 'Bearer {0}'.format(token)
}
r = requests.post(url, headers=headers, data=stream_audio_file(audio))
results = json.loads(r.content)
return results
def stream_audio_file(speech_file, chunk_size=1024):
# Chunk audio file
with open(speech_file, 'rb') as f:
while 1:
data = f.read(1024)
if not data:
break
yield data
if __name__ == '__main__':
handler()
I've followed the above code (and changed the key and audio file name) but keep getting this:
Traceback (most recent call last):
File "/Users/emi/Desktop/proj/taygan tutorial/handler.py", line 55, in <module>
handler()
File "/Users/emi/Desktop/proj/taygan tutorial/handler.py", line 15, in handler
results = get_text(token, YOUR_AUDIO_FILE)
File "/Users/emi/Desktop/proj/taygan tutorial/handler.py", line 40, in get_text
results = json.loads(r.content)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
Complete newbie so really don't understand what's going on. Thanks!
NOTE: I've also tried the code from this
GitHub Repos
but I receive many errors with this one.

Related

json.decoder.JSONDecodeError: Expecting value: line 3 column 1 (char 4)

I have written a script which is hitting Azure DevOps API and get API response from it. The script is working file on local machine but when I am trying to run the same script from Azure pipeline it is giving me error.
Traceback (most recent call last):
File "/azp/$AZP_AGENT_NAME/3/s/terra/agent/agent_queue_status.py", line 19, in <module>
data = json.loads(r)
File "/_work/_tool/Python/3.9.0/x64/lib/python3.9/json/__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "/_work/_tool/Python/3.9.0/x64/lib/python3.9/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/_work/_tool/Python/3.9.0/x64/lib/python3.9/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 3 column 1 (char 4)
##[error]Bash exited with code '1'.
This the my script:
import base64
import requests
import json
AZURE_DEVOPS_PAT = 'my_pat'
authorization = str(base64.b64encode(bytes(':' + AZURE_DEVOPS_PAT, 'ascii')), 'ascii')
headers = {
'Accept': 'application/json',
'Authorization': 'Basic ' + authorization
}
url = 'https://dev.azure.com/{MY-ORG}/(MY-Project)/_settings/agentqueues?__rt=fps&__ver=2'
r = requests.get(url, headers=headers).text
data = json.loads(r)
print(data)
I tried everything. Like changing the way of getting response but no luck.
tried:-
r = requests.get(url, headers=headers).json
-------------------------------------------
r = requests.get(url, headers=headers)
data = r.json()
Please suggest something. The code is working fine on local machine but not with pipeline on Azure agent.

ServiceNow REST API Integration: No JSON object could be decoded

I tried do some integration towards serviceNow records using python script and referring example given in this link to update the records using Http Request Patch method: Table API Python
Here is my code:
#Need to install requests package for python
#sudo easy_install requests
import requests
# Set the request parameters
url = 'https://instance.owndomain.com/api/now/table/sc_req_item/2a2851fe88709010b9120e9b506dd9a9'
user = 'username'
pwd = 'password'
# Set proper headers
headers = {"Content-Type":"application/json","Accept":"application/json"}
# Do the HTTP request
response = requests.patch(url, auth=(user, pwd), headers=headers ,data='{"u_switch_status_automation":"In Processing using Python", "u_switch_description":"The Automation currently processing this SR using Python"}')
# Check for HTTP codes other than 200
if response.status_code != 200:
print('Status:', response.status_code, 'Headers:', response.headers, 'Error Response:',response.json())
exit()
# Decode the JSON response into a dictionary and use the data
print('Status:',response.status_code,'Headers:',response.headers,'Response:',response.json())
And the result I got is as follows:
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:1004: InsecureRequestWarning: Unverified HTTPS request is being made to host 'instance.owndomain.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecureRequestWarning,
Traceback (most recent call last):
File "/home/automation/switchConf/updateRecord.py", line 18, in <module>
print('Status:', response.status_code, 'Headers:', response.headers, 'Error Response:',response.json())
File "/usr/lib/python2.7/site-packages/requests/models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/lib64/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib64/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib64/python2.7/json/decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

How to capture the response based on the Content-Type sent by the server using requests in Python?

I am pretty new to python and learning how to make HTTP request and store the response in a variable.
Below is the similar kind of code snippet that I am trying to make the POST request.
import requests
import simplejson as json
api_url = https://jsonplaceholder.typicode.com/tickets
raw_body = {"searchBy":"city","searchValue":"1","processed":9,"size":47,"filter":{"cityCode":["BA","KE","BE"],"tickets":["BLUE"]}}
raw_header = {"X-Ticket-id": "1234567", "X-Ticket-TimeStamp": "11:01:1212", "X-Ticket-MessageId": "123", 'Content-Type': 'application/json'}
result = requests.post(api_url, headers=json.loads(raw_header), data=raw_body)
#Response Header
response_header_contentType = result.headers['Content-Type'] #---> I am getting response_header_contentType as "text/html; charset=utf-8"
#Trying to get the result in json format
response = result.json() # --> I am getting error at this line. May be because the server is sending the content type as "text/html" and I am trying to capture the json response.
Error in console :
Traceback (most recent call last):
File "C:\sam\python-project\v4\makeApiRequest.py", line 45, in make_API_request
response = result.json()
File "C:\Users\userName\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Users\userName\AppData\Local\Programs\Python\Python37\lib\site-packages\simplejson\__init__.py", line 525, in loads
return _default_decoder.decode(s)
File "C:\Users\userName\AppData\Local\Programs\Python\Python37\lib\site-packages\simplejson\decoder.py", line 370, in decode
obj, end = self.raw_decode(s)
File "C:\Users\userName\AppData\Local\Programs\Python\Python37\lib\site-packages\simplejson\decoder.py", line 400, in raw_decode
return self.scan_once(s, idx=_w(s, idx).end())
simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
So, how can I store the response in a variable based on the content-type sent by the server using requests.
Can somebody please help me here. I tried googling too but did not find any helpful documentation on how to capture the response based on the content-type.
as you already said your contentType is 'text/html' not 'application/json' that normally means that it can not be decoded as json.
If you look at the documentation
https://2.python-requests.org/en/master/user/quickstart/#response-content you can find that there are different ways to decode the body, if you already know you have 'text/html' it makes sense to decode it with response.text.
Hence it makes sense to distinquish based on the content type how to decode your data:
if result.headers['Content-Type'] == 'application/json':
data = result.json()
elif result.headers['Content-Type'] == 'text/html':
data = result.text
else:
data = result.raw

JSONDecodeError Expecting value

I am trying to get json object, and it tells me it's expecting a value even though i define the path to the json in r.json(). Also when i do r.headers[content-type] give me text/html;charset=ISO-8859-1 ... Thank you for your time everyone
import requests
import json
session = requests.Session()
username = "------"
password = "-------"
url_cookie = 'http://ludwig.podiumdata.com:----/podium/j_spring_security_check?j_username=--&j_password=----'
url_get = 'http://ludwig.corp.podiumdata.com:----/qdc/entity/v1/getEntities?type=EXTERNAL&count=2&sortAttr=name&sortDir=ASC'
r = requests.get(url_get, auth=(username,password), verify=False)
r.json()
r.headers['content-type']
Traceback (most recent call last):
File "<ipython-input-108-61f8159bb1b5>", line 10, in <module>
r.json()
File "//anaconda3/lib/python3.7/site-packages/requests/models.py", line 897, in json
return complexjson.loads(self.text, **kwargs)
File "//anaconda3/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "//anaconda3/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "//anaconda3/lib/python3.7/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
JSONDecodeError: Expecting value
Your request is receiving the response as text/html, but you want to receive application/json.
You need to include {'Accept': 'application/json'} as a header in your request.
Example: requests.get(url_get, auth=(username,password), headers={'Accept': 'application/json'}, verify=False)
Also, it looks like you aren't using the Session you created on line 3, but that isn't what is causing this error.

Post file and data to API using Python

I'm experimenting a bit with an API which can detect faces from an image. I'm using Python and want to be able to upload an image that specifies an argument (in the console). For example:
python detect.py jack.jpg
This is meant to send file jack.jpg up to the API. And afterwards print JSON response. Here is the documentation of the API to identify the face.
http://rekognition.com/developer/docs#facerekognize
Below is my code, I'm using Python 2.7.4
#!/usr/bin/python
# Imports
import sys
import requests
import json
# Facedetection.py sends us an argument with a filename
filename = (sys.argv[1])
# API-Keys
rekognition_key = ""
rekognition_secret = ""
array = {'api_key': rekognition_key,
'api_secret': rekognition_secret,
'jobs': 'face_search',
'name_space': 'multify',
'user_id': 'demo',
'uploaded_file': open(filename)
}
endpoint = 'http://rekognition.com/func/api/'
response = requests.post(endpoint, params= array)
data = json.loads(response.content)
print data
I can see that everything looks fine, but my console gets this output:
Traceback (most recent call last):
File "upload.py", line 23, in <module>
data = json.loads(response.content)
File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 383, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
What is wrong?
Success!
The question didn't contain good code. I used code from here:
uploading a file to imgur via python
#!/usr/bin/python
# Imports
import base64
import sys
import requests
import json
from base64 import b64encode
# Facedetection.py sends us an argument with a filename
filename = (sys.argv[1])
# API-Keys
rekognition_key = ""
rekognition_secret = ""
url = "http://rekognition.com/func/api/"
j1 = requests.post(
url,
data = {
'api_key': rekognition_key,
'api_secret': rekognition_secret,
'jobs': 'face_recognize',
'name_space': 'multify',
'user_id': 'demo',
'base64': b64encode(open(filename, 'rb').read()),
}
)
data = json.loads(j1.text)
print data
Now this: python detect.py jack.jpg returns the wanted JSON. Fully working.

Categories

Resources