In google cloud vision API while calling client.text_detection() getting TypeError: type object got multiple values for keyword argument 'features' - ocr

i have used the following code inside of a function, and i am returning the responce
image = vision.types.Image(content=content)
print("vision type: %s" %vision.enums.Feature.Type.DOCUMENT_TEXT_DETECTION)
feature = vision.types.Feature(type=vision.enums.Feature.Type.DOCUMENT_TEXT_DETECTION)
print(type(feature))
response = client.text_detection(image=image,features=
[{'type':str(vision.enums.Feature.Type.TEXT_DETECTION)}], image_context=
{"language_hints":
["en"]})
Error at this line:
response = client.text_detection(image=image,features=
[{'type':str(vision.enums.Feature.Type.TEXT_DETECTION)}], image_context={"language_hints":
["en"]})
request = dict(image=image, features=[copied_features], **kwargs)
TypeError: type object got multiple values for keyword argument 'features'
NOTE:
I have visited their documentation page, however that is outdated,and I specifically wants to set the feature type to either "DOCUMENT_TEXT_DETECTION" or "TEXT_DETECTION"

Change it to:
response = client.text_detection(image=image, image_context=
{"language_hints":
["en"]})
You already have text_detection in this request, you trying to set in again.
Example

Using methods like text_detection or document_text_detection you already declare type.
Use annotate_image to declare entire request json and declare type_ there:
response = client.annotate_image(
{
"image": {"content": image},
"features": [{"type_": "DOCUMENT_TEXT_DETECTION"}],
"image_context": {"language_hints": ["en"]},
}
)

Related

GET method for an Azure function within Azure Data Factory fails

I am trying to invoke an HTTP triggered Azure function built on with a GET request. I setup the linked service as per the recommended steps and the function itself works with a query string through POSTMAN or internet browser, but fails when I try to invoke through Data factory.
{
"errorCode": "3608",
"message": "Call to provided Azure function '' failed with status-'NotFound' and message - 'Invoking Azure function failed with HttpStatusCode - NotFound.'.",
"failureType": "UserError",
"target": "Azure Function1",
"details": []
}
I came across another stackoverflow post https://stackoverflow.com/a/54497119/4212430 where there was a mention of a JSON response for ADF.
I have since changed my python code to provide an HTTP response as a JSON object as below
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
statename = req.params.get('statename')
if not statename:
try:
req_body = req.get_json()
except ValueError:
pass
else:
statename = req_body.get('statename')
if statename:
initiate_main(statename)
host.close()
function_message = {"Response":"Successfully trasnferred BOM files"}
return func.HttpResponse(
json.dumps(function_message),
mimetype="application/json",
status_code=200)
else:
function_message = {"Response":"Error in transferring files"}
return func.HttpResponse(
json.dumps(function_message),
mimetype="application/json",
status_code=400)
But that hasn't helped either.
It turns out that I was using the wrong URI with an api added at the end while I should have just been giving the plain function name

How to parse JSON in Postman Test Script

