Parsing boto3 invoke_endpoint response from AWS SageMaker - parsing

I have a Sagemaker endpoint that I can infer to from boto3 client and get response.
Per boto3 doc, the Body of the response result is a Byte object StreamingBody type. I convert it to a dictionary
response = client.invoke_endpoint(EndpointName=endpoint_name, Body=json.dumps(data))
response_body = response['Body']
dict_response = response_body.read().decode('utf-8')
print(dict_response)
The above code gives me a response like below (stripped down for this post)
I need to retrieve the array from the "floatVal" key. How do I do that?
{
"outputs": {
"score": {
"dtype": "DT_FLOAT",
"floatVal": [
0.00012408883776515722,
...........
-0.8316119909286499,
-0.24423488974571228
],
"tensorShape": {
"dim": [
{
"size": "1"
},
{
"size": "1024"
}
]
}
}
},
"modelSpec": {
"version": "1",
"name": "generic_model",
"signatureName": "serving_default"
}
}

Actually the dict_response is not really a dictionary here, rather a string type. So I had to convert the dict_response to an actual dictionary and then I could retrieve the floatVal key.
Updated code
response = client.invoke_endpoint(EndpointName=endpoint_name, Body=json.dumps(data))
response_body = response['Body']
response_str = response_body.read().decode('utf-8')
response_dict = eval(response_str)
print(response_dict['outputs']['score']['floatVal'])

Related

How To Convert "created_timestamp" Value To A Valid Date In Python

I'm currently working on a Twitter bot that automatically reply messages, I'm doing this by using tweepy (the official python twitter library)
I need to filter messages based on the created time as I don't want to reply same message twice. Now the problem is that the API endpoint returns created_timestamp as string representation of positive integers.
Below is an example of data returned as per the doc
{
"next_cursor": "AB345dkfC",
"events": [
{ "id": "110", "created_timestamp": "1639919665615", ... },
{ "id": "109", "created_timestamp": "1639865141987", ... },
{ "id": "108", "created_timestamp": "1639827437833", ... },
{ "id": "107", "created_timestamp": "1639825389806", ... },
{ "id": "106", "created_timestamp": "1639825389796", ... },
{ "id": "105", "created_timestamp": "1639825389768", ... },
...
]
}
My question is "How do I convert the created_timestamp to a valid date using python" ?.
You might play with timestamps on this resource
And in your case could use methods like:
timestamp = int('timestamp_string')
datetime.fromtimestamp(timestamp, tz=None)
date.fromtimestamp(timestamp)
From the datetime standard library. But integers after the first line are already well comparable if the task is to distinguish differences between the timestamps.

Accessing a specific item in a JSON return in Rails

I have this JSON from the NHL API, and I tried to access the value gamesPlayed:
"teams"=>[
{
"id"=>5,
"name"=>"Pittsburgh Penguins",
"link"=>"/api/v1/teams/5",
"venue"=>{
"id"=>5034,
"name"=>"PPG Paints Arena",
"link"=>"/api/v1/venues/5034",
"city"=>"Pittsburgh",
"timeZone"=>{
"id"=>"America/New_York",
"offset"=>-5,
"tz"=>"EST"
}
},
"abbreviation"=>"PIT",
"teamName"=>"Penguins",
"locationName"=>"Pittsburgh",
"division"=>{
"id"=>18,
"name"=>"Metropolitan",
"nameShort"=>"Metro",
"link"=>"/api/v1/divisions/18",
"abbreviation"=>"M"
},
"conference"=>{
"id"=>6,
"name"=>"Eastern",
"link"=>"/api/v1/conferences/6"
},
"franchise"=>{
"franchiseId"=>17,
"teamName"=>"Penguins",
"link"=>"/api/v1/franchises/17"
},
"teamStats"=>[
{
"type"=>{
"displayName"=>"statsSingleSeason"
},
"splits"=>[
{
"stat"=>{
"gamesPlayed"=>16,
"wins"=>7,
"losses"=>6,
"ot"=>3,
"pts"=>17,
"ptPctg"=>"53.1",
"goalsPerGame"=>3.313,
"goalsAgainstPerGame"=>3.063,
"evGGARatio"=>1.0833,
"powerPlayPercentage"=>"23.4",
"powerPlayGoals"=>11.0,
"powerPlayGoalsAgainst"=>8.0,
"powerPlayOpportunities"=>47.0,
"penaltyKillPercentage"=>"84.0",
"shotsPerGame"=>32.625,
"shotsAllowed"=>33.6875,
"winScoreFirst"=>0.6,
"winOppScoreFirst"=>0.167,
"winLeadFirstPer"=>0.5,
"winLeadSecondPer"=>1.0,
"winOutshootOpp"=>0.333,
"winOutshotByOpp"=>0.444,
"faceOffsTaken"=>1035.0,
"faceOffsWon"=>534.0,
"faceOffsLost"=>501.0,
"faceOffWinPercentage"=>"51.6",
"shootingPctg"=>10.2,
"savePctg"=>0.909
},
"team"=>{
"id"=>5,
"name"=>"Pittsburgh Penguins",
"link"=>"/api/v1/teams/5"
}
},
{
"stat"=>{
"wins"=>"24th",
"losses"=>"15th",
"ot"=>"9th",
"pts"=>"24th",
"ptPctg"=>"19th",
"goalsPerGame"=>"8th",
"goalsAgainstPerGame"=>"19th",
"evGGARatio"=>"11th",
"powerPlayPercentage"=>"10th",
"powerPlayGoals"=>"22nd",
"powerPlayGoalsAgainst"=>"4th",
"powerPlayOpportunities"=>"31st",
"penaltyKillOpportunities"=>"1st",
"penaltyKillPercentage"=>"6th",
"shotsPerGame"=>"12th",
"shotsAllowed"=>"27th",
"winScoreFirst"=>"15th",
"winOppScoreFirst"=>"27th",
"winLeadFirstPer"=>"27th",
"winLeadSecondPer"=>"7th",
"winOutshootOpp"=>"25th",
"winOutshotByOpp"=>"25th",
"faceOffsTaken"=>"25th",
"faceOffsWon"=>"19th",
"faceOffsLost"=>"6th",
"faceOffWinPercentage"=>"8th",
"savePctRank"=>"13th",
"shootingPctRank"=>"12th"
},
"team"=>{
"id"=>5,
"name"=>"Pittsburgh Penguins",
"link"=>"/api/v1/teams/5"
}
}
]
}
],
"shortName"=>"Pittsburgh",
"officialSiteUrl"=>"http://pittsburghpenguins.com/",
"franchiseId"=>17,
"active"=>true
}
}
I am working in ruby on rails and would like to access the gamesPlayed value.
So far I have:
url = 'https://statsapi.web.nhl.com/api/v1/teams/5?expand=team.stats'
uri = URI(url)
response = Net::HTTP.get(uri)
response = JSON.parse(response)
#awayteamgamesplayed = response["teams"][0]["teamStats"]["stat"]["gamesPlayed"]
I can get to the team name using: response["teams"][away_team]["name"] but cant't work out gamesPlayed.
But it doesn't seem to work for gamesPlayed.
Value of teamStats is an Array. You need to access it via an index.
Same for splits
response["teams"][0]["teamStats"][0]["splits"][0]["stat"]["gamesPlayed"]
# => 16
teamStats is an array try this
response["teams"][0]["teamStats"][0]["stat"]["gamesPlayed"]

