Google Cloud Vision Raw JSON Response - google-cloud-vision

When trying out google cloud vision with the drag and drop Try Drag and Drop, the last tab has raw JSON. What parameter do we need to pass to get that data?
I'm currently doing DOCUMENT_TEXT_DETECTION but it only gives data at the level of words and not of individual characters.
Edit: I modified this code vision test and changed the feature ...
feature := &vision.Feature{
Type: "DOCUMENT_TEXT_DETECTION",
}
and the printing to ...
body, err := json.Marshal(res)
fmt.Println(string(body))
I'm only seeing textAnnotations in the output.

The JSON file contains different things like text, locations and etc etc, Your concern is about getting full text.
Here I am adding a Python code, it says that you can get the full text by rendering the JSON file, you will find your required result using data['fullTextAnnotation']['text'], and you can get characters by breaking this file into smaller chunks and I guess JSON file has individual characters in it but I have never worked on it.
import json
from pprint import pprint
data = json.load(open('File Path'))
pprint(data['fullTextAnnotation']['text'])

Well, if you check properly there are various things available in that last tab containing raw JSON.
Based on your requirements you can fetch any of them.
From the response that you get from DOCUMENT_TEXT_DETECTION, you can fetch text_annotations, full_text_annotations, etc.
From text_annotations, you can fetch description, language of entire text, each words of texts, numeric digits, special characters and their respective co-ordinates.
From full_text_annotations, you can fetch pages, blocks of data, paragraphs, and individual characters, with their respective co-ordinates and confidence score.

Using the same code template you are using in Go language:
Search “type Feature struct” in the browser in this page. You can see the following feature types and descriptions:
// Type: The feature type.
//
// Possible values:
// "TYPE_UNSPECIFIED" - Unspecified feature type.
// "FACE_DETECTION" - Run face detection.
// "LANDMARK_DETECTION" - Run landmark detection.
// "LOGO_DETECTION" - Run logo detection.
// "LABEL_DETECTION" - Run label detection.
// "TEXT_DETECTION" - Run text detection / optical character
// recognition (OCR). Text detection
// is optimized for areas of text within a larger image; if the image
// is
// a document, use `DOCUMENT_TEXT_DETECTION` instead.
// "DOCUMENT_TEXT_DETECTION" - Run dense text document OCR. Takes
// precedence when both
// `DOCUMENT_TEXT_DETECTION` and `TEXT_DETECTION` are present.
// "SAFE_SEARCH_DETECTION" - Run Safe Search to detect potentially
// unsafe
// or undesirable content.
// "IMAGE_PROPERTIES" - Compute a set of image properties, such as
// the
// image's dominant colors.
// "CROP_HINTS" - Run crop hints.
// "WEB_DETECTION" - Run web detection.
There is not an option to directly show the JSON tab contents. The JSON tab contents are the addition of all the tabs “output”. Users tend to ask just for one. For example, when someone is analyzing faces is not interested in text detection.
If you need more than one, you can obtain multiple features outputs by “adding” the result of all the possible values together. Based on the facts mentioned, I have added the following lines to your code:
feature2 := &vision.Feature{
Type: "LABEL_DETECTION",
MaxResults: 10,
}
req2 := &vision.AnnotateImageRequest{
Image: img,
Features: []*vision.Feature{feature2},
}
batch2 := &vision.BatchAnnotateImagesRequest{
Requests: []*vision.AnnotateImageRequest{req2},
}
res2, err := svc.Images.Annotate(batch2).Do()
if err != nil {
log.Fatal(err)
}
body2, err := json.Marshal(res2)
fmt.Println(string(body2))
I have tested it and works. You should add this block of code for all the features in which you are interested. If you intend to add many of them, I would suggest to create a function/loop to avoid repeating code.
Anyway, I suggest you to fulfill the request here in order to exactly obtain the JSON output (that gives data at the level of words or letters) through calling the API instead of using a client library. I have used the next code to obtain the bounding box for the numbers of my interest:
{
"requests":
[
{
"features":
[
{
"type":
""
"maxResults":
-- add a property --model
}
{
"type":
""
-- add a property --maxResultsmodel
}
]
"image":
{
"source":
{
"gcsImageUri":
""
-- add a property --imageUri
}
-- add a property --content
}
-- add a property --imageContext
}
]
-- add a property --
}

Related

Elastic - Grok patterns parses string field incorrectly