I am running a chain of collections from 1 API call to another. I want to pull the response body from API call 1 to API call 2 so that it can post the data to my application.
I have created the environment variables and in the tests tab I have created a script to set the variables but when I run the script I get a response of the below:
SyntaxError: Unexpected token [
My test script is:
bodyData = JSON.parse(responseBody)
value = bodyData.[1]country
console.log(value)
The response body looks like this
[
{
"Country": "United Kingdom",
}
]
I know the issue is [] and needs to have a string before it but the API is not defined with a string and I cant just use the below as it's then undefined:
bodyData = JSON.parse(responseBody)
value = bodyData.country
console.log(value)
Any idea how I can get this to work?
You have the reference slightly wrong I think.
This should do it:
let bodyData = pm.response.json()
let country = bodyData[0].Country
console.log(country)
To then set the variable you would need to use:
pm.environment.set("country", country)

KeyError reading a JSON file

EDIT: Here's a bit more context to how the JSON is received. I'm using the ApiAI API to generate a request to their platform, and they have a method to retrieve it, like this:
# instantiate ApiAI
ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
# declare a request obect, fill in in lower lines
request = ai.text_request()
# send ApiAI the request
request.query = "{}".format(textobject.body)
# get response from ApiAI
response = request.getresponse()
response_decode = response.read().decode("utf-8")
response_data = json.loads(response_decode)
I'm coding a webapp in Django and trying to read through a JSON response POSTed to a webhook. The code to read through the JSON, after it has been decoded, is:
if response_data['result']['action'] != "":
Request.objects.create(
request = response_data['result']['resolvedQuery']
)
When I try to run this code, I get this error:
KeyError: 'result'
on the line
if response_data['result']['action'] != "":
I'm confused because it looks to me like 'result' should be a valid key to this JSON that is being read:
{
'id':'65738806-eb8b-4c9a-929f-28dc09d6a333',
'timestamp':'2017-07-10T04:59:46.345Z',
'lang':'en',
'result':{
'source':'agent',
'resolvedQuery':'Foobar',
'action':'Baz'
},
'alternateResult':{
'source':'domains',
'resolvedQuery':'abcdef',
'actionIncomplete':False,
},
'status':{
'code':200,
'errorType':'success'
}
}
Is there another way I should be reading this JSON in my program?
Try:
import JSON
if 'action' in response_data:
parsed_data = json.loads(response_data)
if parsed_data['result']['action'] != "":
Request.objects.create(request = parsed_data['result']['resolvedQuery'])
Thanks for everyone's thoughts. It turned out there was an another error with how I was trying to implement the ApiAI API, and that was causing this error. It now reads through the JSON fine, and I'm using #sasuke's suggestion.

JSON encoding error publishing SNS message with Boto 3

I am trying to send a simple JSON message to an Amazon SNS topic in Boto 3. However, I keep getting a _jsonparsefailure in the tag of the message and I only receive the default value. Here is my code:
mess = {'default': 'default', 'this': 'that'}
jmess = json.JSONEncoder().encode(mess)
response = self.boto_client.publish(
TopicArn = self.TopicArn,
MessageStructure = 'json',
Message = jmess
)
I have also tried json.dumps(), which produces the same result.
mess = {'default': 'default', 'this': 'that'}
jmess = json.dumps(mess)
response = self.boto_client.publish(
TopicArn = self.TopicArn,
MessageStructure = 'json',
Message = jmess
)
I seem to be following all of the guidelines set by the documentation, and I'm not getting an exception when I run the script. There are SQS queues that subscribe to the topic, and I am pulling the result data straight from the console.
This is how I fixed it:
message = {"record_id": "my_id", "name": "value"}
json_message = json.dumps({"default":json.dumps(message)})
sns_client.publish("topic_arn", Subject="test", MessageStructure="json", Message=json_message)
SNS expects "default" as the key which contains the message to be published.
It turns out the message needs to look like this:
json.dumps({"default": "my default", "sqs": json.dumps({"this": "that"})})
Amazon has horrible documentation in this regard.
You can also remove the MessageStructure='json'and send just json.dumps({'this':'that'}) if you set the SQS queue to receive just the raw message. This is simply done through the console.
In Boto 3 (I'm using v1.4.7) this is the format:
sns.publish(TopicArn="topic_arn", Message=json.dumps({"this": "that"},ensure_ascii=False))
There isn't any need for the protocol definition, i.e. "default" unless you are delivering different structures per protocol, i.e., JSON for Lambda and HTML for email.

No MediaTypeFormatter error when trying to parse ReadAsFormDataAsync result in WebAPI

I have created a WebAPI project to help capture statements from a TinCan learning course but I am having extreme difficulty in retrieving any of the Request payload details. Within this payload I pass the whole statement that I am trying to capture but upon trying to read using:
var test = Request.Content.ReadAsFormDataAsync().Result.ToString();
I get the following error message:
No MediaTypeFormatter is available to read an object of type 'FormDataCollection' from content with media type 'application/json'.
I have tried Converting the result object to JSON to overcome this problem but it has not been any use. Do I need to configure json somewhere in the configuration? I have tried adding
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
and also:
var jsonFormatter = config.Formatters.JsonFormatter;
config.Formatters.Insert(0, jsonFormatter);
to my WebApiConfig.cs file as answered in another question of how to return json but I cannot seem to pass this error. I have also set config.formatter to accept application/json but this also has not worked
CONTROLLER CODE
public void Put([FromBody]string statementId)
{
var test = Request.Content.ReadAsFormDataAsync().Result;
System.Diagnostics.EventLog.WriteEntry("Application", "/xAPI/PUT has been called", System.Diagnostics.EventLogEntryType.Error);
}
From the error message you have provided, it seems like request content is in application/json. ReadAsFormDataAsync() can only read content of type application/x-www-form-urlencoded.
In this case, you can use ReadAsAsync<> if you have the type you want to be deserialized defined or simply use ReadAsStringAsync<> if you just want to read the content as a string.