Looping in a C-style For loop instead of using each

how can i loop through a json file using a FOR loop in groovy? I am able to do it with .each but i am in a situation/bug where i cannot use .each loops.
The json file is being read and parsed into an object.
The json looks like this:
{
"workflows1": {
"name": "/wf_multifolder",
"file": "release1/wf_multifolder.XML",
"folderNames": {
"multifolder": "{{multifolder}}",
"agent1": "{{agentx}}"
}
},
"workflows2": {
"name": "/wf_multifolder",
"file": "release1/wf_multifolder.XML",
"folderNames": {
"multifolder": "{{multifolder}}",
"agent1": "{{agentx}}"
}
}
}
Note: i can modify the json file, if need to make the process simpler.. All i am try to do is to loop throgh and extract the values for the keys.
So given the json in a String like so:
def jsonText = '''{
"workflows1": {
"name": "/wf_multifolder",
"file": "release1/wf_multifolder.XML",
"folderNames": {
"multifolder": "{{multifolder}}",
"agent1": "{{agentx}}"
}
},
"workflows2": {
"name": "/wf_multifolder",
"file": "release1/wf_multifolder.XML",
"folderNames": {
"multifolder": "{{multifolder}}",
"agent1": "{{agentx}}"
}
}
}'''
You can just do:
import groovy.json.*
def json = new JsonSlurper().parseText(jsonText)
for(entry in json) {
println "$entry.key has file $entry.value.file"
}
to print:
workflows1 has file release1/wf_multifolder.XML
workflows2 has file release1/wf_multifolder.XML

Extracting value of a node in Java using contains with JsonPath in RestAssured

I have to extract value of book title using JsonPath in RestAssured in Java from following json response
{
"spec": {
"groups": [
{
"name": "book",
"title": "classic-books:1.0.2"
},.......
]
}
}
I am looking to use contains to get the book with a specific title.Please help.
Assume you have response with JSON in it:
response.body().jsonPath().get("spec.groups[i].title");

Youtube ContentID getting ownership info through the API using AppsScript

I am trying to get get ownership information against AssetIDs through the Youtube ContentID API.
I can see the data that I need through the API Explorer but cant seem to drill down the data using dot notation.
Here is the output from the API explorer:
{
"kind": "youtubePartner#asset",
"id": "A146063471697194",
"type": "music_video",
"ownership": {
"kind": "youtubePartner#rightsOwnership",
"general": [
{
"ratio": 100,
"owner": "Indmusic",
"type": "exclude"
}
]
},
"ownershipEffective": {
"kind": "youtubePartner#rightsOwnership",
"general": [
{
"ratio": 100,
"owner": "Indmusic",
"type": "exclude"
}
]
}
}
When accessing the "owner" I receive undefined instead of the listed value.
var url2 = _.sprintf('https://www.googleapis.com/youtube/partner/v1/assets/%s?fetchMetadata=effective&fetchOwnership=effective&key=%s',id,API_KEY);
var result2 = JSON.parse(UrlFetchApp.fetch(url2, getUrlFetchOptions()).getContentText());
Logger.log(result2.ownership.general.owner);
returns undefined
I have tried both ownershipEffective and ownership and they are both undefined.
I can log data from result2.ownership.general but nothing below that.
You can tell that general is an array by the [brackets] in:
"general": [
{
"ratio": 100,
"owner": "Indmusic",
"type": "exclude"
}
]
Try:
Logger.log(result2.ownership.general[0].owner);
general, having been declared an array, requires a position [0] even though there is only 1 item in the array.

Resources