So I have my log message field parsed as separate fields via ingest pipeline and grok processor, but one of these field ( string ) is parsed in format of seperate new log. Better explain it with specific example.
This is my log:
{"#timestamp":"2021-08-27T10:53:04.669661+02:00","#version":1,"host":"fafca1a6b0d9","message":"Loose white designer T-Shirt,L,29,1,sylius,1","type":"sylius","channel":"app","level":"INFO","monolog_level":200}
This is my simple ingest pipeline:
[
{
"grok": {
"field": "message",
"patterns": [
"%{DATA:product-name},%{DATA:product-variant},%{NUMBER:current-stock:float},%{NUMBER:order-quantity:float},%{USERNAME:identity},%{NUMBER:authenticated:float}"
]
}
},
{
"remove": {
"field": "message"
}
}
]
Problem is with product-name field. This field value get parse instead of 'Loose white designer T-Shirt' like this:
{"#Timestamp":"2021-08-27t11:40:28.159124+02:00","#version":1,"host":"fafca1a6b0d9","message":"Loose white designer T-Shirt
It is like the original log format, that is cut in half. What could be wrong? I tested it on Grok debuger with the same message and Grok pattern and this field has been separated correctly,
I want to share my solution for this. Not sure why, but It gets parsed correctly if I put delimeter on a the beginning and end of message and change pattern accordingly. I have put semicolon on beginning and the end.

Define a contract using query string parameter in json path assertion

I'm trying to use SCC to write some contracts before I rebuild the producer side (there are no existing tests!). The examples around lists and deeper data structures in the documents are a bit thin, so I want to understand if this is feasible, or perhaps I have to drop down to calling a command to make the right assertions.
I'm using the latest version v2.11
So -
Given:
An API that will return a list of objects in its payload. The length of the list will depending on the identity of the client, i.e. client A will get 3 items, client B will get 4 items. The identity of the client isn't of interest here.
When:
A client makes a GET request, passing a querystring parameter for item selection within the list of items
Then:
I want to write a contract that takes input from request and proves that the response contains a list of objects, and the item that matches the selector has a boolean field selected:true, while the rest of the items have selected:false. There's an edge where the selector is wrong and no item is selected.
E.g. For the request GET /someapi?id=bbb
Response
{ foo: xxxy, bar: 123, baz: [
{ id: 'aaa', selected: false, .... },
{ id: 'bbb', selected: true, .... },
{ id: 'ccc', selected: false, .... }
] }
Of course the selected item can be anywhere in the list. So I had in mind an assertion like this pseudo code -
jsonPath('$.baz[?(#.id == fromRequest().query("id"))].selected', byEquality( true ) )
But I can't do that fromRequest() stuff in the JSONPath statement. Right now I guess I could simply have the whole response body as the spec, but that seems unwieldy. If it must be, that's fine I guess.
Any ideas or help appreciated.

iOS WatchOS5 how to customize title in GraphicRectangular complication?

I want to remove text from my graphic rectangular complication, or set it to empty string. By default it is the app name. I tried to set display name to " " within watchKit plist file, but that did not seem to change it.
How do I remove text from my graphic rectangular WatchOS5 complication?
I see that there's some way to get (assign?) a CLKTextProvider as described here: https://developer.apple.com/documentation/clockkit/clktextprovider However, it seems to involve adding a localizable strings file and I don't want to mess with this if there's an easier way to get image only for the CLKComplicationTemplateGraphicRectangularLargeImage
func getLocalizableSampleTemplate(for complication: CLKComplication, withHandler handler: #escaping (CLKComplicationTemplate?) -> Void) {
// This method will be called once per supported complication, and the results will be cached
if complication.family == .graphicRectangular {
let template = GraphicTemplate()
template.textProvider = CLKSimpleTextProvider.init(text: "")
handler(template)
}else {
handler(nil)
}
}
class GraphicTemplate: CLKComplicationTemplateGraphicRectangularLargeImage {
}
You don't need to mess with localizable strings (phew).
There are two places you'll need to set up the appearance of the complication.
The sample template - this is displayed to the user as they're customizing a face and scrolling through the list of available complications. You provide this sample in the getLocalizableSample(for: withHandler:) method per family of complication, as you show in your question.
The actual live complication shown on the face, which you provide in the getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: #escaping (CLKComplicationTimelineEntry?) -> Void) method of the CLKComplicationDataSource.
In both places you'll need to return the template with a text provider (you'll crash on runtime if not), although it's fine to return an empty string. This should remove the app name.
let template = CLKComplicationTemplateGraphicRectangularLargeImage()
template.textProvider = CLKSimpleTextProvider.init(text: "")
template.imageProvider = CLKFullColorImageProvider(fullColorImage: myImage)
return template
(By the way, have you seen the recent Apple Tech Talk about complications for watch os5? It's a good one 😄).

Removing of unwanted line returns/breaks in a csv export in openUI5

I'm learning OpenUI5 as part as my new job/internship and I've hit a snag in the product that I'm working on. The exported csv is correct as far as everything that we want is properly exported but if the string/input of an item contains a new line character or is ended with the enter key it breaks the csv export but the model within the table still displays correctly.
description.replace(/(\r\n|\n|\r)/gm," ");
Is what would work to remove any line returns or enters being found within the string but the way that data is bound within this application is within this type of structure:
exportType : new sap.ui.core.util.ExportTypeCSV({
separatorChar : "," //;
}),
models : table.getModel(),
rows : {
path : "/interactions"
},
columns : [ {
name : "description",
template : {
content : "{description}"
}
}] // There is more listings after this but it's not important
// ... more items here
}); // End of the bounded data to export
As stated previously, my item 'description' can contain new line characters but when I convert to to csv in the export, it will do something like this:
90000440,Information Protection Policy,Scene1_QuestionDraw01_Slide1_TrueFalse_0_0,The Information Security Officer is responsible for the review and revision of this policy.
(True or False),false,false,1,1
There isn't supposed to be an actual line return within the outputted csv but since there is a new line character or line return within the description, it outputs one in the export.
Any amount of help that leads to me solving this issue would be fantastic.
Thank you, Jordan.
The best way would be to be able to use string delimiters as indicated in the comment by criticalfix. This normally works by default, see the following code from the current UI5 codebase: github. It might be that you have an UI5 version that does not cover this, because this was fixed last year in summer (see this commit). You can see the versions which contain this commit in the commit itself (immediately above the author line).
If you cannot upgrade to a version that contains this commit, then maybe your first idea of replacing the newlines would be appropriate. You can use a formatter in conjunction with your binding to remove the newlines:
// all the stuff before
columns : [ {
name : "description",
template : {
content : {
path: "description",
formatter: function (description) {
return description.replace(/(\r\n|\n|\r)/gm," ");
}
}
}
}]

Registering and retrieving 'interactions' with SCORM 1.2

We've been using SCORM in our previous e-learning 'engine' but we want to change the elements our Managed Learning Environment (MLE) tracks, namely each completable component in an e-learning module.
At runtime, we run the following code to set up our SCORM connection:
var vault = {}; //vault 'namespace' helps ensure no conflicts with possible other "SCORM" variables
vault.UTILS = {}; //For holding UTILS functions
vault.debug = { isActive: true }; //Enable (true) or disable (false) for debug mode
vault.SCORM = { //Define the SCORM object
version: null, //Store SCORM version.
handleCompletionStatus: true, //Whether or not the wrapper should automatically handle the initial completion status
handleExitMode: true, //Whether or not the wrapper should automatically handle the exit mode
API:{handle: null, isFound: false}, //Create API child object
connection: { isActive: false }, //Create connection child object
data: { completionStatus: null, exitStatus: null}, //Create data child object
debug:{} //Create debug child object
};
vault.SCORM.API.find('win');
vault.SCORM.connection.initialize();
if (vault.SCORM.data.get("cmi.core.lesson_status")=="not attempted") {
vault.SCORM.data.set("cmi.core.lesson_status" , "incomplete");
vault.SCORM.data.save();
}
There are many more functions in the SCORM.js file, but the point is this all works; When the module is loaded into our MLE, the following code triggers course completion:
vault.SCORM.data.set("cmi.core.lesson_status" , "completed");
So how would we register a completable component with SCORM? (Components in our 'engine' are jQuery objects usually called 'element'). Would something like the following work, or are custom calls in SCORM not possible?
vault.SCORM.data.set("cmi.interactions.n."+element.componentId() , "incomplete");
But then if I registered an interaction by specifying an id, as follows...
vault.SCORM.data.set("cmi.interactions.n.id", element.componentId());
...how do I then set or access 'completion' on that component?
I've been reading posts and pdf specs from various sites, but the explanations are sparse at best.
I know there aren't a lot of SCORM followers here, but if you have any info, I'd be keen to hear it.
FWIW, that's my pipwerks SCORM wrapper, but with the variable pipwerks changed to ncalt.
There is documentation on how to use my wrapper at http://pipwerks.com (search for "scorm wrapper" in the search field). The original source code can be found at https://github.com/pipwerks/scorm-api-wrapper.
Note your sample code is not using the wrapper the way it was intended to be used. For example, this:
ncalt.SCORM.data.set("cmi.core.lesson_status" , "completed");
should be this (data is an internal helper and not necessary):
ncalt.SCORM.set("cmi.core.lesson_status" , "completed");
You can shorten it even further via a reference variable, like so:
var scorm = ncalt.SCORM;
scorm.set("cmi.core.lesson_status" , "completed");
scorm.save();
scorm.get("cmi.core.lesson_status"); //returns "completed"
As for your 'components', if you'd like to use SCORM's cmi.interactions model, be sure you're using the correct syntax. The "n" in the SCORM documentation (cmi.interactions.n.id) is meant to represent a number, it's not a literal "n".
scorm.set("cmi.interactions.0.id", "myfirstinteraction");
scorm.save();
To retrieve data from that interaction, you need to specify the number in place of the n:
scorm.get("cmi.interactions.0.id"); //returns "myfirstinteraction"
Note the CMI data model doesn't provide a 'status' field for cmi.interactions. You'd need to use cmi.objectives.
scorm.set("cmi.objectives.0.status", "completed");
scorm.save();
scorm.get("cmi.objectives.0.status"); // returns "completed"
The CMI data model (as available in SCORM) is spelled out here: http://scorm.com/scorm-explained/technical-scorm/run-time/run-time-reference/

Resources